instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public synchronized void destroy() {
started = false;
schedExecutor.shutdownNow();
try {
schedExecutor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.warn("Destroying InMemoryRegistrationStore was interrupted.", e);
}
}
private class Cleaner implements Runnable {
@Override
public void run() {
try {
Collection<Registration> allRegs = new ArrayList<>();
try {
lock.readLock().lock();
allRegs.addAll(regsByEp.values());
} finally {
lock.readLock().unlock();
}
for (Registration reg : allRegs) {
if (!reg.isAlive()) {
// force de-registration
Deregistration removedRegistration = removeRegistration(reg.getId());
expirationListener.registrationExpired(removedRegistration.getRegistration(),
removedRegistration.getObservations());
|
}
}
} catch (Exception e) {
log.warn("Unexpected Exception while registration cleaning", e);
}
}
}
// boolean remove(Object key, Object value) exist only since java8
// So this method is here only while we want to support java 7
protected <K, V> boolean removeFromMap(Map<K, V> map, K key, V value) {
if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
map.remove(key);
return true;
} else
return false;
}
}
|
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbInMemoryRegistrationStore.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AbstractEngineAware {
private final String engineName;
/**
* Creates a engine aware instance for the given engine
*
* @param engineName
*/
public AbstractEngineAware(String engineName) {
this.engineName = engineName;
}
/**
* Return a {@link CommandExecutor} for the current
* engine to execute plugin commands.
*
* @return
*/
protected CommandExecutor getCommandExecutor() {
return Cockpit.getCommandExecutor(engineName);
}
|
/**
* Return a {@link QueryService} for the current
* engine to execute queries against the engine datbase.
*
* @return
*/
protected QueryService getQueryService() {
return Cockpit.getQueryService(engineName);
}
/**
* Return a {@link ProcessEngine} for the current
* engine name to execute queries against the engine.
*
* @return the process engine
*/
protected ProcessEngine getProcessEngine() {
return Cockpit.getProcessEngine(engineName);
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\service\AbstractEngineAware.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class GithubController {
@Autowired
private GithubService githubService;
@GetMapping(path = "/{username}", produces = "application/json;charset=UTF-8")
public ResponseEntity<?> get(@Valid @PathVariable String username
) {
Try<User> githubUserProfile = githubService.findGithubUser(username);
if (githubUserProfile.isFailure()) {
return ResponseEntity.status(HttpStatus.FAILED_DEPENDENCY).body(githubUserProfile.getCause().getMessage());
}
if (githubUserProfile.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Response is empty");
}
if (githubUserProfile.isSuccess()) {
return ResponseEntity.status(HttpStatus.OK).body(githubUserProfile.get());
}
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("username is not valid");
}
@GetMapping(path = "/fail/{username}", produces = "application/json;charset=UTF-8")
|
public ResponseEntity<?> getFail(@Valid @PathVariable String username
) {
Try<User> githubUserProfile = githubService.findGithubUserAndFail(username);
if (githubUserProfile.isFailure()) {
System.out.println("Fail case");
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(githubUserProfile.getCause().getMessage());
}
if (githubUserProfile.isEmpty()) {
System.out.println("Empty case");
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Response is empty");
}
if (githubUserProfile.isSuccess()) {
System.out.println("Success case");
return ResponseEntity.status(HttpStatus.OK).body(githubUserProfile.get());
}
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("username is not valid");
}
}
|
repos\springboot-demo-master\vavr\src\main\java\com\et\vavr\controller\GithubController.java
| 2
|
请完成以下Java代码
|
public int getAD_User_ID()
{
return AD_User_ID;
}
@Override
public void setAD_User_ID(final int aD_User_ID)
{
AD_User_ID = aD_User_ID;
}
@Override
public int getIgnoreC_Printing_Queue_ID()
{
return ignoreC_Printing_Queue_ID;
}
@Override
public void setIgnoreC_Printing_Queue_ID(final int ignoreC_Printing_Queue_ID)
{
this.ignoreC_Printing_Queue_ID = ignoreC_Printing_Queue_ID;
}
@Override
public int getModelTableId()
{
return modelTableId;
}
@Override
public void setModelTableId(int modelTableId)
{
this.modelTableId = modelTableId;
}
@Override
public int getModelFromRecordId()
{
return modelFromRecordId;
}
@Override
public void setModelFromRecordId(int modelFromRecordId)
{
this.modelFromRecordId = modelFromRecordId;
}
@Override
public int getModelToRecordId()
{
return modelToRecordId;
}
@Override
public void setModelToRecordId(int modelToRecordId)
{
this.modelToRecordId = modelToRecordId;
}
@Override
public ISqlQueryFilter getFilter()
{
return filter;
}
@Override
public void setFilter(ISqlQueryFilter filter)
{
this.filter = filter;
}
@Override
public ISqlQueryFilter getModelFilter()
{
|
return modelFilter;
}
@Override
public void setModelFilter(ISqlQueryFilter modelFilter)
{
this.modelFilter = modelFilter;
}
@Override
public Access getRequiredAccess()
{
return requiredAccess;
}
@Override
public void setRequiredAccess(final Access requiredAccess)
{
this.requiredAccess = requiredAccess;
}
@Override
public Integer getCopies()
{
return copies;
}
@Override
public void setCopies(int copies)
{
this.copies = copies;
}
@Override
public String getAggregationKey()
{
return aggregationKey;
}
@Override
public void setAggregationKey(final String aggregationKey)
{
this.aggregationKey=aggregationKey;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrintingQueueQuery.java
| 1
|
请完成以下Java代码
|
public class DataStoreReferenceXMLConverter extends BaseBpmnXMLConverter {
public Class<? extends BaseElement> getBpmnElementType() {
return DataStoreReference.class;
}
@Override
protected String getXMLElementName() {
return ELEMENT_DATA_STORE_REFERENCE;
}
@Override
protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception {
DataStoreReference dataStoreRef = new DataStoreReference();
BpmnXMLUtil.addXMLLocation(dataStoreRef, xtr);
parseChildElements(getXMLElementName(), dataStoreRef, model, xtr);
return dataStoreRef;
}
@Override
protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
DataStoreReference dataStoreRef = (DataStoreReference) element;
if (StringUtils.isNotEmpty(dataStoreRef.getDataStoreRef())) {
xtw.writeAttribute(ATTRIBUTE_DATA_STORE_REF, dataStoreRef.getDataStoreRef());
|
}
if (StringUtils.isNotEmpty(dataStoreRef.getItemSubjectRef())) {
xtw.writeAttribute(ATTRIBUTE_ITEM_SUBJECT_REF, dataStoreRef.getItemSubjectRef());
}
}
@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
DataStoreReference dataStoreRef = (DataStoreReference) element;
if (StringUtils.isNotEmpty(dataStoreRef.getDataState())) {
xtw.writeStartElement(ELEMENT_DATA_STATE);
xtw.writeCharacters(dataStoreRef.getDataState());
xtw.writeEndElement();
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\DataStoreReferenceXMLConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getReferenceScopeId() {
return referenceScopeId;
}
@Override
public void setReferenceScopeId(String referenceScopeId) {
this.referenceScopeId = referenceScopeId;
}
@Override
public String getReferenceScopeType() {
return referenceScopeType;
}
@Override
public void setReferenceScopeType(String referenceScopeType) {
this.referenceScopeType = referenceScopeType;
}
@Override
public String getReferenceScopeDefinitionId() {
return referenceScopeDefinitionId;
}
@Override
public void setReferenceScopeDefinitionId(String referenceScopeDefinitionId) {
this.referenceScopeDefinitionId = referenceScopeDefinitionId;
}
@Override
public String getRootScopeId() {
return rootScopeId;
}
@Override
public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId;
}
@Override
public String getRootScopeType() {
return rootScopeType;
|
}
@Override
public void setRootScopeType(String rootScopeType) {
this.rootScopeType = rootScopeType;
}
@Override
public Date getCreateTime() {
return createTime;
}
@Override
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String getHierarchyType() {
return hierarchyType;
}
@Override
public void setHierarchyType(String hierarchyType) {
this.hierarchyType = hierarchyType;
}
}
|
repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\entity\EntityLinkEntityImpl.java
| 2
|
请完成以下Java代码
|
public class PerformanceMonitoringData
{
private final ArrayList<PerformanceMonitoringService.Metadata> calledBy = new ArrayList<>();
public String getInitiatorFunctionNameFQ()
{
for (final PerformanceMonitoringService.Metadata metadata : calledBy)
{
if (!metadata.isGroupingPlaceholder())
{
return metadata.getFunctionNameFQ();
}
}
return !calledBy.isEmpty() ? calledBy.get(0).getFunctionNameFQ() : "";
}
@Nullable
public String getLastCalledFunctionNameFQ()
{
if (calledBy.isEmpty())
{
return null;
}
else
{
return calledBy.get(calledBy.size() - 1).getFunctionNameFQ();
}
}
public String getInitiatorWindow()
{
final String windowName = !calledBy.isEmpty() ? calledBy.get(0).getWindowNameAndId() : "";
return windowName != null ? windowName : "NONE";
}
public boolean isInitiator() {return calledBy.isEmpty();}
|
public PerformanceMonitoringService.Type getEffectiveType(final PerformanceMonitoringService.Metadata metadata)
{
return !calledBy.isEmpty() ? calledBy.get(0).getType() : metadata.getType();
}
public int getDepth() {return calledBy.size();}
public IAutoCloseable addCalledByIfNotNull(@Nullable final PerformanceMonitoringService.Metadata metadata)
{
if (metadata == null)
{
return () -> {};
}
final int sizeBeforeAdd = calledBy.size();
calledBy.add(metadata);
return () -> {
while (calledBy.size() > sizeBeforeAdd)
{
calledBy.remove(calledBy.size() - 1);
}
};
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.monitoring\src\main\java\de\metas\monitoring\adapter\PerformanceMonitoringData.java
| 1
|
请完成以下Java代码
|
private IReferenceNoGenerator getReferenceNoGeneratorOrNull(String classname)
{
try
{
return Util.getInstance(IReferenceNoGenerator.class, classname);
}
catch (Exception e)
{
logger.error("Error loading referenceNo generator '" + classname + "'. Ignored.", e);
return null;
}
}
@Override
public void linkOnSameReferenceNo(final Object fromModel, final Object toModel)
{
if (fromModel == null)
{
logger.debug("fromModel is null. Skip.");
return;
}
if (toModel == null)
{
logger.debug("toModel is null. Skip.");
return;
}
// We use ctx and trxName from "toModel", because that one was produced now
final Properties ctx = InterfaceWrapperHelper.getCtx(toModel);
final String trxName = InterfaceWrapperHelper.getTrxName(toModel);
|
final String fromTableName = InterfaceWrapperHelper.getModelTableName(fromModel);
final int fromRecordId = InterfaceWrapperHelper.getId(fromModel);
if (fromRecordId <= 0)
{
logger.warn("fromModel {} was not saved yet or does not support simple primary key. Skip.", fromModel);
return;
}
final int toRecordId = InterfaceWrapperHelper.getId(toModel);
if (toRecordId <= 0)
{
logger.warn("toModel {} was not saved yet or does not support simple primary key. Skip.", toModel);
return;
}
final IReferenceNoDAO dao = Services.get(IReferenceNoDAO.class);
final List<I_C_ReferenceNo_Doc> fromAssignments = dao.retrieveAllDocAssignments(ctx,
-1, // referenceNoTypeId - return all assignments
MTable.getTable_ID(fromTableName), // tableId
fromRecordId,
trxName);
for (final I_C_ReferenceNo_Doc fromAssignment : fromAssignments)
{
final I_C_ReferenceNo referenceNo = fromAssignment.getC_ReferenceNo();
dao.getCreateReferenceNoDoc(referenceNo, TableRecordReference.of(toModel));
logger.info("Linked {} to {}", new Object[] { toModel, referenceNo });
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\api\impl\ReferenceNoBL.java
| 1
|
请完成以下Java代码
|
public void setIsNullFieldValue (boolean IsNullFieldValue)
{
set_Value (COLUMNNAME_IsNullFieldValue, Boolean.valueOf(IsNullFieldValue));
}
/** Get Null Value.
@return Null Value */
@Override
public boolean isNullFieldValue ()
{
Object oo = get_Value(COLUMNNAME_IsNullFieldValue);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public org.compiere.model.I_M_Attribute getM_Attribute() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Attribute_ID, org.compiere.model.I_M_Attribute.class);
}
@Override
public void setM_Attribute(org.compiere.model.I_M_Attribute M_Attribute)
{
set_ValueFromPO(COLUMNNAME_M_Attribute_ID, org.compiere.model.I_M_Attribute.class, M_Attribute);
}
/** Set Merkmal.
@param M_Attribute_ID
Product Attribute
*/
@Override
public void setM_Attribute_ID (int M_Attribute_ID)
{
if (M_Attribute_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, Integer.valueOf(M_Attribute_ID));
}
/** Get Merkmal.
@return Product Attribute
*/
@Override
public int getM_Attribute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Attribute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Merkmals-Wert.
@param M_AttributeValue_ID
Product Attribute Value
*/
@Override
public void setM_AttributeValue_ID (int M_AttributeValue_ID)
{
|
if (M_AttributeValue_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeValue_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeValue_ID, Integer.valueOf(M_AttributeValue_ID));
}
/** Get Merkmals-Wert.
@return Product Attribute Value
*/
@Override
public int getM_AttributeValue_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeValue.java
| 1
|
请完成以下Java代码
|
public class WalletsResource {
private static final Db<Stock> stocks = Repository.STOCKS_DB;
private static final Db<Wallet> wallets = Repository.WALLETS_DB;
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response post(Wallet wallet) {
wallets.save(wallet);
return Response.ok(wallet)
.build();
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response get(@PathParam("id") String id) {
Optional<Wallet> wallet = wallets.findById(id);
wallet.orElseThrow(IllegalArgumentException::new);
return Response.ok(wallet.get())
.build();
}
@PUT
@Path("/{id}/{amount}")
@Produces(MediaType.APPLICATION_JSON)
public Response putAmount(@PathParam("id") String id, @PathParam("amount") Double amount) {
Optional<Wallet> wallet = wallets.findById(id);
wallet.orElseThrow(IllegalArgumentException::new);
if (amount < Wallet.MIN_CHARGE) {
throw new InvalidTradeException(Wallet.MIN_CHARGE_MSG);
}
wallet.get()
.addBalance(amount);
wallets.save(wallet.get());
return Response.ok(wallet)
.build();
}
@POST
@Path("/{wallet}/buy/{ticker}")
@Produces(MediaType.APPLICATION_JSON)
public Response postBuyStock(@PathParam("wallet") String walletId, @PathParam("ticker") String id) {
Optional<Stock> stock = stocks.findById(id);
stock.orElseThrow(InvalidTradeException::new);
|
Optional<Wallet> w = wallets.findById(walletId);
w.orElseThrow(InvalidTradeException::new);
Wallet wallet = w.get();
Double price = stock.get()
.getPrice();
if (!wallet.hasFunds(price)) {
RestErrorResponse response = new RestErrorResponse();
response.setSubject(wallet);
response.setMessage("insufficient balance");
throw new WebApplicationException(Response.status(Response.Status.NOT_ACCEPTABLE)
.entity(response)
.build());
}
wallet.addBalance(-price);
wallets.save(wallet);
return Response.ok(wallet)
.build();
}
}
|
repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\exceptionhandling\rest\WalletsResource.java
| 1
|
请完成以下Java代码
|
protected String doIt()
{
final MailText mailText = createMailText();
addLog("@Result@ ---------------------------------");
addLog("Using @AD_Language@: {}", mailText.getAdLanguage());
addLog("@MailHeader@: {}", mailText.getMailHeader());
addLog("@MailText@ (full): {}", mailText.getFullMailText());
return MSG_OK;
}
private MailText createMailText()
{
final MailTemplateId mailTemplateId = MailTemplateId.ofRepoId(getRecord_ID());
final MailTextBuilder mailTextBuilder = mailService.newMailTextBuilder(mailTemplateId);
Object record = null;
if (p_AD_Table_ID > 0 && p_Record_ID >= 0)
{
final String tableName = tableDAO.retrieveTableName(p_AD_Table_ID);
record = InterfaceWrapperHelper.create(getCtx(), tableName, p_Record_ID, Object.class, getTrxName());
if (record != null)
{
mailTextBuilder.recordAndUpdateBPartnerAndContact(record);
}
}
I_C_BPartner bpartner = null;
if (p_C_BPartner_ID > 0)
{
bpartner = bpartnerDAO.getById(p_C_BPartner_ID);
mailTextBuilder.bpartner(bpartner);
}
|
I_AD_User contact = null;
if (p_AD_User_ID >= 0)
{
contact = userDAO.getById(UserId.ofRepoId(p_AD_User_ID));
mailTextBuilder.bpartnerContact(contact);
}
//
// Display configuration
addLog("Using @R_MailText_ID@: {}", mailTemplateId);
addLog("Using @C_BPartner_ID@: {}", bpartner);
addLog("Using @AD_User_ID@: {}", contact);
addLog("Using @Record_ID@: {}", record);
return mailTextBuilder.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\process\R_MailText_Test.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Collection<UserDetails> getObject() throws Exception {
Properties userProperties = new Properties();
Resource resource = getPropertiesResource();
try (InputStream in = resource.getInputStream()) {
userProperties.load(in);
}
return new UserDetailsMapFactoryBean((Map) userProperties).getObject();
}
@Override
public Class<?> getObjectType() {
return Collection.class;
}
/**
* Sets the location of a Resource that is a Properties file in the format defined in
* {@link UserDetailsResourceFactoryBean}.
* @param resourceLocation the location of the properties file that contains the users
* (i.e. "classpath:users.properties")
*/
public void setResourceLocation(String resourceLocation) {
this.resourceLocation = resourceLocation;
}
/**
* Sets a Resource that is a Properties file in the format defined in
* {@link UserDetailsResourceFactoryBean}.
* @param resource the Resource to use
*/
public void setResource(Resource resource) {
this.resource = resource;
}
private Resource getPropertiesResource() {
Resource result = this.resource;
if (result == null && this.resourceLocation != null) {
result = this.resourceLoader.getResource(this.resourceLocation);
}
Assert.notNull(result, "resource cannot be null if resourceLocation is null");
return result;
}
/**
* Create a UserDetailsResourceFactoryBean with the location of a Resource that is a
* Properties file in the format defined in {@link UserDetailsResourceFactoryBean}.
* @param resourceLocation the location of the properties file that contains the users
* (i.e. "classpath:users.properties")
* @return the UserDetailsResourceFactoryBean
*/
public static UserDetailsResourceFactoryBean fromResourceLocation(String resourceLocation) {
UserDetailsResourceFactoryBean result = new UserDetailsResourceFactoryBean();
result.setResourceLocation(resourceLocation);
return result;
}
|
/**
* Create a UserDetailsResourceFactoryBean with a Resource that is a Properties file
* in the format defined in {@link UserDetailsResourceFactoryBean}.
* @param propertiesResource the Resource that is a properties file that contains the
* users
* @return the UserDetailsResourceFactoryBean
*/
public static UserDetailsResourceFactoryBean fromResource(Resource propertiesResource) {
UserDetailsResourceFactoryBean result = new UserDetailsResourceFactoryBean();
result.setResource(propertiesResource);
return result;
}
/**
* Creates a UserDetailsResourceFactoryBean with a resource from the provided String
* @param users the string representing the users
* @return the UserDetailsResourceFactoryBean
*/
public static UserDetailsResourceFactoryBean fromString(String users) {
InMemoryResource resource = new InMemoryResource(users);
return fromResource(resource);
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\core\userdetails\UserDetailsResourceFactoryBean.java
| 2
|
请完成以下Java代码
|
public AttachmentEntityManager getAttachmentEntityManager() {
return processEngineConfiguration.getAttachmentEntityManager();
}
public TableDataManager getTableDataManager() {
return processEngineConfiguration.getTableDataManager();
}
public CommentEntityManager getCommentEntityManager() {
return processEngineConfiguration.getCommentEntityManager();
}
public PropertyEntityManager getPropertyEntityManager() {
return processEngineConfiguration.getPropertyEntityManager();
}
public EventSubscriptionEntityManager getEventSubscriptionEntityManager() {
return processEngineConfiguration.getEventSubscriptionEntityManager();
}
public HistoryManager getHistoryManager() {
return processEngineConfiguration.getHistoryManager();
}
public JobManager getJobManager() {
return processEngineConfiguration.getJobManager();
}
// Involved executions ////////////////////////////////////////////////////////
public void addInvolvedExecution(ExecutionEntity executionEntity) {
if (executionEntity.getId() != null) {
involvedExecutions.put(executionEntity.getId(), executionEntity);
}
}
public boolean hasInvolvedExecutions() {
return involvedExecutions.size() > 0;
}
public Collection<ExecutionEntity> getInvolvedExecutions() {
return involvedExecutions.values();
}
// getters and setters
|
// //////////////////////////////////////////////////////
public Command<?> getCommand() {
return command;
}
public Map<Class<?>, Session> getSessions() {
return sessions;
}
public Throwable getException() {
return exception;
}
public FailedJobCommandFactory getFailedJobCommandFactory() {
return failedJobCommandFactory;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public ActivitiEventDispatcher getEventDispatcher() {
return processEngineConfiguration.getEventDispatcher();
}
public ActivitiEngineAgenda getAgenda() {
return agenda;
}
public Object getResult() {
return resultStack.pollLast();
}
public void setResult(Object result) {
resultStack.add(result);
}
public boolean isReused() {
return reused;
}
public void setReused(boolean reused) {
this.reused = reused;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java
| 1
|
请完成以下Java代码
|
public boolean isAutoOpen() {
return subscriptionConfiguration.getAutoOpen();
}
public void setExternalTaskHandler(ExternalTaskHandler externalTaskHandler) {
this.externalTaskHandler = externalTaskHandler;
}
public SubscriptionConfiguration getSubscriptionConfiguration() {
return subscriptionConfiguration;
}
public void setSubscriptionConfiguration(SubscriptionConfiguration subscriptionConfiguration) {
this.subscriptionConfiguration = subscriptionConfiguration;
}
@Override
public String getTopicName() {
return subscriptionConfiguration.getTopicName();
}
@Override
public Long getLockDuration() {
return subscriptionConfiguration.getLockDuration();
}
@Override
public ExternalTaskHandler getExternalTaskHandler() {
return externalTaskHandler;
}
@Override
public List<String> getVariableNames() {
return subscriptionConfiguration.getVariableNames();
}
@Override
public boolean isLocalVariables() {
return subscriptionConfiguration.getLocalVariables();
}
@Override
public String getBusinessKey() {
return subscriptionConfiguration.getBusinessKey();
}
@Override
public String getProcessDefinitionId() {
return subscriptionConfiguration.getProcessDefinitionId();
}
@Override
public List<String> getProcessDefinitionIdIn() {
return subscriptionConfiguration.getProcessDefinitionIdIn();
}
@Override
public String getProcessDefinitionKey() {
return subscriptionConfiguration.getProcessDefinitionKey();
|
}
@Override
public List<String> getProcessDefinitionKeyIn() {
return subscriptionConfiguration.getProcessDefinitionKeyIn();
}
@Override
public String getProcessDefinitionVersionTag() {
return subscriptionConfiguration.getProcessDefinitionVersionTag();
}
@Override
public Map<String, Object> getProcessVariables() {
return subscriptionConfiguration.getProcessVariables();
}
@Override
public boolean isWithoutTenantId() {
return subscriptionConfiguration.getWithoutTenantId();
}
@Override
public List<String> getTenantIdIn() {
return subscriptionConfiguration.getTenantIdIn();
}
@Override
public boolean isIncludeExtensionProperties() {
return subscriptionConfiguration.getIncludeExtensionProperties();
}
protected String[] toArray(List<String> list) {
return list.toArray(new String[0]);
}
@Override
public void afterPropertiesSet() throws Exception {
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\subscription\SpringTopicSubscriptionImpl.java
| 1
|
请完成以下Java代码
|
public int getC_BPartner_ID()
{
if (m_invoice == null)
getInvoice();
if (m_invoice == null)
return 0;
return m_invoice.getC_BPartner_ID();
} // getC_BPartner_ID
/**
* Before Save
* @param newRecord new
* @return true
*/
@Override
protected boolean beforeSave (boolean newRecord)
{
MPayment payment = new MPayment (getCtx(), getC_Payment_ID(), get_TrxName());
if ((newRecord || is_ValueChanged("C_Invoice_ID"))
&& (payment.getC_Charge_ID() != 0
|| payment.getC_Invoice_ID() != 0
|| payment.getC_Order_ID() != 0))
{
throw new AdempiereException("@PaymentIsAllocated@");
}
BigDecimal check = getAmount()
.add(getDiscountAmt())
.add(getWriteOffAmt())
.add(getOverUnderAmt());
if (check.compareTo(getInvoiceAmt()) != 0)
{
throw new AdempiereException("@InvoiceAmt@(" + getInvoiceAmt() + ") <> @Totals@(" + check + ")");
}
// Org
if (newRecord || is_ValueChanged("C_Invoice_ID"))
{
getInvoice();
if (m_invoice != null)
setAD_Org_ID(m_invoice.getAD_Org_ID());
}
return true;
} // beforeSave
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
//metas start: cg task us025b
if (success)
|
{
updateAmounts();
}
return success;
//metas end: cg task us025b
}
@Override
protected boolean afterDelete(boolean success)
{
//metas start: cg task us025b
if (success)
{
updateAmounts();
}
return success;
//metas end: cg task us025b
}
/**
* metas cg task us025b
* method for updating amounts in payment
*/
private void updateAmounts()
{
String updateSQL = "UPDATE C_Payment "
+ " set PayAmt = (SELECT SUM(Amount) from C_PaymentAllocate WHERE C_Payment_ID=?), "
+ " DiscountAmt = (SELECT SUM(DiscountAmt) from C_PaymentAllocate WHERE C_Payment_ID=?), "
+ " WriteOffAmt = (SELECT SUM(WriteOffAmt) from C_PaymentAllocate WHERE C_Payment_ID=?), "
+ " OverUnderAmt = (SELECT SUM(OverUnderAmt) from C_PaymentAllocate WHERE C_Payment_ID=?), "
+ " IsOverUnderPayment = (SELECT CASE WHEN sum(OverUnderAmt)!=0 THEN 'Y' ELSE 'N' END FROM C_PaymentAllocate WHERE C_Payment_ID=?) "
+ " WHERE C_Payment_ID=?";
DB.executeUpdateAndIgnoreErrorOnFail(updateSQL, new Object[] { getC_Payment_ID(), getC_Payment_ID(), getC_Payment_ID(),
getC_Payment_ID(), getC_Payment_ID(), getC_Payment_ID() },
false, get_TrxName());
}
} // MPaymentAllocate
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MPaymentAllocate.java
| 1
|
请完成以下Java代码
|
protected TenantManager getTenantManager() {
return getSession(TenantManager.class);
}
public void close() {
}
public void flush() {
}
// authorizations ///////////////////////////////////////
protected CommandContext getCommandContext() {
return Context.getCommandContext();
}
protected AuthorizationManager getAuthorizationManager() {
return getSession(AuthorizationManager.class);
}
protected void configureQuery(AbstractQuery<?,?> query, Resource resource) {
getAuthorizationManager().configureQuery(query, resource);
}
protected void checkAuthorization(Permission permission, Resource resource, String resourceId) {
getAuthorizationManager().checkAuthorization(permission, resource, resourceId);
}
public boolean isAuthorizationEnabled() {
return Context.getProcessEngineConfiguration().isAuthorizationEnabled();
}
protected Authentication getCurrentAuthentication() {
return Context.getCommandContext().getAuthentication();
}
protected ResourceAuthorizationProvider getResourceAuthorizationProvider() {
return Context.getProcessEngineConfiguration()
.getResourceAuthorizationProvider();
}
protected void deleteAuthorizations(Resource resource, String resourceId) {
getAuthorizationManager().deleteAuthorizationsByResourceId(resource, resourceId);
}
protected void deleteAuthorizationsForUser(Resource resource, String resourceId, String userId) {
getAuthorizationManager().deleteAuthorizationsByResourceIdAndUserId(resource, resourceId, userId);
}
protected void deleteAuthorizationsForGroup(Resource resource, String resourceId, String groupId) {
getAuthorizationManager().deleteAuthorizationsByResourceIdAndGroupId(resource, resourceId, groupId);
}
public void saveDefaultAuthorizations(final AuthorizationEntity[] authorizations) {
if(authorizations != null && authorizations.length > 0) {
Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() {
public Void call() {
|
AuthorizationManager authorizationManager = getAuthorizationManager();
for (AuthorizationEntity authorization : authorizations) {
if(authorization.getId() == null) {
authorizationManager.insert(authorization);
} else {
authorizationManager.update(authorization);
}
}
return null;
}
});
}
}
public void deleteDefaultAuthorizations(final AuthorizationEntity[] authorizations) {
if(authorizations != null && authorizations.length > 0) {
Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() {
public Void call() {
AuthorizationManager authorizationManager = getAuthorizationManager();
for (AuthorizationEntity authorization : authorizations) {
authorizationManager.delete(authorization);
}
return null;
}
});
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\AbstractManager.java
| 1
|
请完成以下Java代码
|
public void setM_HU_PI_ID (final int M_HU_PI_ID)
{
if (M_HU_PI_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, M_HU_PI_ID);
}
@Override
public int getM_HU_PI_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_ID);
}
@Override
public void setM_HU_PI_Version_ID (final int M_HU_PI_Version_ID)
{
if (M_HU_PI_Version_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, M_HU_PI_Version_ID);
}
@Override
public int getM_HU_PI_Version_ID()
|
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Version_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Version.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ActivitiSpringSecurityPoliciesAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public ProcessSecurityPoliciesManager processSecurityPoliciesManager(
SecurityManager securityManager,
SecurityPoliciesProperties securityPoliciesProperties,
SecurityPoliciesRestrictionApplier<GetProcessDefinitionsPayload> processDefinitionRestrictionApplier,
SecurityPoliciesRestrictionApplier<GetProcessInstancesPayload> processInstanceRestrictionApplier
) {
return new ProcessSecurityPoliciesManagerImpl(
securityManager,
securityPoliciesProperties,
processDefinitionRestrictionApplier,
processInstanceRestrictionApplier
|
);
}
@Bean
@ConditionalOnMissingBean(name = "processInstanceRestrictionApplier")
public SecurityPoliciesRestrictionApplier<GetProcessInstancesPayload> processInstanceRestrictionApplier() {
return new SecurityPoliciesProcessInstanceRestrictionApplier();
}
@Bean
@ConditionalOnMissingBean(name = "processDefinitionRestrictionApplier")
public SecurityPoliciesRestrictionApplier<GetProcessDefinitionsPayload> processDefinitionRestrictionApplier() {
return new SecurityPoliciesProcessDefinitionRestrictionApplier();
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-spring-security-policies\src\main\java\org\activiti\core\common\spring\security\policies\config\ActivitiSpringSecurityPoliciesAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public class ChildBpmnCaseInstanceStateChangeCallback implements RuntimeInstanceStateChangeCallback {
private static final Logger LOGGER = LoggerFactory.getLogger(ChildBpmnCaseInstanceStateChangeCallback.class);
@Override
public void stateChanged(CallbackData callbackData) {
/*
* The child case instance has the execution id as callback id stored.
* When the child case instance is finished, the execution of the parent process instance needs to be triggered.
*/
if (CaseInstanceState.TERMINATED.equals(callbackData.getNewState())
|| CaseInstanceState.COMPLETED.equals(callbackData.getNewState())) {
CommandContext commandContext = CommandContextUtil.getCommandContext();
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
CaseInstanceEntity caseInstance = cmmnEngineConfiguration.getCaseInstanceEntityManager().findById(callbackData.getInstanceId());
ProcessInstanceService processInstanceService = cmmnEngineConfiguration.getProcessInstanceService();
Map<String, Object> variables = new HashMap<>();
for (IOParameter outParameter : processInstanceService.getOutputParametersOfCaseTask(callbackData.getCallbackId())) {
Object value = null;
if (StringUtils.isNotEmpty(outParameter.getSourceExpression())) {
Expression expression = cmmnEngineConfiguration.getExpressionManager().createExpression(outParameter.getSourceExpression().trim());
value = expression.getValue(caseInstance);
} else {
value = caseInstance.getVariable(outParameter.getSource());
}
String variableName = null;
if (StringUtils.isNotEmpty(outParameter.getTarget())) {
variableName = outParameter.getTarget();
|
} else if (StringUtils.isNotEmpty(outParameter.getTargetExpression())) {
Object variableNameValue = cmmnEngineConfiguration.getExpressionManager().createExpression(outParameter.getTargetExpression()).getValue(caseInstance);
if (variableNameValue != null) {
variableName = variableNameValue.toString();
} else {
LOGGER.warn("Out parameter target expression {} did not resolve to a variable name, this is most likely a programmatic error",
outParameter.getTargetExpression());
}
}
variables.put(variableName, value);
}
processInstanceService.triggerCaseTask(callbackData.getCallbackId(), variables);
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\callback\ChildBpmnCaseInstanceStateChangeCallback.java
| 1
|
请完成以下Spring Boot application配置
|
spring.profiles.active=@profileActive@
server.context-path=/Gaoxi-Controller
spring.http.multipart.maxFileSize=2Mb
spring.http.multipart.maxRequestSize=10Mb
# Session有效时间(单位秒,15分钟)
sess
|
ion.expireTime=900
# HTTP Response中Session ID 的名字
session.SessionIdName=sessionId
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Controller\src\main\resources\application.properties
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void saveEntity(List<Entity> entityList) {
Bulk.Builder bulk = new Bulk.Builder();
for(Entity entity : entityList) {
Index index = new Index.Builder(entity).index(Entity.INDEX_NAME).type(Entity.TYPE).build();
bulk.addAction(index);
}
try {
jestClient.execute(bulk.build());
LOGGER.info("ES 插入完成");
} catch (IOException e) {
e.printStackTrace();
LOGGER.error(e.getMessage());
}
}
/**
* 在ES中搜索内容
*/
@Override
public List<Entity> searchEntity(String searchContent){
|
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//searchSourceBuilder.query(QueryBuilders.queryStringQuery(searchContent));
//searchSourceBuilder.field("name");
searchSourceBuilder.query(QueryBuilders.matchQuery("name",searchContent));
Search search = new Search.Builder(searchSourceBuilder.toString())
.addIndex(Entity.INDEX_NAME).addType(Entity.TYPE).build();
try {
JestResult result = jestClient.execute(search);
return result.getSourceAsObjectList(Entity.class);
} catch (IOException e) {
LOGGER.error(e.getMessage());
e.printStackTrace();
}
return null;
}
}
|
repos\Spring-Boot-In-Action-master\springboot_es_demo\src\main\java\com\hansonwang99\springboot_es_demo\service\impl\TestServiceImpl.java
| 2
|
请完成以下Java代码
|
public final class WorkflowLaunchersFacetGroupId
{
@NonNull String asString;
private WorkflowLaunchersFacetGroupId(@NonNull final String string)
{
final String stringNorm = StringUtils.trimBlankToNull(string);
if (stringNorm == null)
{
throw new AdempiereException("Empty/null string is not a valid group ID");
}
if (stringNorm.contains(WorkflowLaunchersFacetId.SEPARATOR))
{
throw new AdempiereException("Group ID `" + string + "` cannot contain `" + WorkflowLaunchersFacetId.SEPARATOR + "`");
}
this.asString = stringNorm;
|
}
@JsonCreator
public static WorkflowLaunchersFacetGroupId ofString(@NonNull final String string)
{
return new WorkflowLaunchersFacetGroupId(string);
}
@Override
@Deprecated
public String toString() {return getAsString();}
@JsonValue
@NonNull
public String getAsString() {return asString;}
public static boolean equals(@Nullable WorkflowLaunchersFacetGroupId id1, @Nullable WorkflowLaunchersFacetGroupId id2) {return Objects.equals(id1, id2);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\rest_workflows\facets\WorkflowLaunchersFacetGroupId.java
| 1
|
请完成以下Java代码
|
public Builder setClearanceStatus(@Nullable final JSONLookupValue clearanceStatusLookupValue)
{
clearanceStatus = clearanceStatusLookupValue;
return this;
}
public Builder setCustomProcessApplyPredicate(@Nullable final BiPredicate<HUEditorRow, ProcessDescriptor> processApplyPredicate)
{
this.customProcessApplyPredicate = processApplyPredicate;
return this;
}
@Nullable
private BiPredicate<HUEditorRow, ProcessDescriptor> getCustomProcessApplyPredicate()
{
return this.customProcessApplyPredicate;
}
/**
* @param currentRow the row that is currently constructed using this builder
*/
private ImmutableMultimap<OrderLineId, HUEditorRow> prepareIncludedOrderLineReservations(@NonNull final HUEditorRow currentRow)
{
final ImmutableMultimap.Builder<OrderLineId, HUEditorRow> includedOrderLineReservationsBuilder = ImmutableMultimap.builder();
for (final HUEditorRow includedRow : buildIncludedRows())
{
includedOrderLineReservationsBuilder.putAll(includedRow.getIncludedOrderLineReservations());
|
}
if (orderLineReservation != null)
{
includedOrderLineReservationsBuilder.put(orderLineReservation, currentRow);
}
return includedOrderLineReservationsBuilder.build();
}
}
@lombok.Builder
@lombok.Value
public static class HUEditorRowHierarchy
{
@NonNull HUEditorRow cuRow;
@Nullable
HUEditorRow parentRow;
@Nullable
HUEditorRow topLevelRow;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRow.java
| 1
|
请完成以下Java代码
|
public BranchAndFinancialInstitutionIdentification4 getSttlmPlc() {
return sttlmPlc;
}
/**
* Sets the value of the sttlmPlc property.
*
* @param value
* allowed object is
* {@link BranchAndFinancialInstitutionIdentification4 }
*
*/
public void setSttlmPlc(BranchAndFinancialInstitutionIdentification4 value) {
this.sttlmPlc = value;
}
/**
* Gets the value of the prtry property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the prtry property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPrtry().add(newItem);
* </pre>
|
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProprietaryAgent2 }
*
*
*/
public List<ProprietaryAgent2> getPrtry() {
if (prtry == null) {
prtry = new ArrayList<ProprietaryAgent2>();
}
return this.prtry;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TransactionAgents2.java
| 1
|
请完成以下Java代码
|
public Optional<WorkplaceId> getWorkplaceIdByUserId(@NonNull final UserId userId)
{
return byUserId.getOrLoad(userId, this::retrieveWorkplaceIdByUserId);
}
@NonNull
private Optional<WorkplaceId> retrieveWorkplaceIdByUserId(@NonNull final UserId userId)
{
return retrieveActiveRecordByUserId(userId).map(WorkplaceUserAssignRepository::extractWorkplaceId);
}
private static WorkplaceId extractWorkplaceId(final I_C_Workplace_User_Assign record) {return WorkplaceId.ofRepoId(record.getC_Workplace_ID());}
@NonNull
private Optional<I_C_Workplace_User_Assign> retrieveActiveRecordByUserId(final @NonNull UserId userId)
{
return queryBL.createQueryBuilder(I_C_Workplace_User_Assign.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Workplace_User_Assign.COLUMNNAME_AD_User_ID, userId)
|
.create()
.firstOnlyOptional(I_C_Workplace_User_Assign.class);
}
public void create(@NonNull final WorkplaceAssignmentCreateRequest request)
{
final UserId userId = request.getUserId();
final WorkplaceId workplaceId = request.getWorkplaceId();
final I_C_Workplace_User_Assign record = retrieveActiveRecordByUserId(userId)
.orElseGet(() -> InterfaceWrapperHelper.newInstance(I_C_Workplace_User_Assign.class));
record.setIsActive(true);
record.setAD_User_ID(userId.getRepoId());
record.setC_Workplace_ID(workplaceId.getRepoId());
InterfaceWrapperHelper.save(record);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workplace\WorkplaceUserAssignRepository.java
| 1
|
请完成以下Java代码
|
public Integer getDefaultScheduleVersion() {
return defaultScheduleVersion;
}
public void setDefaultScheduleVersion(Integer defaultScheduleVersion) {
this.defaultScheduleVersion = defaultScheduleVersion;
}
public Clock getClock() {
if (clock == null) {
clock = new DefaultClockImpl();
}
return clock;
}
public void setClock(Clock clock) {
this.clock = clock;
}
public BusinessCalendarManager getBusinessCalendarManager() {
MapBusinessCalendarManager mapBusinessCalendarManager = new MapBusinessCalendarManager();
|
mapBusinessCalendarManager.addBusinessCalendar(
DurationBusinessCalendar.NAME,
new DurationBusinessCalendar(getClock())
);
mapBusinessCalendarManager.addBusinessCalendar(
DueDateBusinessCalendar.NAME,
new DueDateBusinessCalendar(getClock())
);
mapBusinessCalendarManager.addBusinessCalendar(
AdvancedCycleBusinessCalendar.NAME,
new AdvancedCycleBusinessCalendar(getClock(), defaultScheduleVersion)
);
return mapBusinessCalendarManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\SpringAdvancedBusinessCalendarManagerFactory.java
| 1
|
请完成以下Java代码
|
public class ManualTaskJsonConverter extends BaseBpmnJsonConverter {
public static void fillTypes(
Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap,
Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap
) {
fillJsonTypes(convertersToBpmnMap);
fillBpmnTypes(convertersToJsonMap);
}
public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) {
convertersToBpmnMap.put(STENCIL_TASK_MANUAL, ManualTaskJsonConverter.class);
}
public static void fillBpmnTypes(
Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap
) {
convertersToJsonMap.put(ManualTask.class, ManualTaskJsonConverter.class);
}
|
protected String getStencilId(BaseElement baseElement) {
return STENCIL_TASK_MANUAL;
}
protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {}
protected FlowElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap
) {
ManualTask task = new ManualTask();
return task;
}
}
|
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\ManualTaskJsonConverter.java
| 1
|
请完成以下Java代码
|
public class Purpose2CHCode {
@XmlElement(name = "Cd", required = true)
protected String cd;
/**
* Gets the value of the cd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCd() {
return cd;
|
}
/**
* Sets the value of the cd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCd(String value) {
this.cd = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\Purpose2CHCode.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserToRoleRelationshipRepository implements RelationshipRepositoryV2<User, Long, Role, Long> {
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@Override
public void setRelation(User User, Long roleId, String fieldName) {
// not for many-to-many
}
@Override
public void setRelations(User user, Iterable<Long> roleIds, String fieldName) {
final Set<Role> roles = new HashSet<Role>();
roles.addAll(roleRepository.findAllById(roleIds));
user.setRoles(roles);
userRepository.save(user);
}
@Override
public void addRelations(User user, Iterable<Long> roleIds, String fieldName) {
final Set<Role> roles = user.getRoles();
roles.addAll(roleRepository.findAllById(roleIds));
user.setRoles(roles);
userRepository.save(user);
}
@Override
public void removeRelations(User user, Iterable<Long> roleIds, String fieldName) {
final Set<Role> roles = user.getRoles();
roles.removeAll(roleRepository.findAllById(roleIds));
user.setRoles(roles);
userRepository.save(user);
|
}
@Override
public Role findOneTarget(Long sourceId, String fieldName, QuerySpec querySpec) {
// not for many-to-many
return null;
}
@Override
public ResourceList<Role> findManyTargets(Long sourceId, String fieldName, QuerySpec querySpec) {
final Optional<User> userOptional = userRepository.findById(sourceId);
User user = userOptional.isPresent() ? userOptional.get() : new User();
return querySpec.apply(user.getRoles());
}
@Override
public Class<User> getSourceResourceClass() {
return User.class;
}
@Override
public Class<Role> getTargetResourceClass() {
return Role.class;
}
}
|
repos\tutorials-master\spring-katharsis\src\main\java\com\baeldung\persistence\katharsis\UserToRoleRelationshipRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getPlaceOrderStartTime() {
return placeOrderStartTime;
}
public void setPlaceOrderStartTime(String placeOrderStartTime) {
this.placeOrderStartTime = placeOrderStartTime;
}
public String getPlaceOrderEndTime() {
return placeOrderEndTime;
}
public void setPlaceOrderEndTime(String placeOrderEndTime) {
this.placeOrderEndTime = placeOrderEndTime;
}
public String getRecipientName() {
return recipientName;
}
public void setRecipientName(String recipientName) {
this.recipientName = recipientName;
}
public String getRecipientPhone() {
return recipientPhone;
}
public void setRecipientPhone(String recipientPhone) {
this.recipientPhone = recipientPhone;
}
public String getRecipientLocation() {
return recipientLocation;
}
public void setRecipientLocation(String recipientLocation) {
this.recipientLocation = recipientLocation;
}
public Integer getPayModeCode() {
return payModeCode;
}
public void setPayModeCode(Integer payModeCode) {
this.payModeCode = payModeCode;
}
public String getExpressNo() {
return expressNo;
}
|
public void setExpressNo(String expressNo) {
this.expressNo = expressNo;
}
public String getBuyerId() {
return buyerId;
}
public void setBuyerId(String buyerId) {
this.buyerId = buyerId;
}
public String getSellerId() {
return sellerId;
}
public void setSellerId(String sellerId) {
this.sellerId = sellerId;
}
@Override
public String toString() {
return "OrderQueryReq{" +
"id='" + id + '\'' +
", buyerId='" + buyerId + '\'' +
", buyerName='" + buyerName + '\'' +
", buyerPhone='" + buyerPhone + '\'' +
", buyerMail='" + buyerMail + '\'' +
", sellerId='" + sellerId + '\'' +
", sellerCompanyName='" + sellerCompanyName + '\'' +
", sellerPhone='" + sellerPhone + '\'' +
", sellerMail='" + sellerMail + '\'' +
", orderStateCode=" + orderStateCode +
", placeOrderStartTime='" + placeOrderStartTime + '\'' +
", placeOrderEndTime='" + placeOrderEndTime + '\'' +
", recipientName='" + recipientName + '\'' +
", recipientPhone='" + recipientPhone + '\'' +
", recipientLocation='" + recipientLocation + '\'' +
", payModeCode=" + payModeCode +
", expressNo='" + expressNo + '\'' +
", page=" + page +
", numPerPage=" + numPerPage +
", currentPage=" + currentPage +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\order\OrderQueryReq.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ExternalSystem_Config_WooCommerce
{
public final ExternalSystemConfigRepo externalSystemConfigRepo;
public final ExternalServices externalServices;
public ExternalSystem_Config_WooCommerce(
@NonNull final ExternalSystemConfigRepo externalSystemConfigRepo,
@NonNull final ExternalServices externalServices)
{
this.externalSystemConfigRepo = externalSystemConfigRepo;
this.externalServices = externalServices;
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = I_ExternalSystem_Config_WooCommerce.COLUMNNAME_ExternalSystem_Config_ID)
public void checkType(final I_ExternalSystem_Config_WooCommerce woocommerceConfig)
{
final String parentType =
externalSystemConfigRepo.getParentTypeById(ExternalSystemParentConfigId.ofRepoId(woocommerceConfig.getExternalSystem_Config_ID()));
if (!ExternalSystemType.WOO.getValue().equals(parentType))
{
throw new AdempiereException("Invalid external system type!");
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE })
|
public void generateAndSetUUID(final I_ExternalSystem_Config_WooCommerce woocommerceConfig)
{
if (woocommerceConfig.getCamelHttpResourceAuthKey() == null)
{
woocommerceConfig.setCamelHttpResourceAuthKey(UUID.randomUUID().toString());
}
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW })
public void createExternalSystemInstance(final I_ExternalSystem_Config_WooCommerce woocommerceConfig)
{
final ExternalSystemParentConfigId parentConfigId = ExternalSystemParentConfigId.ofRepoId(woocommerceConfig.getExternalSystem_Config_ID());
externalServices.initializeServiceInstancesIfRequired(parentConfigId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\woocommerce\interceptor\ExternalSystem_Config_WooCommerce.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class PickedData
{
ProductId productId;
Quantity qtyPicked;
Quantity qtyPickedInUOM;
Quantity qtyCatch;
@NonNull
public static PickedData of(@NonNull final StockQtyAndUOMQty stockQtyAndUOMQty)
{
return PickedData.builder()
.productId(stockQtyAndUOMQty.getProductId())
.qtyPicked(stockQtyAndUOMQty.getStockQty())
.qtyPickedInUOM(stockQtyAndUOMQty.getUOMQtyNotNull())
.build();
}
@Builder
@JsonCreator
private PickedData(
@JsonProperty("productId") @NonNull final ProductId productId,
@JsonProperty("qtyPicked") @NonNull final Quantity qtyPicked,
@JsonProperty("qtyCatch") @Nullable final Quantity qtyCatch,
@JsonProperty("qtyPickedInUOM") @NonNull final Quantity qtyPickedInUOM)
{
this.productId = productId;
this.qtyPicked = qtyPicked;
this.qtyPickedInUOM = qtyPickedInUOM;
this.qtyCatch = qtyCatch;
}
public StockQtyAndUOMQty computeInvoicableQtyPicked(@NonNull final InvoicableQtyBasedOn invoicableQtyBasedOn)
{
|
final Quantity pickedInUOM;
switch (invoicableQtyBasedOn)
{
case CatchWeight:
pickedInUOM = coalesce(getCatchWeightInIcUOM(), getQtyPickedInUOM());
break;
case NominalWeight:
pickedInUOM = getQtyPickedInUOM();
break;
default:
throw new AdempiereException("Unexpected InvoicableQtyBasedOn=" + invoicableQtyBasedOn);
}
return StockQtyAndUOMQty.builder()
.productId(productId)
.stockQty(qtyPicked)
.uomQty(pickedInUOM).build();
}
@Nullable
private Quantity getCatchWeightInIcUOM()
{
if (qtyCatch == null)
{
return null;
}
return Quantitys.of(qtyCatch, UOMConversionContext.of(productId), qtyPickedInUOM.getUomId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\internalbusinesslogic\PickedData.java
| 2
|
请完成以下Java代码
|
public OrderedDocumentsList getDocuments(final DocumentQueryOrderByList orderBys)
{
return DocumentQuery.builder(entityDescriptor)
.setParentDocument(parentDocument)
.setChangesCollector(NullDocumentChangesCollector.instance)
.setOrderBys(orderBys)
.retriveDocuments();
}
@Override
public OrderedDocumentsList getDocumentsByIds(@NonNull final DocumentIdsSelection documentIds)
{
if (documentIds.isAll())
{
return getDocuments(DocumentQueryOrderByList.EMPTY);
}
else if (documentIds.isEmpty())
{
return OrderedDocumentsList.newEmpty();
}
else
{
final ImmutableMap<DocumentId, Document> loadedDocuments = DocumentQuery.builder(entityDescriptor)
.setParentDocument(parentDocument)
.setRecordIds(documentIds.toSet())
.setChangesCollector(NullDocumentChangesCollector.instance)
.setOrderBys(DocumentQueryOrderByList.EMPTY)
.retriveDocuments()
.toImmutableMap();
final OrderedDocumentsList result = OrderedDocumentsList.newEmpty();
for (final DocumentId documentId : documentIds.toSet())
{
final Document loadedDocument = loadedDocuments.get(documentId);
if (loadedDocument != null)
{
result.addDocument(loadedDocument);
}
else
{
// No document found for documentId. Ignore it.
}
}
return result;
}
}
@Override
public Optional<Document> getDocumentById(final DocumentId documentId)
{
final Document document = DocumentQuery.builder(entityDescriptor)
.setParentDocument(parentDocument)
.setRecordId(documentId)
.retriveDocumentOrNull();
if (document == null)
{
return Optional.empty();
}
return Optional.of(document);
}
@Override
public void updateStatusFromParent()
{
// nothing
}
@Override
public void assertNewDocumentAllowed()
{
throw new InvalidDocumentStateException(parentDocument, RESULT_TabReadOnly.getName());
}
@Override
public LogicExpressionResult getAllowCreateNewDocument()
{
return RESULT_TabReadOnly;
}
@Override
public Document createNewDocument()
{
|
throw new InvalidDocumentStateException(parentDocument, RESULT_TabReadOnly.getName());
}
@Override
public LogicExpressionResult getAllowDeleteDocument()
{
return RESULT_TabReadOnly;
}
@Override
public void deleteDocuments(final DocumentIdsSelection documentIds)
{
throw new InvalidDocumentStateException(parentDocument, RESULT_TabReadOnly.getName());
}
@Override
public DocumentValidStatus checkAndGetValidStatus(final OnValidStatusChanged onValidStatusChanged)
{
return DocumentValidStatus.documentValid();
}
@Override
public boolean hasChangesRecursivelly()
{
return false;
}
@Override
public void saveIfHasChanges()
{
}
@Override
public void markStaleAll()
{
}
@Override
public void markStale(final DocumentIdsSelection rowIds)
{
}
@Override
public boolean isStale()
{
return false;
}
@Override
public int getNextLineNo()
{
throw new UnsupportedOperationException();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\HighVolumeReadonlyIncludedDocumentsCollection.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SecurityPermitAllConfig {
private final AdminServerProperties adminServer;
public SecurityPermitAllConfig(AdminServerProperties adminServer) {
this.adminServer = adminServer;
}
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authorizeRequest) -> authorizeRequest.anyRequest().permitAll());
http.addFilterAfter(new CustomCsrfFilter(), BasicAuthenticationFilter.class)
.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
|
.csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler())
.ignoringRequestMatchers(
PathPatternRequestMatcher.withDefaults().matcher(POST, this.adminServer.path("/instances")),
PathPatternRequestMatcher.withDefaults()
.matcher(POST, this.adminServer.path("/notifications/**")),
PathPatternRequestMatcher.withDefaults()
.matcher(DELETE, this.adminServer.path("/notifications/**")),
PathPatternRequestMatcher.withDefaults().matcher(DELETE, this.adminServer.path("/instances/*")),
PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/actuator/**"))));
return http.build();
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-servlet\src\main\java\de\codecentric\boot\admin\sample\SecurityPermitAllConfig.java
| 2
|
请完成以下Java代码
|
public Builder postalCode(String postalCode) {
this.postalCode = postalCode;
return this;
}
/**
* Sets the country.
* @param country the country
* @return the {@link Builder}
*/
public Builder country(String country) {
this.country = country;
return this;
}
/**
* Builds a new {@link DefaultAddressStandardClaim}.
|
* @return a {@link AddressStandardClaim}
*/
public AddressStandardClaim build() {
DefaultAddressStandardClaim address = new DefaultAddressStandardClaim();
address.formatted = this.formatted;
address.streetAddress = this.streetAddress;
address.locality = this.locality;
address.region = this.region;
address.postalCode = this.postalCode;
address.country = this.country;
return address;
}
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\DefaultAddressStandardClaim.java
| 1
|
请完成以下Java代码
|
private static String extractFilename(final URL url)
{
final String path = url.getPath();
final int idx = path.lastIndexOf("/");
if (idx < 0)
{
throw new IllegalArgumentException("Cannot extract filename from " + url);
}
return path.substring(idx + 1);
}
public static File unzip(@NonNull final File zipFile)
{
try
{
final File unzipDir = Files.createTempDirectory(zipFile.getName() + "-")
.toFile();
unzipDir.deleteOnExit();
final ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null)
{
unzipEntry(unzipDir, zipEntry, zis);
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
return unzipDir;
}
catch (final Exception ex)
{
throw new RuntimeException("Cannot unzip " + zipFile, ex);
}
}
public static File unzipEntry(
final File destinationDir,
final ZipEntry zipEntry,
|
final ZipInputStream zipInputStream) throws IOException
{
final File destFile = new File(destinationDir, zipEntry.getName());
if (zipEntry.isDirectory())
{
destFile.mkdirs();
}
else
{
final String destDirPath = destinationDir.getCanonicalPath();
final String destFilePath = destFile.getCanonicalPath();
if (!destFilePath.startsWith(destDirPath + File.separator))
{
throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
}
try (final FileOutputStream fos = new FileOutputStream(destFile))
{
final byte[] buffer = new byte[4096];
int len;
while ((len = zipInputStream.read(buffer)) > 0)
{
fos.write(buffer, 0, len);
}
}
}
return destFile;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\util\FileUtils.java
| 1
|
请完成以下Java代码
|
public void popupMenuWillBecomeVisible(final PopupMenuEvent e)
{
AnnotatedTablePopupMenu.this.popupMenuWillBecomeVisible(e);
}
@Override
public void popupMenuWillBecomeInvisible(final PopupMenuEvent e)
{
AnnotatedTablePopupMenu.this.popupMenuWillBecomeInvisible(e);
}
};
public AnnotatedTablePopupMenu(final JTable table)
{
super();
Check.assumeNotNull(table, "table not null");
tableRef = new WeakReference<>(table);
addPopupMenuListener(popupListener);
}
private final JTable getTable()
{
final JTable table = tableRef.get();
Check.assumeNotNull(table, "table not null");
return table;
}
private final List<AnnotatedTableAction> getTableActions()
{
final List<AnnotatedTableAction> tableActions = new ArrayList<>();
for (final MenuElement me : getSubElements())
{
if (!(me instanceof AbstractButton))
{
continue;
|
}
final AbstractButton button = (AbstractButton)me;
final Action action = button.getAction();
if (action instanceof AnnotatedTableAction)
{
final AnnotatedTableAction tableAction = (AnnotatedTableAction)action;
tableActions.add(tableAction);
}
}
return tableActions;
}
private final void popupMenuWillBecomeVisible(final PopupMenuEvent e)
{
for (final AnnotatedTableAction tableAction : getTableActions())
{
tableAction.setTable(getTable());
tableAction.updateBeforeDisplaying();
}
}
private final void popupMenuWillBecomeInvisible(final PopupMenuEvent e)
{
// nothing atm
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTablePopupMenu.java
| 1
|
请完成以下Java代码
|
public class DeleteHistoricProcessInstancesDto {
protected List<String> historicProcessInstanceIds;
protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery;
protected String deleteReason;
protected boolean failIfNotExists = true;
public List<String> getHistoricProcessInstanceIds() {
return historicProcessInstanceIds;
}
public void setHistoricProcessInstanceIds(List<String> historicProcessInstanceIds) {
this.historicProcessInstanceIds = historicProcessInstanceIds;
}
public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) {
this.historicProcessInstanceQuery = historicProcessInstanceQuery;
}
|
public String getDeleteReason() {
return deleteReason;
}
public void setDeleteReason(String deleteReason) {
this.deleteReason = deleteReason;
}
public boolean isFailIfNotExists() {
return failIfNotExists;
}
public void setFailIfNotExists(boolean failIfNotExists) {
this.failIfNotExists = failIfNotExists;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\DeleteHistoricProcessInstancesDto.java
| 1
|
请完成以下Java代码
|
final class FactAcctRepostCommand
{
private final IPostingService postingService = Services.get(IPostingService.class);
private final UserId onErrorNotifyUserId;
private final boolean forcePosting;
private final ImmutableSet<DocumentToRepost> documentsToRepost;
@lombok.Value
@lombok.Builder
public static class DocumentToRepost
{
int adTableId;
int recordId;
ClientId clientId;
public TableRecordReference getRecordRef()
{
return TableRecordReference.of(getAdTableId(), getRecordId());
}
}
@Builder
private FactAcctRepostCommand(
final boolean forcePosting,
@NonNull @Singular("documentToRepost") final Set<DocumentToRepost> documentsToRepost,
@Nullable final UserId onErrorNotifyUserId)
{
Check.assumeNotEmpty(documentsToRepost, "documentsToRepost is not empty");
|
this.forcePosting = forcePosting;
this.documentsToRepost = ImmutableSet.copyOf(documentsToRepost);
this.onErrorNotifyUserId = onErrorNotifyUserId;
}
public void execute()
{
documentsToRepost.stream()
.map(this::toDocumentPostRequest)
.collect(DocumentPostMultiRequest.collect())
.ifPresent(postingService::schedule);
}
private DocumentPostRequest toDocumentPostRequest(final DocumentToRepost doc)
{
return DocumentPostRequest.builder()
.record(doc.getRecordRef())
.clientId(doc.getClientId())
.force(forcePosting)
.onErrorNotifyUserId(onErrorNotifyUserId)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\accounting\process\FactAcctRepostCommand.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ExamplePostController {
private static Logger log = LoggerFactory.getLogger(ExamplePostController.class);
@Autowired ExampleService exampleService;
@PostMapping("/request")
public ResponseEntity postController(@RequestBody LoginForm loginForm) {
log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername());
exampleService.fakeAuthenticate(loginForm);
return ResponseEntity.ok(HttpStatus.OK);
}
@PostMapping("/response")
@ResponseBody
public ResponseTransfer postResponseController(@RequestBody LoginForm loginForm) {
log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername());
return new ResponseTransfer("Thanks For Posting!!!");
}
|
@PostMapping(value = "/content", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseTransfer postResponseJsonContent(@RequestBody LoginForm loginForm) {
log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername());
return new ResponseTransfer("JSON Content!");
}
@PostMapping(value = "/content", produces = MediaType.APPLICATION_XML_VALUE)
@ResponseBody
public ResponseTransfer postResponseXmlContent(@RequestBody LoginForm loginForm) {
log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername());
return new ResponseTransfer("XML Content!");
}
}
|
repos\tutorials-master\spring-web-modules\spring-boot-rest-simple\src\main\java\com\baeldung\requestresponsebody\ExamplePostController.java
| 2
|
请完成以下Java代码
|
public static String stripDmnFileSuffix(String dmnFileResource) {
for (String suffix : DMN_RESOURCE_SUFFIXES) {
if (dmnFileResource.endsWith(suffix)) {
return dmnFileResource.substring(0, dmnFileResource.length() - suffix.length());
}
}
return dmnFileResource;
}
public static String getDecisionRequirementsDiagramResourceName(String dmnFileResource, String decisionKey, String diagramSuffix) {
String dmnFileResourceBase = stripDmnFileSuffix(dmnFileResource);
return dmnFileResourceBase + decisionKey + "." + diagramSuffix;
}
/**
* Finds the name of a resource for the diagram for a decision definition. Assumes that the decision definition's key and (DMN) resource name are already set.
*
* @return name of an existing resource, or null if no matching image resource is found in the resources.
*/
public static String getDecisionRequirementsDiagramResourceNameFromDeployment(
DecisionEntity decisionDefinition, Map<String, EngineResource> resources) {
|
if (StringUtils.isEmpty(decisionDefinition.getResourceName())) {
throw new IllegalStateException("Provided decision definition must have its resource name set.");
}
String dmnResourceBase = stripDmnFileSuffix(decisionDefinition.getResourceName());
String key = decisionDefinition.getKey();
for (String diagramSuffix : DIAGRAM_SUFFIXES) {
String possibleName = dmnResourceBase + key + "." + diagramSuffix;
if (resources.containsKey(possibleName)) {
return possibleName;
}
possibleName = dmnResourceBase + diagramSuffix;
if (resources.containsKey(possibleName)) {
return possibleName;
}
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\deployer\ResourceNameUtil.java
| 1
|
请完成以下Java代码
|
public String getNamespaceURI(String prefix) {
return namespaceUris.get(prefix);
}
public String getPrefix(String namespaceURI) {
return getKeyByValue(namespaceUris, namespaceURI);
}
public Iterator<String> getPrefixes(String namespaceURI) {
return getKeysByValue(namespaceUris, namespaceURI).iterator();
}
private static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
Set<T> keys = new HashSet<T>();
for (Entry<T, E> entry : map.entrySet()) {
|
if (value.equals(entry.getValue())) {
keys.add(entry.getKey());
}
}
return keys;
}
private static <T, E> T getKeyByValue(Map<T, E> map, E value) {
for (Entry<T, E> entry : map.entrySet()) {
if (value.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\diagram\Bpmn20NamespaceContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getEntryUuid()
{
return entryUuid;
}
public void setEntryUuid(String entry_uuid)
{
this.entryUuid = entry_uuid;
}
public String getServerEventId()
{
return serverEventId;
}
public void setServerEventId(String serverEventId)
{
this.serverEventId = serverEventId;
}
/**
*
* @return the date when this record was created, which is also the date when the sync request was submitted towards the remote endpoint.
*/
@Override
public Date getDateCreated()
{
return super.getDateCreated();
}
/**
*
* @return the date when the remote endpoint actually confirmed the data receipt.
*/
public Date getDateConfirmed()
{
return dateConfirmed;
}
|
public void setDateConfirmed(Date dateConfirmed)
{
this.dateConfirmed = dateConfirmed;
}
/**
*
* @return the date when our local endpoint received the remote endpoint's confirmation.
*/
public Date getDateConfirmReceived()
{
return dateConfirmReceived;
}
public void setDateConfirmReceived(Date dateConfirmReceived)
{
this.dateConfirmReceived = dateConfirmReceived;
}
public long getEntryId()
{
return entryId;
}
public void setEntryId(long entryId)
{
this.entryId = entryId;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\SyncConfirm.java
| 2
|
请完成以下Java代码
|
public class ClassLoaderWrapper extends ClassLoader {
private ClassLoader[] parents;
public ClassLoaderWrapper(ClassLoader... parents) {
this.parents = parents;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
//
// Check if class is in the loaded classes cache
//
Class cachedClass = findLoadedClass(name);
if (cachedClass != null) {
if (resolve) {
resolveClass(cachedClass);
}
return cachedClass;
}
//
// Check parent class loaders
//
for (int i = 0; i < parents.length; i++) {
ClassLoader parent = parents[i];
try {
Class clazz = parent.loadClass(name);
if (resolve) {
resolveClass(clazz);
}
return clazz;
} catch (ClassNotFoundException ignored) {
// this parent didn't have the class; try the next one
}
}
throw new ClassNotFoundException(name);
}
|
@Override
public URL getResource(String name) {
//
// Check parent class loaders
//
for (int i = 0; i < parents.length; i++) {
ClassLoader parent = parents[i];
URL url = parent.getResource(name);
if (url != null) {
return url;
}
}
return null;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Enumeration findResources(String name) throws IOException {
List resources = new ArrayList();
//
// Add parent resources
//
for (int i = 0; i < parents.length; i++) {
ClassLoader parent = parents[i];
List parentResources = Collections.list(parent.getResources(name));
resources.addAll(parentResources);
}
return Collections.enumeration(resources);
}
}
|
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\blueprint\ClassLoaderWrapper.java
| 1
|
请完成以下Java代码
|
public class Order {
public enum Direction {
ASC,
DESC,
}
private String property;
private Direction direction;
public Order(String property) {
this(property, Direction.ASC);
}
private Order(String property, Direction direction) {
this.property = property;
|
this.direction = direction;
}
public String getProperty() {
return property;
}
public Direction getDirection() {
return direction;
}
public static Order by(String property, Direction direction) {
return new Order(property, direction);
}
}
|
repos\Activiti-develop\activiti-api\activiti-api-runtime-shared\src\main\java\org\activiti\api\runtime\shared\query\Order.java
| 1
|
请完成以下Java代码
|
public MClickCount getMClickCount()
{
if (getW_ClickCount_ID() == 0)
return null;
if (m_clickCount == null)
m_clickCount = new MClickCount (getCtx(), getW_ClickCount_ID(), get_TrxName());
return m_clickCount;
} // MClickCount
/**
* Get Click Target URL (from ClickCount)
* @return URL
*/
public String getClickTargetURL()
{
getMClickCount();
if (m_clickCount == null)
return "-";
return m_clickCount.getTargetURL();
} // getClickTargetURL
/**
* Set Click Target URL (in ClickCount)
* @param TargetURL url
*/
public void setClickTargetURL(String TargetURL)
{
getMClickCount();
if (m_clickCount == null)
m_clickCount = new MClickCount(this);
if (m_clickCount != null)
{
m_clickCount.setTargetURL(TargetURL);
m_clickCount.save(get_TrxName());
}
} // getClickTargetURL
/**
* Get Weekly Count
* @return weekly count
*/
public ValueNamePair[] getClickCountWeek ()
{
getMClickCount();
if (m_clickCount == null)
|
return new ValueNamePair[0];
return m_clickCount.getCountWeek();
} // getClickCountWeek
/**
* Get CounterCount
* @return Counter Count
*/
public MCounterCount getMCounterCount()
{
if (getW_CounterCount_ID() == 0)
return null;
if (m_counterCount == null)
m_counterCount = new MCounterCount (getCtx(), getW_CounterCount_ID(), get_TrxName());
return m_counterCount;
} // MCounterCount
/**
* Get Sales Rep ID.
* (AD_User_ID of oldest BP user)
* @return Sales Rep ID
*/
public int getSalesRep_ID()
{
if (m_SalesRep_ID == 0)
{
m_SalesRep_ID = getAD_User_ID();
if (m_SalesRep_ID == 0)
m_SalesRep_ID = DB.getSQLValue(null,
"SELECT AD_User_ID FROM AD_User "
+ "WHERE C_BPartner_ID=? AND IsActive='Y' ORDER BY AD_User_ID", getC_BPartner_ID());
}
return m_SalesRep_ID;
} // getSalesRep_ID
} // MAdvertisement
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAdvertisement.java
| 1
|
请完成以下Java代码
|
public class Dino {
private int id;
private String name;
private String color;
private String weight;
public Dino(int id, String name, String color, String weight) {
this.id = id;
this.name = name;
this.color = color;
this.weight = weight;
}
public Dino() {
}
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 String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
}
|
repos\tutorials-master\spring-web-modules\spring-thymeleaf-4\src\main\java\com\baeldung\thymeleaf\expression\Dino.java
| 1
|
请完成以下Java代码
|
public static class DDOrderRefBuilder
{
@Nullable
public DDOrderRef buildOrNull()
{
if (ddOrderCandidateId <= 0 && ddOrderId <= 0)
{
return null;
}
return build();
}
}
@Nullable
public static DDOrderRef ofNullableDDOrderAndLineId(final int ddOrderId, final int ddOrderLineId)
{
return builder().ddOrderId(ddOrderId).ddOrderLineId(ddOrderLineId).buildOrNull();
}
public static DDOrderRef ofNullableDDOrderCandidateId(final int ddOrderCandidateId)
{
return ddOrderCandidateId > 0
? builder().ddOrderCandidateId(ddOrderCandidateId).build()
: null;
|
}
public DDOrderRef withDdOrderCandidateId(final int ddOrderCandidateIdNew)
{
final int ddOrderCandidateIdNewNorm = normalizeId(ddOrderCandidateIdNew);
return this.ddOrderCandidateId != ddOrderCandidateIdNewNorm
? toBuilder().ddOrderCandidateId(ddOrderCandidateIdNewNorm).build()
: this;
}
public static DDOrderRef withDdOrderCandidateId(@Nullable final DDOrderRef ddOrderRef, final int ddOrderCandidateIdNew)
{
return ddOrderRef != null
? ddOrderRef.withDdOrderCandidateId(ddOrderCandidateIdNew)
: ofNullableDDOrderCandidateId(ddOrderCandidateIdNew);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\ddorder\DDOrderRef.java
| 1
|
请完成以下Java代码
|
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Boolean getIsLeaf() {
return isLeaf;
}
public void setIsLeaf(Boolean isLeaf) {
this.isLeaf = isLeaf;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
private List<TreeModel> children;
public List<TreeModel> getChildren() {
return children;
}
public void setChildren(List<TreeModel> children) {
this.children = children;
}
public TreeModel() {
}
public TreeModel(SysPermission permission) {
this.key = permission.getId();
this.icon = permission.getIcon();
this.parentId = permission.getParentId();
this.title = permission.getName();
this.slotTitle = permission.getName();
this.value = permission.getId();
this.isLeaf = permission.isLeaf();
this.label = permission.getName();
if(!permission.isLeaf()) {
this.children = new ArrayList<TreeModel>();
}
}
public TreeModel(String key,String parentId,String slotTitle,Integer ruleFlag,boolean isLeaf) {
this.key = key;
this.parentId = parentId;
this.ruleFlag=ruleFlag;
this.slotTitle = slotTitle;
Map<String,String> map = new HashMap(5);
map.put("title", "hasDatarule");
this.scopedSlots = map;
this.isLeaf = isLeaf;
this.value = key;
if(!isLeaf) {
this.children = new ArrayList<TreeModel>();
}
}
private String parentId;
private String label;
private String value;
public String getParentId() {
return parentId;
|
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
/**
* @return the label
*/
public String getLabel() {
return label;
}
/**
* @param label the label to set
*/
public void setLabel(String label) {
this.label = label;
}
/**
* @return the value
*/
public String getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
public String getSlotTitle() {
return slotTitle;
}
public void setSlotTitle(String slotTitle) {
this.slotTitle = slotTitle;
}
public Integer getRuleFlag() {
return ruleFlag;
}
public void setRuleFlag(Integer ruleFlag) {
this.ruleFlag = ruleFlag;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\TreeModel.java
| 1
|
请完成以下Java代码
|
public final boolean isDateValue()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_Date.equals(valueType);
}
@Override
public final boolean isList()
{
return _attributeValuesProvider != null;
}
@Override
public final boolean isEmpty()
{
return Objects.equals(getValue(), getEmptyValue());
}
@Nullable
@Override
public final Object getEmptyValue()
{
final Object value = getValue();
if (value == null)
{
return null;
}
if (value instanceof BigDecimal)
{
return BigDecimal.ZERO;
}
else if (value instanceof String)
{
return null;
}
else if (TimeUtil.isDateOrTimeObject(value))
{
return null;
}
else
{
throw new InvalidAttributeValueException("Value type '" + value.getClass() + "' not supported for " + attribute);
}
}
@Override
public final void addAttributeValueListener(final IAttributeValueListener listener)
{
listeners.addAttributeValueListener(listener);
}
@Override
public final void removeAttributeValueListener(final IAttributeValueListener listener)
{
listeners.removeAttributeValueListener(listener);
}
@Override
public I_C_UOM getC_UOM()
{
final int uomId = attribute.getC_UOM_ID();
if (uomId > 0)
{
return Services.get(IUOMDAO.class).getById(uomId);
}
else
|
{
return null;
}
}
private IAttributeValueCallout _attributeValueCallout = null;
@Override
public IAttributeValueCallout getAttributeValueCallout()
{
if (_attributeValueCallout == null)
{
final IAttributeValueGenerator attributeValueGenerator = getAttributeValueGeneratorOrNull();
if (attributeValueGenerator instanceof IAttributeValueCallout)
{
_attributeValueCallout = (IAttributeValueCallout)attributeValueGenerator;
}
else
{
_attributeValueCallout = NullAttributeValueCallout.instance;
}
}
return _attributeValueCallout;
}
@Override
public IAttributeValueGenerator getAttributeValueGeneratorOrNull()
{
final I_M_Attribute attribute = getM_Attribute();
final IAttributeValueGenerator attributeValueGenerator = Services.get(IAttributesBL.class).getAttributeValueGeneratorOrNull(attribute);
return attributeValueGenerator;
}
/**
* @return true if NOT disposed
* @see IAttributeStorage#assertNotDisposed()
*/
protected final boolean assertNotDisposed()
{
return getAttributeStorage().assertNotDisposed();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\AbstractAttributeValue.java
| 1
|
请完成以下Java代码
|
public void exportFile(HttpServletResponse response, LocalStorageQueryCriteria criteria) throws IOException {
localStorageService.download(localStorageService.queryAll(criteria), response);
}
@PostMapping
@ApiOperation("上传文件")
@PreAuthorize("@el.check('storage:add')")
public ResponseEntity<Object> createFile(@RequestParam String name, @RequestParam("file") MultipartFile file){
localStorageService.create(name, file);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@ApiOperation("上传图片")
@PostMapping("/pictures")
public ResponseEntity<LocalStorage> uploadPicture(@RequestParam MultipartFile file){
// 判断文件是否为图片
String suffix = FileUtil.getExtensionName(file.getOriginalFilename());
if(!FileUtil.IMAGE.equals(FileUtil.getFileType(suffix))){
throw new BadRequestException("只能上传图片");
}
LocalStorage localStorage = localStorageService.create(null, file);
return new ResponseEntity<>(localStorage, HttpStatus.OK);
}
|
@PutMapping
@Log("修改文件")
@ApiOperation("修改文件")
@PreAuthorize("@el.check('storage:edit')")
public ResponseEntity<Object> updateFile(@Validated @RequestBody LocalStorage resources){
localStorageService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除文件")
@DeleteMapping
@ApiOperation("多选删除")
public ResponseEntity<Object> deleteFile(@RequestBody Long[] ids) {
localStorageService.deleteAll(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
}
|
repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\rest\LocalStorageController.java
| 1
|
请完成以下Java代码
|
public class RetrieveValue {
private static MongoClient mongoClient;
private static MongoDatabase database;
private static String testCollectionName;
private static String databaseName;
public static void setUp() {
if (mongoClient == null) {
mongoClient = new MongoClient("localhost", 27017);
}
databaseName = "baeldung";
testCollectionName = "travel";
}
public static void retrieveValueUsingFind() {
DB database = mongoClient.getDB(databaseName);
DBCollection collection = database.getCollection(testCollectionName);
BasicDBObject queryFilter = new BasicDBObject();
BasicDBObject projection = new BasicDBObject();
projection.put("passengerId", 1);
projection.put("_id", 0);
DBCursor dbCursor = collection.find(queryFilter, projection);
while (dbCursor.hasNext()) {
System.out.println(dbCursor.next());
}
}
public static void retrieveValueUsingAggregation() {
ArrayList<Document> response = new ArrayList<>();
ArrayList<Bson> pipeline = new ArrayList<>(Arrays.asList(
project(fields(Projections.exclude("_id"), Projections.include("passengerId")))));
database = mongoClient.getDatabase(databaseName);
database.getCollection(testCollectionName)
.aggregate(pipeline)
.allowDiskUse(true)
.into(response);
System.out.println("response:- " + response);
}
public static void retrieveValueAggregationUsingDocument() {
ArrayList<Document> response = new ArrayList<>();
ArrayList<Document> pipeline = new ArrayList<>(Arrays.asList(new Document("$project", new Document("passengerId", 1L))));
|
database = mongoClient.getDatabase(databaseName);
database.getCollection(testCollectionName)
.aggregate(pipeline)
.allowDiskUse(true)
.into(response);
System.out.println("response:- " + response);
}
public static void main(String args[]) {
//
// Connect to cluster (default is localhost:27017)
//
setUp();
//
// Fetch the data using find query with projected fields
//
retrieveValueUsingFind();
//
// Fetch the data using aggregate pipeline query with projected fields
//
retrieveValueUsingAggregation();
//
// Fetch the data using aggregate pipeline document query with projected fields
//
retrieveValueAggregationUsingDocument();
}
}
|
repos\tutorials-master\persistence-modules\java-mongodb-2\src\main\java\com\baeldung\mongo\RetrieveValue.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public DecisionRequirementsDefinitionEntity findLatestDefinitionByKey(String key) {
return null;
}
@Override
public DecisionRequirementsDefinitionEntity findLatestDefinitionById(String id) {
return getDbEntityManager().selectById(DecisionRequirementsDefinitionEntity.class, id);
}
@Override
public DecisionRequirementsDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) {
return null;
}
@Override
public DecisionRequirementsDefinitionEntity findDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) {
return null;
}
|
@Override
public DecisionRequirementsDefinitionEntity findDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId) {
return null;
}
@Override
public DecisionRequirementsDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) {
return null;
}
@Override
public DecisionRequirementsDefinitionEntity getCachedResourceDefinitionEntity(String definitionId) {
return getDbEntityManager().getCachedEntity(DecisionRequirementsDefinitionEntity.class, definitionId);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionRequirementsDefinitionManager.java
| 2
|
请完成以下Java代码
|
public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_CreditLimit_Type getC_CreditLimit_Type() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_CreditLimit_Type_ID, org.compiere.model.I_C_CreditLimit_Type.class);
}
@Override
public void setC_CreditLimit_Type(org.compiere.model.I_C_CreditLimit_Type C_CreditLimit_Type)
{
set_ValueFromPO(COLUMNNAME_C_CreditLimit_Type_ID, org.compiere.model.I_C_CreditLimit_Type.class, C_CreditLimit_Type);
}
/** Set Credit Limit Type.
@param C_CreditLimit_Type_ID Credit Limit Type */
@Override
public void setC_CreditLimit_Type_ID (int C_CreditLimit_Type_ID)
{
if (C_CreditLimit_Type_ID < 1)
set_Value (COLUMNNAME_C_CreditLimit_Type_ID, null);
else
set_Value (COLUMNNAME_C_CreditLimit_Type_ID, Integer.valueOf(C_CreditLimit_Type_ID));
}
/** Get Credit Limit Type.
@return Credit Limit Type */
@Override
public int getC_CreditLimit_Type_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_CreditLimit_Type_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_Currency getC_Currency() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_Currency_ID, org.compiere.model.I_C_Currency.class);
}
@Override
public void setC_Currency(org.compiere.model.I_C_Currency C_Currency)
{
set_ValueFromPO(COLUMNNAME_C_Currency_ID, org.compiere.model.I_C_Currency.class, C_Currency);
}
/** Set Währung.
@param C_Currency_ID
Die Währung für diesen Eintrag
*/
@Override
public void setC_Currency_ID (int C_Currency_ID)
{
throw new IllegalArgumentException ("C_Currency_ID is virtual column"); }
|
/** Get Währung.
@return Die Währung für diesen Eintrag
*/
@Override
public int getC_Currency_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Datum von.
@param DateFrom
Startdatum eines Abschnittes
*/
@Override
public void setDateFrom (java.sql.Timestamp DateFrom)
{
set_Value (COLUMNNAME_DateFrom, DateFrom);
}
/** Get Datum von.
@return Startdatum eines Abschnittes
*/
@Override
public java.sql.Timestamp getDateFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DateFrom);
}
/** Set Freigegeben.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Freigegeben.
@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;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_CreditLimit.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ExecuteHistoryJobCmd implements Command<Void> {
private static final Logger LOGGER = LoggerFactory.getLogger(ExecuteHistoryJobCmd.class);
protected JobServiceConfiguration jobServiceConfiguration;
protected String historyJobId;
public ExecuteHistoryJobCmd(String historyJobId, JobServiceConfiguration jobServiceConfiguration) {
this.historyJobId = historyJobId;
this.jobServiceConfiguration = jobServiceConfiguration;
}
@Override
public Void execute(CommandContext commandContext) {
if (historyJobId == null) {
throw new FlowableIllegalArgumentException("historyJobId is null");
}
|
HistoryJobEntity historyJobEntity = jobServiceConfiguration.getHistoryJobEntityManager().findById(historyJobId);
if (historyJobEntity == null) {
throw new JobNotFoundException(historyJobId);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Executing historyJob {}", historyJobEntity.getId());
}
try {
jobServiceConfiguration.getJobManager().execute(historyJobEntity);
} catch (Throwable exception) {
// Finally, Throw the exception to indicate the failure
throw new FlowableException(historyJobEntity + " failed", exception);
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\ExecuteHistoryJobCmd.java
| 2
|
请完成以下Java代码
|
public org.compiere.model.I_C_ValidCombination getP_UsageVariance_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_P_UsageVariance_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setP_UsageVariance_A(org.compiere.model.I_C_ValidCombination P_UsageVariance_A)
{
set_ValueFromPO(COLUMNNAME_P_UsageVariance_Acct, org.compiere.model.I_C_ValidCombination.class, P_UsageVariance_A);
}
/** Set Usage Variance.
@param P_UsageVariance_Acct
The Usage Variance account is the account used Manufacturing Order
*/
@Override
public void setP_UsageVariance_Acct (int P_UsageVariance_Acct)
{
set_Value (COLUMNNAME_P_UsageVariance_Acct, Integer.valueOf(P_UsageVariance_Acct));
}
/** Get Usage Variance.
@return The Usage Variance account is the account used Manufacturing Order
*/
@Override
public int getP_UsageVariance_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_P_UsageVariance_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ValidCombination getP_WIP_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_P_WIP_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setP_WIP_A(org.compiere.model.I_C_ValidCombination P_WIP_A)
{
set_ValueFromPO(COLUMNNAME_P_WIP_Acct, org.compiere.model.I_C_ValidCombination.class, P_WIP_A);
|
}
/** Set Work In Process.
@param P_WIP_Acct
The Work in Process account is the account used Manufacturing Order
*/
@Override
public void setP_WIP_Acct (int P_WIP_Acct)
{
set_Value (COLUMNNAME_P_WIP_Acct, Integer.valueOf(P_WIP_Acct));
}
/** Get Work In Process.
@return The Work in Process account is the account used Manufacturing Order
*/
@Override
public int getP_WIP_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_P_WIP_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Acct.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getScopeType() {
return scopeType;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public String getMetaInfo() {
return metaInfo;
}
@Override
public void setMetaInfo(String metaInfo) {
this.metaInfo = metaInfo;
}
@Override
public ByteArrayRef getByteArrayRef() {
return byteArrayRef;
}
// common methods //////////////////////////////////////////////////////////
protected String getEngineType() {
if (StringUtils.isNotEmpty(scopeType)) {
return scopeType;
} else {
return ScopeTypes.BPMN;
}
}
|
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricVariableInstanceEntity[");
sb.append("id=").append(id);
sb.append(", name=").append(name);
sb.append(", revision=").append(revision);
sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null");
if (longValue != null) {
sb.append(", longValue=").append(longValue);
}
if (doubleValue != null) {
sb.append(", doubleValue=").append(doubleValue);
}
if (textValue != null) {
sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40));
}
if (textValue2 != null) {
sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40));
}
if (byteArrayRef != null && byteArrayRef.getId() != null) {
sb.append(", byteArrayValueId=").append(byteArrayRef.getId());
}
sb.append("]");
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\HistoricVariableInstanceEntityImpl.java
| 2
|
请完成以下Java代码
|
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCustomerAttributeJSON() {
return customerAttributeJSON;
}
public void setCustomerAttributeJSON(String customerAttributeJSON) {
this.customerAttributeJSON = customerAttributeJSON;
}
public Map<String, Object> getCustomerAttributes() {
return customerAttributes;
|
}
public void setCustomerAttributes(Map<String, Object> customerAttributes) {
this.customerAttributes = customerAttributes;
}
private static final ObjectMapper objectMapper = new ObjectMapper();
public void serializeCustomerAttributes() throws JsonProcessingException {
this.customerAttributeJSON = objectMapper.writeValueAsString(customerAttributes);
}
public void deserializeCustomerAttributes() throws IOException {
this.customerAttributes = objectMapper.readValue(customerAttributeJSON, new TypeReference<Map<String, Object>>() {});
}
}
|
repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\persistjson\Customer.java
| 1
|
请完成以下Java代码
|
public String getName() {
return this.name;
}
@Override
public Class<?> getType() {
return this.type;
}
@Override
public @Nullable String getDescription() {
return this.description;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder(this.name);
if (this.description != null) {
result.append(" (").append(this.description).append(")");
}
result.append(":").append(this.type);
return result.toString();
}
}
/**
* Utility to convert to JMX supported types.
*/
private static final class JmxType {
static Class<?> get(Class<?> source) {
if (source.isEnum()) {
return String.class;
|
}
if (Date.class.isAssignableFrom(source) || Instant.class.isAssignableFrom(source)) {
return String.class;
}
if (source.getName().startsWith("java.")) {
return source;
}
if (source.equals(Void.TYPE)) {
return source;
}
return Object.class;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\jmx\annotation\DiscoveredJmxOperation.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public DataSource dataSource() {
File[] files = Paths.get("allTenants").toFile().listFiles();
Map<Object, Object> resolvedDataSources = new HashMap<>();
for (File propertyFile : files) {
Properties tenantProperties = new Properties();
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
try {
tenantProperties.load(new FileInputStream(propertyFile));
String tenantId = tenantProperties.getProperty("name");
dataSourceBuilder.driverClassName(tenantProperties.getProperty("datasource.driver-class-name"));
dataSourceBuilder.username(tenantProperties.getProperty("datasource.username"));
dataSourceBuilder.password(tenantProperties.getProperty("datasource.password"));
dataSourceBuilder.url(tenantProperties.getProperty("datasource.url"));
|
resolvedDataSources.put(tenantId, dataSourceBuilder.build());
} catch (IOException exp) {
throw new RuntimeException("Problem in tenant datasource:" + exp);
}
}
AbstractRoutingDataSource dataSource = new MultitenantDataSource();
dataSource.setDefaultTargetDataSource(resolvedDataSources.get(defaultTenant));
dataSource.setTargetDataSources(resolvedDataSources);
dataSource.afterPropertiesSet();
return dataSource;
}
}
|
repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\multitenant\config\MultitenantConfiguration.java
| 2
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setM_Product_SupplierApproval_Norm_ID (final int M_Product_SupplierApproval_Norm_ID)
{
if (M_Product_SupplierApproval_Norm_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_SupplierApproval_Norm_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_SupplierApproval_Norm_ID, M_Product_SupplierApproval_Norm_ID);
}
@Override
public int getM_Product_SupplierApproval_Norm_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_SupplierApproval_Norm_ID);
|
}
/**
* SupplierApproval_Norm AD_Reference_ID=541363
* Reference name: SupplierApproval_Norm
*/
public static final int SUPPLIERAPPROVAL_NORM_AD_Reference_ID=541363;
/** ISO 9100 Luftfahrt = ISO9100 */
public static final String SUPPLIERAPPROVAL_NORM_ISO9100Luftfahrt = "ISO9100";
/** TS 16949 = TS16949 */
public static final String SUPPLIERAPPROVAL_NORM_TS16949 = "TS16949";
@Override
public void setSupplierApproval_Norm (final java.lang.String SupplierApproval_Norm)
{
set_Value (COLUMNNAME_SupplierApproval_Norm, SupplierApproval_Norm);
}
@Override
public java.lang.String getSupplierApproval_Norm()
{
return get_ValueAsString(COLUMNNAME_SupplierApproval_Norm);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_SupplierApproval_Norm.java
| 1
|
请完成以下Java代码
|
static void startServer(int port) throws IOException {
ServerSocketFactory factory = SSLServerSocketFactory.getDefault();
try (SSLServerSocket listener = (SSLServerSocket) factory.createServerSocket(port)) {
listener.setNeedClientAuth(true);
listener.setEnabledCipherSuites(new String[] { "TLS_AES_128_GCM_SHA256" });
listener.setEnabledProtocols(new String[] { "TLSv1.3" });
System.out.println("listening for messages...");
try (Socket socket = listener.accept()) {
InputStream is = new BufferedInputStream(socket.getInputStream());
OutputStream os = new BufferedOutputStream(socket.getOutputStream());
byte[] data = new byte[2048];
int len = is.read(data);
if (len <= 0) {
|
throw new IOException("no data received");
}
String message = new String(data, 0, len);
System.out.printf("server received %d bytes: %s%n", len, message);
String response = message + " processed by server";
os.write(response.getBytes(), 0, response.getBytes().length);
os.flush();
}
System.out.println("message processed, exiting");
}
}
public static void main(String[] args) throws IOException {
startServer(8443);
}
}
|
repos\tutorials-master\core-java-modules\core-java-11-2\src\main\java\com\baeldung\httpsclientauthentication\SSLSocketEchoServer.java
| 1
|
请完成以下Java代码
|
public Long countByTenantId(TenantId tenantId) {
return dashboardRepository.countByTenantId(tenantId.getId());
}
@Override
public Dashboard findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(dashboardRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public PageData<Dashboard> findByTenantId(UUID tenantId, PageLink pageLink) {
return DaoUtil.toPageData(dashboardRepository.findByTenantId(tenantId, DaoUtil.toPageable(pageLink)));
}
@Override
public DashboardId getExternalIdByInternal(DashboardId internalId) {
return Optional.ofNullable(dashboardRepository.getExternalIdById(internalId.getId()))
.map(DashboardId::new).orElse(null);
}
@Override
public List<Dashboard> findByTenantIdAndTitle(UUID tenantId, String title) {
return DaoUtil.convertDataList(dashboardRepository.findByTenantIdAndTitle(tenantId, title));
}
@Override
public PageData<DashboardId> findIdsByTenantId(TenantId tenantId, PageLink pageLink) {
return DaoUtil.pageToPageData(dashboardRepository.findIdsByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink)).map(DashboardId::new));
}
@Override
public PageData<DashboardId> findAllIds(PageLink pageLink) {
return DaoUtil.pageToPageData(dashboardRepository.findAllIds(DaoUtil.toPageable(pageLink)).map(DashboardId::new));
}
|
@Override
public PageData<Dashboard> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<DashboardFields> findNextBatch(UUID id, int batchSize) {
return dashboardRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.DASHBOARD;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\dashboard\JpaDashboardDao.java
| 1
|
请完成以下Java代码
|
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public int getEventSubscriptionCount() {
return eventSubscriptionCount;
}
public void setEventSubscriptionCount(int eventSubscriptionCount) {
this.eventSubscriptionCount = eventSubscriptionCount;
}
public int getTaskCount() {
return taskCount;
}
public void setTaskCount(int taskCount) {
this.taskCount = taskCount;
}
public int getJobCount() {
return jobCount;
}
public void setJobCount(int jobCount) {
this.jobCount = jobCount;
}
public int getTimerJobCount() {
return timerJobCount;
}
public void setTimerJobCount(int timerJobCount) {
this.timerJobCount = timerJobCount;
}
public int getSuspendedJobCount() {
return suspendedJobCount;
}
public void setSuspendedJobCount(int suspendedJobCount) {
this.suspendedJobCount = suspendedJobCount;
}
public int getDeadLetterJobCount() {
return deadLetterJobCount;
}
public void setDeadLetterJobCount(int deadLetterJobCount) {
|
this.deadLetterJobCount = deadLetterJobCount;
}
public int getVariableCount() {
return variableCount;
}
public void setVariableCount(int variableCount) {
this.variableCount = variableCount;
}
public int getIdentityLinkCount() {
return identityLinkCount;
}
public void setIdentityLinkCount(int identityLinkCount) {
this.identityLinkCount = identityLinkCount;
}
@Override
public void setAppVersion(Integer appVersion) {
this.appVersion = appVersion;
}
@Override
public Integer getAppVersion() {
return appVersion;
}
//toString /////////////////////////////////////////////////////////////////
public String toString() {
if (isProcessInstanceType()) {
return "ProcessInstance[" + getId() + "]";
} else {
StringBuilder strb = new StringBuilder();
if (isScope) {
strb.append("Scoped execution[ id '" + getId() + "' ]");
} else if (isMultiInstanceRoot) {
strb.append("Multi instance root execution[ id '" + getId() + "' ]");
} else {
strb.append("Execution[ id '" + getId() + "' ]");
}
if (activityId != null) {
strb.append(" - activity '" + activityId);
}
if (parentId != null) {
strb.append(" - parent '" + parentId + "'");
}
return strb.toString();
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ExecutionEntityImpl.java
| 1
|
请完成以下Java代码
|
public void setRewardMode (String RewardMode)
{
set_Value (COLUMNNAME_RewardMode, RewardMode);
}
/** Get Reward Mode.
@return Reward Mode */
public String getRewardMode ()
{
return (String)get_Value(COLUMNNAME_RewardMode);
}
/** RewardType AD_Reference_ID=53298 */
public static final int REWARDTYPE_AD_Reference_ID=53298;
/** Percentage = P */
public static final String REWARDTYPE_Percentage = "P";
/** Flat Discount = F */
public static final String REWARDTYPE_FlatDiscount = "F";
/** Absolute Amount = A */
public static final String REWARDTYPE_AbsoluteAmount = "A";
/** Set Reward Type.
@param RewardType
Type of reward which consists of percentage discount, flat discount or absolute amount
*/
public void setRewardType (String RewardType)
{
set_Value (COLUMNNAME_RewardType, RewardType);
}
/** Get Reward Type.
@return Type of reward which consists of percentage discount, flat discount or absolute amount
*/
public String getRewardType ()
{
return (String)get_Value(COLUMNNAME_RewardType);
|
}
/** Set Reihenfolge.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionReward.java
| 1
|
请完成以下Java代码
|
protected @Nullable Resource onMissingResource(@Nullable Resource resource, @NonNull String location) {
throw new ResourceNotFoundException(String.format("Failed to resolve Resource [%1$s] at location [%2$s]",
ResourceUtils.nullSafeGetDescription(resource), location));
}
/**
* Method used by subclasses to process the loaded {@link Resource} as determined by
* the {@link #getResourceLoader() ResourceLoader}.
*
* @param resource {@link Resource} to post-process.
* @return the {@link Resource}.
* @see org.springframework.core.io.Resource
*/
protected Resource postProcess(Resource resource) {
return resource;
}
/**
* Tries to resolve a {@link Resource} at the given {@link String location} using a Spring {@link ResourceLoader},
* such as a Spring {@link ApplicationContext}.
*
* The targeted, identified {@link Resource} can be further {@link #isQualified(Resource) qualified} by subclasses
* based on application requirements or use case (UC).
*
* In the event that a {@link Resource} cannot be identified at the given {@link String location}, then applications
* have 1 last opportunity to handle the missing {@link Resource} event, and either return a different or default
* {@link Resource} or throw a {@link ResourceNotFoundException}.
*
* @param location {@link String location} identifying the {@link Resource} to resolve;
* must not be {@literal null}.
* @throws IllegalArgumentException if {@link String location} is not specified.
* @return an {@link Optional} {@link Resource} handle for the given {@link String location}.
* @see org.springframework.core.io.Resource
* @see #isQualified(Resource)
|
* @see #onMissingResource(Resource, String)
* @see #postProcess(Resource)
* @see java.util.Optional
*/
@Override
public Optional<Resource> resolve(@NonNull String location) {
Assert.hasText(location, () ->
String.format("The location [%s] of the Resource to resolve must be specified", location));
Resource resource = getResourceLoader().getResource(location);
resource = postProcess(resource);
Resource resolvedResource = isQualified(resource)
? resource
: onMissingResource(resource, location);
return Optional.ofNullable(resolvedResource);
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\io\support\ResourceLoaderResourceResolver.java
| 1
|
请完成以下Java代码
|
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 Percentage.
@param Percentage
Percent of the entire amount
*/
public void setPercentage (int Percentage)
{
set_Value (COLUMNNAME_Percentage, Integer.valueOf(Percentage));
|
}
/** Get Percentage.
@return Percent of the entire amount
*/
public int getPercentage ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Percentage);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_C_TaxBase.java
| 1
|
请完成以下Java代码
|
public Void execute(CommandContext commandContext) {
if(dueDate == null && commandContext.getProcessEngineConfiguration().isEnsureJobDueDateNotNull()) {
dueDate = ClockUtil.getCurrentTime();
}
if (jobId != null) {
setJobRetriesByJobId(jobId, commandContext);
} else if(jobDefinitionId != null){
setJobRetriesByJobDefinitionId(commandContext);
} else if(jobIds != null) {
for (String id : jobIds) {
setJobRetriesByJobId(id, commandContext);
}
}
return null;
}
protected void setJobRetriesByJobId(String jobId, CommandContext commandContext) {
JobEntity job = commandContext
.getJobManager()
.findJobById(jobId);
if (job != null) {
for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkUpdateRetriesJob(job);
}
if (job.isInInconsistentLockState()) {
job.resetLock();
}
List<PropertyChange> propertyChanges = new ArrayList<>();
int oldRetries = job.getRetries();
job.setRetries(retries);
propertyChanges.add(new PropertyChange(RETRIES, oldRetries, job.getRetries()));
if (isDueDateSet) {
Date oldDueDate = job.getDuedate();
job.setDuedate(dueDate);
propertyChanges.add(new PropertyChange(DUE_DATE, oldDueDate, job.getDuedate()));
}
commandContext.getOperationLogManager().logJobOperation(getLogEntryOperation(), job.getId(),
job.getJobDefinitionId(), job.getProcessInstanceId(), job.getProcessDefinitionId(),
job.getProcessDefinitionKey(), propertyChanges);
} else {
|
throw LOG.exceptionNoJobFoundForId(jobId);
}
}
protected void setJobRetriesByJobDefinitionId(CommandContext commandContext) {
JobDefinitionManager jobDefinitionManager = commandContext.getJobDefinitionManager();
JobDefinitionEntity jobDefinition = jobDefinitionManager.findById(jobDefinitionId);
if (jobDefinition != null) {
String processDefinitionId = jobDefinition.getProcessDefinitionId();
for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkUpdateRetriesProcessInstanceByProcessDefinitionId(processDefinitionId);
}
}
commandContext
.getJobManager()
.updateFailedJobRetriesByJobDefinitionId(jobDefinitionId, retries, dueDate, isDueDateSet);
List<PropertyChange> propertyChanges = new ArrayList<>();
propertyChanges.add(new PropertyChange(RETRIES, null, retries));
if (isDueDateSet) {
propertyChanges.add(new PropertyChange(DUE_DATE, null, dueDate));
}
commandContext.getOperationLogManager().logJobOperation(getLogEntryOperation(), null, jobDefinitionId, null,
null, null, propertyChanges);
}
protected String getLogEntryOperation() {
return UserOperationLogEntry.OPERATION_TYPE_SET_JOB_RETRIES;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetJobRetriesCmd.java
| 1
|
请完成以下Java代码
|
public BigDecimal getMinPoint() {
return minPoint;
}
public void setMinPoint(BigDecimal minPoint) {
this.minPoint = minPoint;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Integer getUseType() {
return useType;
}
public void setUseType(Integer useType) {
this.useType = useType;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Integer getPublishCount() {
return publishCount;
}
public void setPublishCount(Integer publishCount) {
this.publishCount = publishCount;
}
public Integer getUseCount() {
return useCount;
}
public void setUseCount(Integer useCount) {
this.useCount = useCount;
}
public Integer getReceiveCount() {
return receiveCount;
}
public void setReceiveCount(Integer receiveCount) {
|
this.receiveCount = receiveCount;
}
public Date getEnableTime() {
return enableTime;
}
public void setEnableTime(Date enableTime) {
this.enableTime = enableTime;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Integer getMemberLevel() {
return memberLevel;
}
public void setMemberLevel(Integer memberLevel) {
this.memberLevel = memberLevel;
}
@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(", type=").append(type);
sb.append(", name=").append(name);
sb.append(", platform=").append(platform);
sb.append(", count=").append(count);
sb.append(", amount=").append(amount);
sb.append(", perLimit=").append(perLimit);
sb.append(", minPoint=").append(minPoint);
sb.append(", startTime=").append(startTime);
sb.append(", endTime=").append(endTime);
sb.append(", useType=").append(useType);
sb.append(", note=").append(note);
sb.append(", publishCount=").append(publishCount);
sb.append(", useCount=").append(useCount);
sb.append(", receiveCount=").append(receiveCount);
sb.append(", enableTime=").append(enableTime);
sb.append(", code=").append(code);
sb.append(", memberLevel=").append(memberLevel);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsCoupon.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String category;
private Double price;
public Product(String name, String category, Double price) {
this.name = name;
this.category = category;
this.price = price;
}
public Product() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
|
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-queries-2\src\main\java\com\baeldung\hibernate\groupby\Product.java
| 2
|
请完成以下Java代码
|
public class OrderImpl implements Order {
private String username;
private Map<Book, Integer> items = new HashMap<>();
public OrderImpl(String username) {
this.username = username;
}
@Override
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
|
public Map<Book, Integer> getItems() {
return items;
}
public void setItems(Map<Book, Integer> items) {
this.items = items;
}
@Override
public void add(Book item, Integer quantity) {
Integer q = 0;
if (this.items.containsKey(item)) {
q = this.items.get(item);
}
this.items.put(item, quantity + q);
}
}
|
repos\tutorials-master\patterns-modules\intercepting-filter\src\main\java\com\baeldung\patterns\intercepting\filter\data\OrderImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonInvoiceCandidateReference
{
@ApiModelProperty(position = 10, allowEmptyValue = true, dataType = "java.lang.String", example = "ExternalHeaderId_1",//
value = "Used to select which invoice candidates should be enqueued.")
JsonExternalId externalHeaderId;
@ApiModelProperty(position = 20, allowEmptyValue = true, dataType = "java.lang.String", example = "[\"ExternalLineId_2\", \"ExternalLineId_3\"]", //
value = "Optional, used to select which invoice candidates which have these `C_Invoice_Candidate.ExternalLineId`s should be enqueued.\n"
+ "Inherited from order line candidates.\n"
+ "If not specified, then all invoice candidate with the specified `externalHeaderId` are matched")
@JsonInclude(Include.NON_EMPTY)
List<JsonExternalId> externalLineIds;
@ApiModelProperty(position = 30, allowEmptyValue = true, dataType = "java.lang.String", example = "001",//
value = "The `AD_Org.Value` of the `C_Invoice_Candidate`'s AD_Org_ID")
String orgCode;
@ApiModelProperty(position = 40, allowEmptyValue = true, //
value = "Can be set if the orders' document type is already known. When specified, orgCode of the document type also has to be specified")
JsonDocTypeInfo orderDocumentType;
@ApiModelProperty(position = 50, allowEmptyValue = true, dataType = "java.lang.String", example = "8393",//
value = "Used to select which invoice candidates should be enqueued, based on the referenced order's document no.")
String orderDocumentNo;
@ApiModelProperty(position = 60, allowEmptyValue = true, dataType = "java.lang.Integer", example = "[\"10\", \"20\"]", //
|
value = "Optional, used to select invoice candidates which reference order lines that have these `C_OrderLine.Line`s "
+ "and are part of the order with the`orderDocumentNo` from above.\n"
+ "If not specified, then all invoice candidates that reference the order with the specified `orderDocumentNo` are matched")
@JsonInclude(Include.NON_EMPTY)
List<Integer> orderLines;
@JsonCreator
@Builder(toBuilder = true)
private JsonInvoiceCandidateReference(
@JsonProperty("externalHeaderId") @Nullable final JsonExternalId externalHeaderId,
@JsonProperty("externalLineIds") @Singular @Nullable final List<JsonExternalId> externalLineIds,
@JsonProperty("orderDocumentNo") @Nullable final String orderDocumentNo,
@JsonProperty("orgCode") @Nullable final String orgCode,
@JsonProperty("orderDocumentType") @Nullable final JsonDocTypeInfo orderDocumentType,
@JsonProperty("orderLines") @Singular @Nullable final List<Integer> orderLines)
{
this.externalHeaderId = externalHeaderId;
this.externalLineIds = externalLineIds == null ? ImmutableList.of() : ImmutableList.copyOf(externalLineIds);
this.orderDocumentNo = orderDocumentNo;
this.orgCode = orgCode;
this.orderDocumentType = orderDocumentType;
this.orderLines = orderLines == null ? ImmutableList.of() : ImmutableList.copyOf(orderLines);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api\src\main\java\de\metas\rest_api\invoicecandidates\request\JsonInvoiceCandidateReference.java
| 2
|
请完成以下Java代码
|
public final ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (getSelectedRowIds().isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (!getSelectedRowIds().isSingleDocumentId())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final UomId uomId = productBL.getStockUOMId(productId);
final StockQtyAndUOMQty levelMin = StockQtyAndUOMQtys.createConvert(this.levelMin, productId, uomId);
final StockQtyAndUOMQty levelMax = this.levelMax == null ? levelMin : StockQtyAndUOMQtys.createConvert(this.levelMax, productId, uomId);
replenishInfoRepository.save(ReplenishInfo.builder()
.identifier(ReplenishInfo.Identifier.builder()
.productId(productId)
.warehouseId(warehouseId)
.build())
.min(levelMin)
.max(levelMax)
.build());
return MSG_OK;
}
@Nullable
@Override
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
final MaterialNeedsPlannerRow materialNeedsPlannerRow = MaterialNeedsPlannerRow.ofViewRow(getSingleSelectedRow());
if (PARAM_M_Product_ID.equals(parameter.getColumnName()))
|
{
return materialNeedsPlannerRow.getProductId();
}
else if (PARAM_M_Warehouse_ID.equals(parameter.getColumnName()))
{
return materialNeedsPlannerRow.getWarehouseId();
}
else if (PARAM_Level_Min.equals(parameter.getColumnName()))
{
return materialNeedsPlannerRow.getLevelMin();
}
else if (PARAM_Level_Max.equals(parameter.getColumnName()))
{
return materialNeedsPlannerRow.getLevelMax();
}
else
{
return DEFAULT_VALUE_NOTAVAILABLE;
}
}
@Override
protected void postProcess(final boolean success)
{
getView().invalidateSelection();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\replenish\process\WEBUI_M_Replenish_Add_Update_Demand.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void checkIp(RpUserPayConfig rpUserPayConfig, HttpServletRequest httpServletRequest) {
try {
if (!SecurityRatingEnum.MD5_IP.name().equals(rpUserPayConfig.getSecurityRating())) {
return;
}
String ip = NetworkUtil.getIpAddress(httpServletRequest);
if (StringUtil.isEmpty(ip)) {
throw new TradeBizException(TradeBizException.TRADE_PARAM_ERROR, "获取请求IP错误");
}
String merchantServerIp = rpUserPayConfig.getMerchantServerIp();
if (merchantServerIp.indexOf(ip) < 0) {
throw new TradeBizException(TradeBizException.TRADE_PARAM_ERROR, "非法IP请求");
}
} catch (IOException e) {
LOG.error("获取请求IP异常:", e);
throw new TradeBizException(TradeBizException.TRADE_PARAM_ERROR, "获取请求IP异常");
}
}
/**
* 校验请求参数及支付配置
* @param object
* @param bindingResult
* @param httpServletRequest
* @return
* @throws BizException
*/
public RpUserPayConfig checkParamAndGetUserPayConfig(Object object, BindingResult bindingResult, HttpServletRequest httpServletRequest)throws BizException{
validator.validate(object, bindingResult);
if (bindingResult.hasErrors()) {// 校验银行卡信息是否完整
String errorResponse = getErrorResponse(bindingResult);
LOG.info("请求参数异常:{}", errorResponse);
throw new PayBizException(PayBizException.REQUEST_PARAM_ERR, errorResponse);
}
Object jsonObject = JSONObject.toJSON(object);
|
Map<String, Object> jsonParamMap = JSONObject.parseObject(jsonObject.toString(), Map.class);
LOG.info("parseObject:" + jsonParamMap);
String payKey = String.valueOf(jsonParamMap.get("payKey"));
RpUserPayConfig rpUserPayConfig = rpUserPayConfigService.getByPayKey(payKey);
if (rpUserPayConfig == null) {
LOG.info("payKey[{}]的商户不存在", payKey);
throw new PayBizException(PayBizException.USER_PAY_CONFIG_IS_NOT_EXIST, "用户异常");
}
checkIp(rpUserPayConfig, httpServletRequest );// ip校验
String sign = String.valueOf(jsonParamMap.get("sign"));
if (!MerchantApiUtil.isRightSign(jsonParamMap, rpUserPayConfig.getPaySecret(), sign)) {
LOG.info("参数[{}],MD5签名验证异常sign:{}", jsonParamMap, sign);
throw new TradeBizException(TradeBizException.TRADE_ORDER_ERROR, "订单签名异常");
}
return rpUserPayConfig;
}
/**
* 获取错误返回信息
*
* @param bindingResult
* @return
*/
public String getErrorResponse(BindingResult bindingResult) {
StringBuffer sb = new StringBuffer();
for (ObjectError objectError : bindingResult.getAllErrors()) {
sb.append(objectError.getDefaultMessage()).append(",");
}
sb.delete(sb.length() - 1, sb.length());
return sb.toString();
}
}
|
repos\roncoo-pay-master\roncoo-pay-web-gateway\src\main\java\com\roncoo\pay\service\CnpPayService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private <T extends OAuth2AuthorizedClientProvider> T getAuthorizedClientProviderByType(
Collection<OAuth2AuthorizedClientProvider> authorizedClientProviders, Class<T> providerClass) {
T authorizedClientProvider = null;
for (OAuth2AuthorizedClientProvider current : authorizedClientProviders) {
if (providerClass.isInstance(current)) {
assertAuthorizedClientProviderIsNull(authorizedClientProvider);
authorizedClientProvider = providerClass.cast(current);
}
}
return authorizedClientProvider;
}
private static void assertAuthorizedClientProviderIsNull(
OAuth2AuthorizedClientProvider authorizedClientProvider) {
if (authorizedClientProvider != null) {
// @formatter:off
throw new BeanInitializationException(String.format(
"Unable to create an %s bean. Expected one bean of type %s, but found multiple. " +
"Please consider defining only a single bean of this type, or define an %s bean yourself.",
OAuth2AuthorizedClientManager.class.getName(),
authorizedClientProvider.getClass().getName(),
OAuth2AuthorizedClientManager.class.getName()));
// @formatter:on
}
}
|
private <T> String[] getBeanNamesForType(Class<T> beanClass) {
return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, beanClass, true, true);
}
private <T> T getBeanOfType(ResolvableType resolvableType) {
ObjectProvider<T> objectProvider = this.beanFactory.getBeanProvider(resolvableType, true);
return objectProvider.getIfAvailable();
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configuration\OAuth2ClientConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private void printReq(HttpServletRequest request) {
//获取请求头信息
Enumeration headerNames = request.getHeaderNames();
//使用循环遍历请求头,并通过getHeader()方法获取一个指定名称的头字段
while (headerNames.hasMoreElements()) {
String headerName = (String) headerNames.nextElement();
System.out.println(headerName + " : " + request.getHeader(headerName));
}
System.out.println("============================================================================================");
//获取请求行的相关信息
System.out.println("getMethod:" + request.getMethod());
System.out.println("getQueryString:" + request.getQueryString());
System.out.println("getProtocol:" + request.getProtocol());
System.out.println("getContextPath" + request.getContextPath());
System.out.println("getPathInfo:" + request.getPathInfo());
System.out.println("getPathTranslated:" + request.getPathTranslated());
System.out.println("getServletPath:" + request.getServletPath());
System.out.println("getRemoteAddr:" + request.getRemoteAddr());
System.out.println("getRemoteHost:" + request.getRemoteHost());
System.out.println("getRemotePort:" + request.getRemotePort());
System.out.println("getLocalAddr:" + request.getLocalAddr());
System.out.println("getLocalName:" + request.getLocalName());
System.out.println("getLocalPort:" + request.getLocalPort());
System.out.println("getServerName:" + request.getServerName());
System.out.println("getServerPort:" + request.getServerPort());
System.out.println("getScheme:" + request.getScheme());
System.out.println("getRequestURL:" + request.getRequestURL());
Enumeration<?> temp = request.getParameterNames();
if (null != temp) {
while (temp.hasMoreElements()) {
String en = (String) temp.nextElement();
String value = request.getParameter(en);
System.out.println(en + "===>" + value);
}
}
|
// StringBuffer jb = new StringBuffer();
// String line = null;
// try {
// BufferedReader reader = request.getReader();
// while ((line = reader.readLine()) != null)
// jb.append(line);
// } catch (Exception e) { /*report an error*/ }
//
// try {
// System.out.println(JSONUtil.toJsonPrettyStr(jb.toString()));
// } catch (Exception e) {
// // crash and burn
// e.printStackTrace();
// }
}
}
|
repos\spring-boot-quick-master\quick-hmac\src\main\java\com\quick\hmac\controller\PostController.java
| 2
|
请完成以下Java代码
|
public void renameFile(String bucketName, String keyName, String destinationKeyName) {
CopyObjectRequest copyObjRequest = CopyObjectRequest.builder()
.sourceBucket(bucketName)
.sourceKey(keyName)
.destinationBucket(destinationKeyName)
.destinationKey(bucketName)
.build();
s3Client.copyObject(copyObjRequest);
DeleteObjectRequest deleteRequest = DeleteObjectRequest.builder()
.bucket(bucketName)
.key(keyName)
.build();
s3Client.deleteObject(deleteRequest);
}
public void renameFolder(String bucketName, String sourceFolderKey, String destinationFolderKey) {
ListObjectsV2Request listRequest = ListObjectsV2Request.builder()
.bucket(bucketName)
.prefix(sourceFolderKey)
.build();
ListObjectsV2Response listResponse = s3Client.listObjectsV2(listRequest);
List<S3Object> objects = listResponse.contents();
for (S3Object s3Object : objects) {
String newKey = destinationFolderKey + s3Object.key()
.substring(sourceFolderKey.length());
// Copy object to destination folder
CopyObjectRequest copyRequest = CopyObjectRequest.builder()
|
.sourceBucket(bucketName)
.sourceKey(s3Object.key())
.destinationBucket(bucketName)
.destinationKey(newKey)
.build();
s3Client.copyObject(copyRequest);
// Delete object from source folder
DeleteObjectRequest deleteRequest = DeleteObjectRequest.builder()
.bucket(bucketName)
.key(s3Object.key())
.build();
s3Client.deleteObject(deleteRequest);
}
}
}
|
repos\tutorials-master\aws-modules\aws-s3\src\main\java\com\baeldung\s3\RenameObjectService.java
| 1
|
请完成以下Java代码
|
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public void setAD_User_ID (final int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, AD_User_ID);
}
@Override
public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
@Override
public org.compiere.model.I_AD_Window getAD_Window()
{
return get_ValueAsPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class);
}
@Override
public void setAD_Window(final org.compiere.model.I_AD_Window AD_Window)
{
set_ValueFromPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class, AD_Window);
}
@Override
public void setAD_Window_ID (final int AD_Window_ID)
{
if (AD_Window_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Window_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Window_ID, AD_Window_ID);
}
@Override
public int getAD_Window_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Window_ID);
}
@Override
public void setErrorMsg (final @Nullable java.lang.String ErrorMsg)
{
set_Value (COLUMNNAME_ErrorMsg, ErrorMsg);
}
@Override
public java.lang.String getErrorMsg()
{
return get_ValueAsString(COLUMNNAME_ErrorMsg);
}
@Override
public void setIsProcessing (final boolean IsProcessing)
{
set_Value (COLUMNNAME_IsProcessing, IsProcessing);
|
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_IsProcessing);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setResult (final int Result)
{
set_Value (COLUMNNAME_Result, Result);
}
@Override
public int getResult()
{
return get_ValueAsInt(COLUMNNAME_Result);
}
@Override
public void setWhereClause (final @Nullable java.lang.String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
@Override
public java.lang.String getWhereClause()
{
return get_ValueAsString(COLUMNNAME_WhereClause);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PInstance.java
| 1
|
请完成以下Java代码
|
public class MyStompSessionHandler extends StompSessionHandlerAdapter {
private Logger logger = LogManager.getLogger(MyStompSessionHandler.class);
@Override
public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
logger.info("New session established : " + session.getSessionId());
session.subscribe("/topic/messages", this);
logger.info("Subscribed to /topic/messages");
session.send("/app/chat", getSampleMessage());
logger.info("Message sent to websocket server");
}
@Override
public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) {
logger.error("Got an exception", exception);
}
@Override
public Type getPayloadType(StompHeaders headers) {
return Message.class;
}
|
@Override
public void handleFrame(StompHeaders headers, Object payload) {
Message msg = (Message) payload;
logger.info("Received : " + msg.getText() + " from : " + msg.getFrom());
}
/**
* A sample message instance.
* @return instance of <code>Message</code>
*/
private Message getSampleMessage() {
Message msg = new Message();
msg.setFrom("Nicky");
msg.setText("Howdy!!");
return msg;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-client\src\main\java\com\baeldung\websocket\client\MyStompSessionHandler.java
| 1
|
请完成以下Java代码
|
public static void main(String[] args) throws IOException {
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.bind(new InetSocketAddress(PORT));
serverChannel.configureBlocking(false);
Selector selector = Selector.open();
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Non-blocking Server listening on port " + PORT);
while (true) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iter = keys.iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
iter.remove();
if (key.isAcceptable()) {
SocketChannel client = serverChannel.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
System.out.println("New client connected");
}
else if (key.isReadable()) {
SocketChannel client = (SocketChannel) key.channel();
try {
MyObject obj = receiveObject(client);
if (obj != null) {
System.out.println("Received: " + obj.getName() + ", " + obj.getAge());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
client.close();
}
}
}
}
}
private static MyObject receiveObject(SocketChannel channel)
throws IOException, ClassNotFoundException {
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = channel.read(buffer)) > 0) {
buffer.flip();
byteStream.write(buffer.array(), 0, buffer.limit());
buffer.clear();
}
if (bytesRead == -1) {
channel.close();
return null;
}
byte[] bytes = byteStream.toByteArray();
try (ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
return (MyObject) objIn.readObject();
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-nio-3\src\main\java\com\baeldung\socketchannel\NonBlockingServer.java
| 1
|
请完成以下Java代码
|
public static String getHostName() {
final String DEFAULT_HOST = "localhost";
String hostName = null;
boolean canAccessSystemProps = true;
try {
// we'll do it this way mostly to determine if we should lookup the hostName
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPropertiesAccess();
}
} catch (SecurityException se) {
canAccessSystemProps = false;
}
|
if (canAccessSystemProps) {
try {
hostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException uhe) {
LOGGER.info("Cannot determine localhost name. Fallback to: " + DEFAULT_HOST, uhe);
hostName = DEFAULT_HOST;
}
} else {
hostName = DEFAULT_HOST;
}
return hostName;
}
}
|
repos\flowable-engine-main\modules\flowable-jmx\src\main\java\org\flowable\management\jmx\Utils.java
| 1
|
请完成以下Java代码
|
public class WebSite {
private String url;
private String name;
private String category;
private String status;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
|
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
|
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\stax\WebSite.java
| 1
|
请完成以下Java代码
|
public int getSalesRep_ID()
{
return get_ValueAsInt(COLUMNNAME_SalesRep_ID);
}
@Override
public void setSendEMail (final boolean SendEMail)
{
set_Value (COLUMNNAME_SendEMail, SendEMail);
}
@Override
public boolean isSendEMail()
{
return get_ValueAsBoolean(COLUMNNAME_SendEMail);
}
@Override
public void setTotalLines (final BigDecimal TotalLines)
{
set_ValueNoCheck (COLUMNNAME_TotalLines, TotalLines);
}
@Override
public BigDecimal getTotalLines()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalLines);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public org.compiere.model.I_C_ElementValue getUser1()
{
return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser1(final org.compiere.model.I_C_ElementValue User1)
{
set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1);
}
@Override
public void setUser1_ID (final int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, User1_ID);
}
@Override
public int getUser1_ID()
{
return get_ValueAsInt(COLUMNNAME_User1_ID);
}
|
@Override
public org.compiere.model.I_C_ElementValue getUser2()
{
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser2(final org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
@Override
public void setUser2_ID (final int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, User2_ID);
}
@Override
public int getUser2_ID()
{
return get_ValueAsInt(COLUMNNAME_User2_ID);
}
@Override
public void setUserFlag (final @Nullable java.lang.String UserFlag)
{
set_Value (COLUMNNAME_UserFlag, UserFlag);
}
@Override
public java.lang.String getUserFlag()
{
return get_ValueAsString(COLUMNNAME_UserFlag);
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice.java
| 1
|
请完成以下Java代码
|
public static ProblemDto fromProblem(Problem problem) {
ProblemDto dto = new ProblemDto();
dto.setMessage(problem.getMessage());
dto.setLine(problem.getLine());
dto.setColumn(problem.getColumn());
dto.setMainElementId(problem.getMainElementId());
dto.setЕlementIds(problem.getElementIds());
return dto;
}
// getter / setters ////////////////////////
public String getMessage() {
return message;
}
public void setMessage(String errorMessage) {
this.message = errorMessage;
}
public int getLine() {
return line;
}
public void setLine(int line) {
this.line = line;
}
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
|
}
public String getMainElementId() {
return mainElementId;
}
public void setMainElementId(String mainElementId) {
this.mainElementId = mainElementId;
}
public List<String> getЕlementIds() {
return еlementIds;
}
public void setЕlementIds(List<String> elementIds) {
this.еlementIds = elementIds;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\ProblemDto.java
| 1
|
请完成以下Java代码
|
public I_AD_User getSalesRep() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSalesRep_ID(), get_TrxName()); }
/** Set Sales Representative.
@param SalesRep_ID
Sales Representative or Company Agent
*/
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set SKU.
@param SKU
Stock Keeping Unit
*/
public void setSKU (String SKU)
{
set_Value (COLUMNNAME_SKU, SKU);
}
/** Get SKU.
@return Stock Keeping Unit
*/
public String getSKU ()
{
return (String)get_Value(COLUMNNAME_SKU);
}
/** Set Tax Amount.
@param TaxAmt
Tax Amount for a document
*/
public void setTaxAmt (BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
/** Get Tax Amount.
@return Tax Amount for a document
|
*/
public BigDecimal getTaxAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Tax Indicator.
@param TaxIndicator
Short form for Tax to be printed on documents
*/
public void setTaxIndicator (String TaxIndicator)
{
set_Value (COLUMNNAME_TaxIndicator, TaxIndicator);
}
/** Get Tax Indicator.
@return Short form for Tax to be printed on documents
*/
public String getTaxIndicator ()
{
return (String)get_Value(COLUMNNAME_TaxIndicator);
}
/** Set UPC/EAN.
@param UPC
Bar Code (Universal Product Code or its superset European Article Number)
*/
public void setUPC (String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
@return Bar Code (Universal Product Code or its superset European Article Number)
*/
public String getUPC ()
{
return (String)get_Value(COLUMNNAME_UPC);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Invoice.java
| 1
|
请完成以下Java代码
|
public boolean isPalindromeUsingStringBuilder(String text) {
String clean = text.replaceAll("\\s+", "")
.toLowerCase();
StringBuilder plain = new StringBuilder(clean);
StringBuilder reverse = plain.reverse();
return (reverse.toString()).equals(clean);
}
public boolean isPalindromeUsingStringBuffer(String text) {
String clean = text.replaceAll("\\s+", "")
.toLowerCase();
StringBuffer plain = new StringBuffer(clean);
StringBuffer reverse = plain.reverse();
return (reverse.toString()).equals(clean);
}
public boolean isPalindromeRecursive(String text) {
String clean = text.replaceAll("\\s+", "")
.toLowerCase();
return recursivePalindrome(clean, 0, clean.length() - 1);
}
private boolean recursivePalindrome(String text, int forward, int backward) {
if (forward == backward)
return true;
if ((text.charAt(forward)) != (text.charAt(backward)))
return false;
if (forward < backward + 1) {
return recursivePalindrome(text, forward + 1, backward - 1);
}
|
return true;
}
public boolean isPalindromeUsingIntStream(String text) {
String temp = text.replaceAll("\\s+", "")
.toLowerCase();
return IntStream.range(0, temp.length() / 2)
.noneMatch(i -> temp.charAt(i) != temp.charAt(temp.length() - i - 1));
}
boolean hasPalindromePermutation(String text) {
long charsWithOddOccurrencesCount = text.chars()
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.values()
.stream()
.filter(count -> count % 2 != 0)
.count();
return charsWithOddOccurrencesCount <= 1;
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-algorithms-2\src\main\java\com\baeldung\palindrom\Palindrome.java
| 1
|
请完成以下Java代码
|
public abstract class EventImpl extends FlowNodeImpl implements Event {
protected static ChildElementCollection<Property> propertyCollection;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Event.class, BPMN_ELEMENT_EVENT)
.namespaceUri(BPMN20_NS)
.extendsType(FlowNode.class)
.abstractType();
SequenceBuilder sequence = typeBuilder.sequence();
propertyCollection = sequence.elementCollection(Property.class)
.build();
|
typeBuilder.build();
}
public EventImpl(ModelTypeInstanceContext context) {
super(context);
}
public Collection<Property> getProperties() {
return propertyCollection.get(this);
}
public BpmnShape getDiagramElement() {
return (BpmnShape) super.getDiagramElement();
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\EventImpl.java
| 1
|
请完成以下Java代码
|
public class DmnEvaluatedInputImpl implements DmnEvaluatedInput {
protected String id;
protected String name;
protected String inputVariable;
protected TypedValue value;
public DmnEvaluatedInputImpl(DmnDecisionTableInputImpl input) {
this.id = input.getId();
this.name = input.getName();
this.inputVariable = input.getInputVariable();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInputVariable() {
return inputVariable;
}
public void setInputVariable(String inputVariable) {
this.inputVariable = inputVariable;
}
public TypedValue getValue() {
return value;
}
|
public void setValue(TypedValue value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DmnEvaluatedInputImpl that = (DmnEvaluatedInputImpl) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (inputVariable != null ? !inputVariable.equals(that.inputVariable) : that.inputVariable != null) return false;
return !(value != null ? !value.equals(that.value) : that.value != null);
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (inputVariable != null ? inputVariable.hashCode() : 0);
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "DmnEvaluatedInputImpl{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", inputVariable='" + inputVariable + '\'' +
", value=" + value +
'}';
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\delegate\DmnEvaluatedInputImpl.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractSetBatchStateCmd implements Command<Void> {
public static final String SUSPENSION_STATE_PROPERTY = "suspensionState";
protected String batchId;
public AbstractSetBatchStateCmd(String batchId) {
this.batchId = batchId;
}
public Void execute(CommandContext commandContext) {
ensureNotNull(BadUserRequestException.class, "Batch id must not be null", "batch id", batchId);
BatchManager batchManager = commandContext.getBatchManager();
BatchEntity batch = batchManager.findBatchById(batchId);
ensureNotNull(BadUserRequestException.class, "Batch for id '" + batchId + "' cannot be found", "batch", batch);
checkAccess(commandContext, batch);
setJobDefinitionState(commandContext, batch.getSeedJobDefinitionId());
setJobDefinitionState(commandContext, batch.getMonitorJobDefinitionId());
setJobDefinitionState(commandContext, batch.getBatchJobDefinitionId());
batchManager.updateBatchSuspensionStateById(batchId, getNewSuspensionState());
logUserOperation(commandContext, batch.getTenantId());
return null;
}
protected abstract SuspensionState getNewSuspensionState();
protected void checkAccess(CommandContext commandContext, BatchEntity batch) {
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checkAccess(checker, batch);
}
}
|
protected abstract void checkAccess(CommandChecker checker, BatchEntity batch);
protected void setJobDefinitionState(CommandContext commandContext, String jobDefinitionId) {
createSetJobDefinitionStateCommand(jobDefinitionId).execute(commandContext);
}
protected AbstractSetJobDefinitionStateCmd createSetJobDefinitionStateCommand(String jobDefinitionId) {
AbstractSetJobDefinitionStateCmd suspendJobDefinitionCmd = createSetJobDefinitionStateCommand(new UpdateJobDefinitionSuspensionStateBuilderImpl()
.byJobDefinitionId(jobDefinitionId)
.includeJobs(true)
);
suspendJobDefinitionCmd.disableLogUserOperation();
return suspendJobDefinitionCmd;
}
protected abstract AbstractSetJobDefinitionStateCmd createSetJobDefinitionStateCommand(UpdateJobDefinitionSuspensionStateBuilderImpl builder);
protected void logUserOperation(CommandContext commandContext, String tenantId) {
PropertyChange propertyChange = new PropertyChange(SUSPENSION_STATE_PROPERTY, null, getNewSuspensionState().getName());
commandContext.getOperationLogManager()
.logBatchOperation(getUserOperationType(), batchId, tenantId, propertyChange);
}
protected abstract String getUserOperationType();
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractSetBatchStateCmd.java
| 1
|
请完成以下Java代码
|
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTaskState() {
return taskState;
}
public void setTaskState(String taskState) {
this.taskState = taskState;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[taskId" + taskId
+ ", assignee=" + assignee
+ ", owner=" + owner
+ ", name=" + name
+ ", description=" + description
|
+ ", dueDate=" + dueDate
+ ", followUpDate=" + followUpDate
+ ", priority=" + priority
+ ", parentTaskId=" + parentTaskId
+ ", deleteReason=" + deleteReason
+ ", taskDefinitionKey=" + taskDefinitionKey
+ ", durationInMillis=" + durationInMillis
+ ", startTime=" + startTime
+ ", endTime=" + endTime
+ ", id=" + id
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", activityInstanceId=" + activityInstanceId
+ ", tenantId=" + tenantId
+ ", taskState=" + taskState
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricTaskInstanceEventEntity.java
| 1
|
请完成以下Java代码
|
final class PackageableRowsData implements IRowsData<PackageableRow>
{
public static PackageableRowsData ofSupplier(final Supplier<List<PackageableRow>> rowsSupplier)
{
return new PackageableRowsData(rowsSupplier);
}
public static PackageableRowsData cast(final IRowsData<PackageableRow> rowsData)
{
return (PackageableRowsData)rowsData;
}
public static final PackageableRowsData EMPTY = new PackageableRowsData(ImmutableList::of);
private final ExtendedMemorizingSupplier<Map<DocumentId, PackageableRow>> topLevelRows;
private final ImmutableListMultimap<TableRecordReference, DocumentId> initialDocumentIdsByRecordRef;
private PackageableRowsData(@NonNull final Supplier<List<PackageableRow>> rowsSupplier)
{
topLevelRows = ExtendedMemorizingSupplier.of(() -> Maps.uniqueIndex(rowsSupplier.get(), PackageableRow::getId));
//
// Remember initial rows
// We will use this map to figure out what we can invalidate,
// because we want to cover the case of rows which just vanished (e.g. everything was delivered)
// and the case of rows which appeared back (e.g. the picking candidate was reactivated so we still have QtyToDeliver).
initialDocumentIdsByRecordRef = getAllRows()
.stream()
.collect(ImmutableListMultimap.toImmutableListMultimap(PackageableRow::getTableRecordReference, PackageableRow::getId));
}
@Override
public Map<DocumentId, PackageableRow> getDocumentId2TopLevelRows()
{
|
return topLevelRows.get();
}
@Override
public void invalidateAll()
{
topLevelRows.forget();
}
@Override
public DocumentIdsSelection getDocumentIdsToInvalidate(final TableRecordReferenceSet recordRefs)
{
return recordRefs.streamIds(I_M_ShipmentSchedule.Table_Name, ShipmentScheduleId::ofRepoId)
.flatMap(this::streamDocumentIdsForShipmentScheduleId)
.collect(DocumentIdsSelection.toDocumentIdsSelection());
}
private Stream<DocumentId> streamDocumentIdsForShipmentScheduleId(final ShipmentScheduleId shipmentScheduleId)
{
final TableRecordReference recordRefEffective = PackageableRow.createTableRecordReferenceFromShipmentScheduleId(shipmentScheduleId);
return initialDocumentIdsByRecordRef.get(recordRefEffective).stream();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\PackageableRowsData.java
| 1
|
请完成以下Java代码
|
public class DefaultHealthContributorRegistry extends AbstractRegistry<HealthContributor, Entry>
implements HealthContributorRegistry {
/**
* Create a new empty {@link DefaultHealthContributorRegistry} instance.
*/
public DefaultHealthContributorRegistry() {
this(null, null);
}
/**
* Create a new {@link DefaultHealthContributorRegistry} instance.
* @param nameValidators the name validators to apply
* @param initialRegistrations callback to setup any initial registrations
*/
public DefaultHealthContributorRegistry(
@Nullable Collection<? extends HealthContributorNameValidator> nameValidators,
@Nullable Consumer<BiConsumer<String, HealthContributor>> initialRegistrations) {
super(Entry::new, nameValidators, initialRegistrations);
}
|
@Override
public @Nullable HealthContributor getContributor(String name) {
return super.getContributor(name);
}
@Override
public Stream<Entry> stream() {
return super.stream();
}
@Override
public void registerContributor(String name, HealthContributor contributor) {
super.registerContributor(name, contributor);
}
@Override
public @Nullable HealthContributor unregisterContributor(String name) {
return super.unregisterContributor(name);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\registry\DefaultHealthContributorRegistry.java
| 1
|
请完成以下Java代码
|
public class LongDataTypeTransformer implements DmnDataTypeTransformer {
@Override
public TypedValue transform(Object value) throws IllegalArgumentException {
if (value instanceof Number) {
long longValue = transformNumber((Number) value);
return Variables.longValue(longValue);
} else if (value instanceof String) {
long longValue = transformString((String) value);
return Variables.longValue(longValue);
} else {
throw new IllegalArgumentException();
}
}
protected long transformNumber(Number value) {
if(isLong(value)) {
return value.longValue();
|
} else {
throw new IllegalArgumentException();
}
}
protected boolean isLong(Number value) {
double doubleValue = value.doubleValue();
return doubleValue == (long) doubleValue;
}
protected long transformString(String value) {
return Long.parseLong(value);
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\type\LongDataTypeTransformer.java
| 1
|
请完成以下Java代码
|
public void setM_Indication_ID (int M_Indication_ID)
{
if (M_Indication_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Indication_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Indication_ID, Integer.valueOf(M_Indication_ID));
}
/** Get Indication.
@return Indication */
@Override
public int getM_Indication_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Indication_ID);
if (ii == null)
return 0;
return ii.intValue();
}
|
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_M_Indication.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 18080 # 服务器端口,设置为 18080 避免和本地的 Apollo 端口冲突
# Apollo 相关配置项
app:
id: ${spring.application.name} # 使用的 Apollo 的项目(应用)编号
apollo:
meta: http://127.0.0.1:8080 # Apollo Meta Server 地址
bootstrap:
enabled: true # 是否开启 Apollo 配置预加载功能。默认为 false。
eagerLoad:
enable: true # 是否开启 Apollo 支持日志级别的加载时机。默认为 false。
namespaces: application # 使用的 Apollo 的命名空间,默认为 application。
spring:
application:
name: demo-provider
cloud:
# Sentinel 配置项,对应 SentinelProperties 配置属性类
sentinel:
enabled: true # 是否开启。默认为 true 开启
eager: true # 是否饥饿加载。默认为 false 关闭
transport:
dashboard: 127.0.0.1:7070 # Sentinel 控制台地址
filter:
url-patterns: /** # 拦截请求的地址。默认为 /*
# Sentinel 规则的数据源,是一个
|
Map 类型。key 为数据源名,可自定义;value 为数据源的具体配置
datasource:
ds1:
# 对应 DataSourcePropertiesConfiguration 类
apollo:
namespaceName: application # Apollo 命名空间
flowRulesKey: sentinel.flow-rule # Apollo 配置 key
data-type: json # 数据格式
rule-type: FLOW # 规则类型
|
repos\SpringBoot-Labs-master\labx-04-spring-cloud-alibaba-sentinel\labx-04-sca-sentinel-apollo-provider\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
public class UserEventListenerInstanceImpl implements UserEventListenerInstance {
protected PlanItemInstance innerPlanItemInstance;
public UserEventListenerInstanceImpl(PlanItemInstance planItemInstance) {
this.innerPlanItemInstance = planItemInstance;
}
public static UserEventListenerInstance fromPlanItemInstance(PlanItemInstance planItemInstance) {
if (planItemInstance == null) {
return null;
}
return new UserEventListenerInstanceImpl(planItemInstance);
}
@Override
public String getId() {
return innerPlanItemInstance.getId();
}
@Override
public String getName() {
return innerPlanItemInstance.getName();
}
@Override
public String getCaseInstanceId() {
return innerPlanItemInstance.getCaseInstanceId();
}
@Override
public String getCaseDefinitionId() {
return innerPlanItemInstance.getCaseDefinitionId();
}
@Override
public String getElementId() {
|
return innerPlanItemInstance.getElementId();
}
@Override
public String getPlanItemDefinitionId() {
return innerPlanItemInstance.getPlanItemDefinitionId();
}
@Override
public String getStageInstanceId() {
return innerPlanItemInstance.getStageInstanceId();
}
@Override
public String getState() {
return innerPlanItemInstance.getState();
}
@Override
public String toString() {
return "UserEventListenerInstanceImpl{" +
"id='" + getId() + '\'' +
", name='" + getName() + '\'' +
", caseInstanceId='" + getCaseInstanceId() + '\'' +
", caseDefinitionId='" + getCaseDefinitionId() + '\'' +
", elementId='" + getElementId() + '\'' +
", planItemDefinitionId='" + getPlanItemDefinitionId() + '\'' +
", stageInstanceId='" + getStageInstanceId() + '\'' +
'}';
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\UserEventListenerInstanceImpl.java
| 1
|
请完成以下Java代码
|
/*package */class HUHandlingUnitsInfo implements IHandlingUnitsInfo
{
public static HUHandlingUnitsInfo cast(final IHandlingUnitsInfo handlingUnitsInfo)
{
return (HUHandlingUnitsInfo)handlingUnitsInfo;
}
private final I_M_HU_PI _tuPI;
private int _qtyTU;
private final String _tuPIName;
private final boolean _isQtyWritable;
/* package */HUHandlingUnitsInfo(final I_M_HU_PI tuPI, final int qtyTU)
{
this(tuPI, qtyTU, false);
}
/* package */HUHandlingUnitsInfo(final I_M_HU_PI tuPI, final int qtyTU, final boolean isReadWrite)
{
// task 09688: currently, when in unit testing mode, we allow tuPI to be null
Check.assume(tuPI != null || Adempiere.isUnitTestMode(), "tuPI not null");
_tuPI = tuPI;
_tuPIName = tuPI != null ? tuPI.getName() : null;
_qtyTU = qtyTU;
_isQtyWritable = isReadWrite;
}
@Override
public int getQtyTU()
{
return _qtyTU;
}
@Override
public String getTUName()
{
return _tuPIName;
}
public final I_M_HU_PI getTU_HU_PI()
{
return _tuPI;
}
|
@Override
public IHandlingUnitsInfo add(final IHandlingUnitsInfo infoToAdd)
{
if (infoToAdd == null)
{
return this;
}
//
// TU PI
final I_M_HU_PI tuPI = getTU_HU_PI();
// TODO make sure tuPIs are compatible
//
// Qty TU
final int qtyTU = getQtyTU();
final int qtyTU_ToAdd = infoToAdd.getQtyTU();
final int qtyTU_New = qtyTU + qtyTU_ToAdd;
final boolean isReadWrite = false;
final HUHandlingUnitsInfo infoNew = new HUHandlingUnitsInfo(tuPI, qtyTU_New, isReadWrite);
return infoNew;
}
protected void setQtyTUInner(final int qtyTU)
{
Check.errorIf(!_isQtyWritable, "This instance {} is read-only", this);
_qtyTU = qtyTU;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\materialtracking\spi\impl\HUHandlingUnitsInfo.java
| 1
|
请完成以下Java代码
|
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(name);
out.writeUTF(capital);
out.writeInt(code);
}
|
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.name = in.readUTF();
this.capital = in.readUTF();
this.code = in.readInt();
}
@Override
public String toString() {
return "Country{" +
"name='" + name + '\'' +
", capital='" + capital + '\'' +
", code=" + code +
'}';
}
}
|
repos\tutorials-master\core-java-modules\core-java-serialization\src\main\java\com\baeldung\externalizable\Country.java
| 1
|
请完成以下Java代码
|
public void setAD_User_InCharge_ID (final int AD_User_InCharge_ID)
{
if (AD_User_InCharge_ID < 1)
set_Value (COLUMNNAME_AD_User_InCharge_ID, null);
else
set_Value (COLUMNNAME_AD_User_InCharge_ID, AD_User_InCharge_ID);
}
@Override
public int getAD_User_InCharge_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_InCharge_ID);
}
@Override
public void setC_ILCandHandler_ID (final int C_ILCandHandler_ID)
{
if (C_ILCandHandler_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ILCandHandler_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ILCandHandler_ID, C_ILCandHandler_ID);
}
@Override
public int getC_ILCandHandler_ID()
{
return get_ValueAsInt(COLUMNNAME_C_ILCandHandler_ID);
}
@Override
public void setClassname (final java.lang.String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
@Override
public java.lang.String getClassname()
{
return get_ValueAsString(COLUMNNAME_Classname);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
@Override
public void setIs_AD_User_InCharge_UI_Setting (final boolean Is_AD_User_InCharge_UI_Setting)
{
|
set_Value (COLUMNNAME_Is_AD_User_InCharge_UI_Setting, Is_AD_User_InCharge_UI_Setting);
}
@Override
public boolean is_AD_User_InCharge_UI_Setting()
{
return get_ValueAsBoolean(COLUMNNAME_Is_AD_User_InCharge_UI_Setting);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setTableName (final java.lang.String TableName)
{
set_Value (COLUMNNAME_TableName, TableName);
}
@Override
public java.lang.String getTableName()
{
return get_ValueAsString(COLUMNNAME_TableName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_ILCandHandler.java
| 1
|
请完成以下Java代码
|
private int getSeqNoToUse(final Timestamp today, final List<I_C_SubscriptionProgress> subscriptionProgressList)
{
return subscriptionProgressList.stream()
.filter(sp -> today.before(sp.getEventDate()))
.mapToInt(I_C_SubscriptionProgress::getSeqNo)
.min()//smallest seqNo after today's date
.orElse(subscriptionProgressList.stream()
.mapToInt(I_C_SubscriptionProgress::getSeqNo)
.map(Math::incrementExact)
.max()//greatest seqNo + 1 before today
.orElse(SEQNO_FIRST_VALUE));
}
private void addEventValue(final I_C_SubscriptionProgress changeEvent, final String eventType, @Nullable final Object eventValue)
{
if (Objects.equals(eventType, X_C_SubscriptionProgress.EVENTTYPE_Quantity) && eventValue != null)
{
changeEvent.setQty((BigDecimal)eventValue);
}
}
private void incrementSeqNoAndSave(final I_C_SubscriptionProgress subscriptionProgress)
{
subscriptionProgress.setSeqNo(subscriptionProgress.getSeqNo() + 1);
|
save(subscriptionProgress);
}
public boolean isSubscription(@NonNull final I_C_OrderLine ol)
{
final ConditionsId conditionsId = ConditionsId.ofRepoIdOrNull(ol.getC_Flatrate_Conditions_ID());
if (conditionsId == null)
{
return false;
}
final I_C_Flatrate_Conditions typeConditions = flatrateDAO.getConditionsById(conditionsId);
return X_C_Flatrate_Term.TYPE_CONDITIONS_Subscription.equals(typeConditions.getType_Conditions());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\SubscriptionBL.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.