instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | private static Optional<String> getJsonExportDirectorySettings(@NonNull final ExternalSystemGRSSignumConfig grsSignumConfig)
{
if (!grsSignumConfig.isCreateBPartnerFolders())
{
return Optional.empty();
}
if (Check.isBlank(grsSignumConfig.getBPartnerExportDirectories()) || Check.isBlank(grsSignumConfig.getBasePathForExportDirectories()))
{
throw new AdempiereException("BPartnerExportDirectories and BasePathForExportDirectories must be set!")
.appendParametersToMessage()
.setParameter("ExternalSystem_Config_GRSSignum_ID", grsSignumConfig.getId());
}
final List<String> directories = Arrays
.stream(grsSignumConfig.getBPartnerExportDirectories().split(","))
.filter(Check::isNotBlank)
.collect(ImmutableList.toImmutableList()); | final JsonExportDirectorySettings exportDirectorySettings = JsonExportDirectorySettings.builder()
.basePath(grsSignumConfig.getBasePathForExportDirectories())
.directories(directories)
.build();
try
{
final String serializedExportDirectorySettings = JsonObjectMapperHolder.sharedJsonObjectMapper()
.writeValueAsString(exportDirectorySettings);
return Optional.of(serializedExportDirectorySettings);
}
catch (final JsonProcessingException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\grssignum\ExportBPartnerToGRSService.java | 1 |
请完成以下Java代码 | public void sendSimpleMessageUsingTemplate(String to,
String subject,
String ...templateModel) {
String text = String.format(template.getText(), templateModel);
sendSimpleMessage(to, subject, text);
}
@Override
public void sendMessageWithAttachment(String to,
String subject,
String text,
String pathToAttachment) {
try {
MimeMessage message = emailSender.createMimeMessage();
// pass 'true' to the constructor to create a multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(NOREPLY_ADDRESS);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
FileSystemResource file = new FileSystemResource(new File(pathToAttachment));
helper.addAttachment("Invoice", file);
emailSender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
@Override
public void sendMessageUsingThymeleafTemplate(
String to, String subject, Map<String, Object> templateModel)
throws MessagingException {
Context thymeleafContext = new Context();
thymeleafContext.setVariables(templateModel); | String htmlBody = thymeleafTemplateEngine.process("template-thymeleaf.html", thymeleafContext);
sendHtmlMessage(to, subject, htmlBody);
}
@Override
public void sendMessageUsingFreemarkerTemplate(
String to, String subject, Map<String, Object> templateModel)
throws IOException, TemplateException, MessagingException {
Template freemarkerTemplate = freemarkerConfigurer.getConfiguration().getTemplate("template-freemarker.ftl");
String htmlBody = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerTemplate, templateModel);
sendHtmlMessage(to, subject, htmlBody);
}
private void sendHtmlMessage(String to, String subject, String htmlBody) throws MessagingException {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(NOREPLY_ADDRESS);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(htmlBody, true);
helper.addInline("attachment.png", resourceFile);
emailSender.send(message);
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\mail\EmailServiceImpl.java | 1 |
请完成以下Java代码 | 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 Time based.
@param IsTimeBased
Time based Revenue Recognition rather than Service Level based
*/
public void setIsTimeBased (boolean IsTimeBased)
{
set_Value (COLUMNNAME_IsTimeBased, Boolean.valueOf(IsTimeBased));
}
/** Get Time based.
@return Time based Revenue Recognition rather than Service Level based
*/
public boolean isTimeBased ()
{
Object oo = get_Value(COLUMNNAME_IsTimeBased);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Number of Months.
@param NoMonths Number of Months */
public void setNoMonths (int NoMonths)
{
set_Value (COLUMNNAME_NoMonths, Integer.valueOf(NoMonths)); | }
/** Get Number of Months.
@return Number of Months */
public int getNoMonths ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NoMonths);
if (ii == null)
return 0;
return ii.intValue();
}
/** RecognitionFrequency AD_Reference_ID=196 */
public static final int RECOGNITIONFREQUENCY_AD_Reference_ID=196;
/** Month = M */
public static final String RECOGNITIONFREQUENCY_Month = "M";
/** Quarter = Q */
public static final String RECOGNITIONFREQUENCY_Quarter = "Q";
/** Year = Y */
public static final String RECOGNITIONFREQUENCY_Year = "Y";
/** Set Recognition frequency.
@param RecognitionFrequency Recognition frequency */
public void setRecognitionFrequency (String RecognitionFrequency)
{
set_Value (COLUMNNAME_RecognitionFrequency, RecognitionFrequency);
}
/** Get Recognition frequency.
@return Recognition frequency */
public String getRecognitionFrequency ()
{
return (String)get_Value(COLUMNNAME_RecognitionFrequency);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RevenueRecognition.java | 1 |
请完成以下Java代码 | public String getContentText ()
{
return (String)get_Value(COLUMNNAME_ContentText);
}
/** 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 Direct Deploy.
@param DirectDeploy Direct Deploy */
public void setDirectDeploy (String DirectDeploy)
{
set_Value (COLUMNNAME_DirectDeploy, DirectDeploy);
}
/** Get Direct Deploy.
@return Direct Deploy */
public String getDirectDeploy ()
{
return (String)get_Value(COLUMNNAME_DirectDeploy);
}
/** 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 Summary Level.
@param IsSummary
This is a summary entity
*/
public void setIsSummary (boolean IsSummary)
{
set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary));
}
/** Get Summary Level.
@return This is a summary entity
*/
public boolean isSummary ()
{
Object oo = get_Value(COLUMNNAME_IsSummary);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** MediaType AD_Reference_ID=388 */
public static final int MEDIATYPE_AD_Reference_ID=388;
/** image/gif = GIF */ | public static final String MEDIATYPE_ImageGif = "GIF";
/** image/jpeg = JPG */
public static final String MEDIATYPE_ImageJpeg = "JPG";
/** image/png = PNG */
public static final String MEDIATYPE_ImagePng = "PNG";
/** application/pdf = PDF */
public static final String MEDIATYPE_ApplicationPdf = "PDF";
/** text/css = CSS */
public static final String MEDIATYPE_TextCss = "CSS";
/** text/js = JS */
public static final String MEDIATYPE_TextJs = "JS";
/** Set Media Type.
@param MediaType
Defines the media type for the browser
*/
public void setMediaType (String MediaType)
{
set_Value (COLUMNNAME_MediaType, MediaType);
}
/** Get Media Type.
@return Defines the media type for the browser
*/
public String getMediaType ()
{
return (String)get_Value(COLUMNNAME_MediaType);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Media.java | 1 |
请完成以下Java代码 | public ParsedDeployment build() {
List<ProcessDefinitionEntity> processDefinitions = new ArrayList<>();
Map<ProcessDefinitionEntity, BpmnParse> processDefinitionsToBpmnParseMap = new LinkedHashMap<>();
Map<ProcessDefinitionEntity, EngineResource> processDefinitionsToResourceMap = new LinkedHashMap<>();
DeploymentEntity deploymentEntity = (DeploymentEntity) deployment;
for (EngineResource resource : deploymentEntity.getResources().values()) {
if (isBpmnResource(resource.getName())) {
LOGGER.debug("Processing BPMN resource {}", resource.getName());
BpmnParse parse = createBpmnParseFromResource(resource);
for (ProcessDefinitionEntity processDefinition : parse.getProcessDefinitions()) {
processDefinitions.add(processDefinition);
processDefinitionsToBpmnParseMap.put(processDefinition, parse);
processDefinitionsToResourceMap.put(processDefinition, resource);
}
}
}
return new ParsedDeployment(deploymentEntity, processDefinitions,
processDefinitionsToBpmnParseMap, processDefinitionsToResourceMap);
}
protected BpmnParse createBpmnParseFromResource(EngineResource resource) {
String resourceName = resource.getName();
ByteArrayInputStream inputStream = new ByteArrayInputStream(resource.getBytes());
BpmnParse bpmnParse = bpmnParser.createParse()
.sourceInputStream(inputStream)
.setSourceSystemId(resourceName)
.deployment(deployment)
.name(resourceName);
if (deploymentSettings != null) {
// Schema validation if needed
if (deploymentSettings.containsKey(DeploymentSettings.IS_BPMN20_XSD_VALIDATION_ENABLED)) {
bpmnParse.setValidateSchema((Boolean) deploymentSettings.get(DeploymentSettings.IS_BPMN20_XSD_VALIDATION_ENABLED));
}
// Process validation if needed
if (deploymentSettings.containsKey(DeploymentSettings.IS_PROCESS_VALIDATION_ENABLED)) {
bpmnParse.setValidateProcess((Boolean) deploymentSettings.get(DeploymentSettings.IS_PROCESS_VALIDATION_ENABLED));
} | } else {
// On redeploy, we assume it is validated at the first deploy
bpmnParse.setValidateSchema(false);
bpmnParse.setValidateProcess(false);
}
try {
bpmnParse.execute();
} catch (Exception e) {
LOGGER.error("Could not parse resource {}", resource.getName(), e);
throw e;
}
return bpmnParse;
}
protected boolean isBpmnResource(String resourceName) {
for (String suffix : ResourceNameUtil.BPMN_RESOURCE_SUFFIXES) {
if (resourceName.endsWith(suffix)) {
return true;
}
}
return false;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\deployer\ParsedDeploymentBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Application {
private static Logger logger = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);
//Send an user
System.out.println("Sending an user message.");
jmsTemplate.convertAndSend("userQueue",
new User("rameshfadatare@gmail.com", 5d, true));
logger.info("Waiting for user and confirmation ...");
System.in.read();
context.close();
} | @Bean // Serialize message content to json using TextMessage
public MessageConverter jacksonJmsMessageConverter() {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setTargetType(MessageType.TEXT);
converter.setTypeIdPropertyName("_type");
return converter;
}
@Bean
public JmsListenerContainerFactory<?> connectionFactory(ConnectionFactory connectionFactory,
DefaultJmsListenerContainerFactoryConfigurer configurer) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
// This provides all boot's default to this factory, including the message converter
configurer.configure(factory, connectionFactory);
// You could still override some of Boot's default if necessary.
return factory;
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot2-jms-activemq\src\main\java\net\alanbinu\springboot\Application.java | 2 |
请完成以下Java代码 | public class Division implements CalculatorOperation {
private double left;
private double right;
private double result = 0.0;
public Division(double left, double right) {
this.left = left;
this.right = right;
}
public double getLeft() {
return left;
}
public void setLeft(double left) {
this.left = left;
}
public double getRight() {
return right; | }
public void setRight(double right) {
this.right = right;
}
public double getResult() {
return result;
}
public void setResult(double result) {
this.result = result;
}
@Override
public void perform() {
if (right != 0) {
result = left / right;
}
}
} | repos\tutorials-master\patterns-modules\solid\src\main\java\com\baeldung\o\Division.java | 1 |
请完成以下Java代码 | public RetourenAnteilTypType getRetourenAnteilTyp() {
return retourenAnteilTyp;
}
/**
* Sets the value of the retourenAnteilTyp property.
*
* @param value
* allowed object is
* {@link RetourenAnteilTypType }
*
*/
public void setRetourenAnteilTyp(RetourenAnteilTypType value) {
this.retourenAnteilTyp = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre> | * <complexType>
* <complexContent>
* <extension base="{urn:msv3:v2}RetourePositionType">
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
public static class Position
extends RetourePositionType
{
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourenavisAnkuendigungAntwort.java | 1 |
请完成以下Java代码 | private String getRequestBody(@NonNull final CachedBodyHttpServletRequest requestWrapper)
{
try
{
final ObjectMapper objectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
if (requestWrapper.getContentLength() <= 0)
{
return null;
}
final Object body = objectMapper.readValue(requestWrapper.getInputStream(), Object.class);
return toJson(body);
}
catch (final IOException e)
{
throw new AdempiereException("Failed to parse request body!", e);
}
}
@Nullable
private String toJson(@Nullable final Object obj) | {
if (obj == null)
{
return null;
}
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(obj);
}
catch (final JsonProcessingException e)
{
throw new AdempiereException("Failed to parse object!", e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\dto\ApiRequestMapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DmnDeploymentBuilder parentDeploymentId(String parentDeploymentId) {
deployment.setParentDeploymentId(parentDeploymentId);
return this;
}
@Override
public DmnDeploymentBuilder enableDuplicateFiltering() {
isDuplicateFilterEnabled = true;
return this;
}
@Override
public DmnDeployment deploy() {
return repositoryService.deploy(this);
} | // getters and setters
// //////////////////////////////////////////////////////
public DmnDeploymentEntity getDeployment() {
return deployment;
}
public boolean isDmnXsdValidationEnabled() {
return isDmn20XsdValidationEnabled;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\repository\DmnDeploymentBuilderImpl.java | 2 |
请完成以下Java代码 | public int getPP_Order_ProductAttribute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_ProductAttribute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value); | }
/** Set Zahlwert.
@param ValueNumber
Numeric Value
*/
@Override
public void setValueNumber (java.math.BigDecimal ValueNumber)
{
set_Value (COLUMNNAME_ValueNumber, ValueNumber);
}
/** Get Zahlwert.
@return Numeric Value
*/
@Override
public java.math.BigDecimal getValueNumber ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ValueNumber);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_ProductAttribute.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getCategory() {
return category;
}
public String getDescription() {
return description;
}
public String getName() {
return name;
}
public int getVersion() {
return version;
}
public String getResource() {
return resource;
}
public String getDeploymentId() {
return deploymentId;
}
public String getDiagram() {
return diagram;
}
public boolean isSuspended() {
return suspended;
}
public String getTenantId() {
return tenantId;
}
public String getVersionTag() {
return versionTag; | }
public Integer getHistoryTimeToLive() {
return historyTimeToLive;
}
public boolean isStartableInTasklist() {
return isStartableInTasklist;
}
public static ProcessDefinitionDto fromProcessDefinition(ProcessDefinition definition) {
ProcessDefinitionDto dto = new ProcessDefinitionDto();
dto.id = definition.getId();
dto.key = definition.getKey();
dto.category = definition.getCategory();
dto.description = definition.getDescription();
dto.name = definition.getName();
dto.version = definition.getVersion();
dto.resource = definition.getResourceName();
dto.deploymentId = definition.getDeploymentId();
dto.diagram = definition.getDiagramResourceName();
dto.suspended = definition.isSuspended();
dto.tenantId = definition.getTenantId();
dto.versionTag = definition.getVersionTag();
dto.historyTimeToLive = definition.getHistoryTimeToLive();
dto.isStartableInTasklist = definition.isStartableInTasklist();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\ProcessDefinitionDto.java | 2 |
请完成以下Java代码 | protected final void pickQtyToNewHUs(@NonNull final Consumer<Quantity> pickQtyConsumer)
{
Quantity qtyToPack = getQtyToPack();
if (qtyToPack.signum() <= 0)
{
throw new AdempiereException("@QtyCU@ > 0");
}
final Capacity piipCapacity = getPIIPCapacity();
if (piipCapacity.isInfiniteCapacity())
{
pickQtyConsumer.accept(qtyToPack);
return;
}
final Quantity piipQtyCapacity = piipCapacity.toQuantity();
while (qtyToPack.toBigDecimal().signum() > 0)
{
final Quantity qtyToProcess = piipQtyCapacity.min(qtyToPack);
pickQtyConsumer.accept(qtyToProcess);
qtyToPack = qtyToPack.subtract(qtyToProcess);
}
}
@NonNull
private QuantityTU getQtyTU()
{
return getPIIPCapacity().calculateQtyTU(qtyCUsPerTU, getCurrentShipmentScheuduleUOM(), uomConversionBL) | .orElseThrow(() -> new AdempiereException("QtyTU cannot be obtained for the current request!")
.appendParametersToMessage()
.setParameter("QtyCU", qtyCUsPerTU)
.setParameter("ShipmentScheduleId", getCurrentShipmentScheduleId()));
}
@NonNull
protected final Capacity getPIIPCapacity()
{
final I_M_ShipmentSchedule currentShipmentSchedule = getCurrentShipmentSchedule();
final ProductId productId = ProductId.ofRepoId(currentShipmentSchedule.getM_Product_ID());
final I_C_UOM stockUOM = productBL.getStockUOM(productId);
return huCapacityBL.getCapacity(huPIItemProduct, productId, stockUOM);
}
@NonNull
private BigDecimal getDefaultNrOfHUs()
{
if (qtyCUsPerTU == null || huPIItemProduct == null)
{
return BigDecimal.ONE;
}
return getQtyTU().toBigDecimal();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_PickQtyToComputedHU.java | 1 |
请完成以下Java代码 | private static ImmutableSet<RecordAccessId> extractIds(final Collection<I_AD_User_Record_Access> accessRecords)
{
return accessRecords.stream()
.map(RecordAccessService::extractId)
.collect(ImmutableSet.toImmutableSet());
}
private static RecordAccessId extractId(final I_AD_User_Record_Access record)
{
return RecordAccessId.ofRepoId(record.getAD_User_Record_Access_ID());
}
@Nullable
public String buildUserGroupRecordAccessSqlWhereClause(
final String tableName,
@NonNull final AdTableId adTableId,
@NonNull final String keyColumnNameFQ,
@NonNull final UserId userId,
@NonNull final Set<UserGroupId> userGroupIds,
@NonNull final RoleId roleId)
{
if (!isApplyUserGroupRecordAccess(roleId, tableName))
{
return null;
}
final StringBuilder sql = new StringBuilder();
sql.append(" EXISTS (SELECT 1 FROM " + I_AD_User_Record_Access.Table_Name + " z " + " WHERE " + " z.AD_Table_ID = ").append(adTableId.getRepoId()).append(" AND z.Record_ID=").append(keyColumnNameFQ).append(" AND z.IsActive='Y'");
//
// User or User Group
sql.append(" AND (AD_User_ID=").append(userId.getRepoId());
if (!userGroupIds.isEmpty())
{
sql.append(" OR ").append(DB.buildSqlList("z.AD_UserGroup_ID", userGroupIds));
}
sql.append(")");
//
sql.append(" )"); // EXISTS
//
return sql.toString();
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean isApplyUserGroupRecordAccess(
@NonNull final RoleId roleId,
@NonNull final String tableName)
{ | return configs
.getByRoleId(roleId)
.isTableHandled(tableName);
}
public boolean hasRecordPermission(
@NonNull final UserId userId,
@NonNull final RoleId roleId,
@NonNull final TableRecordReference recordRef,
@NonNull final Access permission)
{
if (!isApplyUserGroupRecordAccess(roleId, recordRef.getTableName()))
{
return true;
}
final RecordAccessQuery query = RecordAccessQuery.builder()
.recordRef(recordRef)
.permission(permission)
.principals(getPrincipals(userId))
.build();
return recordAccessRepository.query(query)
.addOnlyActiveRecordsFilter()
.create()
.anyMatch();
}
private Set<Principal> getPrincipals(@NonNull final UserId userId)
{
final ImmutableSet.Builder<Principal> principals = ImmutableSet.builder();
principals.add(Principal.userId(userId));
for (final UserGroupId userGroupId : userGroupsRepo.getAssignedGroupIdsByUserId(userId))
{
principals.add(Principal.userGroupId(userGroupId));
}
return principals.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\record_access\RecordAccessService.java | 1 |
请完成以下Java代码 | public final Object getEmptyValue()
{
final Object value = getValue();
if (value == null)
{
return null;
}
if (value instanceof BigDecimal)
{
return BigDecimal.ZERO;
}
else if (value instanceof String)
{
return null;
}
else if (TimeUtil.isDateOrTimeObject(value))
{
return null;
}
else
{
throw new InvalidAttributeValueException("Value type '" + value.getClass() + "' not supported for " + attribute);
}
}
@Override
public final void addAttributeValueListener(final IAttributeValueListener listener)
{
listeners.addAttributeValueListener(listener);
}
@Override
public final void removeAttributeValueListener(final IAttributeValueListener listener)
{
listeners.removeAttributeValueListener(listener);
}
@Override
public I_C_UOM getC_UOM()
{
final int uomId = attribute.getC_UOM_ID();
if (uomId > 0)
{
return Services.get(IUOMDAO.class).getById(uomId);
}
else
{ | return null;
}
}
private IAttributeValueCallout _attributeValueCallout = null;
@Override
public IAttributeValueCallout getAttributeValueCallout()
{
if (_attributeValueCallout == null)
{
final IAttributeValueGenerator attributeValueGenerator = getAttributeValueGeneratorOrNull();
if (attributeValueGenerator instanceof IAttributeValueCallout)
{
_attributeValueCallout = (IAttributeValueCallout)attributeValueGenerator;
}
else
{
_attributeValueCallout = NullAttributeValueCallout.instance;
}
}
return _attributeValueCallout;
}
@Override
public IAttributeValueGenerator getAttributeValueGeneratorOrNull()
{
final I_M_Attribute attribute = getM_Attribute();
final IAttributeValueGenerator attributeValueGenerator = Services.get(IAttributesBL.class).getAttributeValueGeneratorOrNull(attribute);
return attributeValueGenerator;
}
/**
* @return true if NOT disposed
* @see IAttributeStorage#assertNotDisposed()
*/
protected final boolean assertNotDisposed()
{
return getAttributeStorage().assertNotDisposed();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\AbstractAttributeValue.java | 1 |
请完成以下Java代码 | public Integer getOrderCount() {
return orderCount;
}
public void setOrderCount(Integer orderCount) {
this.orderCount = orderCount;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Integer getSort() {
return sort;
} | public void setSort(Integer sort) {
this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", type=").append(type);
sb.append(", pic=").append(pic);
sb.append(", startTime=").append(startTime);
sb.append(", endTime=").append(endTime);
sb.append(", status=").append(status);
sb.append(", clickCount=").append(clickCount);
sb.append(", orderCount=").append(orderCount);
sb.append(", url=").append(url);
sb.append(", note=").append(note);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsHomeAdvertise.java | 1 |
请在Spring Boot框架中完成以下Java代码 | 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 |
请完成以下Java代码 | void fillTransient() {
if (priorityValue > 0) {
this.priority = Priority.of(priorityValue);
}
}
@PrePersist
void fillPersistent() {
if (priority != null) {
this.priorityValue = priority.getPriority();
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Status getStatus() {
return status; | }
public void setStatus(Status status) {
this.status = status;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Priority getPriority() {
return priority;
}
public void setPriority(Priority priority) {
this.priority = priority;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
} | repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\enums\Article.java | 1 |
请完成以下Java代码 | public String getRestartedProcessInstanceId() {
return restartedProcessInstanceId;
}
public void setRestartedProcessInstanceId(String restartedProcessInstanceId) {
this.restartedProcessInstanceId = restartedProcessInstanceId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[businessKey=" + businessKey
+ ", startUserId=" + startUserId
+ ", superProcessInstanceId=" + superProcessInstanceId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", superCaseInstanceId=" + superCaseInstanceId
+ ", deleteReason=" + deleteReason
+ ", durationInMillis=" + durationInMillis
+ ", startTime=" + startTime | + ", endTime=" + endTime
+ ", removalTime=" + removalTime
+ ", endActivityId=" + endActivityId
+ ", startActivityId=" + startActivityId
+ ", id=" + id
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", processInstanceId=" + processInstanceId
+ ", tenantId=" + tenantId
+ ", restartedProcessInstanceId=" + restartedProcessInstanceId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricProcessInstanceEventEntity.java | 1 |
请完成以下Java代码 | public ConditionExpression getCondition() {
return conditionChild.getChild(this);
}
public void setCondition(ConditionExpression expression) {
conditionChild.setChild(this, expression);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ApplicabilityRule.class, CMMN_ELEMENT_APPLICABILITY_RULE)
.namespaceUri(CMMN11_NS)
.extendsType(CmmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<ApplicabilityRule>() {
public ApplicabilityRule newInstance(ModelTypeInstanceContext instanceContext) {
return new ApplicabilityRuleImpl(instanceContext);
}
}); | nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
contextRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CONTEXT_REF)
.idAttributeReference(CaseFileItem.class)
.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\ApplicabilityRuleImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public NotificationSettings getNotificationSettings(@AuthenticationPrincipal SecurityUser user) throws ThingsboardException {
accessControlService.checkPermission(user, Resource.ADMIN_SETTINGS, Operation.READ);
TenantId tenantId = user.isSystemAdmin() ? TenantId.SYS_TENANT_ID : user.getTenantId();
return notificationSettingsService.findNotificationSettings(tenantId);
}
@ApiOperation(value = "Get available delivery methods (getAvailableDeliveryMethods)",
notes = "Returns the list of delivery methods that are properly configured and are allowed to be used for sending notifications." +
SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH)
@GetMapping("/notification/deliveryMethods")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
public List<NotificationDeliveryMethod> getAvailableDeliveryMethods(@AuthenticationPrincipal SecurityUser user) throws ThingsboardException {
return notificationCenter.getAvailableDeliveryMethods(user.getTenantId());
} | @PostMapping("/notification/settings/user")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
public UserNotificationSettings saveUserNotificationSettings(@RequestBody @Valid UserNotificationSettings settings,
@AuthenticationPrincipal SecurityUser user) {
return notificationSettingsService.saveUserNotificationSettings(user.getTenantId(), user.getId(), settings);
}
@GetMapping("/notification/settings/user")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
public UserNotificationSettings getUserNotificationSettings(@AuthenticationPrincipal SecurityUser user) {
return notificationSettingsService.getUserNotificationSettings(user.getTenantId(), user.getId(), true);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\NotificationController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public DataSource eventsDataSource(@Qualifier("eventsDataSourceProperties") DataSourceProperties eventsDataSourceProperties) {
return eventsDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
@Bean
public LocalContainerEntityManagerFactoryBean eventsEntityManagerFactory(@Qualifier(EVENTS_DATA_SOURCE) DataSource eventsDataSource,
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(eventsDataSource)
.packages(LifecycleEventEntity.class, StatisticsEventEntity.class, ErrorEventEntity.class, RuleNodeDebugEventEntity.class, RuleChainDebugEventEntity.class, AuditLogEntity.class, CalculatedFieldDebugEventEntity.class)
.persistenceUnit(EVENTS_PERSISTENCE_UNIT)
.build();
}
@Bean(EVENTS_TRANSACTION_MANAGER) | public JpaTransactionManager eventsTransactionManager(@Qualifier("eventsEntityManagerFactory") LocalContainerEntityManagerFactoryBean eventsEntityManagerFactory) {
return new JpaTransactionManager(Objects.requireNonNull(eventsEntityManagerFactory.getObject()));
}
@Bean(EVENTS_TRANSACTION_TEMPLATE)
public TransactionTemplate eventsTransactionTemplate(@Qualifier(EVENTS_TRANSACTION_MANAGER) JpaTransactionManager eventsTransactionManager) {
return new TransactionTemplate(eventsTransactionManager);
}
@Bean(EVENTS_JDBC_TEMPLATE)
public JdbcTemplate eventsJdbcTemplate(@Qualifier(EVENTS_DATA_SOURCE) DataSource eventsDataSource) {
return new JdbcTemplate(eventsDataSource);
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\config\DedicatedEventsJpaDaoConfig.java | 2 |
请完成以下Java代码 | private int getPageLength()
{
return pageLength;
}
public static SqlComposedKey extractComposedKey(
final DocumentId recordId,
final List<? extends SqlEntityFieldBinding> keyFields)
{
final int count = keyFields.size();
if (count < 1)
{
throw new AdempiereException("Invalid composed key: " + keyFields);
}
final List<Object> composedKeyParts = recordId.toComposedKeyParts();
if (composedKeyParts.size() != count)
{
throw new AdempiereException("Invalid composed key '" + recordId + "'. Expected " + count + " parts but it has " + composedKeyParts.size());
}
final ImmutableSet.Builder<String> keyColumnNames = ImmutableSet.builder();
final ImmutableMap.Builder<String, Object> values = ImmutableMap.builder();
for (int i = 0; i < count; i++)
{
final SqlEntityFieldBinding keyField = keyFields.get(i);
final String keyColumnName = keyField.getColumnName();
keyColumnNames.add(keyColumnName); | final Object valueObj = composedKeyParts.get(i);
@Nullable final Object valueConv = DataTypes.convertToValueClass(
keyColumnName,
valueObj,
keyField.getWidgetType(),
keyField.getSqlValueClass(),
null);
if (!JSONNullValue.isNull(valueConv))
{
values.put(keyColumnName, valueConv);
}
}
return SqlComposedKey.of(keyColumnNames.build(), values.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlDocumentQueryBuilder.java | 1 |
请完成以下Java代码 | public final int executeUpdate() throws SQLException
{
return trace(() -> delegate.executeUpdate());
}
@Override
public final void clearParameters() throws SQLException
{
delegate.clearParameters();
}
@Override
public final boolean execute() throws SQLException
{
return trace(() -> delegate.execute());
}
@Override
public final void addBatch() throws SQLException
{
trace(() -> { | delegate.addBatch();
return null;
});
}
@Override
public final ResultSetMetaData getMetaData() throws SQLException
{
return delegate.getMetaData();
}
@Override
public final ParameterMetaData getParameterMetaData() throws SQLException
{
return delegate.getParameterMetaData();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\sql\impl\TracingPreparedStatement.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PurchaseCandidateReminderSchedulerRestController
{
public static final String ENDPOINT = WebConfig.ENDPOINT_ROOT + "/purchaseCandidates/reminders";
@Autowired
private PurchaseCandidateReminderScheduler reminderScheduler;
@Autowired
private UserSession userSession;
private void assertAuth()
{
userSession.assertLoggedIn();
final AdWindowId purchaseCandidatesWindowId = RecordWindowFinder.findAdWindowId(I_C_PurchaseCandidate.Table_Name).get();
if (!userSession.getUserRolePermissions().checkWindowPermission(purchaseCandidatesWindowId).hasWriteAccess())
{
throw new AdempiereException("No read/write access to purchase candidates window");
}
}
@GetMapping
public List<PurchaseCandidateReminder> getReminders()
{
assertAuth();
return reminderScheduler.getReminders(); | }
@PostMapping
public synchronized void addReminder(@RequestBody final PurchaseCandidateReminder reminder)
{
assertAuth();
reminderScheduler.scheduleNotification(reminder);
}
@GetMapping("/nextDispatchTime")
public ZonedDateTime getNextDispatchTime()
{
assertAuth();
return reminderScheduler.getNextDispatchTime();
}
@PostMapping("/reinitialize")
public List<PurchaseCandidateReminder> reinitialize()
{
assertAuth();
reminderScheduler.initialize();
return reminderScheduler.getReminders();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\purchasecandidate\reminder\PurchaseCandidateReminderSchedulerRestController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
@Bean(name = BeanIds.USER_DETAILS_SERVICE)
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.
// 使用内存中的 InMemoryUserDetailsManager
inMemoryAuthentication() | // 不使用 PasswordEncoder 密码编码器
.passwordEncoder(passwordEncoder())
// 配置 yunai 用户
.withUser("yunai").password("1024").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
// 设置 /token/demo/revoke 无需授权
.mvcMatchers("/token/demo/revoke").permitAll()
// 设置其它接口需要授权
.anyRequest().authenticated();
}
} | repos\SpringBoot-Labs-master\lab-68-spring-security-oauth\lab-68-demo03-authorization-server-with-resource-owner-password-credentials\src\main\java\cn\iocoder\springboot\lab68\authorizationserverdemo\config\SecurityConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public abstract class OtpBasedTwoFaProvider<C extends OtpBasedTwoFaProviderConfig, A extends OtpBasedTwoFaAccountConfig> implements TwoFaProvider<C, A> {
private final Cache verificationCodesCache;
protected OtpBasedTwoFaProvider(CacheManager cacheManager) {
this.verificationCodesCache = cacheManager.getCache(CacheConstants.TWO_FA_VERIFICATION_CODES_CACHE);
}
@Override
public final void prepareVerificationCode(SecurityUser user, C providerConfig, A accountConfig) throws ThingsboardException {
String verificationCode = StringUtils.randomNumeric(6);
sendVerificationCode(user, verificationCode, providerConfig, accountConfig);
verificationCodesCache.put(user.getId(), new Otp(System.currentTimeMillis(), verificationCode, accountConfig));
}
protected abstract void sendVerificationCode(SecurityUser user, String verificationCode, C providerConfig, A accountConfig) throws ThingsboardException;
@Override
public final boolean checkVerificationCode(SecurityUser user, String code, C providerConfig, A accountConfig) {
Otp correctVerificationCode = verificationCodesCache.get(user.getId(), Otp.class);
if (correctVerificationCode != null) {
if (System.currentTimeMillis() - correctVerificationCode.getTimestamp()
> TimeUnit.SECONDS.toMillis(providerConfig.getVerificationCodeLifetime())) {
verificationCodesCache.evict(user.getId());
return false; | }
if (code.equals(correctVerificationCode.getValue())
&& accountConfig.equals(correctVerificationCode.getAccountConfig())) {
verificationCodesCache.evict(user.getId());
return true;
}
}
return false;
}
@Data
public static class Otp implements Serializable {
private final long timestamp;
private final String value;
private final OtpBasedTwoFaAccountConfig accountConfig;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\mfa\provider\impl\OtpBasedTwoFaProvider.java | 2 |
请完成以下Java代码 | public Map<String, Object> getTaskLocalVariables() {
return activiti5Task.getTaskLocalVariables();
}
@Override
public Map<String, Object> getProcessVariables() {
return activiti5Task.getProcessVariables();
}
@Override
public Map<String, Object> getCaseVariables() {
return null;
}
@Override
public List<? extends IdentityLinkInfo> getIdentityLinks() {
return null;
}
@Override
public Date getClaimTime() {
return null;
}
@Override
public void setName(String name) {
activiti5Task.setName(name);
}
@Override
public void setLocalizedName(String name) {
activiti5Task.setLocalizedName(name);
}
@Override
public void setDescription(String description) {
activiti5Task.setDescription(description);
}
@Override
public void setLocalizedDescription(String description) {
activiti5Task.setLocalizedDescription(description);
}
@Override
public void setPriority(int priority) {
activiti5Task.setPriority(priority);
}
@Override
public void setOwner(String owner) {
activiti5Task.setOwner(owner);
}
@Override
public void setAssignee(String assignee) {
activiti5Task.setAssignee(assignee);
}
@Override
public DelegationState getDelegationState() {
return activiti5Task.getDelegationState();
}
@Override | public void setDelegationState(DelegationState delegationState) {
activiti5Task.setDelegationState(delegationState);
}
@Override
public void setDueDate(Date dueDate) {
activiti5Task.setDueDate(dueDate);
}
@Override
public void setCategory(String category) {
activiti5Task.setCategory(category);
}
@Override
public void setParentTaskId(String parentTaskId) {
activiti5Task.setParentTaskId(parentTaskId);
}
@Override
public void setTenantId(String tenantId) {
activiti5Task.setTenantId(tenantId);
}
@Override
public void setFormKey(String formKey) {
activiti5Task.setFormKey(formKey);
}
@Override
public boolean isSuspended() {
return activiti5Task.isSuspended();
}
} | repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5TaskWrapper.java | 1 |
请完成以下Java代码 | public boolean acquireLock() {
return acquireLock(lockForceAcquireAfter);
}
@Override
public boolean acquireLock(Duration lockForceAcquireAfter) {
if (hasAcquiredLock) {
return true;
}
try {
hasAcquiredLock = executeCommand(new LockCmd(lockName, lockForceAcquireAfter, engineType));
if (hasAcquiredLock) {
LOGGER.debug("Successfully acquired lock {}", lockName);
}
} catch (FlowableOptimisticLockingException ex) {
LOGGER.debug("Failed to acquire lock {} due to optimistic locking", lockName, ex);
hasAcquiredLock = false;
} catch (FlowableException ex) {
if (ex.getClass().equals(FlowableException.class)) {
// If it is a FlowableException then log a warning and wait to try again
LOGGER.warn("Failed to acquire lock {} due to unknown exception", lockName, ex);
hasAcquiredLock = false;
} else {
// Re-throw any other Flowable specific exception
throw ex;
}
} catch (RuntimeException ex) {
if (ex.getCause() instanceof SQLIntegrityConstraintViolationException) {
// This can happen if 2 nodes try to acquire a lock in the exact same time
LOGGER.debug("Failed to acquire lock {} due to constraint violation", lockName, ex);
} else {
LOGGER.info("Failed to acquire lock {} due to unknown exception", lockName, ex);
}
hasAcquiredLock = false;
}
return hasAcquiredLock;
}
@Override
public void releaseLock() {
executeCommand(new ReleaseLockCmd(lockName, engineType, false));
LOGGER.debug("successfully released lock {}", lockName);
hasAcquiredLock = false;
}
@Override | public void releaseAndDeleteLock() {
executeCommand(new ReleaseLockCmd(lockName, engineType, true));
LOGGER.debug("successfully released and deleted lock {}", lockName);
hasAcquiredLock = false;
}
@Override
public <T> T waitForLockRunAndRelease(Duration waitTime, Supplier<T> supplier) {
waitForLock(waitTime);
try {
return supplier.get();
} finally {
releaseLock();
}
}
protected <T> T executeCommand(Command<T> command) {
return commandExecutor.execute(lockCommandConfig, command);
}
protected Duration getLockPollRate() {
return lockPollRate;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\lock\LockManagerImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | void init() {
jdbcTemplate.setResultsMapCaseInsensitive(true);
}
public void fetchAnthologyAuthors() {
SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withProcedureName("FETCH_AUTHOR_BY_GENRE");
List<Author> authors = simpleJdbcCall.execute(Map.of("p_genre", "Anthology")).entrySet()
.stream()
.filter(m -> "#result-set-1".equals(m.getKey()))
.map(m -> (List<Map<String, Object>>) m.getValue())
.flatMap(List::stream)
.map(BookstoreService::fetchAuthor)
.collect(toList()); | System.out.println("Result: " + authors);
}
public static Author fetchAuthor(Map<String, Object> data) {
Author author = new Author();
author.setId((Long) data.get("id"));
author.setName((String) data.get("name"));
author.setGenre((String) data.get("genre"));
author.setAge((int) data.get("age"));
return author;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootCallStoredProcedureJdbcTemplate\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private void mapTemplateProperties(Template properties, JmsTemplate template) {
PropertyMapper map = PropertyMapper.get();
map.from(properties.getSession().getAcknowledgeMode()::getMode).to(template::setSessionAcknowledgeMode);
map.from(properties.getSession()::isTransacted).to(template::setSessionTransacted);
map.from(properties::getDefaultDestination).to(template::setDefaultDestinationName);
map.from(properties::getDeliveryDelay).as(Duration::toMillis).to(template::setDeliveryDelay);
map.from(properties::determineQosEnabled).to(template::setExplicitQosEnabled);
map.from(properties::getDeliveryMode).as(DeliveryMode::getValue).to(template::setDeliveryMode);
map.from(properties::getPriority).to(template::setPriority);
map.from(properties::getTimeToLive).as(Duration::toMillis).to(template::setTimeToLive);
map.from(properties::getReceiveTimeout).as(Duration::toMillis).to(template::setReceiveTimeout);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(JmsMessagingTemplate.class)
static class MessagingTemplateConfiguration {
@Bean
@ConditionalOnMissingBean(JmsMessageOperations.class)
@ConditionalOnSingleCandidate(JmsTemplate.class)
JmsMessagingTemplate jmsMessagingTemplate(JmsProperties properties, JmsTemplate jmsTemplate) {
JmsMessagingTemplate messagingTemplate = new JmsMessagingTemplate(jmsTemplate);
mapTemplateProperties(properties.getTemplate(), messagingTemplate); | return messagingTemplate;
}
private void mapTemplateProperties(Template properties, JmsMessagingTemplate messagingTemplate) {
PropertyMapper map = PropertyMapper.get();
map.from(properties::getDefaultDestination).to(messagingTemplate::setDefaultDestinationName);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(JmsClient.class)
static class JmsClientConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnSingleCandidate(JmsTemplate.class)
JmsClient jmsClient(JmsTemplate jmsTemplate) {
return JmsClient.create(jmsTemplate);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JmsClientConfigurations.java | 2 |
请完成以下Java代码 | public void launchDailySettCollect(List<RpAccount> accountList, Date endDate) {
if (accountList == null || accountList.isEmpty()) {
return;
}
// 单商户发起结算
for (RpAccount rpAccount : accountList) {
try {
LOG.debug(rpAccount.getUserNo() + ":开始汇总");
dailySettCollectBiz.dailySettCollect(rpAccount, endDate);
LOG.debug(rpAccount.getUserNo() + ":汇总结束");
} catch (Exception e) {
LOG.error(rpAccount.getUserNo()+":汇总异常", e);
}
}
}
/**
* 发起定期自动结算.<br/>
*
* @param userEnterpriseList
* 结算商户.<br/>
*/
public void launchAutoSett(List<RpAccount> accountList) { | if (accountList == null || accountList.isEmpty()) {
return;
}
// 单商户发起结算
for (RpAccount rpAccount : accountList) {
try {
RpUserPayConfig rpUserPayConfig = rpUserPayConfigService.getByUserNo(rpAccount.getUserNo());
if (rpUserPayConfig == null) {
LOG.info(rpAccount.getUserNo() + "没有商家设置信息,不进行结算");
continue;
}
if (rpUserPayConfig.getIsAutoSett().equals(PublicEnum.YES.name())) {
LOG.debug(rpAccount.getUserNo() + ":开始自动结算");
rpSettHandleService.launchAutoSett(rpAccount.getUserNo());
LOG.debug(rpAccount.getUserNo() + ":自动结算结束");
} else {
LOG.info(rpAccount.getUserNo() + ":非自动结算商家");
}
} catch (Exception e) {
LOG.error("自动结算异常:" + rpAccount.getUserNo(), e);
}
}
}
} | repos\roncoo-pay-master\roncoo-pay-app-settlement\src\main\java\com\roncoo\pay\app\settlement\biz\SettBiz.java | 1 |
请完成以下Java代码 | public static long getDaysBetween360(@NonNull final ZonedDateTime from, @NonNull final ZonedDateTime to)
{
if (from.isEqual(to))
{
return 0;
}
if (to.isBefore(from))
{
return getDaysBetween360(to, from) * -1;
}
ZonedDateTime dayFrom = from;
ZonedDateTime dayTo = to;
if (dayFrom.getDayOfMonth() == 31)
{
dayFrom = dayFrom.withDayOfMonth(30);
}
if (dayTo.getDayOfMonth() == 31)
{
dayTo = dayTo.withDayOfMonth(30);
}
final long months = ChronoUnit.MONTHS.between(
YearMonth.from(dayFrom), YearMonth.from(dayTo));
final int daysLeft = dayTo.getDayOfMonth() - dayFrom.getDayOfMonth(); | return 30 * months + daysLeft;
}
/**
* Compute the days between two dates as if each year is 360 days long.
* More details and an implementation for Excel can be found in {@link org.apache.poi.ss.formula.functions.Days360}
*/
public static long getDaysBetween360(@NonNull final Instant from, @NonNull final Instant to)
{
return getDaysBetween360(asZonedDateTime(from), asZonedDateTime(to));
}
public static Instant addDays(@NonNull final Instant baseInstant, final long daysToAdd)
{
return baseInstant.plus(daysToAdd, ChronoUnit.DAYS);
}
} // TimeUtil | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\TimeUtil.java | 1 |
请完成以下Java代码 | public class RuleNodeDebugEventEntity extends EventEntity<RuleNodeDebugEvent> implements BaseEntity<RuleNodeDebugEvent> {
@Column(name = EVENT_TYPE_COLUMN_NAME)
private String eventType;
@Column(name = EVENT_ENTITY_ID_COLUMN_NAME)
private UUID eventEntityId;
@Column(name = EVENT_ENTITY_TYPE_COLUMN_NAME)
private String eventEntityType;
@Column(name = EVENT_MSG_ID_COLUMN_NAME)
private UUID msgId;
@Column(name = EVENT_MSG_TYPE_COLUMN_NAME)
private String msgType;
@Column(name = EVENT_DATA_TYPE_COLUMN_NAME)
private String dataType;
@Column(name = EVENT_RELATION_TYPE_COLUMN_NAME)
private String relationType;
@Column(name = EVENT_DATA_COLUMN_NAME)
private String data;
@Column(name = EVENT_METADATA_COLUMN_NAME)
private String metadata;
@Column(name = EVENT_ERROR_COLUMN_NAME)
private String error;
public RuleNodeDebugEventEntity(RuleNodeDebugEvent event) {
super(event);
this.eventType = event.getEventType();
if (event.getEventEntity() != null) {
this.eventEntityId = event.getEventEntity().getId();
this.eventEntityType = event.getEventEntity().getEntityType().name();
}
this.msgId = event.getMsgId();
this.msgType = event.getMsgType();
this.dataType = event.getDataType(); | this.relationType = event.getRelationType();
this.data = event.getData();
this.metadata = event.getMetadata();
this.error = event.getError();
}
@Override
public RuleNodeDebugEvent toData() {
var builder = RuleNodeDebugEvent.builder()
.tenantId(TenantId.fromUUID(tenantId))
.entityId(entityId)
.serviceId(serviceId)
.id(id)
.ts(ts)
.eventType(eventType)
.msgId(msgId)
.msgType(msgType)
.dataType(dataType)
.relationType(relationType)
.data(data)
.metadata(metadata)
.error(error);
if (eventEntityId != null) {
builder.eventEntity(EntityIdFactory.getByTypeAndUuid(eventEntityType, eventEntityId));
}
return builder.build();
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\RuleNodeDebugEventEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getTypeOfPackaging() {
return typeOfPackaging;
}
/**
* Sets the value of the typeOfPackaging property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTypeOfPackaging(String value) {
this.typeOfPackaging = value;
}
/**
* Gets the value of the nve property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNVE() {
return nve;
}
/**
* Sets the value of the nve property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNVE(String value) {
this.nve = value;
}
/**
* Gets the value of the grossVolume property.
*
* @return
* possible object is | * {@link UnitType }
*
*/
public UnitType getGrossVolume() {
return grossVolume;
}
/**
* Sets the value of the grossVolume property.
*
* @param value
* allowed object is
* {@link UnitType }
*
*/
public void setGrossVolume(UnitType value) {
this.grossVolume = value;
}
/**
* Gets the value of the grossWeight property.
*
* @return
* possible object is
* {@link UnitType }
*
*/
public UnitType getGrossWeight() {
return grossWeight;
}
/**
* Sets the value of the grossWeight property.
*
* @param value
* allowed object is
* {@link UnitType }
*
*/
public void setGrossWeight(UnitType value) {
this.grossWeight = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\PackagingInformationType.java | 2 |
请完成以下Java代码 | public void complete(String externalTaskId, Map<String, Object> variables, Map<String, Object> localVariables) {
try {
engineClient.complete(externalTaskId, variables, localVariables);
} catch (EngineClientException e) {
throw LOG.handledEngineClientException("completing the external task", e);
}
}
@Override
public void handleFailure(ExternalTask externalTask, String errorMessage, String errorDetails, int retries, long retryTimeout) {
handleFailure(externalTask.getId(), errorMessage, errorDetails, retries, retryTimeout);
}
@Override
public void handleFailure(String externalTaskId, String errorMessage, String errorDetails, int retries, long retryTimeout) {
handleFailure(externalTaskId, errorMessage, errorDetails, retries, retryTimeout, null, null);
}
@Override
public void handleFailure(String externalTaskId, String errorMessage, String errorDetails, int retries, long retryTimeout, Map<String, Object> variables, Map<String, Object> locaclVariables) {
try {
engineClient.failure(externalTaskId, errorMessage, errorDetails, retries, retryTimeout, variables, locaclVariables);
} catch (EngineClientException e) {
throw LOG.handledEngineClientException("notifying a failure", e);
}
}
@Override
public void handleBpmnError(ExternalTask externalTask, String errorCode) {
handleBpmnError(externalTask, errorCode, null, null);
}
@Override
public void handleBpmnError(ExternalTask externalTask, String errorCode, String errorMessage) {
handleBpmnError(externalTask, errorCode, errorMessage, null);
}
@Override
public void handleBpmnError(ExternalTask externalTask, String errorCode, String errorMessage, Map<String, Object> variables) {
handleBpmnError(externalTask.getId(), errorCode, errorMessage, variables); | }
@Override
public void handleBpmnError(String externalTaskId, String errorCode, String errorMessage, Map<String, Object> variables) {
try {
engineClient.bpmnError(externalTaskId, errorCode, errorMessage, variables);
} catch (EngineClientException e) {
throw LOG.handledEngineClientException("notifying a BPMN error", e);
}
}
@Override
public void extendLock(ExternalTask externalTask, long newDuration) {
extendLock(externalTask.getId(), newDuration);
}
@Override
public void extendLock(String externalTaskId, long newDuration) {
try {
engineClient.extendLock(externalTaskId, newDuration);
} catch (EngineClientException e) {
throw LOG.handledEngineClientException("extending lock", e);
}
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\task\impl\ExternalTaskServiceImpl.java | 1 |
请完成以下Java代码 | public class CallActivity extends Activity {
protected String calledElement;
protected boolean inheritVariables;
protected List<IOParameter> inParameters = new ArrayList<IOParameter>();
protected List<IOParameter> outParameters = new ArrayList<IOParameter>();
protected String businessKey;
protected boolean inheritBusinessKey;
public String getCalledElement() {
return calledElement;
}
public void setCalledElement(String calledElement) {
this.calledElement = calledElement;
}
public boolean isInheritVariables() {
return inheritVariables;
}
public void setInheritVariables(boolean inheritVariables) {
this.inheritVariables = inheritVariables;
}
public List<IOParameter> getInParameters() {
return inParameters;
}
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
}
public List<IOParameter> getOutParameters() {
return outParameters;
}
public void setOutParameters(List<IOParameter> outParameters) {
this.outParameters = outParameters;
}
public String getBusinessKey() {
return businessKey;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public boolean isInheritBusinessKey() { | return inheritBusinessKey;
}
public void setInheritBusinessKey(boolean inheritBusinessKey) {
this.inheritBusinessKey = inheritBusinessKey;
}
public CallActivity clone() {
CallActivity clone = new CallActivity();
clone.setValues(this);
return clone;
}
public void setValues(CallActivity otherElement) {
super.setValues(otherElement);
setCalledElement(otherElement.getCalledElement());
setBusinessKey(otherElement.getBusinessKey());
setInheritBusinessKey(otherElement.isInheritBusinessKey());
inParameters = new ArrayList<IOParameter>();
if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getInParameters()) {
inParameters.add(parameter.clone());
}
}
outParameters = new ArrayList<IOParameter>();
if (otherElement.getOutParameters() != null && !otherElement.getOutParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getOutParameters()) {
outParameters.add(parameter.clone());
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\CallActivity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BusinessRuleEventProcessorWatcher
{
@NonNull private static final Logger logger = LogManager.getLogger(BusinessRuleEventProcessorWatcher.class);
@NonNull private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
@NonNull private final BusinessRuleService ruleService;
private static final String SYSCONFIG_PollIntervalInSeconds = "BusinessRuleEventProcessorWatcher.pollIntervalInSeconds";
private static final Duration DEFAULT_PollInterval = Duration.ofSeconds(10);
static final String SYSCONFIG_RetrieveBatchSize = "BusinessRuleEventProcessorWatcher.retrieveBatchSize";
private static final QueryLimit DEFAULT_RetrieveBatchSize = QueryLimit.ofInt(2000);
@PostConstruct
public void postConstruct()
{
startThread();
}
private void startThread()
{
final Thread thread = new Thread(this::processEventsLoop);
thread.setDaemon(true);
thread.setName("BusinessRuleEventsProcessor");
thread.start();
logger.info("Started {}", thread);
}
private void processEventsLoop()
{
while (true)
{
try
{
sleep();
}
catch (final InterruptedException e)
{
logger.info("Got interrupt request. Exiting.");
Thread.currentThread().interrupt();
return;
}
try
{
ruleService.processEvents(getRetrieveBatchSize());
}
catch (final Exception ex)
{ | logger.warn("Failed to process. Ignored.", ex);
}
}
}
private void sleep() throws InterruptedException
{
final Duration pollInterval = getPollInterval();
logger.debug("Sleeping {}", pollInterval);
Thread.sleep(pollInterval.toMillis());
}
private Duration getPollInterval()
{
final int pollIntervalInSeconds = sysConfigBL.getIntValue(SYSCONFIG_PollIntervalInSeconds, -1);
return pollIntervalInSeconds > 0 ? Duration.ofSeconds(pollIntervalInSeconds) : DEFAULT_PollInterval;
}
private QueryLimit getRetrieveBatchSize()
{
final int retrieveBatchSize = sysConfigBL.getIntValue(SYSCONFIG_RetrieveBatchSize, -1);
return retrieveBatchSize > 0 ? QueryLimit.ofInt(retrieveBatchSize) : DEFAULT_RetrieveBatchSize;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\server\BusinessRuleEventProcessorWatcher.java | 2 |
请完成以下Java代码 | class ProductBOMCycleDetection
{
public static ProductBOMCycleDetection newInstance()
{
return new ProductBOMCycleDetection();
}
private static final AdMessageKey ERR_PRODUCT_BOM_CYCLE = AdMessageKey.of("Product_BOM_Cycle_Error");
private final Set<ProductId> seenProductIds = new LinkedHashSet<>();
private ProductBOMCycleDetection()
{
}
public void checkCycles(final ProductId productId)
{
try
{
assertNoCycles(productId);
}
catch (final BOMCycleException e)
{
final I_M_Product product = Services.get(IProductBL.class).getById(productId);
throw new AdempiereException(ERR_PRODUCT_BOM_CYCLE, product.getValue());
}
}
private DefaultMutableTreeNode assertNoCycles(final ProductId productId)
{
final DefaultMutableTreeNode productNode = new DefaultMutableTreeNode(productId);
final IProductBOMDAO productBOMDAO = Services.get(IProductBOMDAO.class);
final List<I_PP_Product_BOMLine> productBOMLines = productBOMDAO.retrieveBOMLinesByComponentIdInTrx(productId);
boolean first = true;
for (final I_PP_Product_BOMLine productBOMLine : productBOMLines)
{
// Don't navigate the Co/ByProduct lines (gh480)
if (isByOrCoProduct(productBOMLine))
{
continue;
}
// If not the first bom line at this level
if (!first)
{
clearSeenProducts();
markProductAsSeen(productId);
}
first = false;
final DefaultMutableTreeNode bomNode = assertNoCycles(productBOMLine);
if (bomNode != null)
{
productNode.add(bomNode);
}
} | return productNode;
}
private static boolean isByOrCoProduct(final I_PP_Product_BOMLine bomLine)
{
final BOMComponentType componentType = BOMComponentType.ofCode(Objects.requireNonNull(bomLine.getComponentType()));
return componentType.isByOrCoProduct();
}
@Nullable
private DefaultMutableTreeNode assertNoCycles(final I_PP_Product_BOMLine bomLine)
{
final I_PP_Product_BOM bom = bomLine.getPP_Product_BOM();
if (!bom.isActive())
{
return null;
}
// Check Child = Parent error
final ProductId productId = ProductId.ofRepoId(bomLine.getM_Product_ID());
final ProductId parentProductId = ProductId.ofRepoId(bom.getM_Product_ID());
if (productId.equals(parentProductId))
{
throw new BOMCycleException(bom, productId);
}
// Check BOM Loop Error
if (!markProductAsSeen(parentProductId))
{
throw new BOMCycleException(bom, parentProductId);
}
return assertNoCycles(parentProductId);
}
private void clearSeenProducts()
{
seenProductIds.clear();
}
private boolean markProductAsSeen(final ProductId productId)
{
return seenProductIds.add(productId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\impl\ProductBOMCycleDetection.java | 1 |
请完成以下Java代码 | public String execute()
{
final String name = !Check.isEmpty(this.nameInitial, true)
? this.nameInitial.trim()
: buildDefaultName();
return truncateAndMakeUnique(name);
}
private String buildDefaultName()
{
String defaultName = "";
//
// City
defaultName = appendToName(defaultName, address.getCity());
//
// Address1
defaultName = appendToName(defaultName, address.getAddress1());
// Company Name
defaultName = appendToName(defaultName, companyName);
if (isValidUniqueName(defaultName))
{
return defaultName;
}
//
// Address2
{
defaultName = appendToName(defaultName, address.getAddress2());
if (isValidUniqueName(defaultName))
{
return defaultName;
}
}
//
// Address3
{
defaultName = appendToName(defaultName, address.getAddress3());
if (isValidUniqueName(defaultName))
{
return defaultName;
}
}
//
// Address4
{
defaultName = appendToName(defaultName, address.getAddress4());
if (isValidUniqueName(defaultName))
{
return defaultName;
}
}
//
// Country
if (defaultName.isEmpty())
{
final CountryId countryId = CountryId.ofRepoId(address.getC_Country_ID());
final String countryName = countriesRepo.getCountryNameById(countryId).getDefaultValue();
defaultName = appendToName(defaultName, countryName);
}
return defaultName;
}
private static String appendToName(final String name, final String namePartToAppend)
{
if (name == null || name.isEmpty())
{
return namePartToAppend != null ? namePartToAppend.trim() : "";
} | else if (Check.isEmpty(namePartToAppend, true))
{
return name.trim();
}
else
{
return name.trim() + " " + namePartToAppend.trim();
}
}
private boolean isValidUniqueName(final String name)
{
return !Check.isEmpty(name, true)
&& !existingNames.contains(name);
}
private String truncateAndMakeUnique(@NonNull final String name)
{
Check.assumeNotEmpty(name, "name is not empty");
int i = 2;
String nameUnique = StringUtils.trunc(name, maxLength);
while (existingNames.contains(nameUnique))
{
final String suffix = " (" + i + ")";
nameUnique = StringUtils.trunc(name, maxLength - suffix.length()) + suffix;
i++;
}
return nameUnique;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MakeUniqueLocationNameCommand.java | 1 |
请完成以下Java代码 | public int compare(final I_M_HU_Attribute o1, final I_M_HU_Attribute o2)
{
// Same instance
if (o1 == o2)
{
return 0;
}
final int seqNo1 = getSeqNo(o1);
final int seqNo2 = getSeqNo(o2);
if (seqNo1 < seqNo2)
{
return -1;
}
else if (seqNo1 == seqNo2)
{
// NOTE: basically those are equal but let's have a predictable order, so we are ordering them by M_Attribute_ID
return o1.getM_Attribute_ID() - o2.getM_Attribute_ID();
}
// seqNo1 > seqNo2 | return 1;
}
private int getSeqNo(final I_M_HU_Attribute huAttribute)
{
final AttributeId attributeId = AttributeId.ofRepoId(huAttribute.getM_Attribute_ID());
final int seqNo = piAttributes.getSeqNoByAttributeId(attributeId, 0);
// if the seqNo is zero/null, the attribute shall be last
return seqNo != 0 ? seqNo : Integer.MAX_VALUE;
}
public ImmutableList<I_M_HU_Attribute> sortAndCopy(final Collection<I_M_HU_Attribute> huAttributes)
{
return huAttributes.stream()
.sorted(this)
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\HUAttributesBySeqNoComparator.java | 1 |
请完成以下Java代码 | public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
} | if (getClass() != obj.getClass()) {
return false;
}
return id != null && id.equals(((Book) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootEnableLazyLoadNoTrans\src\main\java\com\bookstore\entity\Book.java | 1 |
请完成以下Java代码 | public class MyDtoWithSpecialField {
private String[] stringValue;
private int intValue;
private boolean booleanValue;
public MyDtoWithSpecialField() {
super();
}
public MyDtoWithSpecialField(final String[] stringValue, final int intValue, final boolean booleanValue) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
}
// API
public String[] getStringValue() {
return stringValue;
}
public void setStringValue(final String[] stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
} | public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
//
@Override
public String toString() {
return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]";
}
} | repos\tutorials-master\jackson-simple\src\main\java\com\baeldung\jackson\ignore\MyDtoWithSpecialField.java | 1 |
请完成以下Java代码 | private void handlePayment(final BPartnerId newPartnerId, final I_C_Payment payment)
{
if (payment == null)
{
// nothing to do
return;
}
// Reverse all allocation from the payment
Services.get(IESRImportBL.class).reverseAllocationForPayment(payment);
InterfaceWrapperHelper.save(payment);
if (newPartnerId == null)
{
// We never let payments without BPartner set because we use the traceability of payments
return;
}
// If the BPartner was changes we also change the BPartner of the payment
payment.setC_BPartner_ID(newPartnerId.getRepoId());
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE,
ifColumnsChanged = I_ESR_ImportLine.COLUMNNAME_PaymentDate)
public void onChangePaymentDate(I_ESR_ImportLine esrImportLine)
{
if (!InterfaceWrapperHelper.isUIAction(esrImportLine))
{
// do nothing if the modification was triggered from the application, not by the user
return;
}
esrImportLine.setIsManual(true); | final Timestamp paymentDate = esrImportLine.getPaymentDate();
if (paymentDate == null)
{
// nothing to do.
}
else
{
esrImportLine.setAccountingDate(paymentDate);
}
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE,
ifColumnsChanged = I_ESR_ImportLine.COLUMNNAME_C_Payment_ID)
public void onChangePayment(I_ESR_ImportLine esrImportLine)
{
if (InterfaceWrapperHelper.isUIAction(esrImportLine))
{
// do nothing if the modification was triggered by the user
return;
}
// if invoice is not set, do nothing
if (esrImportLine.getC_Invoice_ID() <= 0)
{
return;
}
// note that setInvoice doesn't actually save the given esrImportLine, so we are fine to call it from here
Services.get(IESRImportBL.class).setInvoice(esrImportLine, esrImportLine.getC_Invoice());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\model\validator\ESR_ImportLine.java | 1 |
请完成以下Java代码 | public void setAD_UserGroup_ID (int AD_UserGroup_ID)
{
if (AD_UserGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_UserGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_UserGroup_ID, Integer.valueOf(AD_UserGroup_ID));
}
/** Get Nutzergruppe.
@return Nutzergruppe */
@Override
public int getAD_UserGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_UserGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Private_Access.java | 1 |
请完成以下Java代码 | public int getR_StatusCategory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_StatusCategory_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Status.
@param R_Status_ID
Request Status
*/
public void setR_Status_ID (int R_Status_ID)
{
if (R_Status_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_Status_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_Status_ID, Integer.valueOf(R_Status_ID));
}
/** Get Status.
@return Request Status
*/
public int getR_Status_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Status_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getSeqNo()));
}
/** Set Timeout in Days.
@param TimeoutDays
Timeout in Days to change Status automatically
*/
public void setTimeoutDays (int TimeoutDays)
{
set_Value (COLUMNNAME_TimeoutDays, Integer.valueOf(TimeoutDays));
}
/** Get Timeout in Days.
@return Timeout in Days to change Status automatically
*/
public int getTimeoutDays ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_TimeoutDays);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_Status getUpdate_Status() throws RuntimeException | {
return (I_R_Status)MTable.get(getCtx(), I_R_Status.Table_Name)
.getPO(getUpdate_Status_ID(), get_TrxName()); }
/** Set Update Status.
@param Update_Status_ID
Automatically change the status after entry from web
*/
public void setUpdate_Status_ID (int Update_Status_ID)
{
if (Update_Status_ID < 1)
set_Value (COLUMNNAME_Update_Status_ID, null);
else
set_Value (COLUMNNAME_Update_Status_ID, Integer.valueOf(Update_Status_ID));
}
/** Get Update Status.
@return Automatically change the status after entry from web
*/
public int getUpdate_Status_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Update_Status_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_Status.java | 1 |
请完成以下Java代码 | public PageData<Customer> findCustomersByTenantId(TenantId tenantId, PageLink pageLink) {
log.trace("Executing findCustomersByTenantId, tenantId [{}], pageLink [{}]", tenantId, pageLink);
Validator.validateId(tenantId, id -> "Incorrect tenantId " + id);
Validator.validatePageLink(pageLink);
return customerDao.findCustomersByTenantId(tenantId.getId(), pageLink);
}
@Override
public void deleteCustomersByTenantId(TenantId tenantId) {
log.trace("Executing deleteCustomersByTenantId, tenantId [{}]", tenantId);
Validator.validateId(tenantId, id -> "Incorrect tenantId " + id);
customersByTenantRemover.removeEntities(tenantId, tenantId);
}
@Override
public List<Customer> findCustomersByTenantIdAndIds(TenantId tenantId, List<CustomerId> customerIds) {
log.trace("Executing findCustomersByTenantIdAndIds, tenantId [{}], customerIds [{}]", tenantId, customerIds);
return customerDao.findCustomersByTenantIdAndIds(tenantId.getId(), customerIds.stream().map(CustomerId::getId).collect(Collectors.toList()));
}
@Override
public void deleteByTenantId(TenantId tenantId) {
deleteCustomersByTenantId(tenantId);
}
private final PaginatedRemover<TenantId, Customer> customersByTenantRemover =
new PaginatedRemover<>() {
@Override
protected PageData<Customer> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return customerDao.findCustomersByTenantId(id.getId(), pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, Customer entity) {
deleteCustomer(tenantId, new CustomerId(entity.getUuidId()));
}
}; | @Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findCustomerById(tenantId, new CustomerId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(findCustomerByIdAsync(tenantId, new CustomerId(entityId.getId())))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public long countByTenantId(TenantId tenantId) {
return customerDao.countByTenantId(tenantId);
}
@Override
public EntityType getEntityType() {
return EntityType.CUSTOMER;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\customer\CustomerServiceImpl.java | 1 |
请完成以下Java代码 | public class C_Aggregation
{
@ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = I_C_Aggregation.COLUMNNAME_AD_Table_ID)
public void assertTableNotChangedWhenItemsDefined(final I_C_Aggregation aggregation)
{
final boolean hasItems = Services.get(IAggregationDAO.class)
.retrieveAllItemsQuery(aggregation)
.create()
.anyMatch();
if (hasItems)
{
throw new AdempiereException("Changing table not allowed when having items defined");
}
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void deleteItems(final I_C_Aggregation aggregation)
{
Services.get(IAggregationDAO.class)
.retrieveAllItemsQuery(aggregation)
.create()
.delete();
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE })
public void fireListeners(final I_C_Aggregation aggregation, final int changeType) | {
final IAggregationListeners aggregationListeners = Services.get(IAggregationListeners.class);
final ModelChangeType type = ModelChangeType.valueOf(changeType);
if (type.isNew())
{
aggregationListeners.fireAggregationCreated(aggregation);
}
else if (type.isChange())
{
aggregationListeners.fireAggregationChanged(aggregation);
}
else if (type.isDelete())
{
aggregationListeners.fireAggregationDeleted(aggregation);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\model\validator\C_Aggregation.java | 1 |
请完成以下Java代码 | private boolean isConvertAttributeToLowerCase() {
return this.convertAttributeToLowerCase;
}
public void setConvertAttributeToLowerCase(boolean b) {
this.convertAttributeToLowerCase = b;
}
private boolean isConvertAttributeToUpperCase() {
return this.convertAttributeToUpperCase;
}
public void setConvertAttributeToUpperCase(boolean b) {
this.convertAttributeToUpperCase = b;
} | private String getAttributePrefix() {
return (this.attributePrefix != null) ? this.attributePrefix : "";
}
public void setAttributePrefix(String string) {
this.attributePrefix = string;
}
private boolean isAddPrefixIfAlreadyExisting() {
return this.addPrefixIfAlreadyExisting;
}
public void setAddPrefixIfAlreadyExisting(boolean b) {
this.addPrefixIfAlreadyExisting = b;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\core\authority\mapping\SimpleAttributes2GrantedAuthoritiesMapper.java | 1 |
请完成以下Java代码 | public class X_M_Warehouse_Type extends org.compiere.model.PO implements I_M_Warehouse_Type, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = -165383196L;
/** Standard Constructor */
public X_M_Warehouse_Type (Properties ctx, int M_Warehouse_Type_ID, String trxName)
{
super (ctx, M_Warehouse_Type_ID, trxName);
/** if (M_Warehouse_Type_ID == 0)
{
setM_Warehouse_Type_ID (0);
setName (null);
} */
}
/** Load Constructor */
public X_M_Warehouse_Type (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
} | /** Set Warehouse Type.
@param M_Warehouse_Type_ID Warehouse Type */
@Override
public void setM_Warehouse_Type_ID (int M_Warehouse_Type_ID)
{
if (M_Warehouse_Type_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_Type_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_Type_ID, Integer.valueOf(M_Warehouse_Type_ID));
}
/** Get Warehouse Type.
@return Warehouse Type */
@Override
public int getM_Warehouse_Type_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_Type_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Warehouse_Type.java | 1 |
请完成以下Java代码 | public static PaymentDirection ofSOTrx(@NonNull final SOTrx soTrx)
{
final boolean creditMemo = false;
return ofSOTrxAndCreditMemo(soTrx, creditMemo);
}
public static PaymentDirection ofSOTrxAndCreditMemo(@NonNull final SOTrx soTrx, final boolean creditMemo)
{
if (soTrx.isPurchase())
{
return !creditMemo ? PaymentDirection.OUTBOUND : PaymentDirection.INBOUND;
}
else // sales
{
return !creditMemo ? PaymentDirection.INBOUND : PaymentDirection.OUTBOUND;
}
}
public boolean isReceipt()
{
return isInboundPayment();
}
public boolean isInboundPayment()
{
return this == INBOUND;
}
public boolean isOutboundPayment() | {
return this == OUTBOUND;
}
public Amount convertPayAmtToStatementAmt(@NonNull final Amount payAmt)
{
return payAmt.negateIf(isOutboundPayment());
}
public Money convertPayAmtToStatementAmt(@NonNull final Money payAmt)
{
return payAmt.negateIf(isOutboundPayment());
}
public Money convertStatementAmtToPayAmt(@NonNull final Money bankStatementAmt)
{
return bankStatementAmt.negateIf(isOutboundPayment());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\PaymentDirection.java | 1 |
请完成以下Java代码 | public void setTaxIndicator (String TaxIndicator)
{
set_Value (COLUMNNAME_TaxIndicator, TaxIndicator);
}
/** Get Tax Indicator.
@return Short form for Tax to be printed on documents
*/
public String getTaxIndicator ()
{
return (String)get_Value(COLUMNNAME_TaxIndicator);
}
/** Set UPC/EAN.
@param UPC | Bar Code (Universal Product Code or its superset European Article Number)
*/
public void setUPC (String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
@return Bar Code (Universal Product Code or its superset European Article Number)
*/
public String getUPC ()
{
return (String)get_Value(COLUMNNAME_UPC);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Invoice.java | 1 |
请完成以下Java代码 | public class MAssetDelivery extends X_A_Asset_Delivery
{
/**
*
*/
private static final long serialVersionUID = -1731010685101745675L;
/**
* Constructor
*
* @param ctx context
* @param A_Asset_Delivery_ID id or 0
* @param trxName trx
*/
@SuppressWarnings("unused")
public MAssetDelivery(Properties ctx, int A_Asset_Delivery_ID, String trxName)
{
super(ctx, A_Asset_Delivery_ID, trxName);
if (A_Asset_Delivery_ID == 0)
{
setMovementDate(new Timestamp(System.currentTimeMillis()));
}
} // MAssetDelivery
/**
* Load Constructor
*
* @param ctx context
* @param rs result set record | * @param trxName transaction
*/
public MAssetDelivery(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAssetDelivery
/**
* String representation
*
* @return info
*/
@Override
public String toString()
{
return "MAssetDelivery["
+ get_ID()
+ ",A_Asset_ID=" + getA_Asset_ID()
+ ",MovementDate=" + getMovementDate()
+ "]";
} // toString
} // MAssetDelivery | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MAssetDelivery.java | 1 |
请完成以下Java代码 | public class DispatcherHandlerMappingDetails {
private @Nullable HandlerMethodDescription handlerMethod;
private @Nullable HandlerFunctionDescription handlerFunction;
private @Nullable RequestMappingConditionsDescription requestMappingConditions;
public @Nullable HandlerMethodDescription getHandlerMethod() {
return this.handlerMethod;
}
void setHandlerMethod(@Nullable HandlerMethodDescription handlerMethod) {
this.handlerMethod = handlerMethod;
}
public @Nullable HandlerFunctionDescription getHandlerFunction() {
return this.handlerFunction; | }
void setHandlerFunction(@Nullable HandlerFunctionDescription handlerFunction) {
this.handlerFunction = handlerFunction;
}
public @Nullable RequestMappingConditionsDescription getRequestMappingConditions() {
return this.requestMappingConditions;
}
void setRequestMappingConditions(@Nullable RequestMappingConditionsDescription requestMappingConditions) {
this.requestMappingConditions = requestMappingConditions;
}
} | repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\actuate\web\mappings\DispatcherHandlerMappingDetails.java | 1 |
请完成以下Java代码 | public String getMeta_RobotsTag ()
{
return (String)get_Value(COLUMNNAME_Meta_RobotsTag);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name. | @return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WebProject.java | 1 |
请完成以下Java代码 | public void setLineEnding(String lineEnding)
{
this.lineEnding = lineEnding;
}
@SuppressWarnings("UnusedReturnValue")
public CSVWriter setAllowMultilineFields(final boolean allowMultilineFields)
{
this.allowMultilineFields = allowMultilineFields;
return this;
}
public void setHeader(final List<String> header)
{
Check.assumeNotNull(header, "header not null");
Check.assume(!header.isEmpty(), "header not empty");
Check.assume(!headerAppended, "header was not already appended");
this.header = header;
}
private void appendHeader() throws IOException
{
if (headerAppended)
{
return;
}
Check.assumeNotNull(header, "header not null");
final StringBuilder headerLine = new StringBuilder();
for (final String headerCol : header)
{
if (headerLine.length() > 0)
{
headerLine.append(fieldDelimiter);
}
final String headerColQuoted = quoteCsvValue(headerCol);
headerLine.append(headerColQuoted);
}
writer.append(headerLine.toString());
writer.append(lineEnding);
headerAppended = true;
}
@Override
public void appendLine(List<Object> values) throws IOException
{
appendHeader();
final StringBuilder line = new StringBuilder();
final int cols = header.size();
final int valuesCount = values.size();
for (int i = 0; i < cols; i++)
{
final Object csvValue;
if (i < valuesCount)
{
csvValue = values.get(i);
}
else
{
csvValue = null;
}
final String csvValueQuoted = toCsvValue(csvValue);
if (line.length() > 0)
{
line.append(fieldDelimiter);
}
line.append(csvValueQuoted);
}
writer.append(line.toString());
writer.append(lineEnding);
}
private String toCsvValue(Object value)
{ | final String valueStr;
if (value == null)
{
valueStr = "";
}
else if (value instanceof java.util.Date)
{
valueStr = dateFormat.format(value);
}
else
{
valueStr = value.toString();
}
return quoteCsvValue(valueStr);
}
private String quoteCsvValue(String valueStr)
{
return fieldQuote
+ valueStr.replace(fieldQuote, fieldQuote + fieldQuote)
+ fieldQuote;
}
@Override
public void close() throws IOException
{
if (writer == null)
{
return;
}
try
{
writer.flush();
}
finally
{
if (writer != null)
{
try
{
writer.close();
}
catch (IOException e)
{
// shall not happen
e.printStackTrace(); // NOPMD by tsa on 3/13/13 1:46 PM
}
writer = null;
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\CSVWriter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public I_C_InvoiceLine createInvoiceLine(String trxName)
{
throw new UnsupportedOperationException();
}
private List<I_C_AllocationLine> retrieveAllocationLines(final org.compiere.model.I_C_Invoice invoice)
{
Adempiere.assertUnitTestMode();
return db.getRecords(I_C_AllocationLine.class, pojo -> {
if (pojo == null)
{
return false;
}
if (pojo.getC_Invoice_ID() != invoice.getC_Invoice_ID())
{
return false;
}
return true;
});
}
private BigDecimal retrieveAllocatedAmt(final org.compiere.model.I_C_Invoice invoice, final TypedAccessor<BigDecimal> amountAccessor)
{
Adempiere.assertUnitTestMode();
final Properties ctx = InterfaceWrapperHelper.getCtx(invoice);
BigDecimal sum = BigDecimal.ZERO;
for (final I_C_AllocationLine line : retrieveAllocationLines(invoice))
{
final I_C_AllocationHdr ah = line.getC_AllocationHdr();
final BigDecimal lineAmt = amountAccessor.getValue(line);
if ((null != ah) && (ah.getC_Currency_ID() != invoice.getC_Currency_ID()))
{
final BigDecimal lineAmtConv = Services.get(ICurrencyBL.class).convert(
lineAmt, // Amt | CurrencyId.ofRepoId(ah.getC_Currency_ID()), // CurFrom_ID
CurrencyId.ofRepoId(invoice.getC_Currency_ID()), // CurTo_ID
ah.getDateTrx().toInstant(), // ConvDate
CurrencyConversionTypeId.ofRepoIdOrNull(invoice.getC_ConversionType_ID()),
ClientId.ofRepoId(line.getAD_Client_ID()),
OrgId.ofRepoId(line.getAD_Org_ID()));
sum = sum.add(lineAmtConv);
}
else
{
sum = sum.add(lineAmt);
}
}
return sum;
}
public BigDecimal retrieveWriteOffAmt(final org.compiere.model.I_C_Invoice invoice)
{
Adempiere.assertUnitTestMode();
return retrieveAllocatedAmt(invoice, o -> {
final I_C_AllocationLine line = (I_C_AllocationLine)o;
return line.getWriteOffAmt();
});
}
@Override
public List<I_C_InvoiceTax> retrieveTaxes(org.compiere.model.I_C_Invoice invoice)
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\PlainInvoiceDAO.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Deployment deploy(String name, String tenantId, String category, InputStream in) {
return createDeployment().addInputStream(name + BPMN_FILE_SUFFIX, in)
.name(name)
.tenantId(tenantId)
.category(category)
.deploy();
}
@Override
public ProcessDefinition queryByProcessDefinitionKey(String processDefinitionKey) {
ProcessDefinition processDefinition
= createProcessDefinitionQuery()
.processDefinitionKey(processDefinitionKey)
.active().singleResult();
return processDefinition;
} | @Override
public Deployment deployName(String deploymentName) {
List<Deployment> list = repositoryService
.createDeploymentQuery()
.deploymentName(deploymentName).list();
Assert.notNull(list, "list must not be null");
return list.get(0);
}
@Override
public void addCandidateStarterUser(String processDefinitionKey, String userId) {
repositoryService.addCandidateStarterUser(processDefinitionKey, userId);
}
} | repos\spring-boot-quick-master\quick-flowable\src\main\java\com\quick\flowable\service\handler\ProcessHandler.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public OssPolicyResult policy() {
OssPolicyResult result = new OssPolicyResult();
// 存储目录
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String dir = ALIYUN_OSS_DIR_PREFIX+sdf.format(new Date());
// 签名有效期
long expireEndTime = System.currentTimeMillis() + ALIYUN_OSS_EXPIRE * 1000;
Date expiration = new Date(expireEndTime);
// 文件大小
long maxSize = ALIYUN_OSS_MAX_SIZE * 1024 * 1024;
// 回调
OssCallbackParam callback = new OssCallbackParam();
callback.setCallbackUrl(ALIYUN_OSS_CALLBACK);
callback.setCallbackBody("filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
callback.setCallbackBodyType("application/x-www-form-urlencoded");
// 提交节点
String action = "http://" + ALIYUN_OSS_BUCKET_NAME + "." + ALIYUN_OSS_ENDPOINT;
try {
PolicyConditions policyConds = new PolicyConditions();
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, maxSize);
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
byte[] binaryData = postPolicy.getBytes("utf-8");
String policy = BinaryUtil.toBase64String(binaryData);
String signature = ossClient.calculatePostSignature(postPolicy);
String callbackData = BinaryUtil.toBase64String(JSONUtil.parse(callback).toString().getBytes("utf-8"));
// 返回结果
result.setAccessKeyId(ossClient.getCredentialsProvider().getCredentials().getAccessKeyId());
result.setPolicy(policy);
result.setSignature(signature);
result.setDir(dir);
result.setCallback(callbackData);
result.setHost(action); | } catch (Exception e) {
LOGGER.error("签名生成失败", e);
}
return result;
}
@Override
public OssCallbackResult callback(HttpServletRequest request) {
OssCallbackResult result= new OssCallbackResult();
String filename = request.getParameter("filename");
filename = "http://".concat(ALIYUN_OSS_BUCKET_NAME).concat(".").concat(ALIYUN_OSS_ENDPOINT).concat("/").concat(filename);
result.setFilename(filename);
result.setSize(request.getParameter("size"));
result.setMimeType(request.getParameter("mimeType"));
result.setWidth(request.getParameter("width"));
result.setHeight(request.getParameter("height"));
return result;
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\OssServiceImpl.java | 2 |
请完成以下Java代码 | default List<I_PP_Order> getByIds(final Set<PPOrderId> orderIds)
{
return getByIds(orderIds, I_PP_Order.class);
}
<T extends I_PP_Order> List<T> getByIds(Set<PPOrderId> orderIds, Class<T> type);
/**
* Gets released manufacturing orders based on {@link I_M_Warehouse}s.
*
* @return manufacturing orders
*/
List<I_PP_Order> retrieveReleasedManufacturingOrdersForWarehouse(WarehouseId warehouseId);
Stream<I_PP_Order> streamManufacturingOrders(@NonNull ManufacturingOrderQuery query);
SeqNo getNextSeqNoPerDateStartSchedule(@NonNull final I_PP_Order ppOrder);
/**
* @return PP_Order_ID or -1 if not found.
*/
PPOrderId retrievePPOrderIdByOrderLineId(final OrderLineId orderLineId); | void changeOrderScheduling(PPOrderId orderId, Instant scheduledStartDate, Instant scheduledFinishDate);
Stream<I_PP_Order> streamOpenPPOrderIdsOrderedByDatePromised(ResourceId plantId);
List<I_PP_Order> retrieveManufacturingOrders(@NonNull ManufacturingOrderQuery query);
void save(I_PP_Order order);
void saveAll(Collection<I_PP_Order> orders);
void exportStatusMassUpdate(@NonNull final Map<PPOrderId, APIExportStatus> exportStatuses);
IQueryBuilder<I_PP_Order> createQueryForPPOrderSelection(IQueryFilter<I_PP_Order> userSelectionFilter);
ImmutableList<I_PP_OrderCandidate_PP_Order> getPPOrderAllocations(PPOrderId ppOrderId);
ImmutableList<I_PP_Order> getByProductBOMId(ProductBOMId productBOMId);
Stream<I_PP_Order> streamDraftedPPOrdersFor(@NonNull ProductBOMVersionsId bomVersionsId);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\IPPOrderDAO.java | 1 |
请完成以下Java代码 | public I_M_AttributeInstance createNewAttributeInstance(
final Properties ctx,
final I_M_AttributeSetInstance asi,
@NonNull final AttributeId attributeId,
final String trxName)
{
final I_M_AttributeInstance ai = InterfaceWrapperHelper.create(ctx, I_M_AttributeInstance.class, trxName);
ai.setAD_Org_ID(asi.getAD_Org_ID());
ai.setM_AttributeSetInstance(asi);
ai.setM_Attribute_ID(attributeId.getRepoId());
return ai;
}
@Override
public void save(@NonNull final I_M_AttributeSetInstance asi)
{
saveRecord(asi);
}
@Override | public void save(@NonNull final I_M_AttributeInstance ai)
{
saveRecord(ai);
}
@Override
public Set<AttributeId> getAttributeIdsByAttributeSetInstanceId(@NonNull final AttributeSetInstanceId attributeSetInstanceId)
{
return queryBL
.createQueryBuilderOutOfTrx(I_M_AttributeInstance.class)
.addEqualsFilter(I_M_AttributeInstance.COLUMN_M_AttributeSetInstance_ID, attributeSetInstanceId)
.create()
.listDistinct(I_M_AttributeInstance.COLUMNNAME_M_Attribute_ID, Integer.class)
.stream()
.map(AttributeId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeSetInstanceDAO.java | 1 |
请完成以下Java代码 | public class HtmlDocumentBuilder {
protected HtmlWriteContext context = new HtmlWriteContext();
protected Deque<HtmlElementWriter> elements = new ArrayDeque<>();
protected StringWriter writer = new StringWriter();
public HtmlDocumentBuilder(HtmlElementWriter documentElement) {
startElement(documentElement);
}
public HtmlDocumentBuilder startElement(HtmlElementWriter renderer) {
renderer.writeStartTag(context);
elements.push(renderer);
return this;
}
public HtmlDocumentBuilder endElement() {
HtmlElementWriter renderer = elements.pop();
renderer.writeContent(context);
renderer.writeEndTag(context);
return this; | }
public String getHtmlString() {
return writer.toString();
}
public class HtmlWriteContext {
public StringWriter getWriter() {
return writer;
}
public int getElementStackSize() {
return elements.size();
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\engine\HtmlDocumentBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected boolean isEligibleForScheduling(final I_C_Order model)
{
return model != null && model.getC_Order_ID() > 0;
}
@Override
protected Properties extractCtxFromItem(final I_C_Order item)
{
return Env.getCtx();
}
@Override
protected String extractTrxNameFromItem(final I_C_Order item)
{
return ITrx.TRXNAME_ThreadInherited;
}
@Override
protected Object extractModelToEnqueueFromItem(final Collector collector, final I_C_Order item) | {
return TableRecordReference.of(I_C_Order.Table_Name, item.getC_Order_ID());
}
};
@Override
public Result processWorkPackage(final I_C_Queue_WorkPackage workPackage, final String localTrxName)
{
// retrieve the order and generate requests
queueDAO.retrieveAllItems(workPackage, I_C_Order.class)
.forEach(requestBL::createRequestFromOrder);
return Result.SUCCESS;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\request\service\async\spi\impl\R_Request_CreateFromOrder_Async.java | 2 |
请完成以下Java代码 | public List<FlowElementMoveEntry> getMoveToFlowElements() {
return new ArrayList<>(moveToFlowElementMap.values());
}
public void addCurrentActivityToNewElement(String curentActivityId, FlowElement originalFlowElement, FlowElement newFlowElement) {
currentActivityToNewElementMap.put(curentActivityId, new FlowElementMoveEntry(originalFlowElement, newFlowElement));
}
public FlowElementMoveEntry getCurrentActivityToNewElement(String curentActivityId) {
return currentActivityToNewElementMap.get(curentActivityId);
}
public List<String> getNewExecutionIds() {
return newExecutionIds;
}
public boolean hasNewExecutionId(String executionId) {
return newExecutionIds.contains(executionId);
}
public void setNewExecutionIds(List<String> newExecutionIds) {
this.newExecutionIds = newExecutionIds;
}
public void addNewExecutionId(String executionId) {
this.newExecutionIds.add(executionId);
}
public ExecutionEntity getCreatedEventSubProcess(String processDefinitionId) {
return createdEventSubProcesses.get(processDefinitionId);
}
public void addCreatedEventSubProcess(String processDefinitionId, ExecutionEntity executionEntity) {
createdEventSubProcesses.put(processDefinitionId, executionEntity); | }
public Map<String, Map<String, Object>> getFlowElementLocalVariableMap() {
return flowElementLocalVariableMap;
}
public void setFlowElementLocalVariableMap(Map<String, Map<String, Object>> flowElementLocalVariableMap) {
this.flowElementLocalVariableMap = flowElementLocalVariableMap;
}
public void addLocalVariableMap(String activityId, Map<String, Object> localVariables) {
this.flowElementLocalVariableMap.put(activityId, localVariables);
}
public static class FlowElementMoveEntry {
protected FlowElement originalFlowElement;
protected FlowElement newFlowElement;
public FlowElementMoveEntry(FlowElement originalFlowElement, FlowElement newFlowElement) {
this.originalFlowElement = originalFlowElement;
this.newFlowElement = newFlowElement;
}
public FlowElement getOriginalFlowElement() {
return originalFlowElement;
}
public FlowElement getNewFlowElement() {
return newFlowElement;
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\dynamic\MoveExecutionEntityContainer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class Throttler {
/**
* Request throttling type.
*/
private @Nullable ThrottlerType type;
/**
* Maximum number of requests that can be enqueued when the throttling threshold
* is exceeded.
*/
private @Nullable Integer maxQueueSize;
/**
* Maximum number of requests that are allowed to execute in parallel.
*/
private @Nullable Integer maxConcurrentRequests;
/**
* Maximum allowed request rate.
*/
private @Nullable Integer maxRequestsPerSecond;
/**
* How often the throttler attempts to dequeue requests. Set this high enough that
* each attempt will process multiple entries in the queue, but not delay requests
* too much.
*/
private @Nullable Duration drainInterval;
public @Nullable ThrottlerType getType() {
return this.type;
}
public void setType(@Nullable ThrottlerType type) {
this.type = type;
}
public @Nullable Integer getMaxQueueSize() {
return this.maxQueueSize;
}
public void setMaxQueueSize(@Nullable Integer maxQueueSize) {
this.maxQueueSize = maxQueueSize;
}
public @Nullable Integer getMaxConcurrentRequests() {
return this.maxConcurrentRequests;
}
public void setMaxConcurrentRequests(@Nullable Integer maxConcurrentRequests) {
this.maxConcurrentRequests = maxConcurrentRequests;
}
public @Nullable Integer getMaxRequestsPerSecond() {
return this.maxRequestsPerSecond;
}
public void setMaxRequestsPerSecond(@Nullable Integer maxRequestsPerSecond) {
this.maxRequestsPerSecond = maxRequestsPerSecond;
}
public @Nullable Duration getDrainInterval() {
return this.drainInterval;
}
public void setDrainInterval(@Nullable Duration drainInterval) {
this.drainInterval = drainInterval;
} | }
/**
* Name of the algorithm used to compress protocol frames.
*/
public enum Compression {
/**
* Requires 'net.jpountz.lz4:lz4'.
*/
LZ4,
/**
* Requires org.xerial.snappy:snappy-java.
*/
SNAPPY,
/**
* No compression.
*/
NONE
}
public enum ThrottlerType {
/**
* Limit the number of requests that can be executed in parallel.
*/
CONCURRENCY_LIMITING("ConcurrencyLimitingRequestThrottler"),
/**
* Limits the request rate per second.
*/
RATE_LIMITING("RateLimitingRequestThrottler"),
/**
* No request throttling.
*/
NONE("PassThroughRequestThrottler");
private final String type;
ThrottlerType(String type) {
this.type = type;
}
public String type() {
return this.type;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-cassandra\src\main\java\org\springframework\boot\cassandra\autoconfigure\CassandraProperties.java | 2 |
请完成以下Java代码 | public void checkReadHistoricExternalTaskLog(HistoricExternalTaskLogEntity historicExternalTaskLog) {
if (historicExternalTaskLog != null && !getTenantManager().isAuthenticatedTenant(historicExternalTaskLog.getTenantId())) {
throw LOG.exceptionCommandWithUnauthorizedTenant("get the historic external task log '"+ historicExternalTaskLog.getId() + "'");
}
}
@Override
public void checkReadDiagnosticsData() {
}
@Override
public void checkReadHistoryLevel() {
}
@Override
public void checkReadTableCount() {
}
@Override
public void checkReadTableName() {
}
@Override
public void checkReadTableMetaData() {
}
@Override
public void checkReadProperties() {
}
@Override
public void checkSetProperty() {
}
@Override
public void checkDeleteProperty() {
}
@Override
public void checkDeleteLicenseKey() {
}
@Override
public void checkSetLicenseKey() {
}
@Override
public void checkReadLicenseKey() {
}
@Override
public void checkRegisterProcessApplication() {
}
@Override
public void checkUnregisterProcessApplication() {
}
@Override
public void checkReadRegisteredDeployments() {
}
@Override
public void checkReadProcessApplicationForDeployment() {
}
@Override
public void checkRegisterDeployment() {
}
@Override
public void checkUnregisterDeployment() {
} | @Override
public void checkDeleteMetrics() {
}
@Override
public void checkDeleteTaskMetrics() {
}
@Override
public void checkReadSchemaLog() {
}
// helper //////////////////////////////////////////////////
protected TenantManager getTenantManager() {
return Context.getCommandContext().getTenantManager();
}
protected ProcessDefinitionEntity findLatestProcessDefinitionById(String processDefinitionId) {
return Context.getCommandContext().getProcessDefinitionManager().findLatestProcessDefinitionById(processDefinitionId);
}
protected DecisionDefinitionEntity findLatestDecisionDefinitionById(String decisionDefinitionId) {
return Context.getCommandContext().getDecisionDefinitionManager().findDecisionDefinitionById(decisionDefinitionId);
}
protected ExecutionEntity findExecutionById(String processInstanceId) {
return Context.getCommandContext().getExecutionManager().findExecutionById(processInstanceId);
}
protected DeploymentEntity findDeploymentById(String deploymentId) {
return Context.getCommandContext().getDeploymentManager().findDeploymentById(deploymentId);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\multitenancy\TenantCommandChecker.java | 1 |
请完成以下Java代码 | public void execute()
{
final List<PrintingQueueQueryRequest> queryRequests = getPrintingQueueQueryBuilders();
if (queryRequests.isEmpty())
{
Loggables.withLogger(logger, Level.DEBUG).addLog("*** No queries / sysconfigs defined. Create sysconfigs prefixed with `{}`", QUERY_PREFIX);
return;
}
for (final PrintingQueueQueryRequest queryRequest : queryRequests)
{
enqueuePrintQueues(queryRequest);
}
}
private void enqueuePrintQueues(@NonNull final PrintingQueueQueryRequest queryRequest)
{
final List<I_C_Printing_Queue> printingQueues = queryRequest.getQuery().list();
if (printingQueues.isEmpty())
{
Loggables.withLogger(logger, Level.DEBUG).addLog("*** There is nothing to enqueue. Skipping it: {}", queryRequest);
return;
}
final Properties ctx = Env.getCtx();
final I_C_Async_Batch parentAsyncBatchRecord = asyncBatchBL.getAsyncBatchById(printingQueueItemsGeneratedAsyncBatchId);
final AsyncBatchId asyncBatchId = asyncBatchBL.newAsyncBatch()
.setContext(ctx)
.setC_Async_Batch_Type(C_Async_Batch_InternalName_AutomaticallyInvoicePdfPrinting)
.setName(C_Async_Batch_InternalName_AutomaticallyInvoicePdfPrinting)
.setDescription(queryRequest.getQueryName())
.setParentAsyncBatchId(printingQueueItemsGeneratedAsyncBatchId)
.setOrgId(OrgId.ofRepoId(parentAsyncBatchRecord.getAD_Org_ID()))
.buildAndEnqueue();
workPackageQueueFactory
.getQueueForEnqueuing(ctx, PrintingQueuePDFConcatenateWorkpackageProcessor.class)
.newWorkPackage()
.setAsyncBatchId(asyncBatchId)
.addElements(printingQueues)
.buildAndEnqueue();
}
private List<PrintingQueueQueryRequest> getPrintingQueueQueryBuilders()
{
final Map<String, String> filtersMap = sysConfigBL.getValuesForPrefix(QUERY_PREFIX, clientAndOrgId);
final Collection<String> keys = filtersMap.keySet(); | final ArrayList<PrintingQueueQueryRequest> queries = new ArrayList<>();
for (final String key : keys)
{
final String whereClause = filtersMap.get(key);
final IQuery<I_C_Printing_Queue> query = createPrintingQueueQuery(whereClause);
final PrintingQueueQueryRequest request = PrintingQueueQueryRequest.builder()
.queryName(key)
.query(query)
.build();
queries.add(request);
}
return queries;
}
private IQuery<I_C_Printing_Queue> createPrintingQueueQuery(@NonNull final String whereClause)
{
return queryBL
.createQueryBuilder(I_C_Printing_Queue.class)
.addEqualsFilter(I_C_Printing_Queue.COLUMNNAME_AD_Client_ID, clientAndOrgId.getClientId())
.addEqualsFilter(I_C_Printing_Queue.COLUMNNAME_AD_Org_ID, clientAndOrgId.getOrgId())
.addEqualsFilter(I_C_Printing_Queue.COLUMN_C_Async_Batch_ID, printingQueueItemsGeneratedAsyncBatchId)
.addEqualsFilter(I_C_Printing_Queue.COLUMNNAME_Processed, false)
.filter(TypedSqlQueryFilter.of(whereClause))
.create();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\model\validator\ConcatenatePDFsCommand.java | 1 |
请完成以下Java代码 | public frame setNoResize(boolean noresize)
{
if ( noresize == true )
addAttribute("noresize", "noresize");
else
removeAttribute("noresize");
return(this);
}
/**
Sets the lang="" and xml:lang="" attributes
@param lang the lang="" and xml:lang="" attributes
*/
public Element setLang(String lang)
{
addAttribute("lang",lang);
addAttribute("xml:lang",lang);
return this;
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public frame addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public frame addElement(String hashcode,String element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element. | @param element Adds an Element to the element.
*/
public frame addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public frame addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public frame removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\frame.java | 1 |
请完成以下Java代码 | protected EnumItem<E> createValue(String[] params)
{
Map.Entry<String, Map.Entry<String, Integer>[]> args = EnumItem.create(params);
EnumItem<E> nrEnumItem = new EnumItem<E>();
for (Map.Entry<String, Integer> e : args.getValue())
{
nrEnumItem.labelMap.put(valueOf(e.getKey()), e.getValue());
}
return nrEnumItem;
}
/**
* 代理E.valueOf
*
* @param name
* @return
*/
protected abstract E valueOf(String name);
/**
* 代理E.values
*
* @return
*/
protected abstract E[] values();
/**
* 代理new EnumItem<E>
*
* @return
*/
protected abstract EnumItem<E> newItem();
@Override
final protected EnumItem<E>[] loadValueArray(ByteArray byteArray)
{
if (byteArray == null)
{
return null;
}
E[] nrArray = values();
int size = byteArray.nextInt();
EnumItem<E>[] valueArray = new EnumItem[size];
for (int i = 0; i < size; ++i)
{ | int currentSize = byteArray.nextInt();
EnumItem<E> item = newItem();
for (int j = 0; j < currentSize; ++j)
{
E nr = nrArray[byteArray.nextInt()];
int frequency = byteArray.nextInt();
item.labelMap.put(nr, frequency);
}
valueArray[i] = item;
}
return valueArray;
}
@Override
protected void saveValue(EnumItem<E> item, DataOutputStream out) throws IOException
{
out.writeInt(item.labelMap.size());
for (Map.Entry<E, Integer> entry : item.labelMap.entrySet())
{
out.writeInt(entry.getKey().ordinal());
out.writeInt(entry.getValue());
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\common\EnumItemDictionary.java | 1 |
请完成以下Java代码 | private WebuiLetterEntry getLetterEntry(final String letterId)
{
final WebuiLetterEntry letterEntry = lettersById.getIfPresent(letterId);
if (letterEntry == null)
{
throw new EntityNotFoundException("Letter not found").setParameter("letterId", letterId);
}
return letterEntry;
}
public WebuiLetter getLetter(final String letterId)
{
return getLetterEntry(letterId).getLetter();
}
public WebuiLetterChangeResult changeLetter(final String letterId, @NonNull final UnaryOperator<WebuiLetter> letterModifier)
{
return getLetterEntry(letterId).compute(letterModifier);
}
public void removeLetterById(final String letterId)
{
lettersById.invalidate(letterId);
}
public void createC_Letter(@NonNull final WebuiLetter letter)
{
final I_C_Letter persistentLetter = InterfaceWrapperHelper.newInstance(I_C_Letter.class);
persistentLetter.setLetterSubject(letter.getSubject());
persistentLetter.setLetterBody(Strings.nullToEmpty(letter.getContent()));
persistentLetter.setLetterBodyParsed(letter.getContent());
persistentLetter.setAD_BoilerPlate_ID(letter.getTextTemplateId());
persistentLetter.setC_BPartner_ID(letter.getBpartnerId());
persistentLetter.setC_BPartner_Location_ID(letter.getBpartnerLocationId());
persistentLetter.setC_BP_Contact_ID(letter.getBpartnerContactId());
persistentLetter.setBPartnerAddress(Strings.nullToEmpty(letter.getBpartnerAddress()));
InterfaceWrapperHelper.save(persistentLetter);
} | @ToString
private static final class WebuiLetterEntry
{
private WebuiLetter letter;
public WebuiLetterEntry(@NonNull final WebuiLetter letter)
{
this.letter = letter;
}
public synchronized WebuiLetter getLetter()
{
return letter;
}
public synchronized WebuiLetterChangeResult compute(final UnaryOperator<WebuiLetter> modifier)
{
final WebuiLetter letterOld = letter;
final WebuiLetter letterNew = modifier.apply(letterOld);
if (letterNew == null)
{
throw new NullPointerException("letter");
}
letter = letterNew;
return WebuiLetterChangeResult.builder().letter(letterNew).originalLetter(letterOld).build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\letter\WebuiLetterRepository.java | 1 |
请完成以下Java代码 | public Set<MatchingKey> getMatchingKeys()
{
return ImmutableSet.of(MatchingKey.ofTableName(I_PP_Order_Weighting_RunCheck.Table_Name));
}
@Override
public QuickInputDescriptor createQuickInputDescriptor(
final DocumentType documentType,
final DocumentId documentTypeId,
final DetailId detailId,
@NonNull final Optional<SOTrx> soTrx)
{
final DocumentEntityDescriptor entityDescriptor = createEntityDescriptor(documentTypeId, detailId, soTrx);
final QuickInputLayoutDescriptor layout = createLayout(entityDescriptor);
return QuickInputDescriptor.of(entityDescriptor, layout, PPOrderWeightingCheckQuickInputProcessor.class);
}
private DocumentEntityDescriptor createEntityDescriptor(
final DocumentId documentTypeId,
final DetailId detailId,
@NonNull final Optional<SOTrx> soTrx)
{
return DocumentEntityDescriptor.builder()
.setDocumentType(DocumentType.QuickInput, documentTypeId)
.disableDefaultTableCallouts() | .setDetailId(detailId)
.setTableName(I_PP_Order_Weighting_RunCheck.Table_Name)
.addField(DocumentFieldDescriptor.builder(PPOrderWeightingCheckQuickInput.COLUMNNAME_Weight)
.setCaption(TranslatableStrings.adElementOrMessage(PPOrderWeightingCheckQuickInput.COLUMNNAME_Weight))
.setWidgetType(DocumentFieldWidgetType.Quantity)
.setReadonlyLogic(ConstantLogicExpression.FALSE)
.setAlwaysUpdateable(true)
.setMandatoryLogic(ConstantLogicExpression.TRUE)
.setDisplayLogic(ConstantLogicExpression.TRUE)
.addCharacteristic(DocumentFieldDescriptor.Characteristic.PublicField))
.setIsSOTrx(soTrx)
.build();
}
private static QuickInputLayoutDescriptor createLayout(final DocumentEntityDescriptor entityDescriptor)
{
return QuickInputLayoutDescriptor.build(entityDescriptor, new String[][] {
{ PPOrderWeightingCheckQuickInput.COLUMNNAME_Weight }
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\manufacturing\order\weighting\run\quickinput\PPOrderWeightingCheckQuickInputDescriptorFactory.java | 1 |
请完成以下Java代码 | protected String getInternalValueStringInitial()
{
return huAttribute.getValueInitial();
}
@Override
protected BigDecimal getInternalValueNumberInitial()
{
return huAttribute.getValueNumberInitial();
}
@Override
protected void setInternalValueStringInitial(final String value)
{
huAttribute.setValueInitial(value);
}
@Override
protected void setInternalValueNumberInitial(final BigDecimal value)
{
huAttribute.setValueNumberInitial(value);
}
@Override
protected final void onValueChanged(final Object valueOld, final Object valueNew)
{
saveIfNeeded();
}
/**
* Save to database if {@link #isSaveOnChange()}.
*/
private final void saveIfNeeded()
{
if (!saveOnChange)
{
return;
}
save();
}
/**
* Save to database. This method is saving no matter what {@link #isSaveOnChange()} says.
*/
final void save()
{
// Make sure the storage was not disposed
assertNotDisposed();
// Make sure HU Attribute contains the right/fresh data
huAttribute.setValue(valueString);
huAttribute.setValueNumber(valueNumber);
huAttribute.setValueDate(TimeUtil.asTimestamp(valueDate)); | getHUAttributesDAO().save(huAttribute);
}
@Override
public boolean isNew()
{
return huAttribute.getM_HU_Attribute_ID() <= 0;
}
@Override
protected void setInternalValueDate(Date value)
{
huAttribute.setValueDate(TimeUtil.asTimestamp(value));
this.valueDate = value;
}
@Override
protected Date getInternalValueDate()
{
return valueDate;
}
@Override
protected void setInternalValueDateInitial(Date value)
{
huAttribute.setValueDateInitial(TimeUtil.asTimestamp(value));
}
@Override
protected Date getInternalValueDateInitial()
{
return huAttribute.getValueDateInitial();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\HUAttributeValue.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8888
spring:
application:
name: zuul-application
# Zuul 配置项,对应 ZuulProperties 配置类
zuul:
servlet-path: / # ZuulServlet 匹配的路径,默认为 /zuul
# 路由配置项,对应 ZuulRoute Map
routes:
route_yudaoyuanma:
path: /blog/**
| url: http://www.iocoder.cn
route_oschina:
path: /oschina/**
url: https://www.oschina.net | repos\SpringBoot-Labs-master\labx-21\labx-21-sc-zuul-demo01\src\main\resources\application.yaml | 2 |
请在Spring Boot框架中完成以下Java代码 | private PickingJob markAsVoidedAndSave(PickingJob pickingJob)
{
pickingJob = pickingJob.withDocStatus(PickingJobDocStatus.Voided);
pickingJobRepository.save(pickingJob);
return pickingJob;
}
// private PickingJob unpickAllStepsAndSave(final PickingJob pickingJob)
// {
// return PickingJobUnPickCommand.builder()
// .pickingJobRepository(pickingJobRepository)
// .pickingCandidateService(pickingCandidateService)
// .pickingJob(pickingJob)
// .build()
// .execute();
// } | private PickingJob releasePickingSlotAndSave(PickingJob pickingJob)
{
final PickingJobId pickingJobId = pickingJob.getId();
final PickingSlotId pickingSlotId = pickingJob.getPickingSlotId().orElse(null);
if (pickingSlotId != null)
{
pickingJob = pickingJob.withPickingSlot(null);
pickingJobRepository.save(pickingJob);
pickingSlotService.release(pickingSlotId, pickingJobId);
}
return pickingJob;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\PickingJobAbortCommand.java | 2 |
请完成以下Java代码 | public Object getBaseObject()
{
return prospect;
}
@Override
public int getAD_Table_ID()
{
return X_R_Group.Table_ID;
}
@Override
public int getRecord_ID()
{
return prospect.getR_Group_ID();
}
@Override
public EMail sendEMail(I_AD_User from, String toEmail, String subject, final BoilerPlateContext attributes)
{
final Mailbox mailbox = mailService.findMailbox(MailboxQuery.builder()
.clientId(getClientId())
.orgId(getOrgId())
.adProcessId(getProcessInfo().getAdProcessId())
.fromUserId(UserId.ofRepoId(from.getAD_User_ID()))
.build());
return mailService.sendEMail(EMailRequest.builder()
.mailbox(mailbox)
.toList(toEMailAddresses(toEmail))
.subject(text.getSubject())
.message(text.getTextSnippetParsed(attributes))
.html(true)
.build());
} | });
}
private void notifyLetter(MADBoilerPlate text, MRGroupProspect prospect)
{
throw new UnsupportedOperationException();
}
private List<MRGroupProspect> getProspects(int R_Group_ID)
{
final String whereClause = MRGroupProspect.COLUMNNAME_R_Group_ID + "=?";
return new Query(getCtx(), MRGroupProspect.Table_Name, whereClause, get_TrxName())
.setParameters(R_Group_ID)
.list(MRGroupProspect.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\report\AD_BoilderPlate_SendToGroup.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getPath() {
return this.path;
}
public void setPath(String path) {
Assert.notNull(path, "'path' must not be null");
Assert.isTrue(path.length() > 1, "'path' must have length greater than 1");
Assert.isTrue(path.startsWith("/"), "'path' must start with '/'");
this.path = path;
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Settings getSettings() {
return this.settings;
}
public static class Settings {
/**
* Whether to enable trace output.
*/
private boolean trace;
/**
* Whether to enable remote access.
*/
private boolean webAllowOthers; | /**
* Password to access preferences and tools of H2 Console.
*/
private @Nullable String webAdminPassword;
public boolean isTrace() {
return this.trace;
}
public void setTrace(boolean trace) {
this.trace = trace;
}
public boolean isWebAllowOthers() {
return this.webAllowOthers;
}
public void setWebAllowOthers(boolean webAllowOthers) {
this.webAllowOthers = webAllowOthers;
}
public @Nullable String getWebAdminPassword() {
return this.webAdminPassword;
}
public void setWebAdminPassword(@Nullable String webAdminPassword) {
this.webAdminPassword = webAdminPassword;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-h2console\src\main\java\org\springframework\boot\h2console\autoconfigure\H2ConsoleProperties.java | 2 |
请完成以下Java代码 | public Set<CourseRegistration> getRegistrations() {
return registrations;
}
public void setRegistrations(Set<CourseRegistration> registrations) {
this.registrations = registrations;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) | return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Course other = (Course) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
} | repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\manytomany\model\Course.java | 1 |
请完成以下Java代码 | private ItemReader<TestData> dataSourceItemReader() throws Exception {
JdbcPagingItemReader<TestData> reader = new JdbcPagingItemReader<>();
reader.setDataSource(dataSource); // 设置数据源
reader.setFetchSize(5); // 每次取多少条记录
reader.setPageSize(5); // 设置每页数据量
// 指定sql查询语句 select id,field1,field2,field3 from TEST
MySqlPagingQueryProvider provider = new MySqlPagingQueryProvider();
provider.setSelectClause("id,field1,field2,field3"); //设置查询字段
provider.setFromClause("from TEST"); // 设置从哪张表查询
// 将读取到的数据转换为TestData对象
reader.setRowMapper((resultSet, rowNum) -> {
TestData data = new TestData();
data.setId(resultSet.getInt(1));
data.setField1(resultSet.getString(2)); // 读取第一个字段,类型为String
data.setField2(resultSet.getString(3)); | data.setField3(resultSet.getString(4));
return data;
});
Map<String, Order> sort = new HashMap<>(1);
sort.put("id", Order.ASCENDING);
provider.setSortKeys(sort); // 设置排序,通过id 升序
reader.setQueryProvider(provider);
// 设置namedParameterJdbcTemplate等属性
reader.afterPropertiesSet();
return reader;
}
} | repos\SpringAll-master\68.spring-batch-itemreader\src\main\java\cc\mrbird\batch\job\DataSourceItemReaderDemo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private String[] getRelationTypesWithFailureRelation(Class<?> clazz, RuleNode nodeAnnotation) {
List<String> relationTypes = new ArrayList<>(Arrays.asList(nodeAnnotation.relationTypes()));
if (TbOriginatorTypeSwitchNode.class.equals(clazz)) {
relationTypes.addAll(EntityType.NORMAL_NAMES);
}
if (TbMsgTypeSwitchNode.class.equals(clazz)) {
relationTypes.addAll(TbMsgType.NODE_CONNECTIONS);
relationTypes.add(TbNodeConnectionType.OTHER);
}
if (!relationTypes.contains(TbNodeConnectionType.FAILURE)) {
relationTypes.add(TbNodeConnectionType.FAILURE);
}
return relationTypes.toArray(new String[relationTypes.size()]);
}
@Override
public void discoverComponents() {
registerRuleNodeComponents();
log.debug("Found following definitions: {}", components.values());
}
@Override
public List<ComponentDescriptor> getComponents(ComponentType type, RuleChainType ruleChainType) {
if (RuleChainType.CORE.equals(ruleChainType)) {
if (coreComponentsMap.containsKey(type)) {
return Collections.unmodifiableList(coreComponentsMap.get(type));
} else {
return Collections.emptyList();
}
} else if (RuleChainType.EDGE.equals(ruleChainType)) {
if (edgeComponentsMap.containsKey(type)) {
return Collections.unmodifiableList(edgeComponentsMap.get(type));
} else {
return Collections.emptyList();
}
} else {
log.error("Unsupported rule chain type {}", ruleChainType);
throw new RuntimeException("Unsupported rule chain type " + ruleChainType);
}
}
@Override
public List<ComponentDescriptor> getComponents(Set<ComponentType> types, RuleChainType ruleChainType) {
if (RuleChainType.CORE.equals(ruleChainType)) {
return getComponents(types, coreComponentsMap);
} else if (RuleChainType.EDGE.equals(ruleChainType)) { | return getComponents(types, edgeComponentsMap);
} else {
log.error("Unsupported rule chain type {}", ruleChainType);
throw new RuntimeException("Unsupported rule chain type " + ruleChainType);
}
}
@Override
public Optional<ComponentDescriptor> getComponent(String clazz) {
return Optional.ofNullable(components.get(clazz));
}
private List<ComponentDescriptor> getComponents(Set<ComponentType> types, Map<ComponentType, List<ComponentDescriptor>> componentsMap) {
List<ComponentDescriptor> result = new ArrayList<>();
types.stream().filter(componentsMap::containsKey).forEach(type -> {
result.addAll(componentsMap.get(type));
});
return Collections.unmodifiableList(result);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\component\AnnotationComponentDiscoveryService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private static @Nullable Builder getBuilderFromIssuerIfPossible(String registrationId,
@Nullable String configuredProviderId, Map<String, Provider> providers) {
String providerId = (configuredProviderId != null) ? configuredProviderId : registrationId;
if (providers.containsKey(providerId)) {
Provider provider = providers.get(providerId);
String issuer = provider.getIssuerUri();
if (issuer != null) {
Builder builder = ClientRegistrations.fromIssuerLocation(issuer).registrationId(registrationId);
return getBuilder(builder, provider);
}
}
return null;
}
private static Builder getBuilder(String registrationId, @Nullable String configuredProviderId,
Map<String, Provider> providers) {
String providerId = (configuredProviderId != null) ? configuredProviderId : registrationId;
CommonOAuth2Provider provider = getCommonProvider(providerId);
if (provider == null && !providers.containsKey(providerId)) {
throw new IllegalStateException(getErrorMessage(configuredProviderId, registrationId));
}
Builder builder = (provider != null) ? provider.getBuilder(registrationId)
: ClientRegistration.withRegistrationId(registrationId);
if (providers.containsKey(providerId)) {
return getBuilder(builder, providers.get(providerId));
}
return builder;
}
private static String getErrorMessage(@Nullable String configuredProviderId, String registrationId) {
return ((configuredProviderId != null) ? "Unknown provider ID '" + configuredProviderId + "'"
: "Provider ID must be specified for client registration '" + registrationId + "'");
}
private static Builder getBuilder(Builder builder, Provider provider) {
PropertyMapper map = PropertyMapper.get(); | map.from(provider::getAuthorizationUri).to(builder::authorizationUri);
map.from(provider::getTokenUri).to(builder::tokenUri);
map.from(provider::getUserInfoUri).to(builder::userInfoUri);
map.from(provider::getUserInfoAuthenticationMethod)
.as(AuthenticationMethod::new)
.to(builder::userInfoAuthenticationMethod);
map.from(provider::getJwkSetUri).to(builder::jwkSetUri);
map.from(provider::getUserNameAttribute).to(builder::userNameAttributeName);
return builder;
}
private static @Nullable CommonOAuth2Provider getCommonProvider(String providerId) {
try {
return ApplicationConversionService.getSharedInstance().convert(providerId, CommonOAuth2Provider.class);
}
catch (ConversionException ex) {
return null;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-client\src\main\java\org\springframework\boot\security\oauth2\client\autoconfigure\OAuth2ClientPropertiesMapper.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int compareTo(ItemHint other) {
return getName().compareTo(other.getName());
}
public static ItemHint newHint(String name, ValueHint... values) {
return new ItemHint(name, Arrays.asList(values), Collections.emptyList());
}
@Override
public String toString() {
return "ItemHint{name='" + this.name + "', values=" + this.values + ", providers=" + this.providers + '}';
}
/**
* A hint for a value.
*/
public static class ValueHint {
private final Object value;
private final String description;
public ValueHint(Object value, String description) {
this.value = value;
this.description = description;
}
public Object getValue() {
return this.value;
}
public String getDescription() {
return this.description;
}
@Override
public String toString() {
return "ValueHint{value=" + this.value + ", description='" + this.description + '\'' + '}';
}
}
/**
* A value provider.
*/
public static class ValueProvider { | private final String name;
private final Map<String, Object> parameters;
public ValueProvider(String name, Map<String, Object> parameters) {
this.name = name;
this.parameters = parameters;
}
public String getName() {
return this.name;
}
public Map<String, Object> getParameters() {
return this.parameters;
}
@Override
public String toString() {
return "ValueProvider{name='" + this.name + "', parameters=" + this.parameters + '}';
}
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ItemHint.java | 2 |
请完成以下Java代码 | public boolean isAutoComplete() {
return autoCompleteAttribute.getValue(this);
}
public void setAutoComplete(boolean autoComplete) {
autoCompleteAttribute.setValue(this, autoComplete);
}
public Collection<Sentry> getExitCriterias() {
return exitCriteriaRefCollection.getReferenceTargetElements(this);
}
public Collection<Sentry> getExitCriteria() {
if (!isCmmn11()) {
return Collections.unmodifiableCollection(getExitCriterias());
}
else {
List<Sentry> sentries = new ArrayList<Sentry>();
Collection<ExitCriterion> exitCriterions = getExitCriterions();
for (ExitCriterion exitCriterion : exitCriterions) {
Sentry sentry = exitCriterion.getSentry();
if (sentry != null) {
sentries.add(sentry);
}
}
return Collections.unmodifiableCollection(sentries);
}
}
public Collection<ExitCriterion> getExitCriterions() {
return exitCriterionCollection.get(this);
}
public PlanningTable getPlanningTable() {
return planningTableChild.getChild(this);
}
public void setPlanningTable(PlanningTable planningTable) {
planningTableChild.setChild(this, planningTable);
}
public Collection<PlanItemDefinition> getPlanItemDefinitions() {
return planItemDefinitionCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Stage.class, CMMN_ELEMENT_STAGE)
.namespaceUri(CMMN11_NS)
.extendsType(PlanFragment.class)
.instanceProvider(new ModelTypeInstanceProvider<Stage>() {
public Stage newInstance(ModelTypeInstanceContext instanceContext) {
return new StageImpl(instanceContext);
} | });
autoCompleteAttribute = typeBuilder.booleanAttribute(CMMN_ATTRIBUTE_AUTO_COMPLETE)
.defaultValue(false)
.build();
exitCriteriaRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXIT_CRITERIA_REFS)
.namespace(CMMN10_NS)
.idAttributeReferenceCollection(Sentry.class, CmmnAttributeElementReferenceCollection.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
planningTableChild = sequenceBuilder.element(PlanningTable.class)
.build();
planItemDefinitionCollection = sequenceBuilder.elementCollection(PlanItemDefinition.class)
.build();
exitCriterionCollection = sequenceBuilder.elementCollection(ExitCriterion.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\StageImpl.java | 1 |
请完成以下Java代码 | private Optional<TbPair<Long, Long>> findValidPack(List<TbMsg> msgs, long deduplicationTimeoutMs) {
Optional<TbMsg> min = msgs.stream().min(Comparator.comparing(TbMsg::getMetaDataTs));
return min.map(minTsMsg -> {
long packStartTs = minTsMsg.getMetaDataTs();
long packEndTs = packStartTs + deduplicationInterval;
if (packEndTs <= deduplicationTimeoutMs) {
return new TbPair<>(packStartTs, packEndTs);
}
return null;
});
}
private void enqueueForTellNextWithRetry(TbContext ctx, TbMsg msg, int retryAttempt) {
if (retryAttempt <= config.getMaxRetries()) {
ctx.enqueueForTellNext(msg, TbNodeConnectionType.SUCCESS,
() -> log.trace("[{}][{}][{}] Successfully enqueue deduplication result message!", ctx.getSelfId(), msg.getOriginator(), retryAttempt),
throwable -> {
log.trace("[{}][{}][{}] Failed to enqueue deduplication output message due to: ", ctx.getSelfId(), msg.getOriginator(), retryAttempt, throwable);
if (retryAttempt < config.getMaxRetries()) {
ctx.schedule(() -> enqueueForTellNextWithRetry(ctx, msg, retryAttempt + 1), TB_MSG_DEDUPLICATION_RETRY_DELAY, TimeUnit.SECONDS);
} else {
log.trace("[{}][{}] Max retries [{}] exhausted. Dropping deduplication result message [{}]",
ctx.getSelfId(), msg.getOriginator(), config.getMaxRetries(), msg.getId());
}
});
}
}
private void scheduleTickMsg(TbContext ctx, EntityId deduplicationId) {
ctx.tellSelf(ctx.newMsg(null, TbMsgType.DEDUPLICATION_TIMEOUT_SELF_MSG, deduplicationId, TbMsgMetaData.EMPTY, TbMsg.EMPTY_STRING), deduplicationInterval + 1);
}
private String getMergedData(List<TbMsg> msgs) {
ArrayNode mergedData = JacksonUtil.newArrayNode();
msgs.forEach(msg -> { | ObjectNode msgNode = JacksonUtil.newObjectNode();
msgNode.set("msg", JacksonUtil.toJsonNode(msg.getData()));
msgNode.set("metadata", JacksonUtil.valueToTree(msg.getMetaData().getData()));
mergedData.add(msgNode);
});
return JacksonUtil.toString(mergedData);
}
private TbMsgMetaData getMetadata() {
TbMsgMetaData metaData = new TbMsgMetaData();
metaData.putValue("ts", String.valueOf(System.currentTimeMillis()));
return metaData;
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\deduplication\TbMsgDeduplicationNode.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<HCURR1> getHCURR1() {
if (hcurr1 == null) {
hcurr1 = new ArrayList<HCURR1>();
}
return this.hcurr1;
}
/**
* Gets the value of the hpayt1 property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the hpayt1 property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getHPAYT1().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link HPAYT1 }
*
*
*/
public List<HPAYT1> getHPAYT1() {
if (hpayt1 == null) {
hpayt1 = new ArrayList<HPAYT1>();
}
return this.hpayt1;
}
/**
* Gets the value of the halch1 property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the halch1 property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getHALCH1().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link HALCH1 }
*
*
*/ | public List<HALCH1> getHALCH1() {
if (halch1 == null) {
halch1 = new ArrayList<HALCH1>();
}
return this.halch1;
}
/**
* Gets the value of the detail property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the detail property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDETAIL().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DETAILXrech }
*
*
*/
public List<DETAILXrech> getDETAIL() {
if (detail == null) {
detail = new ArrayList<DETAILXrech>();
}
return this.detail;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_invoic\de\metas\edi\esb\jaxb\stepcom\invoic\HEADERXrech.java | 2 |
请完成以下Java代码 | public List<IOParameter> getInParameters() {
return inParameters;
}
@Override
public void addInParameter(IOParameter inParameter) {
if (inParameters == null) {
inParameters = new ArrayList<>();
}
inParameters.add(inParameter);
}
@Override
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
}
@Override
public ScriptTask clone() {
ScriptTask clone = new ScriptTask();
clone.setValues(this);
return clone; | }
public void setValues(ScriptTask otherElement) {
super.setValues(otherElement);
setScriptFormat(otherElement.getScriptFormat());
setScript(otherElement.getScript());
setResultVariable(otherElement.getResultVariable());
setSkipExpression(otherElement.getSkipExpression());
setAutoStoreVariables(otherElement.isAutoStoreVariables());
setDoNotIncludeVariables(otherElement.isDoNotIncludeVariables());
inParameters = null;
if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) {
inParameters = new ArrayList<>();
for (IOParameter parameter : otherElement.getInParameters()) {
inParameters.add(parameter.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ScriptTask.java | 1 |
请完成以下Java代码 | public List<User> getAll() {
Query query = entityManager.createQuery("SELECT e FROM User e");
return query.getResultList();
}
@Override
public void save(User user) {
executeInsideTransaction(entityManager -> entityManager.persist(user));
}
@Override
public void update(User user, String[] params) {
user.setName(Objects.requireNonNull(params[0], "Name cannot be null"));
user.setEmail(Objects.requireNonNull(params[1], "Email cannot be null"));
executeInsideTransaction(entityManager -> entityManager.merge(user));
} | @Override
public void delete(User user) {
executeInsideTransaction(entityManager -> entityManager.remove(user));
}
private void executeInsideTransaction(Consumer<EntityManager> action) {
final EntityTransaction tx = entityManager.getTransaction();
try {
tx.begin();
action.accept(entityManager);
tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e;
}
}
} | repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\daopattern\daos\JpaUserDao.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreatedBefore() {
return createdBefore;
}
public void setCreatedBefore(Date createdBefore) {
this.createdBefore = createdBefore;
}
public Date getCreatedAfter() {
return createdAfter;
}
public void setCreatedAfter(Date createdAfter) {
this.createdAfter = createdAfter;
}
public String getStartUserId() {
return startUserId;
}
public void setStartUserId(String startUserId) {
this.startUserId = startUserId;
}
public String getReferenceId() {
return referenceId;
}
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
public String getReferenceType() {
return referenceType;
}
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
public Boolean getIncludeEnded() {
return includeEnded;
} | public void setIncludeEnded(Boolean includeEnded) {
this.includeEnded = includeEnded;
}
public Boolean getIncludeLocalVariables() {
return includeLocalVariables;
}
public void setIncludeLocalVariables(boolean includeLocalVariables) {
this.includeLocalVariables = includeLocalVariables;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Set<String> getCaseInstanceIds() {
return caseInstanceIds;
}
public void setCaseInstanceIds(Set<String> caseInstanceIds) {
this.caseInstanceIds = caseInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\planitem\PlanItemInstanceQueryRequest.java | 2 |
请完成以下Java代码 | public String getTaskId() {
return taskId;
}
@Override
public String getBatchId() {
return null;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public String getErrorMessage() {
return errorMessage;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTypeName() {
if(value != null) {
return value.getType().getName();
}
else {
return null;
}
}
public String getName() {
return name;
}
public Object getValue() {
if(value != null) {
return value.getValue();
}
else {
return null;
}
}
public TypedValue getTypedValue() {
return value;
} | public ProcessEngineServices getProcessEngineServices() {
return Context.getProcessEngineConfiguration().getProcessEngine();
}
public ProcessEngine getProcessEngine() {
return Context.getProcessEngineConfiguration().getProcessEngine();
}
public static DelegateCaseVariableInstanceImpl fromVariableInstance(VariableInstance variableInstance) {
DelegateCaseVariableInstanceImpl delegateInstance = new DelegateCaseVariableInstanceImpl();
delegateInstance.variableId = variableInstance.getId();
delegateInstance.processDefinitionId = variableInstance.getProcessDefinitionId();
delegateInstance.processInstanceId = variableInstance.getProcessInstanceId();
delegateInstance.executionId = variableInstance.getExecutionId();
delegateInstance.caseExecutionId = variableInstance.getCaseExecutionId();
delegateInstance.caseInstanceId = variableInstance.getCaseInstanceId();
delegateInstance.taskId = variableInstance.getTaskId();
delegateInstance.activityInstanceId = variableInstance.getActivityInstanceId();
delegateInstance.tenantId = variableInstance.getTenantId();
delegateInstance.errorMessage = variableInstance.getErrorMessage();
delegateInstance.name = variableInstance.getName();
delegateInstance.value = variableInstance.getTypedValue();
return delegateInstance;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\listener\DelegateCaseVariableInstanceImpl.java | 1 |
请完成以下Java代码 | public class BufferedPrintConnectionEndpoint implements IPrintConnectionEndpoint
{
private final transient Logger log = Logger.getLogger(getClass().getName());
private final Queue<PrintPackageAndData> printPackageQueue = new LinkedList<PrintPackageAndData>();
private final Map<String, PrintPackageAndData> trx2PrintPackageMap = new HashMap<String, PrintPackageAndData>();
private final Object sync = new Object();
public BufferedPrintConnectionEndpoint()
{
super();
}
@Override
public void addPrinterHW(final PrinterHWList printerHWList)
{
log.info("Found printer HWs: " + printerHWList);
}
public void addPrintPackage(final PrintPackage printPackage, final InputStream printDataStream)
{
synchronized (sync)
{
final String trx = printPackage.getTransactionId();
if (trx2PrintPackageMap.containsKey(trx))
{
throw new IllegalArgumentException("Transaction already exists in queue: " + printPackage);
}
final PrintPackageAndData item = new PrintPackageAndData();
item.printPackage = printPackage;
item.printDataStream = printDataStream;
printPackageQueue.add(item);
trx2PrintPackageMap.put(trx, item);
}
}
@Override
public PrintPackage getNextPrintPackage()
{
synchronized (sync)
{
final PrintPackageAndData item = printPackageQueue.poll();
if (item == null)
{ | return null;
}
System.out.println("getNextPrintPackage: " + item.printPackage);
return item.printPackage;
}
}
@Override
public InputStream getPrintPackageData(final PrintPackage printPackage)
{
synchronized (sync)
{
final String trx = printPackage.getTransactionId();
final PrintPackageAndData item = trx2PrintPackageMap.remove(trx);
if (item == null)
{
throw new IllegalStateException("No data found for " + printPackage);
}
System.out.println("getPrintPackageData: trx=" + trx + " => stream: " + item.printDataStream);
return item.printDataStream;
}
}
@Override
public void sendPrintPackageResponse(final PrintPackage printPackage, final PrintJobInstructionsConfirm response)
{
log.info("Got : " + response + " for " + printPackage);
}
private static class PrintPackageAndData
{
public PrintPackage printPackage;
public InputStream printDataStream;
}
@Override
public LoginResponse login(final LoginRequest loginRequest)
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\endpoint\BufferedPrintConnectionEndpoint.java | 1 |
请完成以下Java代码 | default String getUsername() {
return getClaimAsString(OAuth2TokenIntrospectionClaimNames.USERNAME);
}
/**
* Returns the client identifier {@code (client_id)} for the token
* @return the client identifier for the token
*/
@Nullable
default String getClientId() {
return getClaimAsString(OAuth2TokenIntrospectionClaimNames.CLIENT_ID);
}
/**
* Returns the scopes {@code (scope)} associated with the token
* @return the scopes associated with the token
*/
@Nullable
default List<String> getScopes() {
return getClaimAsStringList(OAuth2TokenIntrospectionClaimNames.SCOPE);
}
/**
* Returns the type of the token {@code (token_type)}, for example {@code bearer}.
* @return the type of the token, for example {@code bearer}.
*/
@Nullable
default String getTokenType() {
return getClaimAsString(OAuth2TokenIntrospectionClaimNames.TOKEN_TYPE);
}
/**
* Returns a timestamp {@code (exp)} indicating when the token expires
* @return a timestamp indicating when the token expires
*/
@Nullable
default Instant getExpiresAt() {
return getClaimAsInstant(OAuth2TokenIntrospectionClaimNames.EXP);
}
/**
* Returns a timestamp {@code (iat)} indicating when the token was issued
* @return a timestamp indicating when the token was issued
*/
@Nullable
default Instant getIssuedAt() {
return getClaimAsInstant(OAuth2TokenIntrospectionClaimNames.IAT);
}
/**
* Returns a timestamp {@code (nbf)} indicating when the token is not to be used
* before | * @return a timestamp indicating when the token is not to be used before
*/
@Nullable
default Instant getNotBefore() {
return getClaimAsInstant(OAuth2TokenIntrospectionClaimNames.NBF);
}
/**
* Returns usually a machine-readable identifier {@code (sub)} of the resource owner
* who authorized the token
* @return usually a machine-readable identifier of the resource owner who authorized
* the token
*/
@Nullable
default String getSubject() {
return getClaimAsString(OAuth2TokenIntrospectionClaimNames.SUB);
}
/**
* Returns the intended audience {@code (aud)} for the token
* @return the intended audience for the token
*/
@Nullable
default List<String> getAudience() {
return getClaimAsStringList(OAuth2TokenIntrospectionClaimNames.AUD);
}
/**
* Returns the issuer {@code (iss)} of the token
* @return the issuer of the token
*/
@Nullable
default URL getIssuer() {
return getClaimAsURL(OAuth2TokenIntrospectionClaimNames.ISS);
}
/**
* Returns the identifier {@code (jti)} for the token
* @return the identifier for the token
*/
@Nullable
default String getId() {
return getClaimAsString(OAuth2TokenIntrospectionClaimNames.JTI);
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\OAuth2TokenIntrospectionClaimAccessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CampaignPrice
{
@NonNull
ProductId productId;
@Nullable
BPartnerId bpartnerId;
@Nullable
BPGroupId bpGroupId;
@Nullable
PricingSystemId pricingSystemId;
@NonNull
CountryId countryId;
@NonNull
Range<LocalDate> validRange;
@Nullable
Money priceList;
@NonNull
Money priceStd; | @NonNull
UomId priceUomId;
@NonNull
TaxCategoryId taxCategoryId;
@NonNull
@Default
InvoicableQtyBasedOn invoicableQtyBasedOn = InvoicableQtyBasedOn.NominalWeight;
public LocalDate getValidFrom()
{
return getValidRange().lowerEndpoint();
}
public CurrencyId getCurrencyId()
{
return getPriceStd().getCurrencyId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\campaign_price\CampaignPrice.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected static int getConfigInt(String name, int defaultVal, int minVal) {
if (cacheMap.containsKey(name)) {
return (int)cacheMap.get(name);
}
int val = NumberUtils.toInt(getConfig(name));
if (val == 0) {
val = defaultVal;
} else if (val < minVal) {
val = minVal;
}
cacheMap.put(name, val);
return val;
}
public static String getAuthUsername() {
return getConfigStr(CONFIG_AUTH_USERNAME);
}
public static String getAuthPassword() {
return getConfigStr(CONFIG_AUTH_PASSWORD);
}
public static int getHideAppNoMachineMillis() {
return getConfigInt(CONFIG_HIDE_APP_NO_MACHINE_MILLIS, 0, 60000); | }
public static int getRemoveAppNoMachineMillis() {
return getConfigInt(CONFIG_REMOVE_APP_NO_MACHINE_MILLIS, 0, 120000);
}
public static int getAutoRemoveMachineMillis() {
return getConfigInt(CONFIG_AUTO_REMOVE_MACHINE_MILLIS, 0, 300000);
}
public static int getUnhealthyMachineMillis() {
return getConfigInt(CONFIG_UNHEALTHY_MACHINE_MILLIS, DEFAULT_MACHINE_HEALTHY_TIMEOUT_MS, 30000);
}
public static void clearCache() {
cacheMap.clear();
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\config\DashboardConfig.java | 2 |
请完成以下Java代码 | protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_Table_MView[")
.append(get_ID()).append("]");
return sb.toString();
}
public org.compiere.model.I_AD_Table getAD_Table() throws RuntimeException
{
return (org.compiere.model.I_AD_Table)MTable.get(getCtx(), org.compiere.model.I_AD_Table.Table_Name)
.getPO(getAD_Table_ID(), get_TrxName()); }
/** Set DB-Tabelle.
@param AD_Table_ID
Database Table information
*/
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get DB-Tabelle.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Staled.
@param IsStaled Staled */
public void setIsStaled (boolean IsStaled)
{
set_Value (COLUMNNAME_IsStaled, Boolean.valueOf(IsStaled));
}
/** Get Staled.
@return Staled */
public boolean isStaled ()
{
Object oo = get_Value(COLUMNNAME_IsStaled);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false; | }
/** Set Gueltig.
@param IsValid
Element ist gueltig
*/
public void setIsValid (boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid));
}
/** Get Gueltig.
@return Element ist gueltig
*/
public boolean isValid ()
{
Object oo = get_Value(COLUMNNAME_IsValid);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Last Refresh Date.
@param LastRefreshDate Last Refresh Date */
public void setLastRefreshDate (Timestamp LastRefreshDate)
{
set_Value (COLUMNNAME_LastRefreshDate, LastRefreshDate);
}
/** Get Last Refresh Date.
@return Last Refresh Date */
public Timestamp getLastRefreshDate ()
{
return (Timestamp)get_Value(COLUMNNAME_LastRefreshDate);
}
/** Set Staled Since.
@param StaledSinceDate Staled Since */
public void setStaledSinceDate (Timestamp StaledSinceDate)
{
set_Value (COLUMNNAME_StaledSinceDate, StaledSinceDate);
}
/** Get Staled Since.
@return Staled Since */
public Timestamp getStaledSinceDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StaledSinceDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_Table_MView.java | 1 |
请完成以下Java代码 | private void saveIssuesToBOMLine(
@NonNull final PickingCandidateId pickingCandidateId,
@NonNull final ImmutableList<PickingCandidateIssueToBOMLine> issuesToPickingOrder)
{
final HashMap<PickingCandidateIssueToBOMLineKey, I_M_Picking_Candidate_IssueToOrder> existingRecordsByKey = streamIssuesToBOMLineRecords(pickingCandidateId)
.collect(GuavaCollectors.toHashMapByKey(PickingCandidateIssueToBOMLineKey::of));
for (final PickingCandidateIssueToBOMLine issue : issuesToPickingOrder)
{
final PickingCandidateIssueToBOMLineKey key = PickingCandidateIssueToBOMLineKey.of(issue);
final I_M_Picking_Candidate_IssueToOrder existingRecord = existingRecordsByKey.remove(key);
final I_M_Picking_Candidate_IssueToOrder record;
if (existingRecord != null)
{
record = existingRecord;
}
else
{
record = newInstance(I_M_Picking_Candidate_IssueToOrder.class);
}
record.setIsActive(true);
record.setM_Picking_Candidate_ID(pickingCandidateId.getRepoId());
record.setPP_Order_BOMLine_ID(issue.getIssueToOrderBOMLineId().getRepoId());
record.setM_HU_ID(issue.getIssueFromHUId().getRepoId());
record.setM_Product_ID(issue.getProductId().getRepoId());
record.setQtyToIssue(issue.getQtyToIssue().toBigDecimal());
record.setC_UOM_ID(issue.getQtyToIssue().getUomId().getRepoId());
saveRecord(record);
}
deleteAll(existingRecordsByKey.values());
}
private Stream<I_M_Picking_Candidate_IssueToOrder> streamIssuesToBOMLineRecords(final PickingCandidateId pickingCandidateId)
{
return queryBL.createQueryBuilder(I_M_Picking_Candidate_IssueToOrder.class) | .addEqualsFilter(I_M_Picking_Candidate_IssueToOrder.COLUMNNAME_M_Picking_Candidate_ID, pickingCandidateId)
.create()
.stream();
}
private void deleteIssuesToBOMLine(@NonNull final Collection<PickingCandidateId> pickingCandidateIds)
{
if (pickingCandidateIds.isEmpty())
{
return;
}
queryBL.createQueryBuilder(I_M_Picking_Candidate_IssueToOrder.class)
.addInArrayFilter(I_M_Picking_Candidate_IssueToOrder.COLUMNNAME_M_Picking_Candidate_ID, pickingCandidateIds)
.create()
.delete();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\PickingCandidateRepository.java | 1 |
请完成以下Java代码 | public class ADRuleDAO implements IADRuleDAO
{
/** Cache by AD_Rule_ID */
private static CCache<Integer, I_AD_Rule> s_cacheById = new CCache<>(I_AD_Rule.Table_Name + "#by#AD_Rule_ID", 20);
private static CCache<String, I_AD_Rule> s_cacheByValue = new CCache<>(I_AD_Rule.Table_Name + "#by#Value", 20);
@Override
public I_AD_Rule retrieveById(final Properties ctx, final int AD_Rule_ID)
{
if (AD_Rule_ID <= 0)
{
return null;
}
return s_cacheById.getOrLoad(AD_Rule_ID, () -> {
final I_AD_Rule rule = InterfaceWrapperHelper.create(ctx, AD_Rule_ID, I_AD_Rule.class, ITrx.TRXNAME_None);
s_cacheByValue.put(rule.getValue(), rule);
return rule;
});
}
@Override
public I_AD_Rule retrieveByValue(final Properties ctx, final String ruleValue)
{
if (ruleValue == null)
{
return null;
}
return s_cacheByValue.getOrLoad(ruleValue, () -> {
final I_AD_Rule rule = retrieveByValue_NoCache(ctx, ruleValue);
if (rule != null)
{
s_cacheById.put(rule.getAD_Rule_ID(), rule); | }
return rule;
});
}
private final I_AD_Rule retrieveByValue_NoCache(final Properties ctx, final String ruleValue)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_Rule.class, ctx, ITrx.TRXNAME_None)
.addEqualsFilter(I_AD_Rule.COLUMNNAME_Value, ruleValue)
.addOnlyActiveRecordsFilter()
.create()
.firstOnly(I_AD_Rule.class);
}
@Override
public List<I_AD_Rule> retrieveByEventType(final Properties ctx, final String eventType)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_Rule.class, ctx, ITrx.TRXNAME_None)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_Rule.COLUMNNAME_EventType, eventType)
.create()
.list(I_AD_Rule.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\script\impl\ADRuleDAO.java | 1 |
请完成以下Java代码 | public void setOrderByClause (java.lang.String OrderByClause)
{
set_Value (COLUMNNAME_OrderByClause, OrderByClause);
}
/** Get Sql ORDER BY.
@return Fully qualified ORDER BY clause
*/
@Override
public java.lang.String getOrderByClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_OrderByClause);
}
/** Set Inaktive Werte anzeigen.
@param ShowInactiveValues Inaktive Werte anzeigen */
@Override
public void setShowInactiveValues (boolean ShowInactiveValues)
{
set_Value (COLUMNNAME_ShowInactiveValues, Boolean.valueOf(ShowInactiveValues));
}
/** Get Inaktive Werte anzeigen.
@return Inaktive Werte anzeigen */
@Override
public boolean isShowInactiveValues ()
{
Object oo = get_Value(COLUMNNAME_ShowInactiveValues);
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
*/
@Override
public void setWhereClause (java.lang.String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
@Override
public java.lang.String getWhereClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Ref_Table.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class QtyTUConvertor implements QtyConvertor
{
@NonNull IHUCapacityBL capacityBL;
@NonNull ProductId productId;
@NonNull I_M_HU_PI_Item_Product packingInstruction;
@NonNull I_C_UOM tuUOM;
@NonNull Map<UomId, Capacity> uomId2Capacity = new HashMap<>();
@Nullable
@Override
public Quantity convert(@Nullable final Quantity quantity)
{
if (quantity == null)
{
return null;
}
final Capacity capacity = getCapacityForUomId(quantity.getUOM());
final BigDecimal qtyTUQty = quantity.toBigDecimal()
.divide(capacity.toBigDecimal(), tuUOM.getStdPrecision(), RoundingMode.UP); | return Quantity.of(qtyTUQty, tuUOM);
}
@Override
public @NonNull UomId getTargetUomId()
{
return UomId.ofRepoId(tuUOM.getC_UOM_ID());
}
@NonNull
private Capacity getCapacityForUomId(@NonNull final I_C_UOM uom)
{
return uomId2Capacity.computeIfAbsent(UomId.ofRepoId(uom.getC_UOM_ID()),
(ignore) -> capacityBL.getCapacity(packingInstruction, productId, uom));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\QtyTUConvertor.java | 2 |
请完成以下Java代码 | public Parameter getSource() {
return sourceRefAttribute.getReferenceTargetElement(this);
}
public void setSource(Parameter parameter) {
sourceRefAttribute.setReferenceTargetElement(this, parameter);
}
public Parameter getTarget() {
return targetRefAttribute.getReferenceTargetElement(this);
}
public void setTarget(Parameter parameter) {
targetRefAttribute.setReferenceTargetElement(this, parameter);
}
public TransformationExpression getTransformation() {
return transformationChild.getChild(this);
}
public void setTransformation(TransformationExpression transformationExpression) {
transformationChild.setChild(this, transformationExpression);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ParameterMapping.class, CMMN_ELEMENT_PARAMETER_MAPPING)
.extendsType(CmmnElement.class)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<ParameterMapping>() {
public ParameterMapping newInstance(ModelTypeInstanceContext instanceContext) {
return new ParameterMappingImpl(instanceContext);
}
});
sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF) | .idAttributeReference(Parameter.class)
.build();
targetRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_REF)
.idAttributeReference(Parameter.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
transformationChild = sequenceBuilder.element(TransformationExpression.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ParameterMappingImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected String getDatabaseName() {
return "test";
}
@Override
public MongoClient mongoClient() {
final ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test");
final MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.build();
return MongoClients.create(mongoClientSettings);
}
@Override
public Collection<String> getMappingBasePackages() {
return Collections.singleton("com.baeldung");
} | @Bean
public UserCascadeSaveMongoEventListener userCascadingMongoEventListener() {
return new UserCascadeSaveMongoEventListener();
}
@Bean
public CascadeSaveMongoEventListener cascadingMongoEventListener() {
return new CascadeSaveMongoEventListener();
}
@Bean
MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
return new MongoTransactionManager(dbFactory);
}
} | repos\tutorials-master\persistence-modules\spring-data-mongodb-2\src\main\java\com\baeldung\config\MongoConfig.java | 2 |
请完成以下Java代码 | public void setProcessDefinitionCategory(String processDefinitionId, String category) {
commandExecutor.execute(new SetProcessDefinitionCategoryCmd(processDefinitionId, category));
}
public InputStream getProcessModel(String processDefinitionId) {
return commandExecutor.execute(new GetDeploymentProcessModelCmd(processDefinitionId));
}
public Model newModel() {
return commandExecutor.execute(new CreateModelCmd());
}
public void saveModel(Model model) {
commandExecutor.execute(new SaveModelCmd((ModelEntity) model));
}
public void deleteModel(String modelId) {
commandExecutor.execute(new DeleteModelCmd(modelId));
}
public void addModelEditorSource(String modelId, byte[] bytes) {
commandExecutor.execute(new AddEditorSourceForModelCmd(modelId, bytes));
}
public void addModelEditorSourceExtra(String modelId, byte[] bytes) {
commandExecutor.execute(new AddEditorSourceExtraForModelCmd(modelId, bytes));
}
public ModelQuery createModelQuery() {
return new ModelQueryImpl(commandExecutor);
}
@Override
public NativeModelQuery createNativeModelQuery() {
return new NativeModelQueryImpl(commandExecutor);
}
public Model getModel(String modelId) {
return commandExecutor.execute(new GetModelCmd(modelId));
}
public byte[] getModelEditorSource(String modelId) { | return commandExecutor.execute(new GetModelEditorSourceCmd(modelId));
}
public byte[] getModelEditorSourceExtra(String modelId) {
return commandExecutor.execute(new GetModelEditorSourceExtraCmd(modelId));
}
public void addCandidateStarterUser(String processDefinitionId, String userId) {
commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null));
}
public void addCandidateStarterGroup(String processDefinitionId, String groupId) {
commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId));
}
public void deleteCandidateStarterGroup(String processDefinitionId, String groupId) {
commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId));
}
public void deleteCandidateStarterUser(String processDefinitionId, String userId) {
commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null));
}
public List<IdentityLink> getIdentityLinksForProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new GetIdentityLinksForProcessDefinitionCmd(processDefinitionId));
}
public List<ValidationError> validateProcess(BpmnModel bpmnModel) {
return commandExecutor.execute(new ValidateBpmnModelCmd(bpmnModel));
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\RepositoryServiceImpl.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.