instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class AsyncAfterMigrationValidator implements MigratingTransitionInstanceValidator {
@Override
public void validate(MigratingTransitionInstance migratingInstance, MigratingProcessInstance migratingProcessInstance,
MigratingTransitionInstanceValidationReportImpl instanceReport) {
ActivityImpl targetActivity = (ActivityImpl) migratingInstance.getTargetScope();
if (targetActivity != null && migratingInstance.isAsyncAfter()) {
MigratingJobInstance jobInstance = migratingInstance.getJobInstance();
AsyncContinuationConfiguration config = (AsyncContinuationConfiguration) jobInstance.getJobEntity().getJobHandlerConfiguration();
String sourceTransitionId = config.getTransitionId();
if (targetActivity.getOutgoingTransitions().size() > 1) {
if (sourceTransitionId == null) {
instanceReport.addFailure("Transition instance is assigned to no sequence flow" | + " and target activity has more than one outgoing sequence flow");
}
else {
TransitionImpl matchingOutgoingTransition = targetActivity.findOutgoingTransition(sourceTransitionId);
if (matchingOutgoingTransition == null) {
instanceReport.addFailure("Transition instance is assigned to a sequence flow"
+ " that cannot be matched in the target activity");
}
}
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instance\AsyncAfterMigrationValidator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MyCloudFoundryConfiguration {
@Bean
public TomcatServletWebServerFactory servletWebServerFactory() {
return new TomcatServletWebServerFactory() {
@Override
protected void prepareContext(Host host, ServletContextInitializer[] initializers) {
super.prepareContext(host, initializers);
StandardContext child = new StandardContext();
child.addLifecycleListener(new Tomcat.FixContextListener());
child.setPath("/cloudfoundryapplication");
ServletContainerInitializer initializer = getServletContextInitializer(getContextPath());
child.addServletContainerInitializer(initializer, Collections.emptySet());
child.setCrossContext(true);
host.addChild(child);
} | };
}
private ServletContainerInitializer getServletContextInitializer(String contextPath) {
return (classes, context) -> {
Servlet servlet = new GenericServlet() {
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
ServletContext context = req.getServletContext().getContext(contextPath);
context.getRequestDispatcher("/cloudfoundryapplication").forward(req, res);
}
};
context.addServlet("cloudfoundry", servlet).addMapping("/*");
};
}
} | repos\spring-boot-4.0.1\documentation\spring-boot-docs\src\main\java\org\springframework\boot\docs\actuator\cloudfoundry\customcontextpath\MyCloudFoundryConfiguration.java | 2 |
请完成以下Java代码 | public static boolean isUniqueContraintError(final Throwable e)
{
if (DB.isPostgreSQL())
{
return isSQLState(e, PG_SQLSTATE_unique_violation);
}
//
return isErrorCode(e, 1);
}
/**
* Check if "integrity constraint (string.string) violated - child record found" exception (aka ORA-02292)
*/
public static boolean isChildRecordFoundError(final Exception e)
{
if (DB.isPostgreSQL())
{
return isSQLState(e, PG_SQLSTATE_foreign_key_violation);
}
return isErrorCode(e, 2292);
}
public static boolean isForeignKeyViolation(final Throwable e)
{
if (DB.isPostgreSQL())
{
return isSQLState(e, PG_SQLSTATE_foreign_key_violation);
}
// NOTE: on oracle there are many ORA-codes for foreign key violation
// below i am adding a few of them, but pls note that it's not tested at all
return isErrorCode(e, 2291) // integrity constraint (string.string) violated - parent key not found
|| isErrorCode(e, 2292) // integrity constraint (string.string) violated - child record found
//
;
}
/**
* Check if "invalid identifier" exception (aka ORA-00904)
*
* @param e exception
*/
public static boolean isInvalidIdentifierError(final Exception e)
{
return isErrorCode(e, 904);
}
/**
* Check if "invalid username/password" exception (aka ORA-01017)
*
* @param e exception | */
public static boolean isInvalidUserPassError(final Exception e)
{
return isErrorCode(e, 1017);
}
/**
* Check if "time out" exception (aka ORA-01013)
*/
public static boolean isTimeout(final Exception e)
{
if (DB.isPostgreSQL())
{
return isSQLState(e, PG_SQLSTATE_query_canceled);
}
return isErrorCode(e, 1013);
}
/**
* Task 08353
*/
public static boolean isDeadLockDetected(final Throwable e)
{
if (DB.isPostgreSQL())
{
return isSQLState(e, PG_SQLSTATE_deadlock_detected);
}
return isErrorCode(e, 40001); // not tested for oracle, just did a brief googling
}
} // DBException | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\exceptions\DBException.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_Channel[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_AD_PrintColor getAD_PrintColor() throws RuntimeException
{
return (I_AD_PrintColor)MTable.get(getCtx(), I_AD_PrintColor.Table_Name)
.getPO(getAD_PrintColor_ID(), get_TrxName()); }
/** Set Print Color.
@param AD_PrintColor_ID
Color used for printing and display
*/
public void setAD_PrintColor_ID (int AD_PrintColor_ID)
{
if (AD_PrintColor_ID < 1)
set_Value (COLUMNNAME_AD_PrintColor_ID, null);
else
set_Value (COLUMNNAME_AD_PrintColor_ID, Integer.valueOf(AD_PrintColor_ID));
}
/** Get Print Color.
@return Color used for printing and display
*/
public int getAD_PrintColor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintColor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Channel.
@param C_Channel_ID
Sales Channel
*/
public void setC_Channel_ID (int C_Channel_ID)
{
if (C_Channel_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Channel_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Channel_ID, Integer.valueOf(C_Channel_ID));
}
/** Get Channel.
@return Sales Channel
*/
public int getC_Channel_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Channel_ID);
if (ii == null)
return 0; | return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Channel.java | 1 |
请完成以下Java代码 | public I_M_HU_PI_Item_Product getM_HU_PI_ItemProductFor(final Object orderObj, final ProductId productId)
{
Check.assumeInstanceOf(orderObj, I_C_Order.class, "orderObj not null");
final I_C_Order order = InterfaceWrapperHelper.create(orderObj, I_C_Order.class);
final I_M_PriceList_Version plv = Services.get(IOrderBL.class).getPriceListVersion(order);
final I_M_ProductPrice productPrice = ProductPrices.newQuery(plv)
.setProductId(productId)
.onlyAttributePricing()
.onlyValidPrices(true)
.retrieveDefault(I_M_ProductPrice.class);
if (productPrice != null)
{
final HUPIItemProductId packingMaterialId = HUPIItemProductId.ofRepoIdOrNull(productPrice.getM_HU_PI_Item_Product_ID()); | if (packingMaterialId != null)
{
return Services.get(IHUPIItemProductDAO.class).getRecordById(packingMaterialId);
}
}
return null;
}
@Override
public void applyChangesFor(final Object document)
{
// Nothing to do for order.
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pricing\spi\impl\OrderPricingHUDocumentHandler.java | 1 |
请完成以下Java代码 | protected void prepare()
{
for (final ProcessInfoParameter para : getParametersAsArray())
{
if (para.getParameter() == null)
{
continue;
}
final String name = para.getParameterName();
if ("TopicName".equals(name))
{
p_TopicName = para.getParameterAsString();
}
else if ("Summary".equals(name))
{
p_Summary = para.getParameterAsString();
}
else if ("AD_User_ID".equals(name))
{
p_AD_User_ID = para.getParameterAsInt();
}
else if ("Counter".equals(name))
{
p_Counter = para.getParameterAsInt();
}
}
}
@Override
protected String doIt() throws Exception
{
final Topic topic = Topic.builder()
.name(p_TopicName)
.type(Type.DISTRIBUTED)
.build();
final IEventBus eventBus = Services.get(IEventBusFactory.class)
.getEventBus(topic); | for (int i = 1; i <= p_Counter; i++)
{
final String detail = "Topic name: " + p_TopicName
+ "\n Index: " + i + "/" + p_Counter
+ "\n Recipient: " + p_AD_User_ID
+ "\n Sender: " + getAD_User_ID()
+ "\n Summary: " + p_Summary;
eventBus.enqueueEvent(Event.builder()
.setSummary(p_Summary)
.setDetailPlain(detail)
.addRecipient_User_ID(p_AD_User_ID)
.build());
}
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\process\EventBus_SendTestEvent.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
// Make sure at least one shipment schedule is processed
final boolean someSchedsAreProcessed = context.streamSelectedModels(I_M_ShipmentSchedule.class)
.anyMatch(I_M_ShipmentSchedule::isProcessed);
if (!someSchedsAreProcessed)
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_SHIPMENT_SCHEDULES_ALL_NOT_PROCESSED));
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final Iterator<I_M_ShipmentSchedule> scheds = getSelectedShipmentSchedules();
int counter = 0;
for (final I_M_ShipmentSchedule shipmentSchedule : IteratorUtils.asIterable(scheds))
{
if (!shipmentSchedule.isProcessed())
{
addLog(msgBL.getMsg(getCtx(), MSG_SHIPMENT_SCHEDULES_SKIP_OPEN, new Object[] { shipmentSchedule.getM_ShipmentSchedule_ID() }));
continue; | }
openInTrx(shipmentSchedule);
counter++;
}
return "@Processed@: " + counter;
}
private Iterator<I_M_ShipmentSchedule> getSelectedShipmentSchedules()
{
final IQueryFilter<I_M_ShipmentSchedule> selectedSchedsFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false));
return queryBL.createQueryBuilder(I_M_ShipmentSchedule.class)
.addOnlyActiveRecordsFilter()
.filter(selectedSchedsFilter)
.create()
.iterate(I_M_ShipmentSchedule.class);
}
private void openInTrx(final I_M_ShipmentSchedule shipmentSchedule)
{
Services.get(ITrxManager.class)
.runInNewTrx((TrxRunnable)localTrxName -> {
InterfaceWrapperHelper.setThreadInheritedTrxName(shipmentSchedule);
shipmentScheduleBL.openShipmentSchedule(shipmentSchedule);
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ShipmentSchedule_OpenProcessed.java | 1 |
请完成以下Java代码 | public void updateStausIfNeededWhenVoiding(@NonNull final I_C_Flatrate_Term term)
{
final OrderId orderId = contractOrderService.getContractOrderId(term);
if (orderId == null
|| !X_C_Flatrate_Term.CONTRACTSTATUS_Voided.equals(term.getContractStatus()))
{
return;
}
final OrderId parentOrderId = contractOrderService.retrieveLinkedFollowUpContractOrder(orderId);
final ImmutableSet<OrderId> orderIds = parentOrderId == null ? ImmutableSet.of(orderId) : ImmutableSet.of(orderId, parentOrderId);
final List<I_C_Order> orders = orderDAO.getByIds(orderIds, I_C_Order.class);
final I_C_Order contractOrder = orders.get(0);
setContractStatusForCurrentOrder(contractOrder, term);
setContractStatusForParentOrderIfNeeded(orders);
}
private void setContractStatusForCurrentOrder(@NonNull final I_C_Order contractOrder, @NonNull final I_C_Flatrate_Term term)
{
// set status for the current order
final List<I_C_Flatrate_Term> terms = contractsDAO.retrieveFlatrateTermsForOrderIdLatestFirst(OrderId.ofRepoId(contractOrder.getC_Order_ID()));
final boolean anyActiveTerms = terms
.stream()
.anyMatch(currentTerm -> term.getC_Flatrate_Term_ID() != currentTerm.getC_Flatrate_Term_ID()
&& subscriptionBL.isActiveTerm(currentTerm));
contractOrderService.setOrderContractStatusAndSave(contractOrder, anyActiveTerms ? I_C_Order.CONTRACTSTATUS_Active : I_C_Order.CONTRACTSTATUS_Cancelled);
}
private void setContractStatusForParentOrderIfNeeded(final List<I_C_Order> orders)
{ | if (orders.size() == 1) // means that the order does not have parent
{
return;
}
final I_C_Order contractOrder = orders.get(0);
final I_C_Order parentOrder = orders.get(1);
if (isActiveParentContractOrder(parentOrder, contractOrder))
{
contractOrderService.setOrderContractStatusAndSave(parentOrder, I_C_Order.CONTRACTSTATUS_Active);
}
}
private boolean isActiveParentContractOrder(@NonNull final I_C_Order parentOrder, @NonNull final I_C_Order contractOrder)
{
return parentOrder.getC_Order_ID() != contractOrder.getC_Order_ID() // different order from the current one
&& !I_C_Order.CONTRACTSTATUS_Cancelled.equals(parentOrder.getContractStatus()) // current order wasn't previously cancelled, although shall not be possible this
&& I_C_Order.CONTRACTSTATUS_Cancelled.equals(contractOrder.getContractStatus()); // current order was cancelled
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\order\UpdateContractOrderStatus.java | 1 |
请完成以下Java代码 | public class AiragKnowledge implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "主键")
private java.lang.String id;
/**
* 创建人
*/
@Schema(description = "创建人")
@Dict(dictTable = "sys_user",dicCode = "username",dicText = "realname")
private java.lang.String createBy;
/**
* 创建日期
*/
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "创建日期")
private java.util.Date createTime;
/**
* 更新人
*/
@Schema(description = "更新人")
private java.lang.String updateBy;
/**
* 更新日期
*/
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "更新日期")
private java.util.Date updateTime;
/**
* 所属部门 | */
@Schema(description = "所属部门")
private java.lang.String sysOrgCode;
/**
* 租户id
*/
@Excel(name = "租户id", width = 15)
@Schema(description = "租户id")
private java.lang.String tenantId;
/**
* 知识库名称
*/
@Excel(name = "知识库名称", width = 15)
@Schema(description = "知识库名称")
private java.lang.String name;
/**
* 向量模型id
*/
@Excel(name = "向量模型id", width = 15, dictTable = "airag_model where model_type = 'EMBED'", dicText = "name", dicCode = "id")
@Dict(dictTable = "airag_model where model_type = 'EMBED'", dicText = "name", dicCode = "id")
@Schema(description = "向量模型id")
private java.lang.String embedId;
/**
* 描述
*/
@Excel(name = "描述", width = 15)
@Schema(description = "描述")
private java.lang.String descr;
/**
* 状态
*/
@Excel(name = "状态", width = 15)
@Schema(description = "状态")
private java.lang.String status;
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\llm\entity\AiragKnowledge.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private String getCauseMessage(Exception e) {
String message;
if (e.getCause() != null && StringUtils.isNotEmpty(e.getCause().getMessage())) {
message = e.getCause().getMessage();
} else {
message = e.getMessage();
}
return message;
}
private void registerResult(EntitiesImportCtx ctx, EntityType entityType, EntityImportResult<?> importResult) {
if (importResult.isCreated()) {
ctx.registerResult(entityType, true);
} else if (importResult.isUpdated() || importResult.isUpdatedRelatedEntities()) {
ctx.registerResult(entityType, false);
}
}
private void processCommitError(User user, VersionCreateRequest request, CommitGitRequest commit, Throwable e) {
log.debug("[{}] Failed to prepare the commit: {}", user.getId(), request, e);
cachePut(commit.getTxId(), new VersionCreationResult(e.getMessage()));
} | private void processLoadError(EntitiesImportCtx ctx, Throwable e) {
log.debug("[{}] Failed to load the commit: {}", ctx.getRequestId(), ctx.getVersionId(), e);
cachePut(ctx.getRequestId(), VersionLoadResult.error(EntityLoadError.runtimeError(e)));
}
private void cachePut(UUID requestId, VersionCreationResult result) {
taskCache.put(requestId, VersionControlTaskCacheEntry.newForExport(result));
}
private VersionLoadResult cachePut(UUID requestId, VersionLoadResult result) {
log.trace("[{}] Cache put: {}", requestId, result);
taskCache.put(requestId, VersionControlTaskCacheEntry.newForImport(result));
return result;
}
private void persistToCache(EntitiesImportCtx ctx) {
cachePut(ctx.getRequestId(), VersionLoadResult.success(new ArrayList<>(ctx.getResults().values())));
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\vc\DefaultEntitiesVersionControlService.java | 2 |
请完成以下Java代码 | public RegisteredClient getRegisteredClient() {
return get(RegisteredClient.class);
}
/**
* Constructs a new {@link Builder} with the provided
* {@link OidcLogoutAuthenticationToken}.
* @param authentication the {@link OidcLogoutAuthenticationToken}
* @return the {@link Builder}
*/
public static Builder with(OidcLogoutAuthenticationToken authentication) {
return new Builder(authentication);
}
/**
* A builder for {@link OidcLogoutAuthenticationContext}.
*/
public static final class Builder extends AbstractBuilder<OidcLogoutAuthenticationContext, Builder> {
private Builder(OidcLogoutAuthenticationToken authentication) {
super(authentication);
}
/**
* Sets the {@link RegisteredClient registered client}.
* @param registeredClient the {@link RegisteredClient}
* @return the {@link Builder} for further configuration
*/
public Builder registeredClient(RegisteredClient registeredClient) {
return put(RegisteredClient.class, registeredClient); | }
/**
* Builds a new {@link OidcLogoutAuthenticationContext}.
* @return the {@link OidcLogoutAuthenticationContext}
*/
@Override
public OidcLogoutAuthenticationContext build() {
Assert.notNull(get(RegisteredClient.class), "registeredClient cannot be null");
return new OidcLogoutAuthenticationContext(getContext());
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\authentication\OidcLogoutAuthenticationContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "oneTaskCase")
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@ApiModelProperty(example = "1")
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
@ApiModelProperty(example = "The One Task Case")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "2")
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@ApiModelProperty(example = "http://localhost:8081/cmmn-repository/deployments/2")
public String getDeploymentUrl() {
return deploymentUrl;
}
public void setDeploymentUrl(String deploymentUrl) {
this.deploymentUrl = deploymentUrl;
}
@ApiModelProperty(example = "Examples")
public String getCategory() {
return category;
}
public void setCategory(String category) { | this.category = category;
}
public void setResource(String resource) {
this.resource = resource;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-repository/deployments/2/resources/testCase.cmmn", value = "Contains the actual deployed CMMN 1.1 xml.")
public String getResource() {
return resource;
}
@ApiModelProperty(example = "This is a case for testing purposes")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setDiagramResource(String diagramResource) {
this.diagramResource = diagramResource;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-repository/deployments/2/resources/testProcess.png", value = "Contains a graphical representation of the case, null when no diagram is available.")
public String getDiagramResource() {
return diagramResource;
}
public void setGraphicalNotationDefined(boolean graphicalNotationDefined) {
this.graphicalNotationDefined = graphicalNotationDefined;
}
@ApiModelProperty(value = "Indicates the case definition contains graphical information (CMMN DI).")
public boolean isGraphicalNotationDefined() {
return graphicalNotationDefined;
}
public void setStartFormDefined(boolean startFormDefined) {
this.startFormDefined = startFormDefined;
}
public boolean isStartFormDefined() {
return startFormDefined;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\CaseDefinitionResponse.java | 2 |
请完成以下Java代码 | abstract class OracleJdbcDockerComposeConnectionDetailsFactory
extends DockerComposeConnectionDetailsFactory<JdbcConnectionDetails> {
private final String defaultDatabase;
protected OracleJdbcDockerComposeConnectionDetailsFactory(OracleContainer container) {
super(container.getImageName());
this.defaultDatabase = container.getDefaultDatabase();
}
@Override
protected JdbcConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) {
return new OracleJdbcDockerComposeConnectionDetails(source.getRunningService(), this.defaultDatabase);
}
/**
* {@link JdbcConnectionDetails} backed by an {@code oracle-xe} or {@code oracle-free}
* {@link RunningService}.
*/
static class OracleJdbcDockerComposeConnectionDetails extends DockerComposeConnectionDetails
implements JdbcConnectionDetails {
private static final String PARAMETERS_LABEL = "org.springframework.boot.jdbc.parameters";
private final OracleEnvironment environment;
private final String jdbcUrl;
OracleJdbcDockerComposeConnectionDetails(RunningService service, String defaultDatabase) { | super(service);
this.environment = new OracleEnvironment(service.env(), defaultDatabase);
this.jdbcUrl = "jdbc:oracle:thin:@" + service.host() + ":" + service.ports().get(1521) + "/"
+ this.environment.getDatabase() + getParameters(service);
}
private String getParameters(RunningService service) {
String parameters = service.labels().get(PARAMETERS_LABEL);
return (StringUtils.hasLength(parameters)) ? "?" + parameters : "";
}
@Override
public String getUsername() {
return this.environment.getUsername();
}
@Override
public String getPassword() {
return this.environment.getPassword();
}
@Override
public String getJdbcUrl() {
return this.jdbcUrl;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\docker\compose\OracleJdbcDockerComposeConnectionDetailsFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void mergeMigration(final I_AD_Migration to, final I_AD_Migration from)
{
Services.get(IMigrationDAO.class).mergeMigration(to, from);
}
@Override
public String getSummary(I_AD_Migration migration)
{
if (migration == null)
{
return "";
}
return "Migration["
+ migration.getSeqNo() + "-" + migration.getName() + "-" + migration.getEntityType()
+ ", ID=" + migration.getAD_Migration_ID()
+ "]";
}
@Override
public void setSeqNo(final I_AD_Migration migration)
{
final int maxSeqNo = Services.get(IMigrationDAO.class).getMigrationLastSeqNo(migration);
final int nextSeqNo = maxSeqNo + 10; | migration.setSeqNo(nextSeqNo);
}
@Override
public String getSummary(final I_AD_MigrationStep step)
{
if (step == null)
{
return "";
}
final I_AD_Migration parent = step.getAD_Migration();
return "Migration: " + parent.getName() + ", Step: " + step.getSeqNo() + ", Type: " + step.getStepType();
}
@Override
public void setSeqNo(final I_AD_MigrationStep step)
{
final int maxSeqNo = Services.get(IMigrationDAO.class).getMigrationStepLastSeqNo(step);
final int nextSeqNo = maxSeqNo + 10;
step.setSeqNo(nextSeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\service\impl\MigrationBL.java | 2 |
请完成以下Java代码 | class DocumentArchiveEntry implements IDocumentAttachmentEntry
{
private final IArchiveBL archiveBL = Services.get(IArchiveBL.class);
/* package */
static DocumentArchiveEntry of(final DocumentId id, final I_AD_Archive archive)
{
return new DocumentArchiveEntry(id, archive);
}
private final DocumentId id;
private final I_AD_Archive archive;
private DocumentArchiveEntry(final DocumentId id, final I_AD_Archive archive)
{
this.id = id;
this.archive = archive;
}
@Override
public DocumentId getId()
{
return id;
}
@Override
public AttachmentEntryType getType()
{
return AttachmentEntryType.Data;
}
@Override
public String getFilename()
{
final String contentType = getContentType();
final String fileExtension = MimeType.getExtensionByType(contentType);
final String name = archive.getName();
return FileUtil.changeFileExtension(name, fileExtension);
}
@Override | public byte[] getData()
{
return archiveBL.getBinaryData(archive);
}
@Override
public String getContentType()
{
return archiveBL.getContentType(archive);
}
@Override
public URI getUrl()
{
return null;
}
@Override
public Instant getCreated()
{
return archive.getCreated().toInstant();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attachments\DocumentArchiveEntry.java | 1 |
请完成以下Java代码 | public boolean isBreaksDiscountType()
{
return PricingConditionsDiscountType.BREAKS.equals(discountType);
}
/**
* Pick the first break that applies based on product, category and attribute instance
*
* @return schema break or null
*/
public PricingConditionsBreak pickApplyingBreak(final @NonNull PricingConditionsBreakQuery query)
{
final BigDecimal breakValue = extractBreakValue(query);
if (breakValue == null)
{
return null;
}
return breaks.stream()
.sorted(SORT_BY_BREAK_VALUE_DESC)
.filter(schemaBreak -> schemaBreakMatches(schemaBreak, breakValue, query))
.findFirst()
.orElse(null);
}
private boolean schemaBreakMatches(
final PricingConditionsBreak schemaBreak,
final BigDecimal breakValue,
final PricingConditionsBreakQuery query)
{
final PricingConditionsBreakMatchCriteria matchCriteria = schemaBreak.getMatchCriteria();
return matchCriteria.breakValueMatches(breakValue)
&& matchCriteria.productMatches(query.getProduct())
&& matchCriteria.attributeMatches(query.getAttributes());
}
private BigDecimal extractBreakValue(final PricingConditionsBreakQuery query)
{
if (!isBreaksDiscountType())
{
throw new AdempiereException("DiscountType shall be Breaks: " + this);
}
else if (breakValueType == BreakValueType.QUANTITY)
{
return query.getQty();
} | else if (breakValueType == BreakValueType.AMOUNT)
{
return query.getAmt();
}
else if (breakValueType == BreakValueType.ATTRIBUTE)
{
final ImmutableAttributeSet attributes = query.getAttributes();
if (attributes.hasAttribute(breakAttributeId))
{
return attributes.getValueAsBigDecimal(breakAttributeId);
}
else
{
return null;
}
}
else
{
throw new AdempiereException("Unknown break value type: " + breakValueType);
}
}
public Stream<PricingConditionsBreak> streamBreaksMatchingAnyOfProducts(final Set<ProductAndCategoryAndManufacturerId> products)
{
Check.assumeNotEmpty(products, "products is not empty");
return getBreaks()
.stream()
.filter(schemaBreak -> schemaBreak.getMatchCriteria().productMatchesAnyOf(products));
}
public PricingConditionsBreak getBreakById(@NonNull final PricingConditionsBreakId breakId)
{
PricingConditionsBreakId.assertMatching(getId(), breakId);
return getBreaks()
.stream()
.filter(schemaBreak -> breakId.equals(schemaBreak.getId()))
.findFirst()
.orElseThrow(() -> new AdempiereException("No break found for " + breakId + " in " + this));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\PricingConditions.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
/*
* The parameter of this method is a FilterInvocation. Developers can extract the currently requested URL from the FilterInvocation.
* The return value is Collection<ConfigAttribute>, indicating the role required by the current request URL.
*/
String requestUrl = ((FilterInvocation) object).getRequestUrl();
/*
* Obtain all resource information from the database, that is, the menu table in this case and the role corresponding to the menu,
* In a real project environment, developers can cache resource information in Redis or other cache databases.
*/
List<Menu> allMenus = menuMapper.getAllMenus();
// Traverse the resource information. During the traversal process, obtain the role information required for the currently requested URL and return it.
for (Menu menu : allMenus) {
if (antPathMatcher.match(menu.getPattern(), requestUrl)) {
List<Role> roles = menu.getRoles();
String[] roleArr = new String[roles.size()];
for (int i = 0; i < roleArr.length; i++) {
roleArr[i] = roles.get(i).getName();
}
return SecurityConfig.createList(roleArr);
}
}
// If the currently requested URL does not have a corresponding pattern in the resource table, it is assumed that the request can be accessed after logging in, that is, ROLE_LOGIN is returned directly.
return SecurityConfig.createList("ROLE_LOGIN");
}
/**
* The getAllConfigAttributes method is used to return all defined permission resources. SpringSecurity will verify whether the relevant configuration is correct when starting. | * If verification is not required, this method can directly return null.
*/
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
/**
* The supports method returns whether the class object supports verification.
*/
@Override
public boolean supports(Class<?> clazz) {
return FilterInvocation.class.isAssignableFrom(clazz);
}
} | repos\springboot-demo-master\security\src\main\java\com\et\security\config\CustomFilterInvocationSecurityMetadataSource.java | 2 |
请完成以下Java代码 | public long iterateValuesUsingLambdaAndForEach() {
return mapIteration.iterateValuesUsingLambdaAndForEach(map);
}
@Benchmark
public long iterateUsingIteratorAndKeySet() {
return mapIteration.iterateUsingIteratorAndKeySet(map);
}
@Benchmark
public long iterateUsingIteratorAndEntrySet() {
return mapIteration.iterateUsingIteratorAndEntrySet(map);
}
@Benchmark
public long iterateUsingKeySetAndEnhanceForLoop() {
return mapIteration.iterateUsingKeySetAndEnhanceForLoop(map);
}
@Benchmark
public long iterateUsingStreamAPIAndEntrySet() {
return mapIteration.iterateUsingStreamAPIAndEntrySet(map);
}
@Benchmark
public long iterateUsingStreamAPIAndKeySet() {
return mapIteration.iterateUsingStreamAPIAndKeySet(map); | }
@Benchmark
public long iterateKeysUsingKeySetAndEnhanceForLoop() {
return mapIteration.iterateKeysUsingKeySetAndEnhanceForLoop(map);
}
@Benchmark
public long iterateUsingMapIteratorApacheCollection() {
return mapIteration.iterateUsingMapIteratorApacheCollection(iterableMap);
}
@Benchmark
public long iterateEclipseMap() throws IOException {
return mapIteration.iterateEclipseMap(mutableMap);
}
@Benchmark
public long iterateMapUsingParallelStreamApi() throws IOException {
return mapIteration.iterateMapUsingParallelStreamApi(map);
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\iteration\MapIterationBenchmark.java | 1 |
请完成以下Java代码 | public MediaSize getMediaSizeDefault()
{
m_mediaSize = Language.getLoginLanguage().getMediaSize();
if (m_mediaSize == null)
m_mediaSize = MediaSize.ISO.A4;
log.debug("Size=" + m_mediaSize);
return m_mediaSize;
} // getMediaSizeDefault
/**
* Get Units Int
* @return units
*/
public int getUnitsInt()
{
String du = getDimensionUnits();
if (du == null || DIMENSIONUNITS_MM.equals(du))
return Size2DSyntax.MM;
else if (DIMENSIONUNITS_Inch.equals(du))
return Size2DSyntax.INCH;
else
throw new AdempiereException("@NotSupported@ @DimensionUnit@ : "+du);
} // getUnits
/**
* Get CPaper
* @return CPaper
*/
public CPaper getCPaper()
{
//Modify Lines By AA Goodwill : Custom Paper Support
CPaper retValue;
if (getCode().toLowerCase().startsWith("custom"))
{
retValue = new CPaper (getSizeX().doubleValue(), getSizeY().doubleValue(), getUnitsInt(),
isLandscape(),
getMarginLeft(), getMarginTop(), getMarginRight(), getMarginBottom());
}
else
{
retValue = new CPaper (getMediaSize(), isLandscape(),
getMarginLeft(), getMarginTop(), getMarginRight(), getMarginBottom());
}
//End Of AA Goodwill
return retValue;
} // getCPaper
@Override
protected boolean beforeSave(boolean newRecord)
{
// Check all settings are correct by reload all data
m_mediaSize = null;
getMediaSize();
getCPaper();
return true;
}
/**
* Media Size Name
*/
class CMediaSizeName extends MediaSizeName
{
/**
*
*/
private static final long serialVersionUID = 8561532175435930293L;
/**
* CMediaSizeName
* @param code
*/
public CMediaSizeName(int code)
{
super (code);
} // CMediaSizeName
/**
* Get String Table | * @return string
*/
public String[] getStringTable ()
{
return super.getStringTable ();
}
/**
* Get Enum Value Table
* @return Media Sizes
*/
public EnumSyntax[] getEnumValueTable ()
{
return super.getEnumValueTable ();
}
} // CMediaSizeName
/**************************************************************************
* Test
* @param args args
*/
public static void main(String[] args)
{
org.compiere.Adempiere.startupEnvironment(true);
// create ("Standard Landscape", true);
// create ("Standard Portrait", false);
// Read All Papers
int[] IDs = PO.getAllIDs ("AD_PrintPaper", null, null);
for (int i = 0; i < IDs.length; i++)
{
System.out.println("--");
MPrintPaper pp = new MPrintPaper(Env.getCtx(), IDs[i], null);
pp.dump();
}
}
} // MPrintPaper | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintPaper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
FileInfo fileInfo = (FileInfo)o;
return Objects.equals(this.fileId, fileInfo.fileId) &&
Objects.equals(this.fileType, fileInfo.fileType) &&
Objects.equals(this.name, fileInfo.name) &&
Objects.equals(this.uploadedDate, fileInfo.uploadedDate);
}
@Override
public int hashCode()
{
return Objects.hash(fileId, fileType, name, uploadedDate);
}
@Override
public String toString()
{ | StringBuilder sb = new StringBuilder();
sb.append("class FileInfo {\n");
sb.append(" fileId: ").append(toIndentedString(fileId)).append("\n");
sb.append(" fileType: ").append(toIndentedString(fileType)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" uploadedDate: ").append(toIndentedString(uploadedDate)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\FileInfo.java | 2 |
请完成以下Java代码 | private String getName(String name, boolean getFirst)
{
if (name == null || name.length() == 0)
{
return "";
}
String first = null;
String last = null;
// Janke, Jorg R - Jorg R Janke
// double names not handled gracefully nor titles
// nor (former) aristrocratic world de/la/von
boolean lastFirst = name.indexOf(',') != -1;
StringTokenizer st = null;
if (lastFirst)
{
st = new StringTokenizer(name, ",");
}
else
{
st = new StringTokenizer(name, " ");
}
while (st.hasMoreTokens())
{
String s = st.nextToken().trim();
if (lastFirst)
{
if (last == null)
{
last = s;
}
else if (first == null)
{
first = s;
}
}
else
{
if (first == null)
{
first = s;
}
else
{
last = s;
}
}
}
if (getFirst)
{
if (first == null)
{
return "";
}
return first.trim();
}
if (last == null)
{
return "";
}
return last.trim();
} // getName
/**
* String Representation
*
* @return Info
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder("MUser[")
.append(get_ID())
.append(",Name=").append(getName()) | .append(",EMail=").append(getEMail())
.append("]");
return sb.toString();
} // toString
/**
* Set EMail - reset validation
*
* @param EMail email
*/
@Override
public void setEMail(String EMail)
{
super.setEMail(EMail);
setEMailVerifyDate(null);
} // setEMail
/**
* Before Save
*
* @param newRecord new
* @return true
*/
@Override
protected boolean beforeSave(boolean newRecord)
{
// New Address invalidates verification
if (!newRecord && is_ValueChanged("EMail"))
{
setEMailVerifyDate(null);
}
if (newRecord || super.getValue() == null || is_ValueChanged("Value"))
{
setValue(super.getValue());
}
return true;
} // beforeSave
} // MUser | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MUser.java | 1 |
请完成以下Java代码 | public List<String> benchmarkGuavaSplitter() {
return Splitter.on(" ").trimResults()
.omitEmptyStrings()
.splitToList(longString);
}
@Benchmark
public String [] benchmarkStringSplit() {
return longString.split(emptyString);
}
@Benchmark
public String [] benchmarkStringSplitPattern() {
return spacePattern.split(longString, 0);
}
@Benchmark
public List benchmarkStringTokenizer() {
StringTokenizer st = new StringTokenizer(longString);
while (st.hasMoreTokens()) {
stringTokenizer.add(st.nextToken());
}
return stringTokenizer;
}
@Benchmark
public List benchmarkStringIndexOf() {
int pos = 0, end;
while ((end = longString.indexOf(' ', pos)) >= 0) {
stringSplit.add(longString.substring(pos, end));
pos = end + 1;
}
//Add last token of string
stringSplit.add(longString.substring(pos));
return stringSplit;
}
@Benchmark
public String benchmarkIntegerToString() {
return Integer.toString(sampleNumber);
}
@Benchmark
public String benchmarkStringValueOf() {
return String.valueOf(sampleNumber);
}
@Benchmark
public String benchmarkStringConvertPlus() {
return sampleNumber + "";
}
@Benchmark
public String benchmarkStringFormat_d() {
return String.format(formatDigit, sampleNumber);
}
@Benchmark
public boolean benchmarkStringEquals() {
return longString.equals(baeldung); | }
@Benchmark
public boolean benchmarkStringEqualsIgnoreCase() {
return longString.equalsIgnoreCase(baeldung);
}
@Benchmark
public boolean benchmarkStringMatches() {
return longString.matches(baeldung);
}
@Benchmark
public boolean benchmarkPrecompiledMatches() {
return longPattern.matcher(baeldung).matches();
}
@Benchmark
public int benchmarkStringCompareTo() {
return longString.compareTo(baeldung);
}
@Benchmark
public boolean benchmarkStringIsEmpty() {
return longString.isEmpty();
}
@Benchmark
public boolean benchmarkStringLengthZero() {
return longString.length() == 0;
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(StringPerformance.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
} | repos\tutorials-master\core-java-modules\core-java-strings\src\main\java\com\baeldung\stringperformance\StringPerformance.java | 1 |
请完成以下Java代码 | public int getM_QualityInsp_LagerKonf_AdditionalFee_ID()
{
return get_ValueAsInt(COLUMNNAME_M_QualityInsp_LagerKonf_AdditionalFee_ID);
}
@Override
public I_M_QualityInsp_LagerKonf_Version getM_QualityInsp_LagerKonf_Version()
{
return get_ValueAsPO(COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, I_M_QualityInsp_LagerKonf_Version.class);
}
@Override
public void setM_QualityInsp_LagerKonf_Version(final I_M_QualityInsp_LagerKonf_Version M_QualityInsp_LagerKonf_Version)
{
set_ValueFromPO(COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, I_M_QualityInsp_LagerKonf_Version.class, M_QualityInsp_LagerKonf_Version);
}
@Override
public void setM_QualityInsp_LagerKonf_Version_ID (final int M_QualityInsp_LagerKonf_Version_ID)
{
if (M_QualityInsp_LagerKonf_Version_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, M_QualityInsp_LagerKonf_Version_ID);
} | @Override
public int getM_QualityInsp_LagerKonf_Version_ID()
{
return get_ValueAsInt(COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_QualityInsp_LagerKonf_AdditionalFee.java | 1 |
请完成以下Java代码 | public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public Date getStartTime() {
return startTime;
}
@Override
public Date getEndTime() {
return endTime;
}
@Override
public Long getDurationInMillis() {
return durationInMillis;
}
@Override
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
} | @Override
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@Override
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
@Override
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
@Override
public void setDurationInMillis(Long durationInMillis) {
this.durationInMillis = durationInMillis;
}
@Override
public String getDeleteReason() {
return deleteReason;
}
@Override
public void setDeleteReason(String deleteReason) {
this.deleteReason = deleteReason;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricScopeInstanceEntityImpl.java | 1 |
请完成以下Java代码 | public String getExecutionId() {
return executionId;
}
/** Follow-up date of the task. */
public Date getFollowUpDate() {
return followUpDate;
}
/** DB id of the task. */
public String getId() {
return id;
}
/**
* The date/time when this task was last updated.
* All operations that fire {@link TaskListener#EVENTNAME_UPDATE} count as an update to the task.
* Returns null if the task was never updated before (i.e. it was only created).
* */
public Date getLastUpdated() {
return lastUpdated;
}
/** Name or title of the task. */
public String getName() {
return name;
}
/**
* The {@link User.getId() userId} of the person responsible for this task.
*/
public String getOwner() {
return owner;
}
/**
* indication of how important/urgent this task is with a number between 0 and
* 100 where higher values mean a higher priority and lower values mean lower
* priority: [0..19] lowest, [20..39] low, [40..59] normal, [60..79] high
* [80..100] highest
*/
public int getPriority() {
return priority;
}
/**
* Reference to the process definition or null if it is not related to a
* process.
*/
public String getProcessDefinitionId() {
return processDefinitionId;
}
/**
* Reference to the process instance or null if it is not related to a process
* instance.
*/ | public String getProcessInstanceId() {
return processInstanceId;
}
/**
* The id of the activity in the process defining this task or null if this is
* not related to a process
*/
public String getTaskDefinitionKey() {
return taskDefinitionKey;
}
/**
* Return the id of the tenant this task belongs to. Can be <code>null</code>
* if the task belongs to no single tenant.
*/
public String getTenantId() {
return tenantId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", eventName=" + eventName
+ ", name=" + name
+ ", createTime=" + createTime
+ ", lastUpdated=" + lastUpdated
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", processInstanceId=" + processInstanceId
+ ", taskDefinitionKey=" + taskDefinitionKey
+ ", assignee=" + assignee
+ ", owner=" + owner
+ ", description=" + description
+ ", dueDate=" + dueDate
+ ", followUpDate=" + followUpDate
+ ", priority=" + priority
+ ", deleteReason=" + deleteReason
+ ", caseDefinitionId=" + caseDefinitionId
+ ", caseExecutionId=" + caseExecutionId
+ ", caseInstanceId=" + caseInstanceId
+ ", tenantId=" + tenantId
+ "]";
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\TaskEvent.java | 1 |
请完成以下Java代码 | public Duration getDefaultLookupSearchStartDelay()
{
final Duration duration = defaultLookupSearchStartDelaySupplier.get();
return duration != null ? duration : Duration.ZERO;
}
public Predicate<DocumentLayoutElementDescriptor> documentLayoutElementFilter()
{
if (_documentLayoutElementFilter == null)
{
_documentLayoutElementFilter = isShowAdvancedFields() ? FILTER_DocumentLayoutElementDescriptor_ALL : FILTER_DocumentLayoutElementDescriptor_BASIC;
}
return _documentLayoutElementFilter;
}
private static final Predicate<DocumentLayoutElementDescriptor> FILTER_DocumentLayoutElementDescriptor_BASIC = new Predicate<DocumentLayoutElementDescriptor>()
{
@Override
public String toString()
{
return "basic layout elements";
}
@Override
public boolean test(final DocumentLayoutElementDescriptor layoutElement)
{
return !layoutElement.isAdvancedField();
}
};
private static final Predicate<DocumentLayoutElementDescriptor> FILTER_DocumentLayoutElementDescriptor_ALL = new Predicate<DocumentLayoutElementDescriptor>()
{ | @Override
public String toString()
{
return "all layout elements";
}
@Override
public boolean test(final DocumentLayoutElementDescriptor layoutElement)
{
return true;
}
};
public String getAdLanguage()
{
return getJsonOpts().getAdLanguage();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentLayoutOptions.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CostDetail
{
@With CostDetailId id;
@NonNull ClientId clientId;
@NonNull OrgId orgId;
@NonNull AcctSchemaId acctSchemaId;
@NonNull CostElementId costElementId;
@NonNull ProductId productId;
@NonNull AttributeSetInstanceId attributeSetInstanceId;
@NonNull CostAmountType amtType;
@NonNull CostAmount amt;
@NonNull @With Quantity qty;
@With boolean changingCosts;
CostDetailPreviousAmounts previousAmounts;
@NonNull CostingDocumentRef documentRef;
@Nullable String description;
@NonNull @With Instant dateAcct;
@Builder
private CostDetail(
final CostDetailId id,
@NonNull final ClientId clientId,
@NonNull final OrgId orgId,
@NonNull final AcctSchemaId acctSchemaId,
@NonNull final CostElementId costElementId,
@NonNull final ProductId productId,
@NonNull final AttributeSetInstanceId attributeSetInstanceId,
@NonNull final CostAmountType amtType,
@NonNull final CostAmount amt,
@NonNull final Quantity qty,
final boolean changingCosts,
final CostDetailPreviousAmounts previousAmounts,
@NonNull final CostingDocumentRef documentRef,
@Nullable final String description,
@NonNull Instant dateAcct)
{
this.id = id;
this.clientId = clientId;
this.orgId = orgId;
this.acctSchemaId = acctSchemaId;
this.costElementId = costElementId;
this.productId = productId;
this.attributeSetInstanceId = attributeSetInstanceId;
this.amtType = amtType;
this.amt = amt;
this.qty = qty;
this.changingCosts = changingCosts;
this.previousAmounts = previousAmounts;
this.documentRef = documentRef;
this.description = description;
this.dateAcct = dateAcct;
if (this.previousAmounts != null | && !CurrencyId.equals(this.previousAmounts.getCurrencyId(), amt.getCurrencyId()))
{
throw new AdempiereException("Previous amounts shall have same currency as the amount: " + this);
}
}
public boolean isInboundTrx()
{
return !isOutboundTrx();
}
public boolean isOutboundTrx()
{
final Boolean outboundTrx = getDocumentRef().getOutboundTrx();
if (outboundTrx != null)
{
return outboundTrx;
}
else
{
return getQty().signum() < 0;
}
}
public CostAmountAndQtyDetailed getAmtAndQtyDetailed() {return CostAmountAndQtyDetailed.of(amt, qty, amtType);}
public CostAmount computePartialCostAmount(@NonNull final Quantity qty, @NonNull final CurrencyPrecision precision)
{
if (qty.equalsIgnoreSource(this.qty))
{
return amt;
}
else if (qty.isZero())
{
return amt.toZero();
}
else
{
final CostAmount price = amt.divide(this.qty, CurrencyPrecision.ofInt(12));
return price.multiply(qty.toBigDecimal()).roundToPrecisionIfNeeded(precision);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostDetail.java | 2 |
请完成以下Java代码 | public void add(CommonStructuredLogFormat format, CommonFormatterFactory<E> factory) {
this.factories.put(format, factory);
}
Collection<String> getCommonNames() {
return this.factories.keySet().stream().map(CommonStructuredLogFormat::getId).toList();
}
@Nullable StructuredLogFormatter<E> get(Instantiator<?> instantiator, String format) {
CommonStructuredLogFormat commonFormat = CommonStructuredLogFormat.forId(format);
CommonFormatterFactory<E> factory = (commonFormat != null) ? this.factories.get(commonFormat) : null;
return (factory != null) ? factory.createFormatter(instantiator) : null;
}
}
/**
* Factory used to create a {@link StructuredLogFormatter} for a given
* {@link CommonStructuredLogFormat}.
*
* @param <E> the log event type
*/
@FunctionalInterface
public interface CommonFormatterFactory<E> {
/**
* Create the {@link StructuredLogFormatter} instance.
* @param instantiator instantiator that can be used to obtain arguments
* @return a new {@link StructuredLogFormatter} instance
*/
StructuredLogFormatter<E> createFormatter(Instantiator<?> instantiator);
}
/**
* {@link StructuredLoggingJsonMembersCustomizer.Builder} implementation.
*/
class JsonMembersCustomizerBuilder implements StructuredLoggingJsonMembersCustomizer.Builder<E> {
private final @Nullable StructuredLoggingJsonProperties properties;
private boolean nested;
JsonMembersCustomizerBuilder(@Nullable StructuredLoggingJsonProperties properties) {
this.properties = properties;
}
@Override
public JsonMembersCustomizerBuilder nested(boolean nested) {
this.nested = nested;
return this;
}
@Override
public StructuredLoggingJsonMembersCustomizer<E> build() {
return (members) -> {
List<StructuredLoggingJsonMembersCustomizer<?>> customizers = new ArrayList<>(); | if (this.properties != null) {
customizers.add(new StructuredLoggingJsonPropertiesJsonMembersCustomizer(
StructuredLogFormatterFactory.this.instantiator, this.properties, this.nested));
}
customizers.addAll(loadStructuredLoggingJsonMembersCustomizers());
invokeCustomizers(members, customizers);
};
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private List<StructuredLoggingJsonMembersCustomizer<?>> loadStructuredLoggingJsonMembersCustomizers() {
return (List) StructuredLogFormatterFactory.this.factoriesLoader.load(
StructuredLoggingJsonMembersCustomizer.class,
ArgumentResolver.from(StructuredLogFormatterFactory.this.instantiator::getArg));
}
@SuppressWarnings("unchecked")
private void invokeCustomizers(Members<E> members,
List<StructuredLoggingJsonMembersCustomizer<?>> customizers) {
LambdaSafe.callbacks(StructuredLoggingJsonMembersCustomizer.class, customizers, members)
.withFilter(LambdaSafe.Filter.allowAll())
.invoke((customizer) -> customizer.customize(members));
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\structured\StructuredLogFormatterFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
@ApiModelProperty(example = "12345")
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
@ApiModelProperty(example = "oneMilestoneCase%3A1%3A4")
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public void setCaseDefinitionId(String caseDefinitionId) {
this.caseDefinitionId = caseDefinitionId;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-milestone-instances/5")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
} | @ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-case-instances/12345")
public String getHistoricCaseInstanceUrl() {
return historicCaseInstanceUrl;
}
public void setHistoricCaseInstanceUrl(String historicCaseInstanceUrl) {
this.historicCaseInstanceUrl = historicCaseInstanceUrl;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-repository/case-definitions/oneMilestoneCase%3A1%3A4")
public String getCaseDefinitionUrl() {
return caseDefinitionUrl;
}
public void setCaseDefinitionUrl(String caseDefinitionUrl) {
this.caseDefinitionUrl = caseDefinitionUrl;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\milestone\HistoricMilestoneInstanceResponse.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Map<String, List<String>> getImgCache() {
return imgCache;
}
@Override
public List<String> getImgCache(String key) {
if(StringUtils.isEmpty(key)){
return new ArrayList<>();
}
return imgCache.get(key);
}
@Override
public Integer getPdfImageCache(String key) {
return pdfImagesCache.get(key);
}
@Override
public void putPdfImageCache(String pdfFilePath, int num) {
pdfImagesCache.put(pdfFilePath, num);
}
@Override
public Map<String, String> getMediaConvertCache() {
return mediaConvertCache;
}
@Override
public void putMediaConvertCache(String key, String value) {
mediaConvertCache.put(key, value);
}
@Override
public String getMediaConvertCache(String key) {
return mediaConvertCache.get(key);
}
@Override
public void cleanCache() {
initPDFCachePool(CacheService.DEFAULT_PDF_CAPACITY);
initIMGCachePool(CacheService.DEFAULT_IMG_CAPACITY);
initPdfImagesCachePool(CacheService.DEFAULT_PDFIMG_CAPACITY);
initMediaConvertCachePool(CacheService.DEFAULT_MEDIACONVERT_CAPACITY);
}
@Override
public void addQueueTask(String url) {
blockingQueue.add(url);
}
@Override
public String takeQueueTask() throws InterruptedException {
return blockingQueue.take(); | }
@Override
public void initPDFCachePool(Integer capacity) {
pdfCache = new ConcurrentLinkedHashMap.Builder<String, String>()
.maximumWeightedCapacity(capacity).weigher(Weighers.singleton())
.build();
}
@Override
public void initIMGCachePool(Integer capacity) {
imgCache = new ConcurrentLinkedHashMap.Builder<String, List<String>>()
.maximumWeightedCapacity(capacity).weigher(Weighers.singleton())
.build();
}
@Override
public void initPdfImagesCachePool(Integer capacity) {
pdfImagesCache = new ConcurrentLinkedHashMap.Builder<String, Integer>()
.maximumWeightedCapacity(capacity).weigher(Weighers.singleton())
.build();
}
@Override
public void initMediaConvertCachePool(Integer capacity) {
mediaConvertCache = new ConcurrentLinkedHashMap.Builder<String, String>()
.maximumWeightedCapacity(capacity).weigher(Weighers.singleton())
.build();
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\service\cache\impl\CacheServiceJDKImpl.java | 2 |
请完成以下Java代码 | private void getAllKeysUsingJsonNodeFields(JsonNode jsonNode, List<String> keys) {
if (jsonNode.isObject()) {
Iterator<Entry<String, JsonNode>> fields = jsonNode.fields();
fields.forEachRemaining(field -> {
keys.add(field.getKey());
getAllKeysUsingJsonNodeFieldNames((JsonNode) field.getValue(), keys);
});
} else if (jsonNode.isArray()) {
ArrayNode arrayField = (ArrayNode) jsonNode;
arrayField.forEach(node -> {
getAllKeysUsingJsonNodeFieldNames(node, keys);
});
}
}
private void getAllKeysUsingJsonNodeFieldNames(JsonNode jsonNode, List<String> keys) {
if (jsonNode.isObject()) {
Iterator<String> fieldNames = jsonNode.fieldNames();
fieldNames.forEachRemaining(fieldName -> {
keys.add(fieldName);
getAllKeysUsingJsonNodeFieldNames(jsonNode.get(fieldName), keys);
});
} else if (jsonNode.isArray()) {
ArrayNode arrayField = (ArrayNode) jsonNode;
arrayField.forEach(node -> {
getAllKeysUsingJsonNodeFieldNames(node, keys);
});
}
}
public List<String> getKeysInJsonUsingJsonParser(String json, ObjectMapper mapper) throws IOException {
List<String> keys = new ArrayList<>();
JsonNode jsonNode = mapper.readTree(json);
JsonParser jsonParser = jsonNode.traverse(); | while (!jsonParser.isClosed()) {
if (jsonParser.nextToken() == JsonToken.FIELD_NAME) {
keys.add((jsonParser.getCurrentName()));
}
}
return keys;
}
public List<String> getKeysInJsonUsingJsonParser(String json) throws JsonParseException, IOException {
List<String> keys = new ArrayList<>();
JsonFactory factory = new JsonFactory();
JsonParser jsonParser = factory.createParser(json);
while (!jsonParser.isClosed()) {
if (jsonParser.nextToken() == JsonToken.FIELD_NAME) {
keys.add((jsonParser.getCurrentName()));
}
}
return keys;
}
} | repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\jsonnode\GetAllKeysFromJSON.java | 1 |
请完成以下Java代码 | public SaveResult save(final @NotNull Document document)
{
trxManager.assertThreadInheritedTrxExists();
assertThisRepository(document.getEntityDescriptor());
DocumentPermissionsHelper.assertCanEdit(document);
final SaveHandler.SaveResult handlerResult = saveHandlers.save(document);
//
// Reload the document
boolean deleted = false;
if (handlerResult.isNeedsRefresh())
{
final DocumentId idNew = handlerResult.getIdNew();
final RefreshResult refreshResult = refresh(document, idNew);
if (refreshResult == RefreshResult.MISSING)
{
deleted = true;
}
}
//
// Notify the parent document that one of it's children were saved
if (!document.isRootDocument())
{
document.getParentDocument().onChildSaved(document);
}
//
return deleted ? SaveResult.DELETED : SaveResult.SAVED;
}
public static Object convertValueToPO(final Object value, final String columnName, final DocumentFieldWidgetType widgetType, final Class<?> targetClass)
{
return SqlValueConverters.convertToPOValue(value, columnName, widgetType, targetClass);
}
@Override
public void delete(@NonNull final Document document)
{
trxManager.assertThreadInheritedTrxExists();
assertThisRepository(document.getEntityDescriptor()); | DocumentPermissionsHelper.assertCanEdit(document, UserSession.getCurrentPermissions());
if (document.isNew())
{
throw new IllegalArgumentException("Cannot delete new document: " + document);
}
saveHandlers.delete(document);
}
@Override
public String retrieveVersion(final DocumentEntityDescriptor entityDescriptor, final int documentIdAsInt)
{
final SqlDocumentEntityDataBindingDescriptor binding = SqlDocumentEntityDataBindingDescriptor.cast(entityDescriptor.getDataBinding());
final String sql = binding.getSqlSelectVersionById()
.orElseThrow(() -> new AdempiereException("Versioning is not supported for " + entityDescriptor));
final Timestamp version = DB.getSQLValueTSEx(ITrx.TRXNAME_ThreadInherited, sql, documentIdAsInt);
return version == null ? VERSION_DEFAULT : String.valueOf(version.getTime());
}
@Override
public int retrieveLastLineNo(final DocumentQuery query)
{
logger.debug("Retrieving last LineNo: query={}", query);
final DocumentEntityDescriptor entityDescriptor = query.getEntityDescriptor();
assertThisRepository(entityDescriptor);
final SqlDocumentQueryBuilder sqlBuilder = SqlDocumentQueryBuilder.of(query);
final SqlAndParams sql = sqlBuilder.getSqlMaxLineNo();
return DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql.getSql(), sql.getSqlParams());
}
public boolean isReadonly(@NonNull final GridTabVO gridTabVO)
{
return saveHandlers.isReadonly(gridTabVO);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlDocumentsRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OrderingPartyExtensionType {
@XmlElement(name = "OrderingPartyExtension", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact")
protected at.erpel.schemas._1p0.documents.extensions.edifact.OrderingPartyExtensionType orderingPartyExtension;
@XmlElement(name = "ErpelOrderingPartyExtension")
protected CustomType erpelOrderingPartyExtension;
/**
* Gets the value of the orderingPartyExtension property.
*
* @return
* possible object is
* {@link at.erpel.schemas._1p0.documents.extensions.edifact.OrderingPartyExtensionType }
*
*/
public at.erpel.schemas._1p0.documents.extensions.edifact.OrderingPartyExtensionType getOrderingPartyExtension() {
return orderingPartyExtension;
}
/**
* Sets the value of the orderingPartyExtension property.
*
* @param value
* allowed object is
* {@link at.erpel.schemas._1p0.documents.extensions.edifact.OrderingPartyExtensionType }
*
*/
public void setOrderingPartyExtension(at.erpel.schemas._1p0.documents.extensions.edifact.OrderingPartyExtensionType value) {
this.orderingPartyExtension = value;
}
/**
* Gets the value of the erpelOrderingPartyExtension property.
*
* @return
* possible object is
* {@link CustomType }
*
*/ | public CustomType getErpelOrderingPartyExtension() {
return erpelOrderingPartyExtension;
}
/**
* Sets the value of the erpelOrderingPartyExtension property.
*
* @param value
* allowed object is
* {@link CustomType }
*
*/
public void setErpelOrderingPartyExtension(CustomType value) {
this.erpelOrderingPartyExtension = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\OrderingPartyExtensionType.java | 2 |
请完成以下Java代码 | public <T> T getDynAttribute(final Object model, final String attributeName)
{
final T value = GridTabWrapper.getWrapper(model).getDynAttribute(attributeName);
return value;
}
@Override
public Object setDynAttribute(final Object model, final String attributeName, final Object value)
{
return GridTabWrapper.getWrapper(model).setDynAttribute(attributeName, value);
}
@Override
public <T extends PO> T getPO(final Object model, final boolean strict)
{
if (strict)
{
return null;
}
if (model instanceof GridTab)
{
final GridTab gridTab = (GridTab)model;
return GridTabWrapper.getPO(Env.getCtx(), gridTab);
}
final GridTabWrapper wrapper = GridTabWrapper.getWrapper(model);
if (wrapper == null)
{
throw new AdempiereException("Cannot extract " + GridTabWrapper.class + " from " + model);
}
return wrapper.getPO(); | }
@Override
public Evaluatee getEvaluatee(final Object model)
{
return GridTabWrapper.getGridTab(model);
}
@Override
public boolean isCopy(final Object model)
{
return GridTabWrapper.getGridTab(model).getTableModel().isRecordCopyingMode();
}
@Override
public boolean isCopying(final Object model)
{
return isCopy(model);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\GridTabInterfaceWrapperHelper.java | 1 |
请完成以下Java代码 | public Optional<IDocumentBillLocationAdapter> getDocumentBillLocationAdapterIfHandled(final Object record)
{
return toOLCand(record).map(OLCandDocumentLocationAdapterFactory::billLocationAdapter);
}
@Override
public Optional<IDocumentDeliveryLocationAdapter> getDocumentDeliveryLocationAdapter(final Object record)
{
return toOLCand(record).map(OLCandDocumentLocationAdapterFactory::dropShipAdapter);
}
@Override
public Optional<IDocumentHandOverLocationAdapter> getDocumentHandOverLocationAdapter(final Object record)
{
return toOLCand(record).map(OLCandDocumentLocationAdapterFactory::handOverLocationAdapter);
}
private static Optional<I_C_OLCand> toOLCand(final Object record)
{
return InterfaceWrapperHelper.isInstanceOf(record, I_C_OLCand.class)
? Optional.of(InterfaceWrapperHelper.create(record, I_C_OLCand.class))
: Optional.empty();
}
public static BPartnerLocationAdapter bpartnerLocationAdapter(@NonNull final I_C_OLCand delegate)
{
return new BPartnerLocationAdapter(delegate);
}
public static BPartnerOverrideLocationAdapter bpartnerLocationOverrideAdapter(@NonNull final I_C_OLCand delegate)
{
return new BPartnerOverrideLocationAdapter(delegate);
}
public static DocumentBillLocationAdapter billLocationAdapter(@NonNull final I_C_OLCand delegate)
{ | return new DocumentBillLocationAdapter(delegate);
}
public static DropShipLocationAdapter dropShipAdapter(@NonNull final I_C_OLCand delegate)
{
return new DropShipLocationAdapter(delegate);
}
public static DropShipOverrideLocationAdapter dropShipOverrideAdapter(@NonNull final I_C_OLCand delegate)
{
return new DropShipOverrideLocationAdapter(delegate);
}
public static HandOverLocationAdapter handOverLocationAdapter(@NonNull final I_C_OLCand delegate)
{
return new HandOverLocationAdapter(delegate);
}
public static HandOverOverrideLocationAdapter handOverOverrideLocationAdapter(@NonNull final I_C_OLCand delegate)
{
return new HandOverOverrideLocationAdapter(delegate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\location\adapter\OLCandDocumentLocationAdapterFactory.java | 1 |
请完成以下Java代码 | public void deleteSelection(final ViewRowIdsOrderedSelection selection)
{
viewSelectionFactory.deleteSelection(selection.getSelectionId());
}
@Override
public SqlViewRowsWhereClause buildSqlWhereClause(final ViewRowIdsOrderedSelection selection, final DocumentIdsSelection rowIds)
{
return SqlViewSelectionQueryBuilder.prepareSqlWhereClause()
.sqlTableAlias(I_M_HU.Table_Name)
.keyColumnNamesMap(SqlViewKeyColumnNamesMap.ofIntKeyField(I_M_HU.COLUMNNAME_M_HU_ID))
.selectionId(selection.getSelectionId())
.rowIds(rowIds)
.rowIdsConverter(getRowIdsConverter())
.build();
}
@Override
public void warmUp(@NonNull final Set<HuId> huIds)
{
InterfaceWrapperHelper.loadByRepoIdAwares(huIds, I_M_HU.class); // caches the given HUs with one SQL query
huReservationService.warmup(huIds);
} | @Nullable
private JSONLookupValue getHUClearanceStatusLookupValue(@NonNull final I_M_HU hu)
{
final ClearanceStatus huClearanceStatus = ClearanceStatus.ofNullableCode(hu.getClearanceStatus());
if (huClearanceStatus == null)
{
return null;
}
final ITranslatableString huClearanceStatusCaption = handlingUnitsBL.getClearanceStatusCaption(huClearanceStatus);
return JSONLookupValue.of(huClearanceStatus.getCode(), huClearanceStatusCaption.translate(Env.getAD_Language()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\SqlHUEditorViewRepository.java | 1 |
请完成以下Java代码 | public Object invoke(ELContext context, Object[] params) {
try {
return method.invoke(null, params);
} catch (IllegalAccessException e) {
throw new ELException(LocalMessages.get("error.identifier.method.access", name));
} catch (IllegalArgumentException e) {
throw new ELException(LocalMessages.get("error.identifier.method.invocation", name, e));
} catch (InvocationTargetException e) {
throw new ELException(
LocalMessages.get("error.identifier.method.invocation", name, e.getCause())
);
}
}
@Override
public MethodInfo getMethodInfo(ELContext context) {
return new MethodInfo(method.getName(), method.getReturnType(), method.getParameterTypes());
}
};
} else if (value instanceof MethodExpression) {
return (MethodExpression) value;
}
throw new MethodNotFoundException(
LocalMessages.get("error.identifier.method.notamethod", name, value.getClass())
);
}
public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) {
return getMethodExpression(bindings, context, returnType, paramTypes).getMethodInfo(context);
}
public Object invoke(
Bindings bindings,
ELContext context,
Class<?> returnType,
Class<?>[] paramTypes,
Object[] params
) {
return getMethodExpression(bindings, context, returnType, paramTypes).invoke(context, params);
}
@Override
public String toString() {
return name; | }
@Override
public void appendStructure(StringBuilder b, Bindings bindings) {
b.append(bindings != null && bindings.isVariableBound(index) ? "<var>" : name);
}
public int getIndex() {
return index;
}
public String getName() {
return name;
}
public int getCardinality() {
return 0;
}
public AstNode getChild(int i) {
return null;
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstIdentifier.java | 1 |
请完成以下Java代码 | public int getBill_Location_Value_ID()
{
return delegate.getBill_Location_Value_ID();
}
@Override
public void setBill_Location_Value_ID(final int Bill_Location_Value_ID)
{
delegate.setBill_Location_Value_ID(Bill_Location_Value_ID);
}
@Override
public int getBill_User_ID()
{
return delegate.getBill_User_ID();
}
@Override
public void setBill_User_ID(final int Bill_User_ID)
{
delegate.setBill_User_ID(Bill_User_ID);
}
@Override
public String getBillToAddress()
{
return delegate.getBillToAddress();
}
@Override
public void setBillToAddress(final String address)
{
delegate.setBillToAddress(address);
}
@Override
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentBillLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentBillLocationAdapter.super.setRenderedAddress(from);
}
public void setFromBillLocation(@NonNull final I_C_Order from) | {
setFrom(OrderDocumentLocationAdapterFactory.billLocationAdapter(from).toDocumentLocation());
}
@Override
public I_C_Order getWrappedRecord()
{
return delegate;
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public OrderBillLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new OrderBillLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Order.class));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderBillLocationAdapter.java | 1 |
请完成以下Java代码 | public void setBackupSource(boolean backupSource) {
this.backupSource = backupSource;
}
/**
* Repackage the source file so that it can be run using '{@literal java -jar}'.
* @param libraries the libraries required to run the archive
* @throws IOException if the file cannot be repackaged
*/
public void repackage(Libraries libraries) throws IOException {
repackage(getSource(), libraries);
}
/**
* Repackage to the given destination so that it can be launched using '
* {@literal java -jar}'.
* @param destination the destination file (may be the same as the source)
* @param libraries the libraries required to run the archive
* @throws IOException if the file cannot be repackaged
*/
public void repackage(File destination, Libraries libraries) throws IOException {
repackage(destination, libraries, null);
}
/**
* Repackage to the given destination so that it can be launched using '
* {@literal java -jar}'.
* @param destination the destination file (may be the same as the source)
* @param libraries the libraries required to run the archive
* @param lastModifiedTime an optional last modified time to apply to the archive and
* its contents
* @throws IOException if the file cannot be repackaged
* @since 4.0.0
*/
public void repackage(File destination, Libraries libraries, @Nullable FileTime lastModifiedTime)
throws IOException {
Assert.isTrue(destination != null && !destination.isDirectory(), "Invalid destination");
getLayout(); // get layout early
destination = destination.getAbsoluteFile();
File source = getSource();
if (isAlreadyPackaged() && source.equals(destination)) {
return;
}
File workingSource = source;
if (source.equals(destination)) {
workingSource = getBackupFile();
workingSource.delete();
renameFile(source, workingSource);
}
destination.delete();
try {
try (JarFile sourceJar = new JarFile(workingSource)) {
repackage(sourceJar, destination, libraries, lastModifiedTime);
}
}
finally { | if (!this.backupSource && !source.equals(workingSource)) {
deleteFile(workingSource);
}
}
}
private void repackage(JarFile sourceJar, File destination, Libraries libraries,
@Nullable FileTime lastModifiedTime) throws IOException {
try (JarWriter writer = new JarWriter(destination, lastModifiedTime)) {
write(sourceJar, libraries, writer, lastModifiedTime != null);
}
if (lastModifiedTime != null) {
destination.setLastModified(lastModifiedTime.toMillis());
}
}
private void renameFile(File file, File dest) {
if (!file.renameTo(dest)) {
throw new IllegalStateException("Unable to rename '" + file + "' to '" + dest + "'");
}
}
private void deleteFile(File file) {
if (!file.delete()) {
throw new IllegalStateException("Unable to delete '" + file + "'");
}
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\Repackager.java | 1 |
请完成以下Java代码 | public void setBinaryData (byte[] BinaryData)
{
set_ValueNoCheck (COLUMNNAME_BinaryData, BinaryData);
}
/** Get Binärwert.
@return Binary Data
*/
@Override
public byte[] getBinaryData ()
{
return (byte[])get_Value(COLUMNNAME_BinaryData);
}
/** Set Migriert am.
@param MigrationDate Migriert am */
@Override
public void setMigrationDate (java.sql.Timestamp MigrationDate)
{
set_Value (COLUMNNAME_MigrationDate, MigrationDate);
}
/** Get Migriert am.
@return Migriert am */
@Override
public java.sql.Timestamp getMigrationDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_MigrationDate);
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{ | Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Mitteilung.
@param TextMsg
Text Message
*/
@Override
public void setTextMsg (java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Mitteilung.
@return Text Message
*/
@Override
public java.lang.String getTextMsg ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextMsg);
}
/** Set Titel.
@param Title
Name this entity is referred to as
*/
@Override
public void setTitle (java.lang.String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
/** Get Titel.
@return Name this entity is referred to as
*/
@Override
public java.lang.String getTitle ()
{
return (java.lang.String)get_Value(COLUMNNAME_Title);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attachment.java | 1 |
请完成以下Java代码 | private String getSQLDefaultValue()
{
final int displayType = referenceId.getRepoId();
if (defaultValue != null
&& !defaultValue.isEmpty()
&& defaultValue.indexOf('@') == -1 // no variables
&& (!(DisplayType.isID(displayType) && defaultValue.equals("-1")))) // not for ID's with default -1
{
if (DisplayType.isText(displayType)
|| displayType == DisplayType.List
|| displayType == DisplayType.YesNo
// Two special columns: Defined as Table but DB Type is String
|| columnName.equals("EntityType") || columnName.equals("AD_Language")
|| (displayType == DisplayType.Button && !(columnName.endsWith("_ID"))))
{
if (!defaultValue.startsWith(DB.QUOTE_STRING) && !defaultValue.endsWith(DB.QUOTE_STRING))
{
return DB.TO_STRING(defaultValue);
}
else
{ | return defaultValue;
}
}
else
{
return defaultValue;
}
}
else
{
return null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\ddl\ColumnDDL.java | 1 |
请完成以下Java代码 | public Response deleteTaskMetrics(String dateString) {
Date date = dateConverter.convertQueryParameterToType(dateString);
getProcessEngine().getManagementService().deleteTaskMetrics(date);
// return no content (204) since resource is deleted
return Response.noContent().build();
}
protected void applyQueryParams(MetricsQuery query, MultivaluedMap<String, String> queryParameters) {
if(queryParameters.getFirst(QUERY_PARAM_START_DATE) != null) {
Date startDate = dateConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_START_DATE));
query.startDate(startDate);
}
if(queryParameters.getFirst(QUERY_PARAM_END_DATE) != null) {
Date endDate = dateConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_END_DATE));
query.endDate(endDate);
}
IntegerConverter intConverter = new IntegerConverter();
intConverter.setObjectMapper(objectMapper);
if (queryParameters.getFirst(QUERY_PARAM_FIRST_RESULT) != null) {
int firstResult = intConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_FIRST_RESULT));
query.offset(firstResult); | }
if (queryParameters.getFirst(QUERY_PARAM_MAX_RESULTS) != null) {
int maxResults = intConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_MAX_RESULTS));
query.limit(maxResults);
}
if(queryParameters.getFirst(QUERY_PARAM_AGG_BY_REPORTER) != null) {
query.aggregateByReporter();
}
}
protected List<MetricsIntervalResultDto> convertToDtos(List<MetricIntervalValue> metrics) {
List<MetricsIntervalResultDto> intervalMetrics = new ArrayList<>();
for (MetricIntervalValue m : metrics) {
intervalMetrics.add(new MetricsIntervalResultDto(m));
}
return intervalMetrics;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\MetricsRestServiceImpl.java | 1 |
请完成以下Java代码 | public void onMessage(Message message) {
if (this.applicationEventPublisher != null) {
this.applicationEventPublisher.publishEvent(new BrokerEvent(this, message.getMessageProperties()));
}
else {
if (logger.isWarnEnabled()) {
logger.warn("No event publisher available for " + message + "; if the BrokerEventListener "
+ "is not defined as a bean, you must provide an ApplicationEventPublisher");
}
}
}
@Override
public void onCreate(@Nullable Connection connection) {
this.bindingsFailedException = null; | TopicExchange exchange = new TopicExchange("amq.rabbitmq.event");
try {
this.admin.declareQueue(this.eventQueue);
Arrays.stream(this.eventKeys).forEach(k -> {
Binding binding = BindingBuilder.bind(this.eventQueue).to(exchange).with(k);
this.admin.declareBinding(binding);
});
}
catch (Exception e) {
logger.error("failed to declare event queue/bindings - is the plugin enabled?", e);
this.bindingsFailedException = e;
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\core\BrokerEventListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void doInTransactionWithoutResult(TransactionStatus status) {
log.info("Starting first transaction ...");
Chapter chapter = chapterRepository.findById(1L).orElseThrow();
Modification modification = new Modification();
modification.setDescription("Rewording first paragraph");
modification.setModification("Reword: ... Added: ...");
modification.setChapter(chapter);
template.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
log.info("Starting second transaction ...");
Chapter chapter = chapterRepository.findById(1L).orElseThrow();
Modification modification = new Modification();
modification.setDescription("Formatting second paragraph");
modification.setModification("Format ...");
modification.setChapter(chapter);
modificationRepository.save(modification); | log.info("Commit second transaction ...");
}
});
log.info("Resuming first transaction ...");
modificationRepository.save(modification);
log.info("Commit first transaction ...");
}
});
log.info("Done!");
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootOptimisticForceIncrement\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | protected Map<String, String> extractExternalSystemParameters(final ExternalSystemParentConfig externalSystemParentConfig)
{
if (Check.isBlank(outboundDataProcessRecordId))
{
throw new AdempiereException("Outbound data process record id is missing.");
}
final ExternalSystemScriptedExportConversionConfig externalSystemScriptedExportConversionConfig = ExternalSystemScriptedExportConversionConfig
.cast(externalSystemParentConfig.getChildConfig());
return externalSystemScriptedExportConversionService.getParameters(externalSystemScriptedExportConversionConfig, getProcessInfo().getCtx(), outboundDataProcessRecordId);
}
@Override
protected String getTabName()
{
return ExternalSystemType.ScriptedExportConversion.getValue(); | }
@Override
protected ExternalSystemType getExternalSystemType()
{
return ExternalSystemType.ScriptedExportConversion;
}
@Override
protected long getSelectedRecordCount(final IProcessPreconditionsContext context)
{
// called when a document is completed, not from the External System window
return 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeScriptedExportConversionAction.java | 1 |
请完成以下Java代码 | public int getSuspensionState() {
return suspensionState;
}
@Override
public void setSuspensionState(int suspensionState) {
this.suspensionState = suspensionState;
}
@Override
public boolean isSuspended() {
return suspensionState == SuspensionState.SUSPENDED.getStateCode();
}
@Override
public String getDerivedFrom() {
return derivedFrom;
}
@Override
public void setDerivedFrom(String derivedFrom) {
this.derivedFrom = derivedFrom;
}
@Override
public String getDerivedFromRoot() {
return derivedFromRoot;
}
@Override
public void setDerivedFromRoot(String derivedFromRoot) {
this.derivedFromRoot = derivedFromRoot;
} | @Override
public int getDerivedVersion() {
return derivedVersion;
}
@Override
public void setDerivedVersion(int derivedVersion) {
this.derivedVersion = derivedVersion;
}
@Override
public String getEngineVersion() {
return engineVersion;
}
@Override
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
public IOSpecification getIoSpecification() {
return ioSpecification;
}
public void setIoSpecification(IOSpecification ioSpecification) {
this.ioSpecification = ioSpecification;
}
@Override
public String toString() {
return "ProcessDefinitionEntity[" + id + "]";
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ProcessDefinitionEntityImpl.java | 1 |
请完成以下Java代码 | public int getM_Picking_Job_Schedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Schedule_ID);
}
@Override
public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID);
}
@Override
public int getM_ShipmentSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
} | @Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQtyToPick (final BigDecimal QtyToPick)
{
set_Value (COLUMNNAME_QtyToPick, QtyToPick);
}
@Override
public BigDecimal getQtyToPick()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_Picking_Job_Schedule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "kermit")
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
@ApiModelProperty(example = "sales")
public String getGroup() {
return group; | }
public void setGroup(String group) {
this.group = group;
}
@ApiModelProperty(example ="candidate")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\engine\RestIdentityLink.java | 2 |
请完成以下Java代码 | public GroupQuery groupNameLike(String nameLike) {
if (nameLike == null) {
throw new FlowableIllegalArgumentException("Provided name is null");
}
this.nameLike = nameLike;
return this;
}
@Override
public GroupQuery groupNameLikeIgnoreCase(String nameLikeIgnoreCase) {
if (nameLikeIgnoreCase == null) {
throw new FlowableIllegalArgumentException("Provided name is null");
}
this.nameLikeIgnoreCase = nameLikeIgnoreCase.toLowerCase();
return this;
}
@Override
public GroupQuery groupType(String type) {
if (type == null) {
throw new FlowableIllegalArgumentException("Provided type is null");
}
this.type = type;
return this;
}
@Override
public GroupQuery groupMember(String userId) {
if (userId == null) {
throw new FlowableIllegalArgumentException("Provided userId is null");
}
this.userId = userId;
return this;
}
@Override
public GroupQuery groupMembers(List<String> userIds) {
if (userIds == null) {
throw new FlowableIllegalArgumentException("Provided userIds is null");
}
this.userIds = userIds;
return this;
}
// sorting ////////////////////////////////////////////////////////
@Override
public GroupQuery orderByGroupId() {
return orderBy(GroupQueryProperty.GROUP_ID);
}
@Override
public GroupQuery orderByGroupName() {
return orderBy(GroupQueryProperty.NAME);
}
@Override
public GroupQuery orderByGroupType() {
return orderBy(GroupQueryProperty.TYPE);
} | // results ////////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getGroupEntityManager(commandContext).findGroupCountByQueryCriteria(this);
}
@Override
public List<Group> executeList(CommandContext commandContext) {
return CommandContextUtil.getGroupEntityManager(commandContext).findGroupByQueryCriteria(this);
}
// getters ////////////////////////////////////////////////////////
@Override
public String getId() {
return id;
}
public List<String> getIds() {
return ids;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public String getType() {
return type;
}
public String getUserId() {
return userId;
}
public List<String> getUserIds() {
return userIds;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\GroupQueryImpl.java | 1 |
请完成以下Java代码 | private ViewLayout createViewLayout(final ViewLayoutKey viewLayoutKey)
{
final ViewLayout viewLayoutOrig = documentDescriptorFactory.getDocumentDescriptor(viewLayoutKey.getWindowId())
.getViewLayout(viewLayoutKey.getViewDataType());
final SqlViewBinding sqlViewBinding = getViewBinding(
viewLayoutKey.getWindowId(),
viewLayoutKey.getViewDataType().getRequiredFieldCharacteristic(),
viewLayoutKey.getProfileId());
final Collection<DocumentFilterDescriptor> filters = sqlViewBinding.getViewFilterDescriptors().getAll();
final boolean hasTreeSupport = sqlViewBinding.hasGroupingFields();
final ViewLayout.ChangeBuilder viewLayoutBuilder = viewLayoutOrig.toBuilder()
.profileId(viewLayoutKey.getProfileId())
.filters(filters)
.treeSupport(hasTreeSupport, true/* treeCollapsible */, ViewLayout.TreeExpandedDepth_AllCollapsed)
.geoLocationSupport(geoLocationDocumentService.containsGeoLocationFilter(filters));
//
// Customize the view layout
// NOTE to developer: keep it last, right before build().
final SqlViewCustomizer sqlViewCustomizer = viewCustomizers.getOrNull(viewLayoutKey.getWindowId(), viewLayoutKey.getProfileId());
if (sqlViewCustomizer != null)
{
sqlViewCustomizer.customizeViewLayout(viewLayoutBuilder);
} | return viewLayoutBuilder.build();
}
public SqlViewBinding getViewBinding(
@NonNull final WindowId windowId,
@Nullable final Characteristic requiredFieldCharacteristic,
@Nullable final ViewProfileId profileId)
{
return viewBindingsFactory.getViewBinding(windowId, requiredFieldCharacteristic, profileId);
}
public List<ViewProfile> getAvailableProfiles(final WindowId windowId)
{
return viewCustomizers.getViewProfilesByWindowId(windowId);
}
@Value
private static class ViewLayoutKey
{
@NonNull WindowId windowId;
@NonNull JSONViewDataType viewDataType;
@Nullable ViewProfileId profileId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\ViewLayoutFactory.java | 1 |
请完成以下Java代码 | public class RepetitionRuleImpl extends CmmnElementImpl implements RepetitionRule {
protected static Attribute<String> nameAttribute;
protected static AttributeReference<CaseFileItem> contextRefAttribute;
protected static ChildElement<ConditionExpression> conditionChild;
/* Camunda extensions */
protected static Attribute<String> camundaRepeatOnStandardEventAttribute;
public RepetitionRuleImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getName() {
return nameAttribute.getValue(this);
}
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public CaseFileItem getContext() {
return contextRefAttribute.getReferenceTargetElement(this);
}
public void setContext(CaseFileItem caseFileItem) {
contextRefAttribute.setReferenceTargetElement(this, caseFileItem);
}
public ConditionExpression getCondition() {
return conditionChild.getChild(this);
}
public void setCondition(ConditionExpression condition) {
conditionChild.setChild(this, condition);
}
public String getCamundaRepeatOnStandardEvent() {
return camundaRepeatOnStandardEventAttribute.getValue(this);
} | public void setCamundaRepeatOnStandardEvent(String standardEvent) {
camundaRepeatOnStandardEventAttribute.setValue(this, standardEvent);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(RepetitionRule.class, CMMN_ELEMENT_REPETITION_RULE)
.namespaceUri(CMMN11_NS)
.extendsType(CmmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<RepetitionRule>() {
public RepetitionRule newInstance(ModelTypeInstanceContext instanceContext) {
return new RepetitionRuleImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
contextRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CONTEXT_REF)
.idAttributeReference(CaseFileItem.class)
.build();
/** Camunda extensions */
camundaRepeatOnStandardEventAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_REPEAT_ON_STANDARD_EVENT)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
conditionChild = sequenceBuilder.element(ConditionExpression.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\RepetitionRuleImpl.java | 1 |
请完成以下Java代码 | private static UserId toValidContactUserIdOrNull(@Nullable final Integer userRepoId)
{
final UserId userId = userRepoId != null ? UserId.ofRepoIdOrNull(userRepoId) : null;
// NOTE: system user is not a valid BP contact
return userId != null && userId.isRegularUser() ? userId : null;
}
private BPartnerContactId(@NonNull final BPartnerId bpartnerId, @NonNull final UserId userId)
{
this.bpartnerId = bpartnerId;
this.userId = userId;
}
@Override
public int getRepoId()
{
return userId.getRepoId();
}
public static int toRepoId(@Nullable final BPartnerContactId id)
{
return id != null ? id.getRepoId() : -1;
}
@Nullable
public static UserId toUserIdOrNull(@Nullable final BPartnerContactId id)
{
return id != null ? id.getUserId() : null;
}
public static boolean equals(@Nullable final BPartnerContactId id1, @Nullable final BPartnerContactId id2)
{
return Objects.equals(id1, id2);
}
@JsonCreator
public static BPartnerContactId ofJsonString(@NonNull final String idStr) | {
try
{
final List<String> parts = Splitter.on("-").splitToList(idStr);
return of(
BPartnerId.ofRepoId(Integer.parseInt(parts.get(0))),
UserId.ofRepoId(Integer.parseInt(parts.get(1))));
}
catch (Exception ex)
{
throw new AdempiereException("Invalid BPartnerContactId string: " + idStr, ex);
}
}
@JsonValue
public String toJson()
{
return bpartnerId.getRepoId() + "-" + userId.getRepoId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPartnerContactId.java | 1 |
请完成以下Java代码 | private static KeyStore loadKeyStore(Path path, String password) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
KeyStore store = KeyStore.getInstance(path.toFile(), password.toCharArray());
try (InputStream stream = Files.newInputStream(path)) {
store.load(stream, password.toCharArray());
}
return store;
}
public static X509KeyManager loadKeyManager(Path path, String password) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
KeyStore store = loadKeyStore(path, password);
KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
factory.init(store, password.toCharArray());
return (X509KeyManager) Stream.of(factory.getKeyManagers())
.filter(X509KeyManager.class::isInstance)
.findAny() | .orElseThrow(() -> new IllegalStateException("no appropriate manager found"));
}
public static X509TrustManager loadTrustManager(Path path, String password) throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException {
KeyStore store = loadKeyStore(path, password);
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(store);
return (X509TrustManager) Stream.of(factory.getTrustManagers())
.filter(X509TrustManager.class::isInstance)
.findAny()
.orElseThrow(() -> new IllegalStateException("no appropriate manager found"));
}
} | repos\tutorials-master\core-java-modules\core-java-networking-6\src\main\java\com\baeldung\multiplecerts\CertUtils.java | 1 |
请完成以下Java代码 | public class AtmTransformer implements ClassFileTransformer {
private static Logger LOGGER = LoggerFactory.getLogger(AtmTransformer.class);
private static final String WITHDRAW_MONEY_METHOD = "withdrawMoney";
/** The internal form class name of the class to transform */
private String targetClassName;
/** The class loader of the class we want to transform */
private ClassLoader targetClassLoader;
public AtmTransformer(String targetClassName, ClassLoader targetClassLoader) {
this.targetClassName = targetClassName;
this.targetClassLoader = targetClassLoader;
}
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
byte[] byteCode = classfileBuffer;
String finalTargetClassName = this.targetClassName.replaceAll("\\.", "/"); //replace . with /
if (!className.equals(finalTargetClassName)) {
return byteCode;
}
if (className.equals(finalTargetClassName) && loader.equals(targetClassLoader)) {
LOGGER.info("[Agent] Transforming class MyAtm");
try {
ClassPool cp = ClassPool.getDefault();
CtClass cc = cp.get(targetClassName);
CtMethod m = cc.getDeclaredMethod(WITHDRAW_MONEY_METHOD);
m.addLocalVariable("startTime", CtClass.longType);
m.insertBefore("startTime = System.currentTimeMillis();");
StringBuilder endBlock = new StringBuilder(); | m.addLocalVariable("endTime", CtClass.longType);
m.addLocalVariable("opTime", CtClass.longType);
endBlock.append("endTime = System.currentTimeMillis();");
endBlock.append("opTime = (endTime-startTime)/1000;");
endBlock.append("LOGGER.info(\"[Application] Withdrawal operation completed in:\" + opTime + \" seconds!\");");
m.insertAfter(endBlock.toString());
byteCode = cc.toBytecode();
cc.detach();
} catch (NotFoundException | CannotCompileException | IOException e) {
LOGGER.error("Exception", e);
}
}
return byteCode;
}
} | repos\tutorials-master\core-java-modules\core-java-jvm\src\main\java\com\baeldung\instrumentation\agent\AtmTransformer.java | 1 |
请完成以下Java代码 | public class OrderedGatewayFilter implements GatewayFilter, Ordered {
private final GatewayFilter delegate;
private final int order;
public OrderedGatewayFilter(GatewayFilter delegate, int order) {
this.delegate = delegate;
this.order = order;
}
public GatewayFilter getDelegate() {
return delegate;
} | @Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return this.delegate.filter(exchange, chain);
}
@Override
public int getOrder() {
return this.order;
}
@Override
public String toString() {
return new StringBuilder("[").append(delegate).append(", order = ").append(order).append("]").toString();
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\OrderedGatewayFilter.java | 1 |
请完成以下Java代码 | public java.sql.Timestamp getRfq_BidStartDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_Rfq_BidStartDate);
}
/**
* RfQType AD_Reference_ID=540661
* Reference name: RfQType
*/
public static final int RFQTYPE_AD_Reference_ID=540661;
/** Default = D */
public static final String RFQTYPE_Default = "D";
/** Procurement = P */
public static final String RFQTYPE_Procurement = "P";
/** Set Ausschreibung Art.
@param RfQType Ausschreibung Art */
@Override
public void setRfQType (java.lang.String RfQType)
{
set_Value (COLUMNNAME_RfQType, RfQType);
}
/** Get Ausschreibung Art.
@return Ausschreibung Art */
@Override
public java.lang.String getRfQType ()
{
return (java.lang.String)get_Value(COLUMNNAME_RfQType);
}
@Override
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class);
} | @Override
public void setSalesRep(org.compiere.model.I_AD_User SalesRep)
{
set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep);
}
/** Set Aussendienst.
@param SalesRep_ID Aussendienst */
@Override
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 Aussendienst.
@return Aussendienst */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class ProfileRestController {
private final ProfileService profileService;
ProfileRestController(ProfileService profileService) {
this.profileService = profileService;
}
@GetMapping("/{username}")
public ProfileModel getProfileByUsername(@AuthenticationPrincipal UserJWTPayload jwtPayload,
@PathVariable UserName username) {
return ofNullable(jwtPayload)
.map(JWTPayload::getUserId)
.map(viewerId -> profileService.viewProfile(viewerId, username))
.map(ProfileModel::fromProfile)
.orElseGet(() -> fromProfile(profileService.viewProfile(username)));
}
@PostMapping("/{username}/follow") | public ProfileModel followUser(@AuthenticationPrincipal UserJWTPayload followerPayload,
@PathVariable UserName username) {
return fromProfile(
profileService.followAndViewProfile(followerPayload.getUserId(), username));
}
@DeleteMapping("/{username}/follow")
public ProfileModel unfollowUser(@AuthenticationPrincipal UserJWTPayload followerPayload,
@PathVariable UserName username) {
return fromProfile(
profileService.unfollowAndViewProfile(followerPayload.getUserId(), username)
);
}
@ResponseStatus(NOT_FOUND)
@ExceptionHandler(NoSuchElementException.class)
void handleNoSuchElementException(NoSuchElementException exception) {
// return NOT FOUND status
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\application\user\ProfileRestController.java | 2 |
请完成以下Java代码 | public boolean isAllowCreateNewHU()
{
// Check if we already reached the maximum number of HUs that we are allowed to create
return getCreatedHUsCount() < maxHUsToCreate;
}
public HUProducerDestination setMaxHUsToCreate(final int maxHUsToCreate)
{
Check.assumeGreaterOrEqualToZero(maxHUsToCreate, "maxHUsToCreate");
this.maxHUsToCreate = maxHUsToCreate;
return this;
}
/**
* Then this producer creates a new HU, than i uses the given {@code parentHUItem} for the new HU's {@link I_M_HU#COLUMN_M_HU_Item_Parent_ID}. | *
* @param parentHUItem
*/
public HUProducerDestination setParent_HU_Item(final I_M_HU_Item parentHUItem)
{
this.parentHUItem = parentHUItem;
return this;
}
@Override
protected I_M_HU_Item getParent_HU_Item()
{
return parentHUItem;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\HUProducerDestination.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JobManager getJobManager() {
return configuration.getJobManager();
}
public JobEntityManager getJobEntityManager() {
return configuration.getJobEntityManager();
}
public DeadLetterJobEntityManager getDeadLetterJobEntityManager() {
return configuration.getDeadLetterJobEntityManager();
}
public SuspendedJobEntityManager getSuspendedJobEntityManager() {
return configuration.getSuspendedJobEntityManager();
} | public ExternalWorkerJobEntityManager getExternalWorkerJobEntityManager() {
return configuration.getExternalWorkerJobEntityManager();
}
public TimerJobEntityManager getTimerJobEntityManager() {
return configuration.getTimerJobEntityManager();
}
public HistoryJobEntityManager getHistoryJobEntityManager() {
return configuration.getHistoryJobEntityManager();
}
public CommandExecutor getCommandExecutor() {
return configuration.getCommandExecutor();
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\ServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ResponseEntity<Resource> downloadFile(@RequestParam(defaultValue = "/home/djl-test/images-test") String directoryPath) {
List<String> imgPathList = new ArrayList<>();
try (Stream<Path> paths = Files.walk(Paths.get(directoryPath))) {
// Filter only regular files (excluding directories)
paths.filter(Files::isRegularFile)
.forEach(c-> imgPathList.add(c.toString()));
} catch (IOException e) {
return ResponseEntity.status(500).build();
}
Random random = new Random();
String filePath = imgPathList.get(random.nextInt(imgPathList.size()));
Path file = Paths.get(filePath);
Resource resource = new FileSystemResource(file.toFile());
if (!resource.exists()) {
return ResponseEntity.notFound().build();
} | HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getFileName().toString());
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE);
try {
return ResponseEntity.ok()
.headers(headers)
.contentLength(resource.contentLength())
.body(resource);
} catch (IOException e) {
return ResponseEntity.status(500).build();
}
}
} | repos\springboot-demo-master\djl\src\main\java\com\et\controller\ImageClassificationController.java | 2 |
请完成以下Java代码 | private @Nullable MessageBatch doReleaseBatch() {
if (this.messages.isEmpty()) {
return null;
}
Message message = assembleMessage();
MessageBatch messageBatch = new MessageBatch(this.exchange, this.routingKey, message);
this.messages.clear();
this.currentSize = 0;
this.exchange = null;
this.routingKey = null;
return messageBatch;
}
private Message assembleMessage() {
if (this.messages.size() == 1) {
return this.messages.get(0);
}
MessageProperties messageProperties = this.messages.get(0).getMessageProperties();
byte[] body = new byte[this.currentSize];
ByteBuffer bytes = ByteBuffer.wrap(body);
for (Message message : this.messages) {
bytes.putInt(message.getBody().length);
bytes.put(message.getBody());
}
messageProperties.getHeaders().put(MessageProperties.SPRING_BATCH_FORMAT,
MessageProperties.BATCH_FORMAT_LENGTH_HEADER4);
messageProperties.getHeaders().put(AmqpHeaders.BATCH_SIZE, this.messages.size());
return new Message(body, messageProperties);
}
@Override
public boolean canDebatch(MessageProperties properties) {
return MessageProperties.BATCH_FORMAT_LENGTH_HEADER4.equals(properties
.getHeaders()
.get(MessageProperties.SPRING_BATCH_FORMAT));
}
/**
* Debatch a message that has a header with {@link MessageProperties#SPRING_BATCH_FORMAT}
* set to {@link MessageProperties#BATCH_FORMAT_LENGTH_HEADER4}.
* @param message the batched message.
* @param fragmentConsumer a consumer for each fragment.
* @since 2.2
*/
@Override | public void deBatch(Message message, Consumer<Message> fragmentConsumer) {
ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBody());
MessageProperties messageProperties = message.getMessageProperties();
messageProperties.getHeaders().remove(MessageProperties.SPRING_BATCH_FORMAT);
while (byteBuffer.hasRemaining()) {
int length = byteBuffer.getInt();
if (length < 0 || length > byteBuffer.remaining()) {
throw new ListenerExecutionFailedException("Bad batched message received",
new MessageConversionException("Insufficient batch data at offset " + byteBuffer.position()),
message);
}
byte[] body = new byte[length];
byteBuffer.get(body);
messageProperties.setContentLength(length);
// Caveat - shared MessageProperties, except for last
Message fragment;
if (byteBuffer.hasRemaining()) {
fragment = new Message(body, messageProperties);
}
else {
MessageProperties lastProperties = new MessageProperties();
BeanUtils.copyProperties(messageProperties, lastProperties);
lastProperties.setLastInBatch(true);
fragment = new Message(body, lastProperties);
}
fragmentConsumer.accept(fragment);
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\batch\SimpleBatchingStrategy.java | 1 |
请完成以下Java代码 | protected void executeInternal(
CommandContext commandContext,
AttachmentEntity attachment,
String processInstanceId,
String processDefinitionId
) {
commandContext.getAttachmentEntityManager().delete(attachment, false);
if (attachment.getContentId() != null) {
commandContext.getByteArrayEntityManager().deleteByteArrayById(attachment.getContentId());
}
if (attachment.getTaskId() != null) {
commandContext
.getHistoryManager()
.createAttachmentComment(
attachment.getTaskId(),
attachment.getProcessInstanceId(),
attachment.getName(),
false | );
}
if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
commandContext
.getProcessEngineConfiguration()
.getEventDispatcher()
.dispatchEvent(
ActivitiEventBuilder.createEntityEvent(
ActivitiEventType.ENTITY_DELETED,
attachment,
processInstanceId,
processInstanceId,
processDefinitionId
)
);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\DeleteAttachmentCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean delete(Alarm alarm, User user) {
var tenantId = alarm.getTenantId();
var alarmId = alarm.getId();
var alarmOriginator = alarm.getOriginator();
boolean deleted;
try {
deleted = alarmSubscriptionService.deleteAlarm(tenantId, alarmId);
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(alarmOriginator.getEntityType()), ActionType.ALARM_DELETE, user, e, alarmId);
throw e;
}
if (deleted) {
logEntityActionService.logEntityAction(tenantId, alarmOriginator, alarm, alarm.getCustomerId(), ActionType.ALARM_DELETE, user, alarmId);
}
return deleted;
}
private static long getOrDefault(long ts) {
return ts > 0 ? ts : System.currentTimeMillis();
}
private void addSystemAlarmComment(Alarm alarm, User user, AlarmCommentSubType subType, String param, String value) {
Map<String, String> params = new LinkedHashMap<>(1);
params.put(param, value);
addSystemAlarmComment(alarm, user, subType, params);
}
private void addSystemAlarmComment(Alarm alarm, User user, AlarmCommentSubType subType, String param, String value, String param2, String value2) {
Map<String, String> params = new LinkedHashMap<>(2);
params.put(param, value);
params.put(param2, value2);
addSystemAlarmComment(alarm, user, subType, params);
}
private void addSystemAlarmComment(Alarm alarm, User user, AlarmCommentSubType subType, Map<String, String> params) { | ObjectNode commentNode = JacksonUtil.newObjectNode();
commentNode.put("text", String.format(subType.getText(), params.values().toArray()))
.put("subtype", subType.name());
params.forEach(commentNode::put);
AlarmComment alarmComment = AlarmComment.builder()
.alarmId(alarm.getId())
.type(AlarmCommentType.SYSTEM)
.comment(commentNode)
.build();
try {
alarmCommentService.saveAlarmComment(alarm, alarmComment, user);
} catch (ThingsboardException e) {
log.error("Failed to save alarm comment", e);
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\alarm\DefaultTbAlarmService.java | 2 |
请完成以下Java代码 | public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** Set Error Msg.
@param ErrorMsg Error Msg */
public void setErrorMsg (String ErrorMsg)
{
set_Value (COLUMNNAME_ErrorMsg, ErrorMsg);
}
/** Get Error Msg.
@return Error Msg */
public String getErrorMsg ()
{
return (String)get_Value(COLUMNNAME_ErrorMsg);
}
/** 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 Unique.
@param IsUnique Unique */
public void setIsUnique (boolean IsUnique)
{
set_Value (COLUMNNAME_IsUnique, Boolean.valueOf(IsUnique));
}
/** Get Unique.
@return Unique */
public boolean isUnique ()
{
Object oo = get_Value(COLUMNNAME_IsUnique);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_ValueNoCheck (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 Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); | }
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
@Override
public String getBeforeChangeWarning()
{
return (String)get_Value(COLUMNNAME_BeforeChangeWarning);
}
@Override
public void setBeforeChangeWarning(String BeforeChangeWarning)
{
set_Value (COLUMNNAME_BeforeChangeWarning, BeforeChangeWarning);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Index_Table.java | 1 |
请完成以下Java代码 | private String toJsonString(@NonNull final DocumentPostRequest request)
{
try
{
return jsonObjectMapper.writeValueAsString(request);
}
catch (Exception ex)
{
throw new AdempiereException("Failed converting to JSON: " + request, ex);
}
}
@NonNull
private DocumentPostRequest fromJson(@NonNull final String json)
{
try
{
return jsonObjectMapper.readValue(json, DocumentPostRequest.class);
}
catch (JsonProcessingException e)
{
throw new AdempiereException("Failed converting from JSON: " + json, e);
}
}
}
//
//
// -------------------------------------------------------------------------
//
//
@lombok.Builder
@lombok.ToString
private static final class DocumentPostRequestHandlerAsEventListener implements IEventListener
{
@NonNull private final DocumentPostRequestHandler handler;
@NonNull private final EventConverter eventConverter;
@NonNull private final EventLogUserService eventLogUserService; | @Override
public void onEvent(@NonNull final IEventBus eventBus, @NonNull final Event event)
{
final DocumentPostRequest request = eventConverter.extractDocumentPostRequest(event);
try (final IAutoCloseable ignored = switchCtx(request);
final MDCCloseable ignored1 = TableRecordMDC.putTableRecordReference(request.getRecord());
final MDCCloseable ignored2 = MDC.putCloseable("eventHandler.className", handler.getClass().getName()))
{
eventLogUserService.invokeHandlerAndLog(InvokeHandlerAndLogRequest.builder()
.handlerClass(handler.getClass())
.invokaction(() -> handleRequest(request))
.build());
}
}
private void handleRequest(@NonNull final DocumentPostRequest request)
{
handler.handleRequest(request);
}
private IAutoCloseable switchCtx(@NonNull final DocumentPostRequest request)
{
final Properties ctx = createCtx(request);
return Env.switchContext(ctx);
}
private Properties createCtx(@NonNull final DocumentPostRequest request)
{
final Properties ctx = Env.newTemporaryCtx();
Env.setClientId(ctx, request.getClientId());
return ctx;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\posting\DocumentPostingBusService.java | 1 |
请完成以下Java代码 | public TimerJobQuery orderByExecutionId() {
return orderBy(JobQueryProperty.EXECUTION_ID);
}
public TimerJobQuery orderByJobId() {
return orderBy(JobQueryProperty.JOB_ID);
}
public TimerJobQuery orderByProcessInstanceId() {
return orderBy(JobQueryProperty.PROCESS_INSTANCE_ID);
}
public TimerJobQuery orderByJobRetries() {
return orderBy(JobQueryProperty.RETRIES);
}
public TimerJobQuery orderByTenantId() {
return orderBy(JobQueryProperty.TENANT_ID);
}
// results //////////////////////////////////////////
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext.getTimerJobEntityManager().findJobCountByQueryCriteria(this);
}
public List<Job> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext.getTimerJobEntityManager().findJobsByQueryCriteria(this, page);
}
// getters //////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public boolean getRetriesLeft() {
return retriesLeft;
}
public boolean getExecutable() {
return executable;
}
public Date getNow() {
return Context.getProcessEngineConfiguration().getClock().getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage; | }
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getId() {
return id;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public boolean isOnlyTimers() {
return onlyTimers;
}
public boolean isOnlyMessages() {
return onlyMessages;
}
public Date getDuedateHigherThan() {
return duedateHigherThan;
}
public Date getDuedateLowerThan() {
return duedateLowerThan;
}
public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual;
}
public Date getDuedateLowerThanOrEqual() {
return duedateLowerThanOrEqual;
}
public boolean isNoRetriesLeft() {
return noRetriesLeft;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TimerJobQueryImpl.java | 1 |
请完成以下Java代码 | public class DefaultOneTimeToken implements OneTimeToken {
@Serial
private static final long serialVersionUID = -1545822943352278549L;
private final String token;
private final String username;
private final Instant expireAt;
public DefaultOneTimeToken(String token, String username, Instant expireAt) {
Assert.hasText(token, "token cannot be empty");
Assert.hasText(username, "username cannot be empty");
Assert.notNull(expireAt, "expireAt cannot be null");
this.token = token;
this.username = username;
this.expireAt = expireAt; | }
@Override
public String getTokenValue() {
return this.token;
}
@Override
public String getUsername() {
return this.username;
}
public Instant getExpiresAt() {
return this.expireAt;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\ott\DefaultOneTimeToken.java | 1 |
请完成以下Java代码 | public int getAD_ImpFormat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_ImpFormat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ansprechpartner.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
@Override
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get Ansprechpartner.
@return User within the system - Internal or Business Partner Contact
*/
@Override
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_DataImport getC_DataImport()
{
return get_ValueAsPO(COLUMNNAME_C_DataImport_ID, org.compiere.model.I_C_DataImport.class);
}
@Override
public void setC_DataImport(org.compiere.model.I_C_DataImport C_DataImport)
{
set_ValueFromPO(COLUMNNAME_C_DataImport_ID, org.compiere.model.I_C_DataImport.class, C_DataImport);
}
/** Set Daten Import.
@param C_DataImport_ID Daten Import */
@Override
public void setC_DataImport_ID (int C_DataImport_ID)
{
if (C_DataImport_ID < 1)
set_Value (COLUMNNAME_C_DataImport_ID, null);
else
set_Value (COLUMNNAME_C_DataImport_ID, Integer.valueOf(C_DataImport_ID));
}
/** Get Daten Import.
@return Daten Import */
@Override
public int getC_DataImport_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DataImport_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Data Import Run.
@param C_DataImport_Run_ID Data Import Run */
@Override
public void setC_DataImport_Run_ID (int C_DataImport_Run_ID)
{
if (C_DataImport_Run_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DataImport_Run_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DataImport_Run_ID, Integer.valueOf(C_DataImport_Run_ID));
}
/** Get Data Import Run.
@return Data Import Run */ | @Override
public int getC_DataImport_Run_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DataImport_Run_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beleg fertig stellen.
@param IsDocComplete
Legt fest, ob ggf erstellte Belege (z.B. Produktionsaufträge) auch direkt automatisch fertig gestellt werden sollen.
*/
@Override
public void setIsDocComplete (boolean IsDocComplete)
{
set_Value (COLUMNNAME_IsDocComplete, Boolean.valueOf(IsDocComplete));
}
/** Get Beleg fertig stellen.
@return Legt fest, ob ggf erstellte Belege (z.B. Produktionsaufträge) auch direkt automatisch fertig gestellt werden sollen.
*/
@Override
public boolean isDocComplete ()
{
Object oo = get_Value(COLUMNNAME_IsDocComplete);
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_DataImport_Run.java | 1 |
请完成以下Java代码 | public int getDLM_Partition_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set Partition is vollständig.
*
* @param IsPartitionComplete
* Sagt aus, ob das System dieser Partition noch weitere Datensätze hinzufügen muss bevor sie als Ganzes verschoben werden kann.
*/
@Override
public void setIsPartitionComplete(final boolean IsPartitionComplete)
{
set_Value(COLUMNNAME_IsPartitionComplete, Boolean.valueOf(IsPartitionComplete));
}
/**
* Get Partition is vollständig.
*
* @return Sagt aus, ob das System dieser Partition noch weitere Datensätze hinzufügen muss bevor sie als Ganzes verschoben werden kann.
*/
@Override
public boolean isPartitionComplete()
{
final Object oo = get_Value(COLUMNNAME_IsPartitionComplete);
if (oo != null)
{
if (oo instanceof Boolean)
{
return ((Boolean)oo).booleanValue();
}
return "Y".equals(oo);
}
return false;
}
/**
* Set Anz. zugeordneter Datensätze.
*
* @param PartitionSize Anz. zugeordneter Datensätze
*/
@Override
public void setPartitionSize(final int PartitionSize)
{
set_Value(COLUMNNAME_PartitionSize, Integer.valueOf(PartitionSize));
}
/**
* Get Anz. zugeordneter Datensätze.
*
* @return Anz. zugeordneter Datensätze
*/
@Override
public int getPartitionSize()
{ | final Integer ii = (Integer)get_Value(COLUMNNAME_PartitionSize);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set Ziel-DLM-Level.
*
* @param Target_DLM_Level Ziel-DLM-Level
*/
@Override
public void setTarget_DLM_Level(final int Target_DLM_Level)
{
set_Value(COLUMNNAME_Target_DLM_Level, Integer.valueOf(Target_DLM_Level));
}
/**
* Get Ziel-DLM-Level.
*
* @return Ziel-DLM-Level
*/
@Override
public int getTarget_DLM_Level()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_Target_DLM_Level);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition.java | 1 |
请完成以下Java代码 | public boolean isReady() {
return false;
}
public boolean isDelivered() {
return false;
}
public int getTimeToDelivery() {
return timeToDelivery;
}
PizzaStatusEnum(int timeToDelivery) {
this.timeToDelivery = timeToDelivery;
}
}
public PizzaStatusEnum getStatus() {
return status;
}
public void setStatus(PizzaStatusEnum status) {
this.status = status;
}
public boolean isDeliverable() {
return this.status.isReady();
}
public void printTimeToDeliver() {
System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
}
public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList()); | }
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
return pzList.stream().collect(Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
}
public void deliver() {
if (isDeliverable()) {
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
this.setStatus(PizzaStatusEnum.DELIVERED);
}
}
public int getDeliveryTimeInDays() {
switch (status) {
case ORDERED: return 5;
case READY: return 2;
case DELIVERED: return 0;
}
return 0;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-types\src\main\java\com\baeldung\enums\Pizza.java | 1 |
请完成以下Java代码 | protected final void invalidateView(@NonNull final IView view)
{
viewsRepo.invalidateView(view);
}
protected final void invalidateView(@NonNull final ViewId viewId)
{
viewsRepo.invalidateView(viewId);
}
protected final void invalidateView()
{
final IView view = getView();
invalidateView(view.getViewId());
}
protected final void invalidateParentView()
{
final IView view = getView();
final ViewId parentViewId = view.getParentViewId();
if (parentViewId != null)
{
invalidateView(parentViewId);
}
}
protected final boolean isSingleSelectedRow()
{
return getSelectedRowIds().isSingleDocumentId();
}
protected final DocumentIdsSelection getSelectedRowIds()
{
final ViewRowIdsSelection viewRowIdsSelection = Check.assumeNotNull(_viewRowIdsSelection, "View loaded");
return viewRowIdsSelection.getRowIds();
}
protected final <ID extends RepoIdAware> ImmutableSet<ID> getSelectedIds(@NonNull final IntFunction<ID> idMapper, @NonNull final QueryLimit limit)
{
final DocumentIdsSelection selectedRowsIds = getSelectedRowIds();
if (selectedRowsIds.isAll())
{
return streamSelectedRows()
.limit(limit.toIntOr(Integer.MAX_VALUE))
.map(row -> row.getId().toId(idMapper))
.collect(ImmutableSet.toImmutableSet());
}
else
{
return selectedRowsIds.toIdsFromInt(idMapper);
}
}
@OverridingMethodsMustInvokeSuper
protected IViewRow getSingleSelectedRow()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
final DocumentId documentId = selectedRowIds.getSingleDocumentId();
return getView().getById(documentId); | }
@OverridingMethodsMustInvokeSuper
protected Stream<? extends IViewRow> streamSelectedRows()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
return getView().streamByIds(selectedRowIds);
}
protected final ViewRowIdsSelection getParentViewRowIdsSelection()
{
return _parentViewRowIdsSelection;
}
protected final ViewRowIdsSelection getChildViewRowIdsSelection()
{
return _childViewRowIdsSelection;
}
@SuppressWarnings("SameParameterValue")
protected final <T extends IView> T getChildView(@NonNull final Class<T> viewType)
{
final ViewRowIdsSelection childViewRowIdsSelection = getChildViewRowIdsSelection();
Check.assumeNotNull(childViewRowIdsSelection, "child view is set");
final IView childView = viewsRepo.getView(childViewRowIdsSelection.getViewId());
return viewType.cast(childView);
}
protected final DocumentIdsSelection getChildViewSelectedRowIds()
{
final ViewRowIdsSelection childViewRowIdsSelection = getChildViewRowIdsSelection();
return childViewRowIdsSelection != null ? childViewRowIdsSelection.getRowIds() : DocumentIdsSelection.EMPTY;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\ViewBasedProcessTemplate.java | 1 |
请完成以下Java代码 | public String toString()
{
if (HanLP.Config.ShowTermNature)
return word + "/" + nature;
return word;
}
/**
* 长度
* @return
*/
public int length()
{
return word.length();
}
/**
* 获取本词语在HanLP词库中的频次
* @return 频次,0代表这是个OOV
*/
public int getFrequency() | {
return LexiconUtility.getFrequency(word);
}
/**
* 判断Term是否相等
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof Term)
{
Term term = (Term)obj;
if (this.nature == term.nature && this.word.equals(term.word))
{
return true;
}
}
return super.equals(obj);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\common\Term.java | 1 |
请完成以下Java代码 | public String getReferenceNumber() {
return referenceNumber;
}
/**
* Sets the value of the referenceNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReferenceNumber(String value) {
this.referenceNumber = value;
}
/**
* Gets the value of the customerNote property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCustomerNote() { | return customerNote;
}
/**
* Sets the value of the customerNote property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCustomerNote(String value) {
this.customerNote = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\EsrQRType.java | 1 |
请完成以下Java代码 | public boolean usingCoreJava(String strNum) {
if (strNum == null) {
return false;
}
try {
Double.parseDouble(strNum);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
public boolean usingPreCompiledRegularExpressions(String strNum) {
if (strNum == null) {
return false;
}
return pattern.matcher(strNum)
.matches();
} | public boolean usingNumberUtils_isCreatable(String strNum) {
return NumberUtils.isCreatable(strNum);
}
public boolean usingNumberUtils_isParsable(String strNum) {
return NumberUtils.isParsable(strNum);
}
public boolean usingStringUtils_isNumeric(String strNum) {
return StringUtils.isNumeric(strNum);
}
public boolean usingStringUtils_isNumericSpace(String strNum) {
return StringUtils.isNumericSpace(strNum);
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations\src\main\java\com\baeldung\isnumeric\IsNumeric.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public abstract class AbstractJobServiceEngineEntityManager<EntityImpl extends Entity, DM extends DataManager<EntityImpl>>
extends AbstractServiceEngineEntityManager<JobServiceConfiguration, EntityImpl, DM> {
public AbstractJobServiceEngineEntityManager(JobServiceConfiguration jobServiceConfiguration, String engineType, DM dataManager) {
super(jobServiceConfiguration, engineType, dataManager);
}
@Override
protected FlowableEntityEvent createEntityEvent(FlowableEngineEventType eventType, Entity entity) {
return FlowableJobEventBuilder.createEntityEvent(eventType, entity);
}
protected void deleteByteArrayRef(ByteArrayRef jobByteArrayRef) {
if (jobByteArrayRef != null) {
jobByteArrayRef.delete(serviceConfiguration.getEngineName()); | }
}
protected void bulkDeleteByteArraysById(List<String> byteArrayIds) {
if (byteArrayIds != null && byteArrayIds.size() > 0) {
CommandContext commandContext = Context.getCommandContext();
if (commandContext != null) {
AbstractEngineConfiguration abstractEngineConfiguration = commandContext.getEngineConfigurations().get(serviceConfiguration.getEngineName());
abstractEngineConfiguration.getByteArrayEntityManager().bulkDeleteByteArraysById(byteArrayIds);
} else {
throw new IllegalStateException("Could not bulk delete byte arrays. Was not able to get Command Context");
}
}
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\AbstractJobServiceEngineEntityManager.java | 2 |
请完成以下Java代码 | private Set<Object> getSimilarKeysToUpdate(final JTable table, final Object valueOld, final int rowIndexModel)
{
final UIDefaultsTableModel tableModel = (UIDefaultsTableModel)table.getModel();
final Set<Object> keysWithSameValue = tableModel.getKeysWithSameValue(valueOld, rowIndexModel);
if (keysWithSameValue.isEmpty())
{
return Collections.emptySet();
}
final JXList list = new JXList(keysWithSameValue.toArray());
list.setVisibleRowCount(20);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
final Object[] params = new Object[] {
"Following keys have the same value. Do you want to change them too?",
new JScrollPane(list) };
final int answer = JOptionPane.showConfirmDialog(
table, // parentComponent
params, // message
"Change similar keys?", // title
JOptionPane.YES_NO_OPTION // messageType
);
if (answer != JOptionPane.YES_OPTION)
{
return Collections.emptySet();
}
final Set<Object> keysToUpdate = new LinkedHashSet<>(Arrays.asList(list.getSelectedValues()));
return keysToUpdate;
}
}
/**
* {@link RowFilter} which includes only rows which contains a given <code>text</code>.
*
* @author tsa
*
*/
static class FullTextSearchRowFilter extends RowFilter<TableModel, Integer>
{
public static FullTextSearchRowFilter ofText(final String text)
{
if (Check.isEmpty(text, true))
{
return null;
}
else
{
return new FullTextSearchRowFilter(text);
}
}
private final String textUC;
private FullTextSearchRowFilter(final String text)
{
super(); | textUC = text.toUpperCase();
}
@Override
public boolean include(final javax.swing.RowFilter.Entry<? extends TableModel, ? extends Integer> entry)
{
for (int i = entry.getValueCount() - 1; i >= 0; i--)
{
String entryValue = entry.getStringValue(i);
if (entryValue == null || entryValue.isEmpty())
{
continue;
}
entryValue = entryValue.toUpperCase();
if (entryValue.indexOf(textUC) >= 0)
{
return true;
}
}
return false;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\plaf\UIDefaultsEditorDialog.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getUserId() {
return userId;
}
@Override
public String getData() {
return data;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getScopeId() {
return scopeId;
}
@Override
public String getScopeDefinitionId() { | return scopeDefinitionId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void create() {
// add is not supported by default
throw new RuntimeException("Operation is not supported");
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\BaseHistoricTaskLogEntryBuilderImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class UserConsumerServiceImpl implements UserConsumerService {
private static final String BASE_URL = "http://localhost:8080/users";
private final RestTemplate restTemplate;
private static final ObjectMapper mapper = new ObjectMapper();
public UserConsumerServiceImpl(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Override
public List<String> processUserDataFromObjectArray() {
ResponseEntity<Object[]> responseEntity = restTemplate.getForEntity(BASE_URL, Object[].class);
Object[] objects = responseEntity.getBody();
return Arrays.stream(objects)
.map(object -> mapper.convertValue(object, User.class))
.map(User::getName)
.collect(Collectors.toList());
}
@Override
public List<String> processUserDataFromUserArray() {
ResponseEntity<User[]> responseEntity = restTemplate.getForEntity(BASE_URL, User[].class);
User[] userArray = responseEntity.getBody();
return Arrays.stream(userArray)
.map(User::getName)
.collect(Collectors.toList());
}
@Override
public List<String> processUserDataFromUserList() {
ResponseEntity<List<User>> responseEntity =
restTemplate.exchange(
BASE_URL,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<User>>() {}
);
List<User> users = responseEntity.getBody();
return users.stream()
.map(User::getName)
.collect(Collectors.toList());
} | @Override
public List<String> processNestedUserDataFromUserArray() {
ResponseEntity<User[]> responseEntity = restTemplate.getForEntity(BASE_URL, User[].class);
User[] userArray = responseEntity.getBody();
//we can get more info if we need :
MediaType contentType = responseEntity.getHeaders().getContentType();
HttpStatusCode statusCode = responseEntity.getStatusCode();
return Arrays.stream(userArray)
.flatMap(user -> user.getAddressList().stream())
.map(Address::getPostCode)
.collect(Collectors.toList());
}
@Override
public List<String> processNestedUserDataFromUserList() {
ResponseEntity<List<User>> responseEntity =
restTemplate.exchange(
BASE_URL,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<User>>() {}
);
List<User> userList = responseEntity.getBody();
return userList.stream()
.flatMap(user -> user.getAddressList().stream())
.map(Address::getPostCode)
.collect(Collectors.toList());
}
} | repos\tutorials-master\spring-web-modules\spring-resttemplate-2\src\main\java\com\baeldung\resttemplate\json\consumer\service\UserConsumerServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ProductRepositoryImpl implements ProductRepository {
private static List<Product> productList = new ArrayList<>();
public ProductRepositoryImpl() {
for (int i = 1; i <= 10; i++){
Product product = new Product();
product.setId(i);
product.setName(String.format("Product %d", i));
product.setDescription(String.format("Product %d description", i));
product.setAttributes(createAttributes(i));
productList.add(product);
}
}
private Map<String, Attribute> createAttributes(int i) { | Map<String, Attribute> attributeMap = new HashMap<>();
attributeMap.put(String.format("attribute_%d",i), new Attribute(String.format("Attribute%d name",i),"This is custom attribute description","This is custom attribute unit"));
attributeMap.put("size", new Attribute((i & 1) == 0 ? "Small" : "Large","This is custom attribute description","This is custom attribute unit"));
return attributeMap;
}
@Override
public List<Product> getProducts(Integer pageSize, Integer pageNumber) {
return productList.stream().skip(pageSize*pageNumber).limit(pageSize).collect(Collectors.toList());
}
@Override
public Product getProduct(Integer id) {
return productList.stream().filter(product -> product.getId().equals(id)).findFirst().orElse(null);
}
} | repos\tutorials-master\graphql-modules\graphql-java\src\main\java\com\baeldung\graphqlreturnmap\repository\impl\ProductRepositoryImpl.java | 2 |
请完成以下Java代码 | public String getUserAgent() {
return userAgent;
}
@Override
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
@Override
public String getUserId() {
return userId;
}
@Override
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public String getTokenData() {
return tokenData;
}
@Override
public void setTokenData(String tokenData) {
this.tokenData = tokenData;
}
@Override
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<>();
persistentState.put("tokenValue", tokenValue);
persistentState.put("tokenDate", tokenDate);
persistentState.put("ipAddress", ipAddress); | persistentState.put("userAgent", userAgent);
persistentState.put("userId", userId);
persistentState.put("tokenData", tokenData);
return persistentState;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "TokenEntity[tokenValue=" + tokenValue + ", userId=" + userId + "]";
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\TokenEntityImpl.java | 1 |
请完成以下Java代码 | public void onModelChange(final Object model, final ModelChangeType changeType) throws Exception
{
if (!changeType.isAfter())
{
return;
}
//
// Model was created on changed
if (changeType.isNewOrChange())
{
createOrUpdateAllocation(model);
}
//
// Model was deleted
else if (changeType.isDelete())
{
deleteAllocation(model);
}
}
private void createOrUpdateAllocation(final Object model)
{
final IDeliveryDayBL deliveryDayBL = Services.get(IDeliveryDayBL.class);
final IContextAware context = InterfaceWrapperHelper.getContextAware(model);
final IDeliveryDayAllocable deliveryDayAllocable = handler.asDeliveryDayAllocable(model);
final I_M_DeliveryDay_Alloc deliveryDayAlloc = deliveryDayBL.getCreateDeliveryDayAlloc(context, deliveryDayAllocable);
if (deliveryDayAlloc == null)
{
// Case: no delivery day allocation was found and no delivery day on which we could allocate was found
return;
}
deliveryDayBL.getDeliveryDayHandlers()
.updateDeliveryDayAllocFromModel(deliveryDayAlloc, deliveryDayAllocable); | InterfaceWrapperHelper.save(deliveryDayAlloc);
}
private void deleteAllocation(Object model)
{
final IDeliveryDayDAO deliveryDayDAO = Services.get(IDeliveryDayDAO.class);
final IContextAware context = InterfaceWrapperHelper.getContextAware(model);
final IDeliveryDayAllocable deliveryDayAllocable = handler.asDeliveryDayAllocable(model);
final I_M_DeliveryDay_Alloc deliveryDayAlloc = deliveryDayDAO.retrieveDeliveryDayAllocForModel(context, deliveryDayAllocable);
if (deliveryDayAlloc != null)
{
InterfaceWrapperHelper.delete(deliveryDayAlloc);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\model\validator\DeliveryDayAllocableInterceptor.java | 1 |
请完成以下Java代码 | public RuntimeParameter upsertRuntimeParameter(@NonNull final RuntimeParameterUpsertRequest request)
{
final RuntimeParamUniqueKey uniqueKey = request.getRuntimeParamUniqueKey();
final I_ExternalSystem_RuntimeParameter record = getRecordByUniqueKey(uniqueKey)
.orElseGet(() -> InterfaceWrapperHelper.newInstance(I_ExternalSystem_RuntimeParameter.class));
record.setExternalSystem_Config_ID(uniqueKey.getExternalSystemParentConfigId().getRepoId());
record.setExternal_Request(uniqueKey.getRequest());
record.setName(uniqueKey.getName());
record.setValue(request.getValue());
saveRecord(record);
return recordToModel(record);
}
@NonNull
public ImmutableList<RuntimeParameter> getByConfigIdAndRequest(@NonNull final ExternalSystemParentConfigId configId, @NonNull final String externalRequest)
{
return queryBL.createQueryBuilder(I_ExternalSystem_RuntimeParameter.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_ExternalSystem_RuntimeParameter.COLUMNNAME_ExternalSystem_Config_ID, configId.getRepoId())
.addEqualsFilter(I_ExternalSystem_RuntimeParameter.COLUMNNAME_External_Request, externalRequest)
.create()
.list()
.stream()
.map(this::recordToModel)
.collect(ImmutableList.toImmutableList());
}
@NonNull
private RuntimeParameter recordToModel(@NonNull final I_ExternalSystem_RuntimeParameter record)
{ | return RuntimeParameter.builder()
.runtimeParameterId(RuntimeParameterId.ofRepoId(record.getExternalSystem_RuntimeParameter_ID()))
.externalSystemParentConfigId(ExternalSystemParentConfigId.ofRepoId(record.getExternalSystem_Config_ID()))
.request(record.getExternal_Request())
.name(record.getName())
.value(record.getValue())
.build();
}
@NonNull
private Optional<I_ExternalSystem_RuntimeParameter> getRecordByUniqueKey(@NonNull final RuntimeParamUniqueKey uniqueKey)
{
return queryBL.createQueryBuilder(I_ExternalSystem_RuntimeParameter.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_ExternalSystem_RuntimeParameter.COLUMNNAME_External_Request, uniqueKey.getRequest())
.addEqualsFilter(I_ExternalSystem_RuntimeParameter.COLUMNNAME_Name, uniqueKey.getName())
.addEqualsFilter(I_ExternalSystem_RuntimeParameter.COLUMNNAME_ExternalSystem_Config_ID, uniqueKey.getExternalSystemParentConfigId().getRepoId())
.create()
.firstOnlyOptional(I_ExternalSystem_RuntimeParameter.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\runtimeparameters\RuntimeParametersRepository.java | 1 |
请完成以下Java代码 | public void afterReceiveCompletion(final Message<?> message, final @NonNull MessageChannel channel, final Exception ex)
{
if (ex != null)
{
logger.warn("Failed receiving: message={}, channel={}", message, channel, ex);
}
}
}
private static class AuthorizationHandshakeInterceptor implements HandshakeInterceptor
{
private static final Logger logger = LogManager.getLogger(AuthorizationHandshakeInterceptor.class);
@Override
public boolean beforeHandshake(@NonNull final ServerHttpRequest request, final @NonNull ServerHttpResponse response, final @NonNull WebSocketHandler wsHandler, final @NonNull Map<String, Object> attributes)
{
final UserSession userSession = UserSession.getCurrentOrNull();
if (userSession == null)
{
logger.warn("Websocket connection not allowed (missing userSession)");
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return false;
}
if (!userSession.isLoggedIn())
{ | logger.warn("Websocket connection not allowed (not logged in) - userSession={}", userSession);
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return false;
}
return true;
}
@Override
public void afterHandshake(final @NonNull ServerHttpRequest request, final @NonNull ServerHttpResponse response, final @NonNull WebSocketHandler wsHandler, final Exception exception)
{
// nothing
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\websocket\WebsocketConfig.java | 1 |
请完成以下Java代码 | public Dimension getPreferredSize()
{
return new Dimension(0, 0);
}
};
private Color thumbColor;
private Color thumbColorMouseOver;
private Color thumbColorDragging;
private boolean isMouseButtonPressed = false;
MetasFreshScrollBarUI()
{
super();
noButton.setVisible(false);
noButton.setEnabled(false);
}
@Override
protected void installDefaults()
{
super.installDefaults();
trackColor = AdempierePLAF.getColor(KEY_Track_Color);
thumbColor = AdempierePLAF.getColor(KEY_Thumb_Color, DEFAULT_Thumb_Color);
thumbColorMouseOver = AdempierePLAF.getColor(KEY_Thumb_MouseOver_Color, DEFAULT_Thumb_MouseOver_Color);
thumbColorDragging = AdempierePLAF.getColor(KEY_Thumb_Dragging_Color, DEFAULT_Thumb_Dragging_Color);
scrollBarWidth = AdempierePLAF.getInt(KEY_Width, DEFAULT_Width);
}
@Override
protected void paintThumb(final Graphics g, final JComponent c, final Rectangle r)
{
final Color color;
if (!scrollbar.isEnabled())
{
color = thumbColor;
}
else if (isDragging || isMouseButtonPressed)
{
color = thumbColorDragging;
}
else if (isThumbRollover())
{
color = thumbColorMouseOver;
}
else
{
color = thumbColor;
}
g.setColor(color);
g.fillRect(r.x, r.y, r.width, r.height);
}
@Override
protected void paintTrack(final Graphics g, final JComponent c, final Rectangle r) | {
g.setColor(trackColor);
g.fillRect(r.x, r.y, r.width, r.height);
}
@Override
protected JButton createDecreaseButton(final int orientation)
{
return noButton;
}
@Override
protected JButton createIncreaseButton(final int orientation)
{
return noButton;
}
@Override
protected TrackListener createTrackListener()
{
return new MetasTrackListener();
}
private class MetasTrackListener extends TrackListener
{
@Override
public void mousePressed(MouseEvent e)
{
isMouseButtonPressed = true;
super.mousePressed(e);
scrollbar.repaint(getThumbBounds());
}
@Override
public void mouseReleased(MouseEvent e)
{
isMouseButtonPressed = false;
super.mouseReleased(e);
scrollbar.repaint(getThumbBounds());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\MetasFreshScrollBarUI.java | 1 |
请完成以下Java代码 | 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);
}
@Override
public void setIsDefault (final boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, IsDefault);
}
@Override
public boolean isDefault()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefault);
}
@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 setWEBUI_Dashboard_ID (final int WEBUI_Dashboard_ID)
{
if (WEBUI_Dashboard_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_Dashboard_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_Dashboard_ID, WEBUI_Dashboard_ID);
}
@Override
public int getWEBUI_Dashboard_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_Dashboard_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_Dashboard.java | 1 |
请完成以下Java代码 | public boolean invoke(final String tableName, final Object[] ids, final IContextAware ctx)
{
// do some basic checking
if (Check.isEmpty(tableName, true))
{
return false;
}
if (ids == null || ids.length != 1 || ids[0] == null)
{
return false;
}
if (!(ids[0] instanceof Integer))
{
return false;
}
final Mutable<Boolean> unArchiveWorked = new Mutable<>(false);
// attempt to load the record
final IConnectionCustomizerService connectionCustomizerService = Services.get(IConnectionCustomizerService.class);
try (final AutoCloseable customizer = connectionCustomizerService.registerTemporaryCustomizer(DLMConnectionCustomizer.seeThemAllCustomizer()))
{
Services.get(ITrxManager.class).runInNewTrx(new TrxRunnable()
{
@Override
public void run(final String localTrxName) throws Exception
{
final PlainContextAware localCtx = PlainContextAware.newWithTrxName(ctx.getCtx(), localTrxName);
final TableRecordReference reference = TableRecordReference.of(tableName, (int)ids[0]);
final IDLMAware model = reference.getModel(localCtx, IDLMAware.class); | if (model == null)
{
logger.info("Unable to load record for reference={}; returning false.", reference);
return;
}
if (model.getDLM_Level() == IMigratorService.DLM_Level_LIVE)
{
logger.info("The record could be loaded, but already had DLM_Level={}; returning false; reference={}; ", IMigratorService.DLM_Level_LIVE, reference);
return;
}
logger.info("Setting DLM_Level to {} for {}", IMigratorService.DLM_Level_LIVE, reference);
model.setDLM_Level(IMigratorService.DLM_Level_LIVE);
InterfaceWrapperHelper.save(model);
unArchiveWorked.setValue(true);
}
});
return unArchiveWorked.getValue();
}
catch (final Exception e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\po\UnArchiveRecordHandler.java | 1 |
请完成以下Java代码 | public void setRuntimeService(RuntimeService runtimeService) {
this.runtimeService = runtimeService;
}
public void setRepositoryService(RepositoryService repositoryService) {
this.repositoryService = repositoryService;
}
public void setManagementService(ManagementService managementService) {
this.managementService = managementService;
}
public boolean isCopyVariablesToProperties() {
return copyVariablesToProperties;
}
public void setCopyVariablesToProperties(boolean copyVariablesToProperties) {
this.copyVariablesToProperties = copyVariablesToProperties;
}
public boolean isCopyCamelBodyToBody() {
return copyCamelBodyToBody;
}
public void setCopyCamelBodyToBody(boolean copyCamelBodyToBody) {
this.copyCamelBodyToBody = copyCamelBodyToBody;
}
public boolean isCopyVariablesToBodyAsMap() {
return copyVariablesToBodyAsMap;
}
public void setCopyVariablesToBodyAsMap(boolean copyVariablesToBodyAsMap) {
this.copyVariablesToBodyAsMap = copyVariablesToBodyAsMap;
}
public String getCopyVariablesFromProperties() {
return copyVariablesFromProperties;
}
public void setCopyVariablesFromProperties(String copyVariablesFromProperties) {
this.copyVariablesFromProperties = copyVariablesFromProperties;
}
public String getCopyVariablesFromHeader() {
return copyVariablesFromHeader;
} | public void setCopyVariablesFromHeader(String copyVariablesFromHeader) {
this.copyVariablesFromHeader = copyVariablesFromHeader;
}
public boolean isCopyCamelBodyToBodyAsString() {
return copyCamelBodyToBodyAsString;
}
public void setCopyCamelBodyToBodyAsString(boolean copyCamelBodyToBodyAsString) {
this.copyCamelBodyToBodyAsString = copyCamelBodyToBodyAsString;
}
public boolean isSetProcessInitiator() {
return StringUtils.isNotEmpty(getProcessInitiatorHeaderName());
}
public Map<String, Object> getReturnVarMap() {
return returnVarMap;
}
public void setReturnVarMap(Map<String, Object> returnVarMap) {
this.returnVarMap = returnVarMap;
}
public String getProcessInitiatorHeaderName() {
return processInitiatorHeaderName;
}
public void setProcessInitiatorHeaderName(String processInitiatorHeaderName) {
this.processInitiatorHeaderName = processInitiatorHeaderName;
}
@Override
public boolean isLenientProperties() {
return true;
}
public long getTimeout() {
return timeout;
}
public int getTimeResolution() {
return timeResolution;
}
} | repos\flowable-engine-main\modules\flowable-camel\src\main\java\org\flowable\camel\FlowableEndpoint.java | 1 |
请完成以下Java代码 | public void openSession(@PathParam("username") String username, Session session) {
ONLINE_USER_SESSIONS.put(username, session);
String message = "欢迎用户[" + username + "] 来到聊天室!";
logger.info("用户登录:"+message);
sendMessageAll(message);
}
@OnMessage
public void onMessage(@PathParam("username") String username, String message) {
logger.info("发送消息:"+message);
sendMessageAll("用户[" + username + "] : " + message);
}
@OnClose
public void onClose(@PathParam("username") String username, Session session) {
//当前的Session 移除
ONLINE_USER_SESSIONS.remove(username);
//并且通知其他人当前用户已经离开聊天室了
sendMessageAll("用户[" + username + "] 已经离开聊天室了!");
try {
session.close();
} catch (IOException e) {
logger.error("onClose error",e); | }
}
@OnError
public void onError(Session session, Throwable throwable) {
try {
session.close();
} catch (IOException e) {
logger.error("onError excepiton",e);
}
logger.info("Throwable msg "+throwable.getMessage());
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-10 课: 使用 Spring Boot WebSocket 创建聊天室\spring-boot-websocket\src\main\java\com\neo\ChatRoomServerEndpoint.java | 1 |
请完成以下Java代码 | public BigDecimal getTrxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TrxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* TrxType AD_Reference_ID=215
* Reference name: C_Payment Trx Type
*/
public static final int TRXTYPE_AD_Reference_ID=215;
/** Sales = S */
public static final String TRXTYPE_Sales = "S";
/** DelayedCapture = D */
public static final String TRXTYPE_DelayedCapture = "D";
/** CreditPayment = C */
public static final String TRXTYPE_CreditPayment = "C";
/** VoiceAuthorization = F */
public static final String TRXTYPE_VoiceAuthorization = "F";
/** Authorization = A */
public static final String TRXTYPE_Authorization = "A";
/** Void = V */
public static final String TRXTYPE_Void = "V";
/** Rückzahlung = R */
public static final String TRXTYPE_Rueckzahlung = "R";
@Override
public void setTrxType (final @Nullable java.lang.String TrxType)
{
set_Value (COLUMNNAME_TrxType, TrxType);
}
@Override | public java.lang.String getTrxType()
{
return get_ValueAsString(COLUMNNAME_TrxType);
}
@Override
public void setValutaDate (final @Nullable java.sql.Timestamp ValutaDate)
{
set_Value (COLUMNNAME_ValutaDate, ValutaDate);
}
@Override
public java.sql.Timestamp getValutaDate()
{
return get_ValueAsTimestamp(COLUMNNAME_ValutaDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_I_BankStatement.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DocumentTypeType getDocumentType() {
return documentType;
}
/**
* Sets the value of the documentType property.
*
* @param value
* allowed object is
* {@link DocumentTypeType }
*
*/
public void setDocumentType(DocumentTypeType value) {
this.documentType = value;
}
/**
* In case a certain position in a document shall be referenced, this element may be used.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDocumentPositionNumber() {
return documentPositionNumber;
}
/**
* Sets the value of the documentPositionNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDocumentPositionNumber(String value) {
this.documentPositionNumber = value;
}
/**
* Reference date of the document. Typcially this element refers to the document date of the preceding document.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getReferenceDate() {
return referenceDate;
}
/**
* Sets the value of the referenceDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar } | *
*/
public void setReferenceDate(XMLGregorianCalendar value) {
this.referenceDate = value;
}
/**
* An optional description in free-text or a specification of the reference type for the DocumentType 'DocumentReference'.
*
* @return
* possible object is
* {@link DescriptionType }
*
*/
public DescriptionType getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link DescriptionType }
*
*/
public void setDescription(DescriptionType value) {
this.description = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DocumentReferenceType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ArticleEntity implements Serializable {
private String id;
private String title;
private String content;
private UserEntity userEntity;
private List<CommentEntity> commentEntityList;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public UserEntity getUserEntity() {
return userEntity;
}
public void setUserEntity(UserEntity userEntity) { | this.userEntity = userEntity;
}
public List<CommentEntity> getCommentEntityList() {
return commentEntityList;
}
public void setCommentEntityList(List<CommentEntity> commentEntityList) {
this.commentEntityList = commentEntityList;
}
@Override
public String toString() {
return "ArticleEntity{" +
"id='" + id + '\'' +
", title='" + title + '\'' +
", content='" + content + '\'' +
", userEntity=" + userEntity +
", commentEntityList=" + commentEntityList +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\ArticleEntity.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getDOCUMENTID() {
return documentid;
}
/**
* Sets the value of the documentid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDOCUMENTID(String value) {
this.documentid = value;
}
/**
* Gets the value of the amountqual property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAMOUNTQUAL() {
return amountqual;
}
/**
* Sets the value of the amountqual property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAMOUNTQUAL(String value) {
this.amountqual = value;
}
/**
* Gets the value of the amount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAMOUNT() {
return amount;
}
/**
* Sets the value of the amount property. | *
* @param value
* allowed object is
* {@link String }
*
*/
public void setAMOUNT(String value) {
this.amount = value;
}
/**
* Gets the value of the currency property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCURRENCY() {
return currency;
}
/**
* Sets the value of the currency property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCURRENCY(String value) {
this.currency = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\TAMOU1.java | 2 |
请完成以下Java代码 | public void handle(DecrementProductCountCommand command) {
if (orderConfirmed) {
throw new OrderAlreadyConfirmedException(command.getOrderId());
}
if (count <= 1) {
apply(new ProductRemovedEvent(command.getOrderId(), productId));
} else {
apply(new ProductCountDecrementedEvent(command.getOrderId(), productId));
}
}
@EventSourcingHandler
public void on(ProductCountIncrementedEvent event) {
this.count++;
}
@EventSourcingHandler
public void on(ProductCountDecrementedEvent event) {
this.count--;
}
@EventSourcingHandler
public void on(OrderConfirmedEvent event) {
this.orderConfirmed = true;
} | @Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OrderLine orderLine = (OrderLine) o;
return Objects.equals(productId, orderLine.productId) && Objects.equals(count, orderLine.count);
}
@Override
public int hashCode() {
return Objects.hash(productId, count);
}
} | repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\commandmodel\order\OrderLine.java | 1 |
请完成以下Java代码 | public void setIsRfQQty (boolean IsRfQQty)
{
set_Value (COLUMNNAME_IsRfQQty, Boolean.valueOf(IsRfQQty));
}
/** Get RfQ Quantity.
@return The quantity is used when generating RfQ Responses
*/
@Override
public boolean isRfQQty ()
{
Object oo = get_Value(COLUMNNAME_IsRfQQty);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Margin %.
@param Margin
Margin for a product as a percentage
*/
@Override
public void setMargin (java.math.BigDecimal Margin)
{
set_Value (COLUMNNAME_Margin, Margin);
}
/** Get Margin %.
@return Margin for a product as a percentage
*/
@Override
public java.math.BigDecimal getMargin ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Margin);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Offer Amount.
@param OfferAmt
Amount of the Offer
*/
@Override
public void setOfferAmt (java.math.BigDecimal OfferAmt)
{
set_Value (COLUMNNAME_OfferAmt, OfferAmt);
}
/** Get Offer Amount.
@return Amount of the Offer | */
@Override
public java.math.BigDecimal getOfferAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OfferAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Menge.
@param Qty
Quantity
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Quantity
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQLineQty.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_C_AllocationLine getReversalLine()
{
return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_C_AllocationLine.class);
}
@Override
public void setReversalLine(org.compiere.model.I_C_AllocationLine ReversalLine)
{
set_ValueFromPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_C_AllocationLine.class, ReversalLine);
}
/** Set Storno-Zeile.
@param ReversalLine_ID Storno-Zeile */
@Override
public void setReversalLine_ID (int ReversalLine_ID)
{
if (ReversalLine_ID < 1)
set_Value (COLUMNNAME_ReversalLine_ID, null);
else
set_Value (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID));
}
/** Get Storno-Zeile.
@return Storno-Zeile */
@Override
public int getReversalLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID);
if (ii == null) | return 0;
return ii.intValue();
}
/** Set Abschreiben.
@param WriteOffAmt
Amount to write-off
*/
@Override
public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt)
{
set_ValueNoCheck (COLUMNNAME_WriteOffAmt, WriteOffAmt);
}
/** Get Abschreiben.
@return Amount to write-off
*/
@Override
public java.math.BigDecimal getWriteOffAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AllocationLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String remit(HttpServletRequest request, Model model, DwzAjax dwz) {
String settId = request.getParameter("settId");
String settStatus = request.getParameter("settStatus");
String remark = request.getParameter("remark");
rpSettHandleService.remit(settId, settStatus, remark);
dwz.setStatusCode(DWZ.SUCCESS);
dwz.setMessage(DWZ.SUCCESS_MSG);
model.addAttribute("dwz", dwz);
return DWZ.AJAX_DONE;
}
/**
* 函数功能说明 :查看
*
* @参数: @return
* @return String
* @throws
*/
@RequestMapping(value = "/view", method = RequestMethod.GET)
public String view(Model model, @RequestParam("id") String id) {
RpSettRecord settRecord = rpSettQueryService.getDataById(id);
model.addAttribute("settRecord", settRecord);
return "sett/view"; | }
/**
* 函数功能说明 :根据支付产品获取支付方式
*
* @参数: @return
* @return String
* @throws
*/
@RequestMapping(value = "/getSettAmount", method = RequestMethod.GET)
@ResponseBody
public RpAccount getSettAmount(@RequestParam("userNo") String userNo) {
RpAccount rpAccount = rpAccountService.getDataByUserNo(userNo);
return rpAccount;
}
} | repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\sett\SettController.java | 2 |
请完成以下Java代码 | public Optional<GLCategoryId> getDefaultId(@NonNull final ClientId clientId)
{
return getDefaults(clientId).getDefaultId();
}
private DefaultGLCategories getDefaults(final ClientId clientId)
{
return defaultsCache.getOrLoad(clientId, this::retrieveDefaults);
}
private DefaultGLCategories retrieveDefaults(final ClientId clientId)
{
final ImmutableList<GLCategory> list = queryBL.createQueryBuilder(I_GL_Category.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_GL_Category.COLUMNNAME_AD_Client_ID, clientId)
.addEqualsFilter(I_GL_Category.COLUMNNAME_IsDefault, true)
.orderBy(I_GL_Category.COLUMNNAME_GL_Category_ID) // just to have a predictable order
.create()
.stream()
.map(GLCategoryRepository::fromRecord)
.collect(ImmutableList.toImmutableList());
return new DefaultGLCategories(list);
}
private static GLCategory fromRecord(@NonNull final I_GL_Category record)
{
return GLCategory.builder()
.id(GLCategoryId.ofRepoId(record.getGL_Category_ID()))
.name(record.getName())
.categoryType(GLCategoryType.ofCode(record.getCategoryType()))
.isDefault(record.isDefault())
.clientId(ClientId.ofRepoId(record.getAD_Client_ID()))
.build();
} | private static class DefaultGLCategories
{
private final ImmutableMap<GLCategoryType, GLCategory> byCategoryType;
private final ImmutableList<GLCategory> list;
DefaultGLCategories(final ImmutableList<GLCategory> list)
{
this.byCategoryType = Maps.uniqueIndex(list, GLCategory::getCategoryType);
this.list = list;
}
public Optional<GLCategoryId> getByCategoryType(@NonNull final GLCategoryType categoryType)
{
final GLCategory category = byCategoryType.get(categoryType);
if (category != null)
{
return Optional.of(category.getId());
}
return getDefaultId();
}
public Optional<GLCategoryId> getDefaultId()
{
return !list.isEmpty()
? Optional.of(list.get(0).getId())
: Optional.empty();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\GLCategoryRepository.java | 1 |
请完成以下Java代码 | public void setC_DataImport_Run_ID (int C_DataImport_Run_ID)
{
if (C_DataImport_Run_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DataImport_Run_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DataImport_Run_ID, Integer.valueOf(C_DataImport_Run_ID));
}
/** Get Data Import Run.
@return Data Import Run */
@Override
public int getC_DataImport_Run_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DataImport_Run_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beleg fertig stellen.
@param IsDocComplete
Legt fest, ob ggf erstellte Belege (z.B. Produktionsaufträge) auch direkt automatisch fertig gestellt werden sollen.
*/
@Override
public void setIsDocComplete (boolean IsDocComplete)
{
set_Value (COLUMNNAME_IsDocComplete, Boolean.valueOf(IsDocComplete)); | }
/** Get Beleg fertig stellen.
@return Legt fest, ob ggf erstellte Belege (z.B. Produktionsaufträge) auch direkt automatisch fertig gestellt werden sollen.
*/
@Override
public boolean isDocComplete ()
{
Object oo = get_Value(COLUMNNAME_IsDocComplete);
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_DataImport_Run.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Builder setRecord(final int AD_Table_ID, final int Record_ID)
{
this.AD_Table_ID = AD_Table_ID;
this.Record_ID = Record_ID;
return this;
}
public Builder setReportTemplatePath(final String reportTemplatePath)
{
this.reportTemplatePath = reportTemplatePath;
return this;
}
public Builder setSQLStatement(final String sqlStatement)
{
this.sqlStatement = sqlStatement;
return this;
}
public Builder setApplySecuritySettings(final boolean applySecuritySettings)
{
this.applySecuritySettings = applySecuritySettings;
return this;
}
private ImmutableList<ProcessInfoParameter> getProcessInfoParameters()
{
return Services.get(IADPInstanceDAO.class).retrieveProcessInfoParameters(pinstanceId)
.stream()
.map(this::transformProcessInfoParameter)
.collect(ImmutableList.toImmutableList());
}
private ProcessInfoParameter transformProcessInfoParameter(final ProcessInfoParameter piParam) | {
//
// Corner case: REPORT_SQL_QUERY
// => replace @AD_PInstance_ID@ placeholder with actual value
if (ReportConstants.REPORT_PARAM_SQL_QUERY.equals(piParam.getParameterName()))
{
final String parameterValue = piParam.getParameterAsString();
if (parameterValue != null)
{
final String parameterValueEffective = parameterValue.replace(ReportConstants.REPORT_PARAM_SQL_QUERY_AD_PInstance_ID_Placeholder, String.valueOf(pinstanceId.getRepoId()));
return ProcessInfoParameter.of(ReportConstants.REPORT_PARAM_SQL_QUERY, parameterValueEffective);
}
}
//
// Default: don't touch the original parameter
return piParam;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\server\ReportContext.java | 2 |
请完成以下Java代码 | public class FinReportPeriod
{
/**
* Constructor
* @param C_Period_ID period
* @param Name name
* @param StartDate period start date
* @param EndDate period end date
* @param YearStartDate year start date
*/
public FinReportPeriod (int C_Period_ID, String Name, Timestamp StartDate, Timestamp EndDate,
Timestamp YearStartDate)
{
m_C_Period_ID = C_Period_ID;
m_Name = Name;
m_StartDate = StartDate;
m_EndDate = EndDate;
m_YearStartDate = YearStartDate;
} //
private int m_C_Period_ID;
private String m_Name;
private Timestamp m_StartDate;
private Timestamp m_EndDate;
private Timestamp m_YearStartDate;
/**
* Get Period Info
* @return BETWEEN start AND end
*/
public String getPeriodWhere ()
{
StringBuffer sql = new StringBuffer ("BETWEEN ");
sql.append(DB.TO_DATE(m_StartDate))
.append(" AND ")
.append(DB.TO_DATE(m_EndDate));
return sql.toString();
} // getPeriodWhere
/**
* Get Year Info
* @return BETWEEN start AND end
*/
public String getYearWhere ()
{
StringBuffer sql = new StringBuffer ("BETWEEN ");
sql.append(DB.TO_DATE(m_YearStartDate))
.append(" AND ")
.append(DB.TO_DATE(m_EndDate));
return sql.toString();
} // getPeriodWhere
/**
* Get Total Info
* @return <= end
*/
public String getTotalWhere ()
{
StringBuffer sql = new StringBuffer ("<= ");
sql.append(DB.TO_DATE(m_EndDate));
return sql.toString();
} // getPeriodWhere
/**
* Is date in period
* @param date date
* @return true if in period
*/
public boolean inPeriod (Timestamp date)
{
if (date == null)
return false;
if (date.before(m_StartDate))
return false;
if (date.after(m_EndDate))
return false;
return true;
} // inPeriod
/**
* Get Name
* @return name
*/
public String getName()
{
return m_Name;
}
/**
* Get C_Period_ID
* @return period
*/
public int getC_Period_ID()
{
return m_C_Period_ID; | }
/**
* Get End Date
* @return end date
*/
public Timestamp getEndDate()
{
return m_EndDate;
}
/**
* Get Start Date
* @return start date
*/
public Timestamp getStartDate()
{
return m_StartDate;
}
/**
* Get Year Start Date
* @return year start date
*/
public Timestamp getYearStartDate()
{
return m_YearStartDate;
}
/**
* Get natural balance dateacct filter
* @param alias table name or alias name
* @return is balance sheet a/c and <= end or BETWEEN start AND end
*/
public String getNaturalWhere(String alias) {
String yearWhere = getYearWhere();
String totalWhere = getTotalWhere();
String bs = " EXISTS (SELECT C_ElementValue_ID FROM C_ElementValue WHERE C_ElementValue_ID = " + alias + ".Account_ID AND AccountType NOT IN ('R', 'E'))";
String full = totalWhere + " AND ( " + bs + " OR TRUNC(" + alias + ".DateAcct) " + yearWhere + " ) ";
return full;
}
} // FinReportPeriod | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\report\FinReportPeriod.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.