instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class ProcessEngineXmlImpl implements ProcessEngineXml { protected String name; protected boolean isDefault; protected String configurationClass; protected String jobAcquisitionName; protected String datasource; protected Map<String, String> properties; protected List<ProcessEnginePluginXml> plugins; public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isDefault() { return isDefault; } public void setDefault(boolean isDefault) { this.isDefault = isDefault; } public String getConfigurationClass() { return configurationClass; } public void setConfigurationClass(String configurationClass) { this.configurationClass = configurationClass; } public Map<String, String> getProperties() { return properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; } public String getDatasource() {
return datasource; } public void setDatasource(String datasource) { this.datasource = datasource; } public String getJobAcquisitionName() { return jobAcquisitionName; } public void setJobAcquisitionName(String jobAcquisitionName) { this.jobAcquisitionName = jobAcquisitionName; } public List<ProcessEnginePluginXml> getPlugins() { return plugins; } public void setPlugins(List<ProcessEnginePluginXml> plugins) { this.plugins = plugins; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\metadata\ProcessEngineXmlImpl.java
1
请完成以下Java代码
private static WFActivityStatus computeStatus( @NonNull final Quantity qtyToReceive, @NonNull final Quantity qtyReceived) { if (qtyReceived.isZero()) { return WFActivityStatus.NOT_STARTED; } final Quantity qtyToReceiveRemaining = qtyToReceive.subtract(qtyReceived); return qtyToReceiveRemaining.signum() != 0 ? WFActivityStatus.IN_PROGRESS : WFActivityStatus.COMPLETED; } public FinishedGoodsReceiveLine withReceivingTarget(@Nullable final ReceivingTarget receivingTarget) { return !Objects.equals(this.receivingTarget, receivingTarget) ? toBuilder().receivingTarget(receivingTarget).build() : this; }
public FinishedGoodsReceiveLine withQtyReceived(@NonNull final Quantity qtyReceived) { return !Objects.equals(this.qtyReceived, qtyReceived) ? toBuilder().qtyReceived(qtyReceived).build() : this; } @NonNull public ITranslatableString getProductValueAndProductName() { final TranslatableStringBuilder message = TranslatableStrings.builder() .append(getProductValue()) .append(" ") .append(getProductName()); return message.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\FinishedGoodsReceiveLine.java
1
请完成以下Java代码
public String getUsername() { return user.getUsername(); } @Override public String getPassword() { return user.getPassword(); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { final List<GrantedAuthority> authorities = new ArrayList<>(); for (final Privilege privilege : user.getPrivileges()) { authorities.add(new SimpleGrantedAuthority(privilege.getName())); } return authorities; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; }
@Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } public User getUser() { return user; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\security\MyUserPrincipal.java
1
请完成以下Java代码
public int getDisplayType() { return gridField.getDisplayType(); } public ReferenceId getAD_Reference_Value_ID() { return gridField.getAD_Reference_Value_ID(); } public boolean isLookup() { return gridField.isLookup(); } public Lookup getLookup() { return gridField.getLookup(); } public boolean isVirtualColumn() { return gridField.isVirtualColumn(); } /** * Creates the editor component * * @param tableEditor true if table editor * @return editor or null if editor could not be created */ public VEditor createEditor(final boolean tableEditor) { // Reset lookup state // background: the lookup implements MutableComboBoxModel which stores the selected item. // If this lookup was previously used somewhere, the selected item is retained from there and we will get unexpected results. final Lookup lookup = gridField.getLookup(); if (lookup != null) { lookup.setSelectedItem(null); } // // Create a new editor VEditor editor = swingEditorFactory.getEditor(gridField, tableEditor); if (editor == null && tableEditor) { editor = new VString(); } // // Configure the new editor if (editor != null) { editor.setMandatory(false); editor.setReadWrite(true); } return editor; } public CLabel createEditorLabel() { return swingEditorFactory.getLabel(gridField); } @Override public Object convertValueToFieldType(final Object valueObj) { return UserQueryFieldHelper.parseValueObjectByColumnDisplayType(valueObj, getDisplayType(), getColumnName()); } @Override public String getValueDisplay(final Object value) { String infoDisplay = value == null ? "" : value.toString(); if (isLookup())
{ final Lookup lookup = getLookup(); if (lookup != null) { infoDisplay = lookup.getDisplay(value); } } else if (getDisplayType() == DisplayType.YesNo) { final IMsgBL msgBL = Services.get(IMsgBL.class); infoDisplay = msgBL.getMsg(Env.getCtx(), infoDisplay); } return infoDisplay; } @Override public boolean matchesColumnName(final String columnName) { if (columnName == null || columnName.isEmpty()) { return false; } if (columnName.equals(getColumnName())) { return true; } if (gridField.isVirtualColumn()) { if (columnName.equals(gridField.getColumnSQL(false))) { return true; } if (columnName.equals(gridField.getColumnSQL(true))) { return true; } } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelSearchField.java
1
请完成以下Java代码
private void repairFileChannel() throws IOException { tracker.closedFileChannel(this.path); this.fileChannel = FileChannel.open(this.path, StandardOpenOption.READ); tracker.openedFileChannel(this.path); } void open() throws IOException { synchronized (this.lock) { if (this.referenceCount == 0) { debug.log("Opening '%s'", this.path); this.fileChannel = FileChannel.open(this.path, StandardOpenOption.READ); this.buffer = ByteBuffer.allocateDirect(BUFFER_SIZE); tracker.openedFileChannel(this.path); } this.referenceCount++; debug.log("Reference count for '%s' incremented to %s", this.path, this.referenceCount); } } void close() throws IOException { synchronized (this.lock) { if (this.referenceCount == 0) { return; } this.referenceCount--; if (this.referenceCount == 0) { debug.log("Closing '%s'", this.path); this.buffer = null; this.bufferPosition = -1; this.bufferSize = 0; this.fileChannel.close(); tracker.closedFileChannel(this.path); this.fileChannel = null; if (this.randomAccessFile != null) { this.randomAccessFile.close(); tracker.closedFileChannel(this.path); this.randomAccessFile = null; } } debug.log("Reference count for '%s' decremented to %s", this.path, this.referenceCount); } } <E extends Exception> void ensureOpen(Supplier<E> exceptionSupplier) throws E { synchronized (this.lock) { if (this.referenceCount == 0) {
throw exceptionSupplier.get(); } } } @Override public String toString() { return this.path.toString(); } } /** * Internal tracker used to check open and closing of files in tests. */ interface Tracker { Tracker NONE = new Tracker() { @Override public void openedFileChannel(Path path) { } @Override public void closedFileChannel(Path path) { } }; void openedFileChannel(Path path); void closedFileChannel(Path path); } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\zip\FileDataBlock.java
1
请完成以下Java代码
public String getName() { return type; } @Schema(description = "JSON object with the alarm Id. " + "Specify this field to update the alarm. " + "Referencing non-existing alarm Id will cause error. " + "Omit this field to create new alarm.") @Override public AlarmId getId() { return super.getId(); } @Schema(description = "Timestamp of the alarm creation, in milliseconds", example = "1634058704567", accessMode = Schema.AccessMode.READ_ONLY) @Override public long getCreatedTime() { return super.getCreatedTime(); } @JsonProperty(access = JsonProperty.Access.READ_ONLY) @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "status of the Alarm", example = "ACTIVE_UNACK", accessMode = Schema.AccessMode.READ_ONLY) public AlarmStatus getStatus() { return toStatus(cleared, acknowledged); }
public static AlarmStatus toStatus(boolean cleared, boolean acknowledged) { if (cleared) { return acknowledged ? AlarmStatus.CLEARED_ACK : AlarmStatus.CLEARED_UNACK; } else { return acknowledged ? AlarmStatus.ACTIVE_ACK : AlarmStatus.ACTIVE_UNACK; } } @JsonIgnore public DashboardId getDashboardId() { return Optional.ofNullable(getDetails()).map(details -> details.get("dashboardId")) .filter(JsonNode::isTextual).map(id -> new DashboardId(UUID.fromString(id.asText()))).orElse(null); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\alarm\Alarm.java
1
请完成以下Java代码
protected String getDescription() { Assert.state(this.servlet != null, "Unable to return description for null servlet"); return "servlet " + getServletName(); } @Override protected ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) { String name = getServletName(); return servletContext.addServlet(name, this.servlet); } /** * Configure registration settings. Subclasses can override this method to perform * additional configuration if required. * @param registration the registration */ @Override protected void configure(ServletRegistration.Dynamic registration) { super.configure(registration); String[] urlMapping = StringUtils.toStringArray(this.urlMappings); if (urlMapping.length == 0 && this.alwaysMapUrl) { urlMapping = DEFAULT_MAPPINGS; } if (!ObjectUtils.isEmpty(urlMapping)) { registration.addMapping(urlMapping); } registration.setLoadOnStartup(this.loadOnStartup);
if (this.multipartConfig != null) { registration.setMultipartConfig(this.multipartConfig); } } /** * Returns the servlet name that will be registered. * @return the servlet name */ public String getServletName() { return getOrDeduceName(this.servlet); } @Override public String toString() { return getServletName() + " urls=" + getUrlMappings(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\ServletRegistrationBean.java
1
请完成以下Java代码
public class ModificationDto { protected List<ProcessInstanceModificationInstructionDto> instructions; protected List<String> processInstanceIds; protected ProcessInstanceQueryDto processInstanceQuery; protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery; protected String processDefinitionId; protected boolean skipIoMappings; protected boolean skipCustomListeners; protected String annotation; public List<ProcessInstanceModificationInstructionDto> getInstructions() { return instructions; } public void setInstructions(List<ProcessInstanceModificationInstructionDto> instructions) { this.instructions = instructions; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public List<String> getProcessInstanceIds() { return processInstanceIds; } public void setProcessInstanceIds(List<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; } public ProcessInstanceQueryDto getProcessInstanceQuery() { return processInstanceQuery; } public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) { this.processInstanceQuery = processInstanceQuery; } public boolean isSkipIoMappings() { return skipIoMappings; } public void setSkipIoMappings(boolean skipIoMappings) { this.skipIoMappings = skipIoMappings; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public void setSkipCustomListeners(boolean skipCustomListeners) { this.skipCustomListeners = skipCustomListeners; }
public void applyTo(ModificationBuilder builder, ProcessEngine processEngine, ObjectMapper objectMapper) { for (ProcessInstanceModificationInstructionDto instruction : instructions) { instruction.applyTo(builder, processEngine, objectMapper); } } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { this.historicProcessInstanceQuery = historicProcessInstanceQuery; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\ModificationDto.java
1
请完成以下Java代码
public boolean isOnly() {return mode == Mode.ONLY;} @Override public boolean test(@Nullable final T value) { if (mode == Mode.ANY) { return true; } else if (mode == Mode.NONE) { return false; } else if (mode == Mode.ONLY) { return onlyValues.contains(value); } else { throw Check.mkEx("Unknown mode: " + this); // shall not happen } } private void assertNotAny() { if (isAny()) { throw Check.mkEx("Expected predicate to not be ANY"); } } public @NonNull Set<T> toSet() { assertNotAny(); return onlyValues; // we can return it as is because it's already readonly } @SafeVarargs public final InSetPredicate<T> intersectWith(@NonNull final T... onlyValues) { return intersectWith(only(onlyValues)); } public InSetPredicate<T> intersectWith(@NonNull final Set<T> onlyValues) { return intersectWith(only(onlyValues)); }
public InSetPredicate<T> intersectWith(@NonNull final InSetPredicate<T> other) { if (isNone() || other.isNone()) { return none(); } if (isAny()) { return other; } else if (other.isAny()) { return this; } return only(Sets.intersection(this.toSet(), other.toSet())); } public interface CaseConsumer<T> { void anyValue(); void noValue(); void onlyValues(Set<T> onlyValues); } public void apply(@NonNull final CaseConsumer<T> caseConsumer) { switch (mode) { case ANY: caseConsumer.anyValue(); break; case NONE: caseConsumer.noValue(); break; case ONLY: caseConsumer.onlyValues(onlyValues); break; default: throw new IllegalStateException("Unknown mode: " + mode); // shall not happen } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\InSetPredicate.java
1
请完成以下Java代码
public void onMsg(TbContext ctx, TbMsg msg) { EntityType originatorEntityType = msg.getOriginator().getEntityType(); if (!EntityType.DEVICE.equals(originatorEntityType)) { ctx.tellFailure(msg, new IllegalArgumentException( "Unsupported originator entity type: [" + originatorEntityType + "]. Only DEVICE entity type is supported." )); return; } DeviceId originator = new DeviceId(msg.getOriginator().getId()); rateLimits.compute(originator, (__, rateLimit) -> { if (rateLimit == null) { rateLimit = new TbRateLimits(rateLimitConfig); } boolean isNotRateLimited = rateLimit.tryConsume(); if (isNotRateLimited) { sendEventAndTell(ctx, originator, msg); } else { ctx.tellNext(msg, "Rate limited"); } return rateLimit; }); } private void sendEventAndTell(TbContext ctx, DeviceId originator, TbMsg msg) { TenantId tenantId = ctx.getTenantId(); long eventTs = msg.getMetaDataTs(); DeviceStateManager deviceStateManager = ctx.getDeviceStateManager(); TbCallback callback = getMsgEnqueuedCallback(ctx, msg); switch (event) { case CONNECT_EVENT: deviceStateManager.onDeviceConnect(tenantId, originator, eventTs, callback); break; case ACTIVITY_EVENT: deviceStateManager.onDeviceActivity(tenantId, originator, eventTs, callback); break; case DISCONNECT_EVENT: deviceStateManager.onDeviceDisconnect(tenantId, originator, eventTs, callback); break; case INACTIVITY_EVENT: deviceStateManager.onDeviceInactivity(tenantId, originator, eventTs, callback); break; default: ctx.tellFailure(msg, new IllegalStateException("Configured event [" + event + "] is not supported!")); } }
private TbCallback getMsgEnqueuedCallback(TbContext ctx, TbMsg msg) { return new TbCallback() { @Override public void onSuccess() { ctx.tellSuccess(msg); } @Override public void onFailure(Throwable t) { ctx.tellFailure(msg, t); } }; } @Override public void onPartitionChangeMsg(TbContext ctx, PartitionChangeMsg msg) { rateLimits.entrySet().removeIf(entry -> !ctx.isLocalEntity(entry.getKey())); } @Override public void destroy() { if (rateLimits != null) { rateLimits.clear(); rateLimits = null; } rateLimitConfig = null; event = null; } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\action\TbDeviceStateNode.java
1
请完成以下Java代码
public class GetTaskVariableCmdTyped implements Command<TypedValue>, Serializable { private static final long serialVersionUID = 1L; protected String taskId; protected String variableName; protected boolean isLocal; protected boolean deserializeValue; public GetTaskVariableCmdTyped(String taskId, String variableName, boolean isLocal, boolean deserializeValue) { this.taskId = taskId; this.variableName = variableName; this.isLocal = isLocal; this.deserializeValue = deserializeValue; } public TypedValue execute(CommandContext commandContext) { ensureNotNull("taskId", taskId); ensureNotNull("variableName", variableName); TaskEntity task = Context .getCommandContext() .getTaskManager() .findTaskById(taskId); ensureNotNull("task " + taskId + " doesn't exist", "task", task); checkGetTaskVariableTyped(task, commandContext); TypedValue value;
if (isLocal) { value = task.getVariableLocalTyped(variableName, deserializeValue); } else { value = task.getVariableTyped(variableName, deserializeValue); } return value; } protected void checkGetTaskVariableTyped(TaskEntity task, CommandContext commandContext) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkReadTaskVariable(task); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetTaskVariableCmdTyped.java
1
请完成以下Java代码
void play(String audioFilePath) { try { InputStream inputStream = getClass().getClassLoader() .getResourceAsStream(audioFilePath); AudioInputStream audioStream = AudioSystem.getAudioInputStream(inputStream); AudioFormat format = audioStream.getFormat(); DataLine.Info info = new DataLine.Info(Clip.class, format); Clip audioClip = (Clip) AudioSystem.getLine(info); audioClip.addLineListener(this); audioClip.open(audioStream); audioClip.start(); while (!isPlaybackCompleted) { try { Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } audioClip.close(); audioStream.close();
} catch (UnsupportedAudioFileException | LineUnavailableException | IOException ex) { System.out.println("Error occured during playback process:"+ ex.getMessage()); } } public static void main(String[] args) { String audioFilePath = "AudioFileWithWavFormat.wav"; // Clip can not play mpeg/mp3 format audio. We'll get exception if we run with below commented mp3 and mpeg format audio. // String audioFilePath = "AudioFileWithMpegFormat.mpeg"; // String audioFilePath = "AudioFileWithMp3Format.mp3"; SoundPlayerUsingClip player = new SoundPlayerUsingClip(); player.play(audioFilePath); } }
repos\tutorials-master\javax-sound\src\main\java\com\baeldung\SoundPlayerUsingClip.java
1
请完成以下Java代码
public class Notice extends BaseEntity { @Serial private static final long serialVersionUID = 1L; /** * 主键id */ @Schema(description = "主键") @TableId(value = "id", type = IdType.ASSIGN_ID) @JsonSerialize(using = ToStringSerializer.class) private Long id; /** * 标题 */ @Schema(description = "标题") private String title; /** * 通知类型 */ @Schema(description = "通知类型")
private Integer category; /** * 发布日期 */ @Schema(description = "发布日期") private Date releaseTime; /** * 内容 */ @Schema(description = "内容") private String content; }
repos\SpringBlade-master\blade-service-api\blade-demo-api\src\main\java\com\example\demo\entity\Notice.java
1
请完成以下Java代码
public static void main(String[] args) { SpringApplication.run(Application.class, args).close(); } /* * Boot will autowire this into the container factory. */ @Bean public CommonErrorHandler errorHandler(KafkaOperations<Object, Object> template) { return new DefaultErrorHandler( new DeadLetterPublishingRecoverer(template), new FixedBackOff(1000L, 2)); } @Bean public RecordMessageConverter converter() { return new JsonMessageConverter(); } @KafkaListener(id = "fooGroup", topics = "topic1") public void listen(Foo2 foo) { logger.info("Received: " + foo); if (foo.getFoo().startsWith("fail")) { throw new RuntimeException("failed"); } this.exec.execute(() -> System.out.println("Hit Enter to terminate...")); } @KafkaListener(id = "dltGroup", topics = "topic1-dlt") public void dltListen(byte[] in) {
logger.info("Received from DLT: " + new String(in)); this.exec.execute(() -> System.out.println("Hit Enter to terminate...")); } @Bean public NewTopic topic() { return new NewTopic("topic1", 1, (short) 1); } @Bean public NewTopic dlt() { return new NewTopic("topic1-dlt", 1, (short) 1); } @Bean @Profile("default") // Don't run from test(s) public ApplicationRunner runner() { return args -> { System.out.println("Hit Enter to terminate..."); System.in.read(); }; } }
repos\spring-kafka-main\samples\sample-01\src\main\java\com\example\Application.java
1
请完成以下Java代码
public class CompositeDeliveryDayHandler implements IDeliveryDayHandler { private final CopyOnWriteArrayList<IDeliveryDayHandler> handlers = new CopyOnWriteArrayList<>(); public final void addDeliveryDayHandler(final IDeliveryDayHandler handler) { Check.assumeNotNull(handler, "handler not null"); handlers.addIfAbsent(handler); } @Override public final void updateDeliveryDayAllocFromModel(final I_M_DeliveryDay_Alloc deliveryDayAlloc, final IDeliveryDayAllocable deliveryDayAllocable) { for (final IDeliveryDayHandler handler : handlers) { handler.updateDeliveryDayAllocFromModel(deliveryDayAlloc, deliveryDayAllocable); } } @Override public void updateDeliveryDayWhenAllocationChanged(I_M_DeliveryDay deliveryDay, I_M_DeliveryDay_Alloc deliveryDayAlloc, I_M_DeliveryDay_Alloc deliveryDayAllocOld) {
for (final IDeliveryDayHandler handler : handlers) { handler.updateDeliveryDayWhenAllocationChanged(deliveryDay, deliveryDayAlloc, deliveryDayAllocOld); } } @Override public void updateTourInstanceWhenDeliveryDayChanged(I_M_Tour_Instance tourInstance, I_M_DeliveryDay deliveryDay, I_M_DeliveryDay deliveryDayOld) { for (final IDeliveryDayHandler handler : handlers) { handler.updateTourInstanceWhenDeliveryDayChanged(tourInstance, deliveryDay, deliveryDayOld); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\spi\CompositeDeliveryDayHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class PhonecallSchedule { @NonNull PhonecallSchemaVersionLineId schemaVersionLineId; @Nullable PhonecallScheduleId id; @NonNull OrgId orgId; @NonNull BPartnerLocationId bpartnerAndLocationId; @NonNull UserId contactId; @NonNull LocalDate date; @NonNull ZonedDateTime startTime; @NonNull ZonedDateTime endTime;
boolean isOrdered; boolean isCalled; UserId salesRepId; @Nullable String description; public PhonecallSchemaId getPhonecallSchemaId() { return getSchemaVersionLineId().getVersionId().getPhonecallSchemaId(); } public PhonecallSchemaVersionId getPhonecallSchemaVersionId() { return getSchemaVersionLineId().getVersionId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\phonecall\PhonecallSchedule.java
2
请完成以下Java代码
public String getType() { return TYPE; } @Override public void execute(JobEntity job, String configuration, VariableScope variableScope, CommandContext commandContext) { PlanItemInstanceEntity planItemInstanceEntity = (PlanItemInstanceEntity) variableScope; VariableService variableService = cmmnEngineConfiguration.getVariableServiceConfiguration().getVariableService(); List<VariableInstanceEntity> jobVariables = variableService.findVariableInstanceBySubScopeIdAndScopeType(planItemInstanceEntity.getId(), ScopeTypes.CMMN_EXTERNAL_WORKER); if (!jobVariables.isEmpty()) { for (VariableInstanceEntity jobVariable : jobVariables) { planItemInstanceEntity.setVariable(jobVariable.getName(), jobVariable.getValue()); variableService.deleteVariableInstance(jobVariable); }
if (planItemInstanceEntity instanceof CountingPlanItemInstanceEntity) { ((CountingPlanItemInstanceEntity) planItemInstanceEntity) .setVariableCount(((CountingPlanItemInstanceEntity) planItemInstanceEntity).getVariableCount() - jobVariables.size()); } } if (configuration != null && configuration.startsWith("terminate:")) { //TODO maybe pass exitType and exitEventType CommandContextUtil.getAgenda(commandContext).planTerminatePlanItemInstanceOperation(planItemInstanceEntity, null, null); } else { CommandContextUtil.getAgenda(commandContext).planCompletePlanItemInstanceOperation(planItemInstanceEntity); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\job\ExternalWorkerTaskCompleteJobHandler.java
1
请完成以下Java代码
public int hashCode() { if (hashcode == 0) { hashcode = new HashcodeBuilder() .append(name) .toHashcode(); } return hashcode; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } final ResourceAsPermission other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(this.name, other.name)
.isEqual(); } @Override public Resource getResource() { return this; } @Override public boolean hasAccess(final Access access) { // TODO: return accesses.contains(access); throw new UnsupportedOperationException("Not implemented"); } @Override public Permission mergeWith(Permission accessFrom) { checkCompatibleAndCast(accessFrom); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\ResourceAsPermission.java
1
请完成以下Java代码
public I_I_Replenish retrieveImportRecord(final Properties ctx, final ResultSet rs) throws SQLException { return new X_I_Replenish(ctx, rs, ITrx.TRXNAME_ThreadInherited); } /* * @param isInsertOnly ignored. This import is only for updates. */ @Override protected ImportRecordResult importRecord( @NonNull final IMutable<Object> state_NOTUSED, @NonNull final I_I_Replenish importRecord, final boolean isInsertOnly_NOTUSED) { if (ReplenishImportHelper.isValidRecordForImport(importRecord)) { return importReplenish(importRecord); } else { throw new AdempiereException(MSG_NoValidRecord); } } private ImportRecordResult importReplenish(@NonNull final I_I_Replenish importRecord) { final ImportRecordResult replenishImportResult; final I_M_Replenish replenish; if (importRecord.getM_Replenish_ID() <= 0) {
replenish = ReplenishImportHelper.createNewReplenish(importRecord); replenishImportResult = ImportRecordResult.Inserted; } else { replenish = ReplenishImportHelper.uppdateReplenish(importRecord); replenishImportResult = ImportRecordResult.Updated; } InterfaceWrapperHelper.save(replenish); importRecord.setM_Replenish_ID(replenish.getM_Replenish_ID()); InterfaceWrapperHelper.save(importRecord); return replenishImportResult; } @Override protected void markImported(@NonNull final I_I_Replenish importRecord) { importRecord.setI_IsImported(X_I_Replenish.I_ISIMPORTED_Imported); importRecord.setProcessed(true); InterfaceWrapperHelper.save(importRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\replenishment\impexp\ReplenishmentImportProcess.java
1
请完成以下Java代码
public OAuth2TokenValidator<Jwt> build() { List.of(JoseHeaderNames.TYP, JwtClaimNames.EXP, JwtClaimNames.SUB, JwtClaimNames.IAT, JwtClaimNames.JTI, JwtClaimNames.ISS, JwtClaimNames.AUD, "client_id") .forEach((name) -> Assert.isTrue(this.validators.containsKey(name), name + " must be validated")); return new DelegatingOAuth2TokenValidator<>(this.validators.values()); } } private static final class RequireClaimValidator implements OAuth2TokenValidator<Jwt> { private final String claimName; RequireClaimValidator(String claimName) { this.claimName = claimName; } @Override public OAuth2TokenValidatorResult validate(Jwt token) { if (token.getClaim(this.claimName) == null) { return OAuth2TokenValidatorResult .failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, this.claimName + " must have a value", "https://datatracker.ietf.org/doc/html/rfc9068#name-data-structure")); } return OAuth2TokenValidatorResult.success(); }
OAuth2TokenValidator<Jwt> isEqualTo(String value) { return and(satisfies((jwt) -> value.equals(jwt.getClaim(this.claimName)))); } OAuth2TokenValidator<Jwt> satisfies(Predicate<Jwt> predicate) { return and((jwt) -> { OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, this.claimName + " is not valid", "https://datatracker.ietf.org/doc/html/rfc9068#name-data-structure"); if (predicate.test(jwt)) { return OAuth2TokenValidatorResult.success(); } return OAuth2TokenValidatorResult.failure(error); }); } OAuth2TokenValidator<Jwt> and(OAuth2TokenValidator<Jwt> that) { return (jwt) -> { OAuth2TokenValidatorResult result = validate(jwt); return (result.hasErrors()) ? result : that.validate(jwt); }; } } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtValidators.java
1
请完成以下Java代码
private static Map.Entry<BPartnerId, AvailabilityRequestItem> toVendorAndRequestItem(final Map.Entry<TrackingId, PurchaseCandidatesGroup> entry) { final TrackingId trackingId = entry.getKey(); final PurchaseCandidatesGroup purchaseCandidatesGroup = entry.getValue(); final BPartnerId vendorId = purchaseCandidatesGroup.getVendorId(); final AvailabilityRequestItem requestItem = createAvailabilityRequestItem(trackingId, purchaseCandidatesGroup); return GuavaCollectors.entry(vendorId, requestItem); } private static AvailabilityRequestItem createAvailabilityRequestItem(final TrackingId trackingId, final PurchaseCandidatesGroup purchaseCandidatesGroup) { final Quantity qtyToPurchase = purchaseCandidatesGroup.getQtyToPurchase(); final ProductAndQuantity productAndQuantity = ProductAndQuantity.of( purchaseCandidatesGroup.getVendorProductNo(), qtyToPurchase.toBigDecimal().max(ONE), // check availability for at least one, even if qtyToPurchase is still zero qtyToPurchase.getUOMId()); return AvailabilityRequestItem.builder() .trackingId(trackingId) .productAndQuantity(productAndQuantity) .purchaseCandidateId(PurchaseCandidateId.getRepoIdOr(purchaseCandidatesGroup.getSinglePurchaseCandidateIdOrNull(), -1)) .salesOrderLineId(OrderAndLineId.getOrderLineRepoIdOr(purchaseCandidatesGroup.getSingleSalesOrderAndLineIdOrNull(), -1)) .build();
} private static AvailabilityRequest createAvailabilityRequestOrNull(final BPartnerId vendorId, final Collection<AvailabilityRequestItem> requestItems) { if (requestItems.isEmpty()) { return null; } return AvailabilityRequest.builder() .vendorId(vendorId.getRepoId()) .availabilityRequestItems(requestItems) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\availability\AvailabilityCheckService.java
1
请完成以下Java代码
public String getSourceCaseDefinitionId() { return sourceCaseDefinitionId; } public void setSourceCaseDefinitionId(String sourceCaseDefinitionId) { this.sourceCaseDefinitionId = sourceCaseDefinitionId; } public String getTargetCaseDefinitionId() { return targetCaseDefinitionId; } public void setTargetCaseDefinitionId(String targetCaseDefinitionId) { this.targetCaseDefinitionId = targetCaseDefinitionId; }
public String getMigrationMessage() { return migrationMessage; } public void setMigrationMessage(String migrationMessage) { this.migrationMessage = migrationMessage; } public String getMigrationStacktrace() { return migrationStacktrace; } public void setMigrationStacktrace(String migrationStacktrace) { this.migrationStacktrace = migrationStacktrace; } }
repos\flowable-engine-main\modules\flowable-cmmn-api\src\main\java\org\flowable\cmmn\api\migration\CaseInstanceBatchMigrationPartResult.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Landscape. @param IsLandscape Landscape orientation */ public void setIsLandscape (boolean IsLandscape) { set_Value (COLUMNNAME_IsLandscape, Boolean.valueOf(IsLandscape)); } /** Get Landscape. @return Landscape orientation */ public boolean isLandscape () { Object oo = get_Value(COLUMNNAME_IsLandscape); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Label Height. @param LabelHeight Height of the label */ public void setLabelHeight (int LabelHeight) { set_Value (COLUMNNAME_LabelHeight, Integer.valueOf(LabelHeight)); } /** Get Label Height. @return Height of the label */ public int getLabelHeight () { Integer ii = (Integer)get_Value(COLUMNNAME_LabelHeight); if (ii == null) return 0; return ii.intValue(); } /** Set Label Width. @param LabelWidth Width of the Label */ public void setLabelWidth (int LabelWidth) { set_Value (COLUMNNAME_LabelWidth, Integer.valueOf(LabelWidth));
} /** Get Label Width. @return Width of the Label */ public int getLabelWidth () { Integer ii = (Integer)get_Value(COLUMNNAME_LabelWidth); if (ii == null) return 0; return ii.intValue(); } /** 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 Printer Name. @param PrinterName Name of the Printer */ public void setPrinterName (String PrinterName) { set_Value (COLUMNNAME_PrinterName, PrinterName); } /** Get Printer Name. @return Name of the Printer */ public String getPrinterName () { return (String)get_Value(COLUMNNAME_PrinterName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintLabel.java
1
请在Spring Boot框架中完成以下Java代码
public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } @CamundaQueryParam(value = "includeDeploymentsWithoutTenantId", converter = BooleanConverter.class) public void setIncludeDeploymentsWithoutTenantId(Boolean includeDeploymentsWithoutTenantId) { this.includeDeploymentsWithoutTenantId = includeDeploymentsWithoutTenantId; } @Override protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected DeploymentQuery createNewQuery(ProcessEngine engine) { return engine.getRepositoryService().createDeploymentQuery(); } @Override protected void applyFilters(DeploymentQuery query) { if (withoutSource != null && withoutSource && source != null) { throw new InvalidRequestException(Status.BAD_REQUEST, "The query parameters \"withoutSource\" and \"source\" cannot be used in combination."); } if (id != null) { query.deploymentId(id); } if (name != null) { query.deploymentName(name); } if (nameLike != null) { query.deploymentNameLike(nameLike); } if (TRUE.equals(withoutSource)) { query.deploymentSource(null); } if (source != null) { query.deploymentSource(source); } if (before != null) { query.deploymentBefore(before); } if (after != null) { query.deploymentAfter(after); }
if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (TRUE.equals(includeDeploymentsWithoutTenantId)) { query.includeDeploymentsWithoutTenantId(); } } @Override protected void applySortBy(DeploymentQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_ID_VALUE)) { query.orderByDeploymentId(); } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { query.orderByDeploymentName(); } else if (sortBy.equals(SORT_BY_DEPLOYMENT_TIME_VALUE)) { query.orderByDeploymentTime(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\DeploymentQueryDto.java
2
请完成以下Java代码
public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Product Operation. @param M_ProductOperation_ID Product Manufacturing Operation */ public void setM_ProductOperation_ID (int M_ProductOperation_ID) { if (M_ProductOperation_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ProductOperation_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ProductOperation_ID, Integer.valueOf(M_ProductOperation_ID)); } /** Get Product Operation. @return Product Manufacturing Operation */ public int getM_ProductOperation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductOperation_ID); if (ii == null) return 0; return ii.intValue(); } /** 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 Setup Time.
@param SetupTime Setup time before starting Production */ public void setSetupTime (BigDecimal SetupTime) { set_Value (COLUMNNAME_SetupTime, SetupTime); } /** Get Setup Time. @return Setup time before starting Production */ public BigDecimal getSetupTime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SetupTime); if (bd == null) return Env.ZERO; return bd; } /** Set Teardown Time. @param TeardownTime Time at the end of the operation */ public void setTeardownTime (BigDecimal TeardownTime) { set_Value (COLUMNNAME_TeardownTime, TeardownTime); } /** Get Teardown Time. @return Time at the end of the operation */ public BigDecimal getTeardownTime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TeardownTime); if (bd == null) return Env.ZERO; return bd; } /** Set Runtime per Unit. @param UnitRuntime Time to produce one unit */ public void setUnitRuntime (BigDecimal UnitRuntime) { set_Value (COLUMNNAME_UnitRuntime, UnitRuntime); } /** Get Runtime per Unit. @return Time to produce one unit */ public BigDecimal getUnitRuntime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_UnitRuntime); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ProductOperation.java
1
请完成以下Java代码
public BigDecimal getPriceLastPO () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceLastPO); if (bd == null) return Env.ZERO; return bd; } /** Set List Price. @param PriceList List Price */ public void setPriceList (BigDecimal PriceList) { set_Value (COLUMNNAME_PriceList, PriceList); } /** Get List Price. @return List Price */ public BigDecimal getPriceList () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceList); if (bd == null) return Env.ZERO; return bd; } /** Set PO Price. @param PricePO Price based on a purchase order */ public void setPricePO (BigDecimal PricePO) { set_Value (COLUMNNAME_PricePO, PricePO); } /** Get PO Price. @return Price based on a purchase order */ public BigDecimal getPricePO () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PricePO); if (bd == null) return Env.ZERO; return bd; } /** Set Quality Rating. @param QualityRating Method for rating vendors */ public void setQualityRating (int QualityRating) { set_Value (COLUMNNAME_QualityRating, Integer.valueOf(QualityRating)); } /** Get Quality Rating. @return Method for rating vendors */ public int getQualityRating () { Integer ii = (Integer)get_Value(COLUMNNAME_QualityRating); if (ii == null) return 0; return ii.intValue(); } /** Set Royalty Amount. @param RoyaltyAmt
(Included) Amount for copyright, etc. */ public void setRoyaltyAmt (BigDecimal RoyaltyAmt) { set_Value (COLUMNNAME_RoyaltyAmt, RoyaltyAmt); } /** Get Royalty Amount. @return (Included) Amount for copyright, etc. */ public BigDecimal getRoyaltyAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RoyaltyAmt); if (bd == null) return Env.ZERO; return bd; } /** 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); } /** Set Partner Category. @param VendorCategory Product Category of the Business Partner */ public void setVendorCategory (String VendorCategory) { set_Value (COLUMNNAME_VendorCategory, VendorCategory); } /** Get Partner Category. @return Product Category of the Business Partner */ public String getVendorCategory () { return (String)get_Value(COLUMNNAME_VendorCategory); } /** Set Partner Product Key. @param VendorProductNo Product Key of the Business Partner */ public void setVendorProductNo (String VendorProductNo) { set_Value (COLUMNNAME_VendorProductNo, VendorProductNo); } /** Get Partner Product Key. @return Product Key of the Business Partner */ public String getVendorProductNo () { return (String)get_Value(COLUMNNAME_VendorProductNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_PO.java
1
请完成以下Java代码
public UUID getId() { return id; } public OrderStatus getStatus() { return status; } public BigDecimal getPrice() { return price; } public List<OrderItem> getOrderItems() { return Collections.unmodifiableList(orderItems); } @Override public int hashCode() { return Objects.hash(id, orderItems, price, status);
} @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Order)) return false; Order other = (Order) obj; return Objects.equals(id, other.id) && Objects.equals(orderItems, other.orderItems) && Objects.equals(price, other.price) && status == other.status; } private Order() { } }
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\dddhexagonalspring\domain\Order.java
1
请完成以下Java代码
private List<DocLine_Inventory> loadLines(final I_M_Inventory inventory) { final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID()); return Services.get(IInventoryDAO.class) .retrieveLinesForInventoryId(inventoryId) .stream() .map(line -> new DocLine_Inventory(line, this)) .collect(ImmutableList.toImmutableList()); } @Override public BigDecimal getBalance() { return BigDecimal.ZERO; } /** * Create Facts (the accounting logic) for * MMI. * * <pre> * Inventory * Inventory DR CR * InventoryDiff DR CR (or Charge) * </pre> * * @param as account schema * @return Fact */ @Override public List<Fact> createFacts(final AcctSchema as) { setC_Currency_ID(as.getCurrencyId()); final Fact fact = new Fact(this, as, PostingType.Actual); getDocLines().forEach(line -> createFactsForInventoryLine(fact, line)); return ImmutableList.of(fact); } /** * <pre>
* Inventory * Inventory DR CR * InventoryDiff DR CR (or Charge) * </pre> */ private void createFactsForInventoryLine(final Fact fact, final DocLine_Inventory line) { final AcctSchema as = fact.getAcctSchema(); final CostAmount costs = line.getCreateCosts(as); // // Inventory DR/CR fact.createLine() .setDocLine(line) .setAccount(line.getAccount(ProductAcctType.P_Asset_Acct, as)) .setAmtSourceDrOrCr(costs.toMoney()) .setQty(line.getQty()) .locatorId(line.getM_Locator_ID()) .buildAndAdd(); // // Charge/InventoryDiff CR/DR final Account invDiff = line.getInvDifferencesAccount(as, costs.toBigDecimal().negate()); final FactLine cr = fact.createLine() .setDocLine(line) .setAccount(invDiff) .setAmtSourceDrOrCr(costs.toMoney().negate()) .setQty(line.getQty().negate()) .locatorId(line.getM_Locator_ID()) .buildAndAdd(); if (line.getC_Charge_ID().isPresent()) // explicit overwrite for charge { cr.setAD_Org_ID(line.getOrgId()); } } } // Doc_Inventory
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_Inventory.java
1
请完成以下Java代码
private static void run(String args[]) throws Exception { MessageDigest digest = MessageDigest.getInstance("SHA1"); digest.digest(new byte[256]); byte[] dummy = digest.digest(); int hashLen = dummy.length; long size = Long.parseLong(args[1]); MappedByteBuffer shm = createSharedMemory(args[0], size + hashLen); long addr = getBufferAddress(shm); System.out.printf("Buffer address: 0x%08x\n", addr); Random rnd = new Random(); long start = System.currentTimeMillis(); long iterations = 0; int capacity = shm.capacity(); System.out.println("Starting consumer iterations..."); long matchCount = 0; long mismatchCount = 0; byte[] expectedHash = new byte[hashLen]; SpinLock lock = new SpinLock(addr); while (System.currentTimeMillis() - start < 30_000) { if (!lock.tryLock(5_000)) { throw new RuntimeException("Unable to acquire lock"); } try { for (int i = 4; i < capacity - hashLen; i++) { byte value = shm.get(i); digest.update(value); } byte[] hash = digest.digest(); shm.position(capacity-hashLen); shm.get(expectedHash); if (Arrays.equals(hash, expectedHash)) { matchCount++; } else { mismatchCount++; } iterations++; } finally { lock.unlock(); } }
System.out.printf("%d iteractions run. matches=%d, mismatches=%d\n", iterations, matchCount, mismatchCount); } private static MappedByteBuffer createSharedMemory(String path, long size) { try (FileChannel fc = (FileChannel) Files.newByteChannel( new File(path).toPath(), EnumSet.of( StandardOpenOption.CREATE, StandardOpenOption.SPARSE, StandardOpenOption.WRITE, StandardOpenOption.READ))) { return fc.map(FileChannel.MapMode.READ_WRITE, 0, size); } catch (IOException ioe) { throw new RuntimeException(ioe); } } private static long getBufferAddress(MappedByteBuffer shm) { try { Class<?> cls = shm.getClass(); Method maddr = cls.getMethod("address"); maddr.setAccessible(true); Long addr = (Long) maddr.invoke(shm); if (addr == null) { throw new RuntimeException("Unable to retrieve buffer's address"); } return addr; } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { throw new RuntimeException(ex); } } }
repos\tutorials-master\core-java-modules\core-java-sun\src\main\java\com\baeldung\sharedmem\ConsumerAppWithSpinLock.java
1
请在Spring Boot框架中完成以下Java代码
public OAuth2TokenValidatorResult validate(Jwt jwt) { Collection<OAuth2Error> errors = new ArrayList<>(); LogoutTokenClaimAccessor logoutClaims = jwt::getClaims; Map<String, Object> events = logoutClaims.getEvents(); if (events == null) { errors.add(invalidLogoutToken("events claim must not be null")); } else if (events.get(BACK_CHANNEL_LOGOUT_EVENT) == null) { errors.add(invalidLogoutToken("events claim map must contain \"" + BACK_CHANNEL_LOGOUT_EVENT + "\" key")); } String issuer = logoutClaims.getIssuer().toExternalForm(); if (issuer == null) { errors.add(invalidLogoutToken("iss claim must not be null")); } else if (!this.issuer.equals(issuer)) { errors.add(invalidLogoutToken( "iss claim value must match `ClientRegistration#getProviderDetails#getIssuerUri`")); } List<String> audience = logoutClaims.getAudience(); if (audience == null) { errors.add(invalidLogoutToken("aud claim must not be null")); } else if (!audience.contains(this.audience)) { errors.add(invalidLogoutToken("aud claim value must include `ClientRegistration#getClientId`")); } Instant issuedAt = logoutClaims.getIssuedAt(); if (issuedAt == null) {
errors.add(invalidLogoutToken("iat claim must not be null")); } String jwtId = logoutClaims.getId(); if (jwtId == null) { errors.add(invalidLogoutToken("jti claim must not be null")); } if (logoutClaims.getSubject() == null && logoutClaims.getSessionId() == null) { errors.add(invalidLogoutToken("sub and sid claims must not both be null")); } if (logoutClaims.getClaim("nonce") != null) { errors.add(invalidLogoutToken("nonce claim must not be present")); } return OAuth2TokenValidatorResult.failure(errors); } private static OAuth2Error invalidLogoutToken(String description) { return new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, description, LOGOUT_VALIDATION_URL); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\client\OidcBackChannelLogoutTokenValidator.java
2
请完成以下Java代码
public class X_M_AttributeSet_IncludedTab extends org.compiere.model.PO implements I_M_AttributeSet_IncludedTab, org.compiere.model.I_Persistent { private static final long serialVersionUID = 777904131L; /** Standard Constructor */ public X_M_AttributeSet_IncludedTab (final Properties ctx, final int M_AttributeSet_IncludedTab_ID, @Nullable final String trxName) { super (ctx, M_AttributeSet_IncludedTab_ID, trxName); } /** Load Constructor */ public X_M_AttributeSet_IncludedTab (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public org.compiere.model.I_M_AttributeSet getM_AttributeSet() { return get_ValueAsPO(COLUMNNAME_M_AttributeSet_ID, org.compiere.model.I_M_AttributeSet.class); } @Override public void setM_AttributeSet(final org.compiere.model.I_M_AttributeSet M_AttributeSet) { set_ValueFromPO(COLUMNNAME_M_AttributeSet_ID, org.compiere.model.I_M_AttributeSet.class, M_AttributeSet); } @Override
public void setM_AttributeSet_ID (final int M_AttributeSet_ID) { if (M_AttributeSet_ID < 0) set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, M_AttributeSet_ID); } @Override public int getM_AttributeSet_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSet_ID); } @Override public void setM_AttributeSet_IncludedTab_ID (final int M_AttributeSet_IncludedTab_ID) { if (M_AttributeSet_IncludedTab_ID < 1) set_ValueNoCheck (COLUMNNAME_M_AttributeSet_IncludedTab_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSet_IncludedTab_ID, M_AttributeSet_IncludedTab_ID); } @Override public int getM_AttributeSet_IncludedTab_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSet_IncludedTab_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSet_IncludedTab.java
1
请完成以下Java代码
public String getRmtId() { return rmtId; } /** * Sets the value of the rmtId property. * * @param value * allowed object is * {@link String } * */ public void setRmtId(String value) { this.rmtId = value; } /** * Gets the value of the rmtLctnMtd property. * * @return * possible object is * {@link RemittanceLocationMethod2Code } * */ public RemittanceLocationMethod2Code getRmtLctnMtd() { return rmtLctnMtd; } /** * Sets the value of the rmtLctnMtd property. * * @param value * allowed object is * {@link RemittanceLocationMethod2Code } * */ public void setRmtLctnMtd(RemittanceLocationMethod2Code value) { this.rmtLctnMtd = value; } /** * Gets the value of the rmtLctnElctrncAdr property. * * @return * possible object is * {@link String } * */ public String getRmtLctnElctrncAdr() { return rmtLctnElctrncAdr; } /** * Sets the value of the rmtLctnElctrncAdr property. * * @param value
* allowed object is * {@link String } * */ public void setRmtLctnElctrncAdr(String value) { this.rmtLctnElctrncAdr = value; } /** * Gets the value of the rmtLctnPstlAdr property. * * @return * possible object is * {@link NameAndAddress10 } * */ public NameAndAddress10 getRmtLctnPstlAdr() { return rmtLctnPstlAdr; } /** * Sets the value of the rmtLctnPstlAdr property. * * @param value * allowed object is * {@link NameAndAddress10 } * */ public void setRmtLctnPstlAdr(NameAndAddress10 value) { this.rmtLctnPstlAdr = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\RemittanceLocation2.java
1
请完成以下Java代码
protected void makeDecisionsConsistentWithPersistedVersions(ParsedDeployment parsedDeployment) { for (DecisionEntity decision : parsedDeployment.getAllDecisions()) { DecisionEntity persistedDecision = dmnDeploymentHelper.getPersistedInstanceOfDecision(decision); if (persistedDecision != null) { decision.setId(persistedDecision.getId()); decision.setVersion(persistedDecision.getVersion()); } } } public IdGenerator getIdGenerator() { return idGenerator; } public void setIdGenerator(IdGenerator idGenerator) { this.idGenerator = idGenerator; } public ParsedDeploymentBuilderFactory getExParsedDeploymentBuilderFactory() { return parsedDeploymentBuilderFactory; } public void setParsedDeploymentBuilderFactory(ParsedDeploymentBuilderFactory parsedDeploymentBuilderFactory) { this.parsedDeploymentBuilderFactory = parsedDeploymentBuilderFactory; } public DmnDeploymentHelper getDmnDeploymentHelper() { return dmnDeploymentHelper; } public void setDmnDeploymentHelper(DmnDeploymentHelper dmnDeploymentHelper) {
this.dmnDeploymentHelper = dmnDeploymentHelper; } public CachingAndArtifactsManager getCachingAndArtifcatsManager() { return cachingAndArtifactsManager; } public void setCachingAndArtifactsManager(CachingAndArtifactsManager manager) { this.cachingAndArtifactsManager = manager; } public boolean isUsePrefixId() { return usePrefixId; } public void setUsePrefixId(boolean usePrefixId) { this.usePrefixId = usePrefixId; } public DecisionRequirementsDiagramHelper getDecisionRequirementsDiagramHelper() { return decisionRequirementsDiagramHelper; } public void setDecisionRequirementsDiagramHelper(DecisionRequirementsDiagramHelper decisionRequirementsDiagramHelper) { this.decisionRequirementsDiagramHelper = decisionRequirementsDiagramHelper; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\deployer\DmnDeployer.java
1
请完成以下Java代码
private void loadIfNeeded() { if (loaded) { return; } load(); loaded = true; } private void load() { // // Load the HU // NOTE: instead of getting the HU by using huStorage.getM_HU() we are loading it directly because the huStorage's transaction is already closed, // and our ModelCacheService will log a WARNING about this. // see ModelCacheService (line ~194): "No transaction was found for " + trxName + ". Skip cache." final int huId = huStorage.getM_HU_ID(); if (huId <= 0) { loaded = true; return; } final I_M_HU hu = InterfaceWrapperHelper.create(Env.getCtx(), huId, I_M_HU.class, ITrx.TRXNAME_ThreadInherited); if (hu == null) { return; } // Fire only for top-level HUs to minimize the number of events if (!Services.get(IHandlingUnitsBL.class).isTopLevel(hu)) { return; } final ShipmentScheduleSegmentFromHU huSegment = new ShipmentScheduleSegmentFromHU(hu); // If this HU does not contain QtyOnHand storages, there is no point to go forward // because actually nothing changed from QOH perspective if (!huSegment.hasQtyOnHandChanges()) { return; }
productIds = CollectionUtils.asSet(huStorage.getM_Product_ID()); bpartnerIds = huSegment.getBpartnerIds(); locatorIds = huSegment.getLocatorIds(); } @Override public Set<Integer> getProductIds() { loadIfNeeded(); return productIds; } @Override public Set<Integer> getBpartnerIds() { loadIfNeeded(); return bpartnerIds; } @Override public Set<Integer> getLocatorIds() { loadIfNeeded(); return locatorIds; } @Override public Set<Integer> getBillBPartnerIds() { return ImmutableSet.of(); } @Override public Set<ShipmentScheduleAttributeSegment> getAttributes() { return ImmutableSet.of(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\segments\ShipmentScheduleSegmentFromHUStorage.java
1
请完成以下Java代码
public static void main(String[] args) { SpringApplication.run(StartApplication.class, args); } @Autowired BookRepository bookRepository; @Bean public CommandLineRunner startup() { return args -> { Book b1 = new Book("Book A", BigDecimal.valueOf(9.99), LocalDate.of(2023, 8, 31)); Book b2 = new Book("Book B", BigDecimal.valueOf(19.99), LocalDate.of(2023, 7, 31)); Book b3 = new Book("Book C",
BigDecimal.valueOf(29.99), LocalDate.of(2023, 6, 10)); Book b4 = new Book("Book D", BigDecimal.valueOf(39.99), LocalDate.of(2023, 5, 5)); Book b5 = new Book("Book E", BigDecimal.valueOf(49.99), LocalDate.of(2023, 4, 1)); Book b6 = new Book("Book F", BigDecimal.valueOf(59.99), LocalDate.of(2023, 3, 1)); bookRepository.saveAll(List.of(b1, b2, b3, b4, b5, b6)); }; } }
repos\spring-boot-master\spring-data-jpa-paging-sorting\src\main\java\com\mkyong\StartApplication.java
1
请完成以下Java代码
private void weightHU(@NonNull final HuId huId, @NonNull final BigDecimal weightGross) { if (weightGross.signum() < 0) { throw new AdempiereException("Invalid weightGross: " + weightGross) .setParameter("huId", huId); } final I_M_HU hu = handlingUnitsBL.getById(huId); final IMutableHUContext huContext = handlingUnitsBL.createMutableHUContext(); final IAttributeStorage huAttributes = huContext.getHUAttributeStorageFactory().getAttributeStorage(hu); final PlainWeightable targetWeight = Weightables.plainOf(huAttributes); if (!targetWeight.isWeightable()) { throw new AdempiereException("HU is not targetWeight: " + handlingUnitsBL.getDisplayName(hu)) .setParameter("targetWeight", targetWeight); } targetWeight.setWeightGross(weightGross); Weightables.updateWeightNet(targetWeight); WeightHUCommand.builder() .huQtyService(huQtyService) // .huId(huId) .targetWeight(targetWeight) .build() // .execute(); } public PPOrderIssueSchedule changeSeqNo(@NonNull final PPOrderIssueSchedule issueSchedule, @NonNull final SeqNo newSeqNo) { if (SeqNo.equals(issueSchedule.getSeqNo(), newSeqNo)) { return issueSchedule;
} final PPOrderIssueSchedule issueScheduleChanged = issueSchedule.withSeqNo(newSeqNo); issueScheduleRepository.saveChanges(issueScheduleChanged); return issueScheduleChanged; } public void updateQtyToIssue( @NonNull final PPOrderIssueScheduleId issueScheduleId, @NonNull final Quantity qtyToIssue) { final PPOrderIssueSchedule issueSchedule = issueScheduleRepository.getById(issueScheduleId); if (issueSchedule.getQtyToIssue().equals(qtyToIssue)) { return; } final PPOrderIssueSchedule issueScheduleChanged = issueSchedule.withQtyToIssue(qtyToIssue); issueScheduleRepository.saveChanges(issueScheduleChanged); } public void delete(@NonNull final PPOrderIssueSchedule issueSchedule) { if (issueSchedule.isIssued()) { throw new AdempiereException("Deleting issued schedules is not allowed"); } issueScheduleRepository.deleteNotProcessedById(issueSchedule.getId()); } public boolean matchesByOrderId(@NonNull final PPOrderId ppOrderId) { return issueScheduleRepository.matchesByOrderId(ppOrderId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\issue_schedule\PPOrderIssueScheduleService.java
1
请完成以下Java代码
public class ManagerInfo extends Manager implements Serializable { private static final long serialVersionUID = 1L; /** * 状态 */ private String stateStr; /** * 所属项目id列表(逗号分隔) */ private String pids; /** * 所属项目名列表(逗号分隔) */ private String pnames; /** * 所属项目id列表 */ private List<Integer> pidsList; /** * 一个管理员具有多个角色 */ private List<SysRole> roles;// 一个用户具有多个角色 public ManagerInfo() { } public List<SysRole> getRoles() { return roles; } public void setRoles(List<SysRole> roles) { this.roles = roles; } /** * 密码盐 */ public String getCredentialsSalt() { return getUsername() + getSalt(); }
@Override public String toString() { return "username:" + getUsername() + "|name=" + getName(); } public String getStateStr() { return stateStr; } public void setStateStr(String stateStr) { this.stateStr = stateStr; } public String getPids() { return pids; } public void setPids(String pids) { this.pids = pids; } public List<Integer> getPidsList() { return pidsList; } public void setPidsList(List<Integer> pidsList) { this.pidsList = pidsList; } public String getPnames() { return pnames; } public void setPnames(String pnames) { this.pnames = pnames; } }
repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\model\ManagerInfo.java
1
请完成以下Java代码
public List<List<Object>> getCartesianProductRecursive(List<List<Object>> sets) { List<List<Object>> result = new ArrayList<>(); getCartesianProductRecursiveHelper(sets, 0, new ArrayList<>(), result); return result; } private void getCartesianProductRecursiveHelper(List<List<Object>> sets, int index, List<Object> current, List<List<Object>> result) { if(index == sets.size()) { result.add(new ArrayList<>(current)); return; } List<Object> currentSet = sets.get(index); for(Object element: currentSet) { current.add(element); getCartesianProductRecursiveHelper(sets, index+1, current, result); current.remove(current.size() - 1); } } public List<List<Object>> getCartesianProductUsingStreams(List<List<Object>> sets) { return cartesianProduct(sets,0).collect(Collectors.toList()); } public Stream<List<Object>> cartesianProduct(List<List<Object>> sets, int index) {
if(index == sets.size()) { List<Object> emptyList = new ArrayList<>(); return Stream.of(emptyList); } List<Object> currentSet = sets.get(index); return currentSet.stream().flatMap(element -> cartesianProduct(sets, index+1) .map(list -> { List<Object> newList = new ArrayList<>(list); newList.add(0, element); return newList; })); } public List<List<Object>> getCartesianProductUsingGuava(List<Set<Object>> sets) { Set<List<Object>> cartesianProduct = Sets.cartesianProduct(sets); List<List<Object>> cartesianList = new ArrayList<>(cartesianProduct); return cartesianList; } }
repos\tutorials-master\core-java-modules\core-java-collections-set-2\src\main\java\com\baeldung\cartesianproduct\CartesianProduct.java
1
请完成以下Java代码
public boolean isEmpty() { return this.session.getAttributeNames().isEmpty(); } @Override public boolean containsKey(Object key) { return key instanceof String && this.session.getAttributeNames().contains(key); } @Override public boolean containsValue(Object value) { return this.session.getAttributeNames() .stream() .anyMatch((attrName) -> this.session.getAttribute(attrName) != null); } @Override @Nullable public Object get(Object key) { if (key instanceof String) { return this.session.getAttribute((String) key); } return null; } @Override public Object put(String key, Object value) { Object original = this.session.getAttribute(key); this.session.setAttribute(key, value); return original; } @Override @Nullable public Object remove(Object key) { if (key instanceof String) { String attrName = (String) key; Object original = this.session.getAttribute(attrName); this.session.removeAttribute(attrName); return original; } return null; } @Override public void putAll(Map<? extends String, ?> m) { for (Entry<? extends String, ?> entry : m.entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public void clear() { for (String attrName : this.session.getAttributeNames()) { remove(attrName); } } @Override public Set<String> keySet() { return this.session.getAttributeNames(); } @Override public Collection<Object> values() { return this.values; } @Override public Set<Entry<String, Object>> entrySet() { Set<String> attrNames = keySet(); Set<Entry<String, Object>> entries = new HashSet<>(attrNames.size()); for (String attrName : attrNames) { Object value = this.session.getAttribute(attrName); entries.add(new AbstractMap.SimpleEntry<>(attrName, value)); } return Collections.unmodifiableSet(entries); } private class SessionValues extends AbstractCollection<Object> { @Override public Iterator<Object> iterator() { return new Iterator<Object>() { private Iterator<Entry<String, Object>> i = entrySet().iterator();
@Override public boolean hasNext() { return this.i.hasNext(); } @Override public Object next() { return this.i.next().getValue(); } @Override public void remove() { this.i.remove(); } }; } @Override public int size() { return SpringSessionMap.this.size(); } @Override public boolean isEmpty() { return SpringSessionMap.this.isEmpty(); } @Override public void clear() { SpringSessionMap.this.clear(); } @Override public boolean contains(Object v) { return SpringSessionMap.this.containsValue(v); } } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\server\session\SpringSessionWebSessionStore.java
1
请在Spring Boot框架中完成以下Java代码
public class ProcessDefinitionDecisionCollectionResource extends BaseProcessDefinitionResource { @ApiOperation(value = "List decisions for a process-definition", nickname = "listProcessDefinitionDecisions", tags = { "Process Definitions" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the process definition was found and the decisions are returned.", response = DecisionResponse.class, responseContainer = "List"), @ApiResponse(code = 404, message = "Indicates the requested process definition was not found.") }) @GetMapping(value = "/repository/process-definitions/{processDefinitionId}/decisions", produces = "application/json") public List<DecisionResponse> getDecisionsForProcessDefinition( @ApiParam(name = "processDefinitionId") @PathVariable String processDefinitionId) { ProcessDefinition processDefinition = getProcessDefinitionFromRequest(processDefinitionId); List<DmnDecision> decisions = repositoryService.getDecisionsForProcessDefinition(processDefinition.getId()); return restResponseFactory.createDecisionResponseList(decisions, processDefinitionId); } /**
* @deprecated */ @Deprecated @ApiOperation(value = "List decision tables for a process-definition", nickname = "listProcessDefinitionDecisionTables", tags = { "Process Definitions" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the process definition was found and the decision tables are returned.", response = DecisionResponse.class, responseContainer = "List"), @ApiResponse(code = 404, message = "Indicates the requested process definition was not found.") }) @GetMapping(value = "/repository/process-definitions/{processDefinitionId}/decision-tables", produces = "application/json") public List<DecisionResponse> getDecisionTablesForProcessDefinition( @ApiParam(name = "processDefinitionId") @PathVariable String processDefinitionId) { return getDecisionsForProcessDefinition(processDefinitionId); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ProcessDefinitionDecisionCollectionResource.java
2
请完成以下Java代码
public class CamundaVariableOnPartImpl extends CmmnModelElementInstanceImpl implements CamundaVariableOnPart { protected static Attribute<String> camundaVariableNameAttribute; protected static ChildElement<CamundaVariableTransitionEvent> camundaVariableEventChild; public CamundaVariableOnPartImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CamundaVariableOnPart.class, CAMUNDA_ELEMENT_VARIABLE_ON_PART) .namespaceUri(CAMUNDA_NS) .instanceProvider(new ModelTypeInstanceProvider<CamundaVariableOnPart>() { public CamundaVariableOnPart newInstance(ModelTypeInstanceContext instanceContext) { return new CamundaVariableOnPartImpl(instanceContext); } }); camundaVariableNameAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_VARIABLE_NAME) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); camundaVariableEventChild = sequenceBuilder.element(CamundaVariableTransitionEvent.class) .build(); typeBuilder.build(); } public String getVariableName() { return camundaVariableNameAttribute.getValue(this); }
public void setVariableName(String name) { camundaVariableNameAttribute.setValue(this, name); } public VariableTransition getVariableEvent() { CamundaVariableTransitionEvent child = camundaVariableEventChild.getChild(this); return child.getValue(); } public void setVariableEvent(VariableTransition variableTransition) { CamundaVariableTransitionEvent child = camundaVariableEventChild.getChild(this); child.setValue(variableTransition); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\camunda\CamundaVariableOnPartImpl.java
1
请完成以下Java代码
private AvailableForSalesConfig retrieveConfigRecord(@NonNull final ConfigQuery query) { final I_MD_AvailableForSales_Config configRecord = Services.get(IQueryBL.class) .createQueryBuilder(I_MD_AvailableForSales_Config.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_MD_AvailableForSales_Config.COLUMNNAME_AD_Client_ID, query.getClientId()) .addInArrayFilter(I_MD_AvailableForSales_Config.COLUMNNAME_AD_Org_ID, query.getOrgId(), OrgId.ANY) .orderByDescending(I_MD_AvailableForSales_Config.COLUMNNAME_AD_Org_ID) .create() .first(); return ofRecord(configRecord); } @NonNull private AvailableForSalesConfig ofRecord(@Nullable final I_MD_AvailableForSales_Config configRecord) { if (configRecord == null) { return AvailableForSalesConfig .builder() .featureEnabled(false) .insufficientQtyAvailableForSalesColorId(null) .salesOrderLookBehindHours(0) .shipmentDateLookAheadHours(0) .build();
} return AvailableForSalesConfig .builder() .featureEnabled(configRecord.isFeatureActivated()) .insufficientQtyAvailableForSalesColorId(ColorId.ofRepoId(configRecord.getInsufficientQtyAvailableForSalesColor_ID())) .salesOrderLookBehindHours(configRecord.getSalesOrderLookBehindHours()) .shipmentDateLookAheadHours(configRecord.getShipmentDateLookAheadHours()) .runAsync(configRecord.isAsync()) .asyncTimeoutMillis(configRecord.getAsyncTimeoutMillis()) .qtyPerWarehouse(configRecord.isQtyPerWarehouse()) .build(); } @Value @Builder public static class ConfigQuery { ClientId clientId; OrgId orgId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\AvailableForSalesConfigRepo.java
1
请在Spring Boot框架中完成以下Java代码
public String getScopeId() { return scopeId; } public String getScopeDefinitionId() { return scopeDefinitionId; } public String getSubScopeId() { return subScopeId; } public String getScopeType() { return scopeType; } public Date getFromDate() { return fromDate; } public Date getToDate() { return toDate; } public String getTenantId() { return tenantId; } public long getFromLogNumber() { return fromLogNumber; }
public long getToLogNumber() { return toLogNumber; } @Override public long executeCount(CommandContext commandContext) { return taskServiceConfiguration.getHistoricTaskLogEntryEntityManager().findHistoricTaskLogEntriesCountByQueryCriteria(this); } @Override public List<HistoricTaskLogEntry> executeList(CommandContext commandContext) { return taskServiceConfiguration.getHistoricTaskLogEntryEntityManager().findHistoricTaskLogEntriesByQueryCriteria(this); } @Override public HistoricTaskLogEntryQuery orderByLogNumber() { orderBy(HistoricTaskLogEntryQueryProperty.LOG_NUMBER); return this; } @Override public HistoricTaskLogEntryQuery orderByTimeStamp() { orderBy(HistoricTaskLogEntryQueryProperty.TIME_STAMP); return this; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\HistoricTaskLogEntryQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName;
} public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\repositoryvsdaopattern\User.java
2
请完成以下Java代码
public int getMSV3_BestellungAntwort_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungAntwort_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Id. @param MSV3_Id Id */ @Override public void setMSV3_Id (java.lang.String MSV3_Id) { set_Value (COLUMNNAME_MSV3_Id, MSV3_Id); } /** Get Id. @return Id */ @Override public java.lang.String getMSV3_Id () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Id); } /** Set NachtBetrieb. @param MSV3_NachtBetrieb NachtBetrieb */ @Override public void setMSV3_NachtBetrieb (boolean MSV3_NachtBetrieb)
{ set_Value (COLUMNNAME_MSV3_NachtBetrieb, Boolean.valueOf(MSV3_NachtBetrieb)); } /** Get NachtBetrieb. @return NachtBetrieb */ @Override public boolean isMSV3_NachtBetrieb () { Object oo = get_Value(COLUMNNAME_MSV3_NachtBetrieb); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_BestellungAntwort.java
1
请完成以下Java代码
public List<I_M_MatchPO> getByInvoiceId(@NonNull final InvoiceId invoiceId) { final String sql = "SELECT * FROM M_MatchPO mi" + " INNER JOIN C_InvoiceLine il ON (mi.C_InvoiceLine_ID=il.C_InvoiceLine_ID) " + "WHERE il.C_Invoice_ID=?"; final List<Object> sqlParams = Arrays.asList(invoiceId); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_ThreadInherited); DB.setParameters(pstmt, sqlParams); rs = pstmt.executeQuery(); final List<I_M_MatchPO> result = new ArrayList<>(); while (rs.next()) { result.add(new MMatchPO(Env.getCtx(), rs, ITrx.TRXNAME_ThreadInherited)); } return result; } catch (final Exception e) { throw new DBException(e, sql, sqlParams); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } }
@Override public List<I_M_MatchPO> getByOrderLineId(final OrderLineId orderLineId) { if (orderLineId == null) { return ImmutableList.of(); } return Services.get(IQueryBL.class) .createQueryBuilder(I_M_MatchPO.class) .addEqualsFilter(I_M_MatchPO.COLUMN_C_OrderLine_ID, orderLineId) .orderBy(I_M_MatchPO.COLUMN_C_OrderLine_ID) .create() .listImmutable(I_M_MatchPO.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\MatchPODAO.java
1
请在Spring Boot框架中完成以下Java代码
public class DAMOU1 { @XmlElement(name = "DOCUMENTID", required = true) protected String documentid; @XmlElement(name = "LINENUMBER", required = true) protected String linenumber; @XmlElement(name = "AMOUNTQUAL", required = true) protected String amountqual; @XmlElement(name = "AMOUNT") protected String amount; @XmlElement(name = "CURRENCY") protected String currency; /** * Gets the value of the documentid property. * * @return * possible object is * {@link String } * */ public String getDOCUMENTID() { return documentid; } /** * Sets the value of the documentid property. * * @param value * allowed object is * {@link String } * */ public void setDOCUMENTID(String value) { this.documentid = value; } /** * Gets the value of the linenumber property. * * @return * possible object is * {@link String } * */ public String getLINENUMBER() { return linenumber; } /** * Sets the value of the linenumber property. * * @param value * allowed object is * {@link String } * */ public void setLINENUMBER(String value) { this.linenumber = value; } /** * Gets the value of the amountqual property. * * @return * possible object is * {@link String } * */ public String getAMOUNTQUAL() { return amountqual; } /** * Sets the value of the amountqual property. * * @param value * allowed object is * {@link String } * */ public void setAMOUNTQUAL(String value) { this.amountqual = value; } /**
* Gets the value of the amount property. * * @return * possible object is * {@link String } * */ public String getAMOUNT() { return amount; } /** * Sets the value of the amount property. * * @param value * allowed object is * {@link String } * */ public void setAMOUNT(String value) { this.amount = value; } /** * Gets the value of the currency property. * * @return * possible object is * {@link String } * */ public String getCURRENCY() { return currency; } /** * Sets the value of the currency property. * * @param value * allowed object is * {@link String } * */ public void setCURRENCY(String value) { this.currency = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DAMOU1.java
2
请在Spring Boot框架中完成以下Java代码
public class SpringbootRedisApplication { private static final Logger LOGGER = LoggerFactory.getLogger(SpringbootRedisApplication.class); @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.addMessageListener(listenerAdapter, new PatternTopic("chat")); return container; } @Bean MessageListenerAdapter listenerAdapter(Receiver receiver) { return new MessageListenerAdapter(receiver, "receiveMessage"); } @Bean Receiver receiver(CountDownLatch latch) { return new Receiver(latch); } @Bean CountDownLatch latch() { return new CountDownLatch(1); } @Bean StringRedisTemplate template(RedisConnectionFactory connectionFactory) { return new StringRedisTemplate(connectionFactory); } public static void main(String[] args) throws Exception{ ApplicationContext ctx = SpringApplication.run(SpringbootRedisApplication.class, args);
StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class); CountDownLatch latch = ctx.getBean(CountDownLatch.class); LOGGER.info("Sending message..."); template.convertAndSend("chat", "Hello from Redis!"); latch.await(); System.exit(0); } /** * 2017-04-20 17:25:15.536 INFO 39148 --- [ main] com.forezp.SpringbootRedisApplication : Sending message... * 2017-04-20 17:25:15.544 INFO 39148 --- [ container-2] com.forezp.message.Receiver : Received <Hello from Redis!> */ }
repos\SpringBootLearning-master\springboot-redis-message\src\main\java\com\forezp\SpringbootRedisApplication.java
2
请完成以下Java代码
public boolean isDetached() { return externalTask.getExecutionId() == null; } @Override public void detachState() { externalTask.getExecution().removeExternalTask(externalTask); externalTask.setExecution(null); } @Override public void attachState(MigratingScopeInstance owningInstance) { ExecutionEntity representativeExecution = owningInstance.resolveRepresentativeExecution(); representativeExecution.addExternalTask(externalTask); externalTask.setExecution(representativeExecution); } @Override public void attachState(MigratingTransitionInstance targetTransitionInstance) { throw MIGRATION_LOGGER.cannotAttachToTransitionInstance(this); } @Override public void migrateState() { ScopeImpl targetActivity = migratingActivityInstance.getTargetScope(); ProcessDefinition targetProcessDefinition = (ProcessDefinition) targetActivity.getProcessDefinition();
externalTask.setActivityId(targetActivity.getId()); externalTask.setProcessDefinitionId(targetProcessDefinition.getId()); externalTask.setProcessDefinitionKey(targetProcessDefinition.getKey()); } public String getId() { return externalTask.getId(); } public ScopeImpl getTargetScope() { return migratingActivityInstance.getTargetScope(); } public void addMigratingDependentInstance(MigratingInstance migratingInstance) { dependentInstances.add(migratingInstance); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingExternalTaskInstance.java
1
请完成以下Java代码
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (!response.containsHeader(REFERRER_POLICY_HEADER)) { response.setHeader(REFERRER_POLICY_HEADER, this.policy.getPolicy()); } } public enum ReferrerPolicy { NO_REFERRER("no-referrer"), NO_REFERRER_WHEN_DOWNGRADE("no-referrer-when-downgrade"), SAME_ORIGIN("same-origin"), ORIGIN("origin"), STRICT_ORIGIN("strict-origin"), ORIGIN_WHEN_CROSS_ORIGIN("origin-when-cross-origin"), STRICT_ORIGIN_WHEN_CROSS_ORIGIN("strict-origin-when-cross-origin"), UNSAFE_URL("unsafe-url"); private static final Map<String, ReferrerPolicy> REFERRER_POLICIES;
static { Map<String, ReferrerPolicy> referrerPolicies = new HashMap<>(); for (ReferrerPolicy referrerPolicy : values()) { referrerPolicies.put(referrerPolicy.getPolicy(), referrerPolicy); } REFERRER_POLICIES = Collections.unmodifiableMap(referrerPolicies); } private final String policy; ReferrerPolicy(String policy) { this.policy = policy; } public String getPolicy() { return this.policy; } public static @Nullable ReferrerPolicy get(String referrerPolicy) { return REFERRER_POLICIES.get(referrerPolicy); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\ReferrerPolicyHeaderWriter.java
1
请完成以下Java代码
public void initialize() { this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new BasicThreadFactory.Builder().namingPattern(threadName).build()); this.changeDetectionRunnable = createChangeDetectionRunnable(); this.scheduledExecutorService.scheduleAtFixedRate(this.changeDetectionRunnable, initialDelayInMs, delayInMs, TimeUnit.MILLISECONDS); } @Override public void shutdown() { if (scheduledExecutorService != null) { scheduledExecutorService.shutdown(); } } protected Runnable createChangeDetectionRunnable() { return new EventRegistryChangeDetectionRunnable(eventRegistryChangeDetectionManager); } public ScheduledExecutorService getScheduledExecutorService() { return scheduledExecutorService; } public void setScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) { this.scheduledExecutorService = scheduledExecutorService;
} public String getThreadName() { return threadName; } public void setThreadName(String threadName) { this.threadName = threadName; } public Runnable getChangeDetectionRunnable() { return changeDetectionRunnable; } public void setChangeDetectionRunnable(Runnable changeDetectionRunnable) { this.changeDetectionRunnable = changeDetectionRunnable; } public EventRegistryChangeDetectionManager getEventRegistryChangeDetectionManager() { return eventRegistryChangeDetectionManager; } @Override public void setEventRegistryChangeDetectionManager(EventRegistryChangeDetectionManager eventRegistryChangeDetectionManager) { this.eventRegistryChangeDetectionManager = eventRegistryChangeDetectionManager; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\management\DefaultEventRegistryChangeDetectionExecutor.java
1
请完成以下Java代码
public String getId() { // membership doesn't have an id, returning a fake one to make the internals work return userId + groupId; } @Override public void setId(String id) { // membership doesn't have an id } @Override public String getUserId() { return userId; } @Override
public void setUserId(String userId) { this.userId = userId; } @Override public String getGroupId() { return groupId; } @Override public void setGroupId(String groupId) { this.groupId = groupId; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\MembershipEntityImpl.java
1
请完成以下Java代码
public AuthorizationQuery resourceType(int resourceType) { this.resourceType = resourceType; queryByResourceType = true; return this; } public AuthorizationQuery resourceId(String resourceId) { this.resourceId = resourceId; return this; } public AuthorizationQuery hasPermission(Permission p) { queryByPermission = true; if (resourcesIntersection.size() == 0) { resourcesIntersection.addAll(Arrays.asList(p.getTypes())); } else { resourcesIntersection.retainAll(new HashSet<Resource>(Arrays.asList(p.getTypes()))); } this.permission |= p.getValue(); return this; } public AuthorizationQuery authorizationType(Integer type) { this.authorizationType = type; return this; } public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext.getAuthorizationManager() .selectAuthorizationCountByQueryCriteria(this); } public List<Authorization> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext.getAuthorizationManager() .selectAuthorizationByQueryCriteria(this); } @Override protected boolean hasExcludingConditions() { return super.hasExcludingConditions() || containsIncompatiblePermissions() || containsIncompatibleResourceType(); } /** * check whether there are any compatible resources * for all of the filtered permission parameters */ private boolean containsIncompatiblePermissions() { return queryByPermission && resourcesIntersection.isEmpty(); } /** * check whether the permissions' resources * are compatible to the filtered resource parameter */ private boolean containsIncompatibleResourceType() { if (queryByResourceType && queryByPermission) { Resource[] resources = resourcesIntersection.toArray(new Resource[resourcesIntersection.size()]); return !ResourceTypeUtil.resourceIsContainedInArray(resourceType, resources); } return false; } // getters //////////////////////////// public String getId() { return id;
} public boolean isQueryByPermission() { return queryByPermission; } public String[] getUserIds() { return userIds; } public String[] getGroupIds() { return groupIds; } public int getResourceType() { return resourceType; } public String getResourceId() { return resourceId; } public int getPermission() { return permission; } public boolean isQueryByResourceType() { return queryByResourceType; } public Set<Resource> getResourcesIntersection() { return resourcesIntersection; } public AuthorizationQuery orderByResourceType() { orderBy(AuthorizationQueryProperty.RESOURCE_TYPE); return this; } public AuthorizationQuery orderByResourceId() { orderBy(AuthorizationQueryProperty.RESOURCE_ID); return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\AuthorizationQueryImpl.java
1
请完成以下Java代码
public VariableType getResult(ResultSet rs, String columnName) throws SQLException { String typeName = rs.getString(columnName); VariableType type = getVariableTypes().getVariableType(typeName); if (type == null && typeName != null) { throw new ActivitiException("unknown variable type name " + typeName); } return type; } public VariableType getResult(CallableStatement cs, int columnIndex) throws SQLException { String typeName = cs.getString(columnIndex); VariableType type = getVariableTypes().getVariableType(typeName); if (type == null) { throw new ActivitiException("unknown variable type name " + typeName); } return type; } public void setParameter(PreparedStatement ps, int i, VariableType parameter, JdbcType jdbcType) throws SQLException { String typeName = parameter.getTypeName(); ps.setString(i, typeName); } protected VariableTypes getVariableTypes() {
if (variableTypes == null) { variableTypes = Context.getProcessEngineConfiguration().getVariableTypes(); } return variableTypes; } public VariableType getResult(ResultSet resultSet, int columnIndex) throws SQLException { String typeName = resultSet.getString(columnIndex); VariableType type = getVariableTypes().getVariableType(typeName); if (type == null) { throw new ActivitiException("unknown variable type name " + typeName); } return type; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\IbatisVariableTypeHandler.java
1
请完成以下Java代码
private void audit(final OPERATION operation) { setOperation(operation); setTimestamp((new Date()).getTime()); } public enum OPERATION { INSERT, UPDATE, DELETE; private String value; OPERATION() { value = toString(); } public static OPERATION parse(final String value) { OPERATION operation = null;
for (final OPERATION op : OPERATION.values()) { if (op.getValue().equals(value)) { operation = op; break; } } return operation; } public String getValue() { return value; } } }
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\domain\Bar.java
1
请完成以下Java代码
public void adjustPage() { if (totalCount <= 0) { totalCount = 0; } if (pageSize <= 0) { pageSize = DEF_COUNT; } if (pageNo <= 0) { pageNo = 1; } if ((pageNo - 1) * pageSize >= totalCount) { pageNo = totalCount / pageSize; } } public int getPageNo() { return pageNo; } public int getPageSize() { return pageSize; } public int getTotalCount() { return totalCount; } public int getTotalPage() { int totalPage = totalCount / pageSize; if (totalCount % pageSize != 0 || totalPage == 0) { totalPage++; } return totalPage; } public boolean isFirstPage() { return pageNo <= 1; } public boolean isLastPage() { return pageNo >= getTotalPage(); } public int getNextPage() { if (isLastPage()) { return pageNo; } else { return pageNo + 1; } } public int getPrePage() { if (isFirstPage()) { return pageNo; } else { return pageNo - 1; } } protected int totalCount = 0;
protected int pageSize = 20; protected int pageNo = 1; public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } protected int filterNo; public int getFilterNo() { return filterNo; } public void setFilterNo(int filterNo) { this.filterNo = filterNo; } }
repos\springboot-demo-master\elasticsearch\src\main\java\demo\et59\elaticsearch\page\SimplePage.java
1
请在Spring Boot框架中完成以下Java代码
private ImmutableList<PickingJob> executeInTrx() { final ImmutableList.Builder<PickingJob> result = ImmutableList.builder(); for (final PickingJob initialPickingJob : initialPickingJobs) { final PickingJob pickingJob = execute(initialPickingJob); result.add(pickingJob); } return result.build(); } private PickingJob execute(@NonNull final PickingJob initialPickingJob) { //noinspection OptionalGetWithoutIsPresent return Stream.of(initialPickingJob) .sequential() .map(this::releasePickingSlotAndSave) // NOTE: abort is not "reversing", so we don't have to reverse (unpick) what we picked. // Even more, imagine that those picked things are already phisically splitted out. //.map(this::unpickAllStepsAndSave) .peek(huService::releaseAllReservations) .peek(pickingJobLockService::unlockSchedules) .map(this::markAsVoidedAndSave) .findFirst() .get(); } 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 void setEmployeeNumber(String no) { ((InetOrgPerson) this.instance).employeeNumber = no; } public void setDestinationIndicator(String destination) { ((InetOrgPerson) this.instance).destinationIndicator = destination; } public void setHomePhone(String homePhone) { ((InetOrgPerson) this.instance).homePhone = homePhone; } public void setStreet(String street) { ((InetOrgPerson) this.instance).street = street; } public void setPostalCode(String postalCode) {
((InetOrgPerson) this.instance).postalCode = postalCode; } public void setPostalAddress(String postalAddress) { ((InetOrgPerson) this.instance).postalAddress = postalAddress; } public void setMobile(String mobile) { ((InetOrgPerson) this.instance).mobile = mobile; } public void setHomePostalAddress(String homePostalAddress) { ((InetOrgPerson) this.instance).homePostalAddress = homePostalAddress; } } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\InetOrgPerson.java
1
请完成以下Java代码
public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQtyDeliveredInInvoiceUOM (final @Nullable BigDecimal QtyDeliveredInInvoiceUOM) { set_Value (COLUMNNAME_QtyDeliveredInInvoiceUOM, QtyDeliveredInInvoiceUOM); } @Override public BigDecimal getQtyDeliveredInInvoiceUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInInvoiceUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyDeliveredInStockingUOM (final BigDecimal QtyDeliveredInStockingUOM) { set_Value (COLUMNNAME_QtyDeliveredInStockingUOM, QtyDeliveredInStockingUOM); } @Override public BigDecimal getQtyDeliveredInStockingUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInStockingUOM); return bd != null ? bd : BigDecimal.ZERO; }
@Override public void setQtyDeliveredInUOM (final BigDecimal QtyDeliveredInUOM) { set_Value (COLUMNNAME_QtyDeliveredInUOM, QtyDeliveredInUOM); } @Override public BigDecimal getQtyDeliveredInUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyEnteredInBPartnerUOM (final @Nullable BigDecimal QtyEnteredInBPartnerUOM) { set_Value (COLUMNNAME_QtyEnteredInBPartnerUOM, QtyEnteredInBPartnerUOM); } @Override public BigDecimal getQtyEnteredInBPartnerUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEnteredInBPartnerUOM); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_DesadvLine_InOutLine.java
1
请完成以下Java代码
public HUConsolidationJob closeTarget(@NonNull final HUConsolidationJobId jobId, @NonNull final UserId callerId) { return jobRepository.updateById(jobId, job -> { job.assertUserCanEdit(callerId); return targetCloser.closeTarget(job); }); } public void printTargetLabel(@NonNull final HUConsolidationJobId jobId, @NotNull final UserId callerId) { final HUConsolidationJob job = jobRepository.getById(jobId); final HUConsolidationTarget currentTarget = job.getCurrentTargetNotNull(); labelPrinter.printLabel(currentTarget); } public HUConsolidationJob consolidate(@NonNull final ConsolidateRequest request) { return ConsolidateCommand.builder() .jobRepository(jobRepository) .huQRCodesService(huQRCodesService)
.pickingSlotService(pickingSlotService) .request(request) .build() .execute(); } public JsonHUConsolidationJobPickingSlotContent getPickingSlotContent(final HUConsolidationJobId jobId, final PickingSlotId pickingSlotId) { return GetPickingSlotContentCommand.builder() .jobRepository(jobRepository) .huQRCodesService(huQRCodesService) .pickingSlotService(pickingSlotService) .jobId(jobId) .pickingSlotId(pickingSlotId) .build() .execute(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\HUConsolidationJobService.java
1
请完成以下Java代码
private Map<BPartnerLocationId, BPartnerLocationId> getBPartnerLocationIdMap(final int bpartnerId) { final Map<BPartnerLocationId, GLN> oldLocationToGlnMap = getOldLocationIdToGlnMap(); final Map<GLN, BPartnerLocationId> glnToNewLocationMap = getGlnToNewLocationMap(bpartnerId); oldLocationToGlnMap.forEach((oldLocation, gln) -> { if (!glnToNewLocationMap.containsKey(gln)) { throw new AdempiereException(NO_LOCATION_FOR_GLN, gln); } }); return oldLocationToGlnMap.keySet() .stream() .collect(ImmutableMap.toImmutableMap(oldLocation -> oldLocation, oldLocation -> glnToNewLocationMap.get(oldLocationToGlnMap.get(oldLocation)))); } @NonNull private Map<GLN, BPartnerLocationId> getGlnToNewLocationMap(final int bpartnerId) { return bPartnerDAO.retrieveBPartnerLocations(BPartnerId.ofRepoId(bpartnerId)) .stream() .filter(loc -> !Check.isBlank(loc.getGLN())) .collect(Collectors.toMap(param -> GLN.ofString(param.getGLN()), param -> BPartnerLocationId.ofRepoId(param.getC_BPartner_ID(), param.getC_BPartner_Location_ID()))); } @NonNull private Map<BPartnerLocationId, GLN> getOldLocationIdToGlnMap() { final Map<BPartnerLocationId, GLN> oldLocationToGlnMap = createQueryBuilder() .andCollect(I_C_OLCand.COLUMNNAME_C_BPartner_Location_ID, I_C_BPartner_Location.class) .addOnlyActiveRecordsFilter() .create() .stream() .filter(Objects::nonNull) .filter(loc -> !Check.isBlank(loc.getGLN())) .collect(Collectors.toMap(param -> BPartnerLocationId.ofRepoId(param.getC_BPartner_ID(), param.getC_BPartner_Location_ID()), param -> GLN.ofString(param.getGLN()))); if (oldLocationToGlnMap.size() == 0) { throw new AdempiereException(NO_GLNS); } return oldLocationToGlnMap; } @Override protected String doIt() throws Exception
{ final OLCandUpdateResult result = olCandUpdateBL.updateOLCands(getCtx(), createIterator(), params); return "@Success@: " + result.getUpdated() + " @Processed@, " + result.getSkipped() + " @Skipped@"; } private Iterator<I_C_OLCand> createIterator() { return createQueryBuilder() .create() .setRequiredAccess(Access.READ) // 04471: enqueue only those records on which user has access to .iterate(I_C_OLCand.class); } private IQueryBuilder<I_C_OLCand> createQueryBuilder() { final IQueryFilter<I_C_OLCand> queryFilter = getQueryFilter(); final IQueryBuilder<I_C_OLCand> queryBuilder = Services.get(IQueryBL.class).createQueryBuilder(I_C_OLCand.class, getCtx(), get_TrxName()) .filter(queryFilter) .filter(ActiveRecordQueryFilter.getInstance(I_C_OLCand.class)); queryBuilder.orderBy() .addColumn(I_C_OLCand.COLUMNNAME_C_OLCand_ID); return queryBuilder; } @VisibleForTesting protected IQueryFilter<I_C_OLCand> getQueryFilter() { return getProcessInfo().getQueryFilterOrElseFalse(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\process\C_OLCand_SetOverrideValues.java
1
请完成以下Java代码
protected Map<Integer, I_M_HU> retrieveModelsByParent(I_M_HU_Item huItem) { return query(I_M_HU.class) .addEqualsFilter(I_M_HU.COLUMN_M_HU_Item_Parent_ID, huItem.getM_HU_Item_ID()) .create() .mapById(I_M_HU.class); } /** * Recursively collect all M_HU_IDs and M_HU_Item_IDs starting from <code>startHUIds</code> to the bottom, including those too. * * @param startHUIds * @param huIdsCollector * @param huItemIdsCollector */ protected final void collectHUAndItemIds(final Set<Integer> startHUIds, final Set<Integer> huIdsCollector, final Set<Integer> huItemIdsCollector) { Set<Integer> huIdsToCheck = new HashSet<>(startHUIds); while (!huIdsToCheck.isEmpty()) { huIdsCollector.addAll(huIdsToCheck); final Set<Integer> huItemIds = retrieveM_HU_Item_Ids(huIdsToCheck); huItemIdsCollector.addAll(huItemIds); final Set<Integer> includedHUIds = retrieveIncludedM_HUIds(huItemIds); huIdsToCheck = new HashSet<>(includedHUIds); huIdsToCheck.removeAll(huIdsCollector); } } private final Set<Integer> retrieveM_HU_Item_Ids(final Set<Integer> huIds) { if (huIds.isEmpty()) { return Collections.emptySet(); }
final List<Integer> huItemIdsList = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU_Item.class, getContext()) .addInArrayOrAllFilter(I_M_HU_Item.COLUMN_M_HU_ID, huIds) .create() .listIds(); return new HashSet<>(huItemIdsList); } private final Set<Integer> retrieveIncludedM_HUIds(final Set<Integer> huItemIds) { if (huItemIds.isEmpty()) { return Collections.emptySet(); } final List<Integer> huIdsList = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU.class, getContext()) .addInArrayOrAllFilter(I_M_HU.COLUMN_M_HU_Item_Parent_ID, huItemIds) .create() .listIds(); return new HashSet<>(huIdsList); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\snapshot\impl\M_HU_SnapshotHandler.java
1
请完成以下Java代码
final class DefaultClientResponseField implements ClientResponseField { private final DefaultClientGraphQlResponse response; private final ResponseField field; DefaultClientResponseField(DefaultClientGraphQlResponse response, ResponseField field) { this.response = response; this.field = field; } @Override public String getPath() { return this.field.getPath(); } @Override public List<Object> getParsedPath() { return this.field.getParsedPath(); } @Override public @Nullable <T> T getValue() { return this.field.getValue(); } @Override public List<ResponseError> getErrors() { return this.field.getErrors(); } @Override public @Nullable <D> D toEntity(Class<D> entityType) { return toEntity(ResolvableType.forType(entityType)); } @Override public @Nullable <D> D toEntity(ParameterizedTypeReference<D> entityType) { return toEntity(ResolvableType.forType(entityType)); } @Override
public <D> List<D> toEntityList(Class<D> elementType) { List<D> list = toEntity(ResolvableType.forClassWithGenerics(List.class, elementType)); return (list != null) ? list : Collections.emptyList(); } @Override public <D> List<D> toEntityList(ParameterizedTypeReference<D> elementType) { List<D> list = toEntity(ResolvableType.forClassWithGenerics(List.class, ResolvableType.forType(elementType))); return (list != null) ? list : Collections.emptyList(); } @SuppressWarnings("unchecked") private @Nullable <T> T toEntity(ResolvableType targetType) { if (getValue() == null) { if (this.response.isValid() && getErrors().isEmpty()) { return null; } throw new FieldAccessException(this.response.getRequest(), this.response, this); } DataBufferFactory bufferFactory = DefaultDataBufferFactory.sharedInstance; MimeType mimeType = MimeTypeUtils.APPLICATION_JSON; Map<String, Object> hints = Collections.emptyMap(); try { DataBuffer buffer = ((Encoder<T>) this.response.getEncoder()).encodeValue( (T) getValue(), bufferFactory, ResolvableType.forInstance(getValue()), mimeType, hints); return ((Decoder<T>) this.response.getDecoder()).decode(buffer, targetType, mimeType, hints); } catch (Throwable ex) { throw new GraphQlClientException("Cannot read field '" + this.field.getPath() + "'", ex, this.response.getRequest()); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultClientResponseField.java
1
请完成以下Java代码
public void setIsSummary (boolean IsSummary) { set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary)); } /** Get Zusammenfassungseintrag. @return This is a summary entity */ @Override 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; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Board. @param WEBUI_Board_ID Board */ @Override public void setWEBUI_Board_ID (int WEBUI_Board_ID) { if (WEBUI_Board_ID < 1) set_Value (COLUMNNAME_WEBUI_Board_ID, null); else set_Value (COLUMNNAME_WEBUI_Board_ID, Integer.valueOf(WEBUI_Board_ID)); } /** Get Board. @return Board */ @Override public int getWEBUI_Board_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_WEBUI_Board_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Browse name. @param WEBUI_NameBrowse Browse name */ @Override public void setWEBUI_NameBrowse (java.lang.String WEBUI_NameBrowse) { set_Value (COLUMNNAME_WEBUI_NameBrowse, WEBUI_NameBrowse); } /** Get Browse name. @return Browse name */ @Override public java.lang.String getWEBUI_NameBrowse () { return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameBrowse); } /** Set New record name. @param WEBUI_NameNew New record name */ @Override public void setWEBUI_NameNew (java.lang.String WEBUI_NameNew) { set_Value (COLUMNNAME_WEBUI_NameNew, WEBUI_NameNew); } /** Get New record name. @return New record name */ @Override public java.lang.String getWEBUI_NameNew () { return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameNew); } /** Set New record name (breadcrumb). @param WEBUI_NameNewBreadcrumb New record name (breadcrumb) */ @Override public void setWEBUI_NameNewBreadcrumb (java.lang.String WEBUI_NameNewBreadcrumb) { set_Value (COLUMNNAME_WEBUI_NameNewBreadcrumb, WEBUI_NameNewBreadcrumb); } /** Get New record name (breadcrumb). @return New record name (breadcrumb) */ @Override public java.lang.String getWEBUI_NameNewBreadcrumb () { return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameNewBreadcrumb); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Menu.java
1
请完成以下Java代码
public void setFact_Acct_ID (int Fact_Acct_ID) { if (Fact_Acct_ID < 1) set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, null); else set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID)); } /** Get Accounting Fact. @return Accounting Fact */ @Override public int getFact_Acct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Zeile Nr.. @param Line Unique line for this document */ @Override public void setLine (int Line)
{ set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Zeile Nr.. @return Unique line for this document */ @Override public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); 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_C_TaxDeclarationAcct.java
1
请在Spring Boot框架中完成以下Java代码
PackingItem createNewState() { return root.copy(); } @Override protected final PackingItem getDelegate() { final PackingItem state = getStateOrNull(); if (state != null) { return state; } return root; } /** * @return * <ul> * <li>the {@link PackingItem} as it is in current transaction * </li>or the main {@link PackingItem} (i.e. the root) if there is no transaction running * </ul> */ private PackingItem getStateOrNull() { final TransactionalPackingItemSupport transactionalSupport = TransactionalPackingItemSupport.getCreate(); if (transactionalSupport == null) { // not running in transaction return null; } return transactionalSupport.getState(this); } /** * Called by API when the transaction is committed. *
* @param state */ public void commit(final PackingItem state) { root.updateFrom(state); } /** * Creates a new instance which wraps a copy of this instances {@link #getDelegate()} value. */ @Override public IPackingItem copy() { return new TransactionalPackingItem(this); } @Override public boolean isSameAs(final IPackingItem item) { return Util.same(this, item); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\TransactionalPackingItem.java
2
请完成以下Java代码
public static PackageableRowsData cast(final IRowsData<PackageableRow> rowsData) { return (PackageableRowsData)rowsData; } public static final PackageableRowsData EMPTY = new PackageableRowsData(ImmutableList::of); private final ExtendedMemorizingSupplier<Map<DocumentId, PackageableRow>> topLevelRows; private final ImmutableListMultimap<TableRecordReference, DocumentId> initialDocumentIdsByRecordRef; private PackageableRowsData(@NonNull final Supplier<List<PackageableRow>> rowsSupplier) { topLevelRows = ExtendedMemorizingSupplier.of(() -> Maps.uniqueIndex(rowsSupplier.get(), PackageableRow::getId)); // // Remember initial rows // We will use this map to figure out what we can invalidate, // because we want to cover the case of rows which just vanished (e.g. everything was delivered) // and the case of rows which appeared back (e.g. the picking candidate was reactivated so we still have QtyToDeliver). initialDocumentIdsByRecordRef = getAllRows() .stream() .collect(ImmutableListMultimap.toImmutableListMultimap(PackageableRow::getTableRecordReference, PackageableRow::getId)); } @Override public Map<DocumentId, PackageableRow> getDocumentId2TopLevelRows() { return topLevelRows.get(); }
@Override public void invalidateAll() { topLevelRows.forget(); } @Override public DocumentIdsSelection getDocumentIdsToInvalidate(final TableRecordReferenceSet recordRefs) { return recordRefs.streamIds(I_M_ShipmentSchedule.Table_Name, ShipmentScheduleId::ofRepoId) .flatMap(this::streamDocumentIdsForShipmentScheduleId) .collect(DocumentIdsSelection.toDocumentIdsSelection()); } private Stream<DocumentId> streamDocumentIdsForShipmentScheduleId(final ShipmentScheduleId shipmentScheduleId) { final TableRecordReference recordRefEffective = PackageableRow.createTableRecordReferenceFromShipmentScheduleId(shipmentScheduleId); return initialDocumentIdsByRecordRef.get(recordRefEffective).stream(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\PackageableRowsData.java
1
请在Spring Boot框架中完成以下Java代码
public static class IssueTo { @NonNull String issueStepId; @NonNull String huQRCode; @Nullable BigDecimal huWeightGrossBeforeIssue; @NonNull BigDecimal qtyIssued; @Nullable BigDecimal qtyRejected; @Nullable String qtyRejectedReasonCode; } @Nullable IssueTo issueTo; @Value @Builder @Jacksonized public static class ReceiveFrom { @NonNull String lineId; @NonNull BigDecimal qtyReceived; @Nullable String bestBeforeDate; @Nullable String productionDate; @Nullable String lotNo; @Nullable BigDecimal catchWeight; @Nullable String catchWeightUomSymbol; @Nullable ScannedCode barcode; @Nullable JsonLUReceivingTarget aggregateToLU; @Nullable JsonTUReceivingTarget aggregateToTU; @JsonIgnore public FinishedGoodsReceiveLineId getFinishedGoodsReceiveLineId() {return FinishedGoodsReceiveLineId.ofString(lineId);} } @Nullable ReceiveFrom receiveFrom; @Value @Builder @Jacksonized public static class PickTo { @NonNull String wfProcessId; @NonNull String activityId; @NonNull String lineId; } @Nullable PickTo pickTo;
@Builder @Jacksonized private JsonManufacturingOrderEvent( @NonNull final String wfProcessId, @NonNull final String wfActivityId, // @Nullable final IssueTo issueTo, @Nullable final ReceiveFrom receiveFrom, @Nullable final PickTo pickTo) { if (CoalesceUtil.countNotNulls(issueTo, receiveFrom) != 1) { throw new AdempiereException("One and only one action like issueTo, receiveFrom etc shall be specified in an event."); } this.wfProcessId = wfProcessId; this.wfActivityId = wfActivityId; this.issueTo = issueTo; this.receiveFrom = receiveFrom; this.pickTo = pickTo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\rest_api\json\JsonManufacturingOrderEvent.java
2
请完成以下Java代码
public BootstrapConfig getBootstrapConfigByEndpoint(String endpoint) { return bootstrapConfigStore.getAll().get(endpoint); } public SecurityInfo addValueToStore(TbLwM2MSecurityInfo store, String endpoint) { /* add value to store from BootstrapJson */ SecurityInfo securityInfo = null; if (store != null && store.getBootstrapCredentialConfig() != null && store.getSecurityMode() != null) { securityInfo = store.getSecurityInfo(); this.setBootstrapConfigSecurityInfo(store); BootstrapConfig bsConfigNew = store.getBootstrapConfig(); if (bsConfigNew != null) { try { boolean bootstrapServerUpdateEnable = ((Lwm2mDeviceProfileTransportConfiguration) store.getDeviceProfile().getProfileData().getTransportConfiguration()).isBootstrapServerUpdateEnable(); if (!bootstrapServerUpdateEnable) { Optional<Map.Entry<Integer, BootstrapConfig.ServerSecurity>> securities = bsConfigNew.security.entrySet().stream().filter(sec -> sec.getValue().bootstrapServer).findAny(); if (securities.isPresent()) { bsConfigNew.security.entrySet().remove(securities.get()); int serverSortId = securities.get().getValue().serverId; Optional<Map.Entry<Integer, BootstrapConfig.ServerConfig>> serverConfigs = bsConfigNew.servers.entrySet().stream().filter(serv -> (serv.getValue()).shortId == serverSortId).findAny(); if (serverConfigs.isPresent()) { bsConfigNew.servers.entrySet().remove(serverConfigs.get()); } } } for (String config : bootstrapConfigStore.getAll().keySet()) { if (config.equals(endpoint)) {
bootstrapConfigStore.remove(config); } } bootstrapConfigStore.add(endpoint, bsConfigNew); } catch (InvalidConfigurationException e) { if (e.getMessage().contains("Psk identity") && e.getMessage().contains("already used for this bootstrap server")) { log.trace("Invalid Bootstrap Configuration", e); } else { log.error("Invalid Bootstrap Configuration", e); } } } } return securityInfo; } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\bootstrap\store\LwM2MBootstrapSecurityStore.java
1
请在Spring Boot框架中完成以下Java代码
public class M_Inventory { public static final AdMessageKey MSG_WEBUI_ADD_VIRTUAL_INV_NOT_ALLOWED = AdMessageKey.of("MSG_WEBUI_ADD_VIRTUAL_INV_NOT_ALLOWED"); public M_Inventory() { final IProgramaticCalloutProvider programaticCalloutProvider = Services.get(IProgramaticCalloutProvider.class); programaticCalloutProvider.registerAnnotatedCallout(this); } @CalloutMethod(columnNames = I_M_Inventory.COLUMNNAME_C_DocType_ID) public void updateFromDocType(final I_M_Inventory inventoryRecord, final ICalloutField field) { final IDocumentNoInfo documentNoInfo = Services.get(IDocumentNoBuilderFactory.class) .createPreliminaryDocumentNoBuilder() .setNewDocType(getDocTypeOrNull(inventoryRecord)) .setOldDocumentNo(inventoryRecord.getDocumentNo()) .setDocumentModel(inventoryRecord) .buildOrNull(); if (documentNoInfo == null) { return; } if (InventoryDocSubType.VirtualInventory.getCode().equals(documentNoInfo.getDocSubType())) { throw new AdempiereException(MSG_WEBUI_ADD_VIRTUAL_INV_NOT_ALLOWED);
} // DocumentNo if (documentNoInfo.isDocNoControlled()) { inventoryRecord.setDocumentNo(documentNoInfo.getDocumentNo()); } } private I_C_DocType getDocTypeOrNull(final I_M_Inventory inventoryRecord) { final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(inventoryRecord.getC_DocType_ID()); return docTypeId != null ? Services.get(IDocTypeDAO.class).getById(docTypeId) : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\callout\M_Inventory.java
2
请完成以下Java代码
public int hashCode() { return Objects.hash(userRolePermissionsKey, adLanguage); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof MenuTreeKey) { final MenuTreeKey other = (MenuTreeKey)obj; return Objects.equals(userRolePermissionsKey, other.userRolePermissionsKey) && Objects.equals(adLanguage, other.adLanguage); } else { return false; } } public UserRolePermissionsKey getUserRolePermissionsKey() { return userRolePermissionsKey; } public String getAD_Language() { return adLanguage; } } private static final class UserMenuFavorites { private static Builder builder() { return new Builder(); } private final UserId adUserId; private final Set<Integer> menuIds = ConcurrentHashMap.newKeySet(); private UserMenuFavorites(final Builder builder) { adUserId = builder.adUserId; Check.assumeNotNull(adUserId, "Parameter adUserId is not null"); menuIds.addAll(builder.menuIds); } public UserId getAdUserId() { return adUserId; } public boolean isFavorite(final MenuNode menuNode) { return menuIds.contains(menuNode.getAD_Menu_ID()); } public void setFavorite(final int adMenuId, final boolean favorite) { if (favorite) { menuIds.add(adMenuId); } else
{ menuIds.remove(adMenuId); } } public static class Builder { private UserId adUserId; private final Set<Integer> menuIds = new HashSet<>(); private Builder() { } public MenuTreeRepository.UserMenuFavorites build() { return new UserMenuFavorites(this); } public Builder adUserId(final UserId adUserId) { this.adUserId = adUserId; return this; } public Builder addMenuIds(final List<Integer> adMenuIds) { if (adMenuIds.isEmpty()) { return this; } menuIds.addAll(adMenuIds); return this; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\MenuTreeRepository.java
1
请完成以下Java代码
public boolean isSameDeployment() { return sameDeployment; } public void setSameDeployment(boolean sameDeployment) { this.sameDeployment = sameDeployment; } public String getValidateFormFields() { return validateFormFields; } public void setValidateFormFields(String validateFormFields) { this.validateFormFields = validateFormFields; } @Override public void addExitCriterion(Criterion exitCriterion) { exitCriteria.add(exitCriterion); } public Integer getDisplayOrder() { return displayOrder; } public void setDisplayOrder(Integer displayOrder) { this.displayOrder = displayOrder; } public String getIncludeInStageOverview() { return includeInStageOverview; } public void setIncludeInStageOverview(String includeInStageOverview) { this.includeInStageOverview = includeInStageOverview; }
@Override public List<Criterion> getExitCriteria() { return exitCriteria; } @Override public void setExitCriteria(List<Criterion> exitCriteria) { this.exitCriteria = exitCriteria; } public String getBusinessStatus() { return businessStatus; } public void setBusinessStatus(String businessStatus) { this.businessStatus = businessStatus; } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Stage.java
1
请完成以下Java代码
public static Vertex newPlaceInstance(String realWord, int frequency) { return new Vertex(Predefine.TAG_PLACE, realWord, new CoreDictionary.Attribute(Nature.ns, frequency)); } /** * 创建一个机构名实例 * * @param realWord * @param frequency * @return */ public static Vertex newOrganizationInstance(String realWord, int frequency) { return new Vertex(Predefine.TAG_GROUP, realWord, new CoreDictionary.Attribute(Nature.nt, frequency)); } /** * 创建一个时间实例 * * @param realWord 时间对应的真实字串 * @return 时间顶点 */ public static Vertex newTimeInstance(String realWord) { return new Vertex(Predefine.TAG_TIME, realWord, new CoreDictionary.Attribute(Nature.t, 1000)); } /** * 生成线程安全的起始节点 * @return */ public static Vertex newB() {
return new Vertex(Predefine.TAG_BIGIN, " ", new CoreDictionary.Attribute(Nature.begin, Predefine.TOTAL_FREQUENCY / 10), CoreDictionary.getWordID(Predefine.TAG_BIGIN)); } /** * 生成线程安全的终止节点 * @return */ public static Vertex newE() { return new Vertex(Predefine.TAG_END, " ", new CoreDictionary.Attribute(Nature.end, Predefine.TOTAL_FREQUENCY / 10), CoreDictionary.getWordID(Predefine.TAG_END)); } public int length() { return realWord.length(); } @Override public String toString() { return realWord; // return "WordNode{" + // "word='" + word + '\'' + // (word.equals(realWord) ? "" : (", realWord='" + realWord + '\'')) + //// ", attribute=" + attribute + // '}'; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\common\Vertex.java
1
请完成以下Java代码
public class PmsFeightTemplate implements Serializable { private Long id; private String name; @ApiModelProperty(value = "计费类型:0->按重量;1->按件数") private Integer chargeType; @ApiModelProperty(value = "首重kg") private BigDecimal firstWeight; @ApiModelProperty(value = "首费(元)") private BigDecimal firstFee; private BigDecimal continueWeight; private BigDecimal continmeFee; @ApiModelProperty(value = "目的地(省、市)") private String dest; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getChargeType() { return chargeType; } public void setChargeType(Integer chargeType) { this.chargeType = chargeType; } public BigDecimal getFirstWeight() { return firstWeight; } public void setFirstWeight(BigDecimal firstWeight) { this.firstWeight = firstWeight; }
public BigDecimal getFirstFee() { return firstFee; } public void setFirstFee(BigDecimal firstFee) { this.firstFee = firstFee; } public BigDecimal getContinueWeight() { return continueWeight; } public void setContinueWeight(BigDecimal continueWeight) { this.continueWeight = continueWeight; } public BigDecimal getContinmeFee() { return continmeFee; } public void setContinmeFee(BigDecimal continmeFee) { this.continmeFee = continmeFee; } public String getDest() { return dest; } public void setDest(String dest) { this.dest = dest; } @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(", chargeType=").append(chargeType); sb.append(", firstWeight=").append(firstWeight); sb.append(", firstFee=").append(firstFee); sb.append(", continueWeight=").append(continueWeight); sb.append(", continmeFee=").append(continmeFee); sb.append(", dest=").append(dest); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsFeightTemplate.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_CompensationGroup_Schema_Category_ID (final int C_CompensationGroup_Schema_Category_ID) { if (C_CompensationGroup_Schema_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_Schema_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_Schema_Category_ID, C_CompensationGroup_Schema_Category_ID); } @Override public int getC_CompensationGroup_Schema_Category_ID() { return get_ValueAsInt(COLUMNNAME_C_CompensationGroup_Schema_Category_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description);
} @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CompensationGroup_Schema_Category.java
1
请完成以下Java代码
public class AlipayConfig implements Serializable { @Id @Column(name = "config_id") @ApiModelProperty(value = "ID", hidden = true) private Long id; @NotBlank @ApiModelProperty(value = "应用ID") private String appId; @NotBlank @ApiModelProperty(value = "商户私钥") private String privateKey; @NotBlank @ApiModelProperty(value = "支付宝公钥") private String publicKey; @ApiModelProperty(value = "签名方式") private String signType="RSA2"; @Column(name = "gateway_url") @ApiModelProperty(value = "支付宝开放安全地址", hidden = true) private String gatewayUrl = "https://openapi.alipaydev.com/gateway.do"; @ApiModelProperty(value = "编码", hidden = true) private String charset= "utf-8"; @NotBlank
@ApiModelProperty(value = "异步通知地址") private String notifyUrl; @NotBlank @ApiModelProperty(value = "订单完成后返回的页面") private String returnUrl; @ApiModelProperty(value = "类型") private String format="JSON"; @NotBlank @ApiModelProperty(value = "商户号") private String sysServiceProviderId; }
repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\domain\AlipayConfig.java
1
请完成以下Java代码
public Quantity getQtyRejected() { return pickFroms.getQtyRejected().orElseGet(qtyToPick::toZero); } public PickingJobStep reduceWithPickedEvent( @NonNull PickingJobStepPickFromKey key, @NonNull PickingJobStepPickedTo pickedTo) { return withChangedPickFroms(pickFroms -> pickFroms.reduceWithPickedEvent(key, pickedTo)); } public PickingJobStep reduceWithUnpickEvent( @NonNull PickingJobStepPickFromKey key, @NonNull PickingJobStepUnpickInfo unpicked) { return withChangedPickFroms(pickFroms -> pickFroms.reduceWithUnpickEvent(key, unpicked)); } private PickingJobStep withChangedPickFroms(@NonNull final UnaryOperator<PickingJobStepPickFromMap> mapper) { final PickingJobStepPickFromMap newPickFroms = mapper.apply(this.pickFroms); return !Objects.equals(this.pickFroms, newPickFroms) ? toBuilder().pickFroms(newPickFroms).build() : this; } public ImmutableSet<PickingJobStepPickFromKey> getPickFromKeys() { return pickFroms.getKeys(); } public PickingJobStepPickFrom getPickFrom(@NonNull final PickingJobStepPickFromKey key) { return pickFroms.getPickFrom(key); }
public PickingJobStepPickFrom getPickFromByHUQRCode(@NonNull final HUQRCode qrCode) { return pickFroms.getPickFromByHUQRCode(qrCode); } @NonNull public List<HuId> getPickedHUIds() { return pickFroms.getPickedHUIds(); } @NonNull public Optional<PickingJobStepPickedToHU> getLastPickedHU() { return pickFroms.getLastPickedHU(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobStep.java
1
请完成以下Java代码
public void setGap (int rowGap, int colGap) { m_rowGap = rowGap; m_colGap = colGap; } // setGap /************************************************************************** * Layout & Calculate Image Size. * Set p_width & p_height * @return true if calculated */ protected boolean calculateSize() { p_height = 0; for (int r = 0; r < m_rows; r++) { p_height += m_rowHeight[r]; if (m_rowHeight[r] > 0) p_height += m_rowGap; } p_height -= m_rowGap; // remove last p_width = 0; for (int c = 0; c < m_cols; c++) { p_width += m_colWidth[c]; if (m_colWidth[c] > 0) p_width += m_colGap; } p_width -= m_colGap; // remove last return true; } // calculateSize /** * Paint it * @param g2D Graphics * @param pageStart top left Location of page * @param pageNo page number for multi page support (0 = header/footer) - ignored * @param ctx print context * @param isView true if online view (IDs are links) */ public void paint(Graphics2D g2D, int pageNo, Point2D pageStart, Properties ctx, boolean isView)
{ Point2D.Double location = getAbsoluteLocation(pageStart); float y = (float)location.y; // for (int row = 0; row < m_rows; row++) { float x = (float)location.x; for (int col = 0; col < m_cols; col++) { if (m_textLayout[row][col] != null) { float yy = y + m_textLayout[row][col].getAscent(); // if (m_iterator[row][col] != null) // g2D.drawString(m_iterator[row][col], x, yy); // else m_textLayout[row][col].draw(g2D, x, yy); } x += m_colWidth[col]; if (m_colWidth[col] > 0) x += m_colGap; } y += m_rowHeight[row]; if (m_rowHeight[row] > 0) y += m_rowGap; } } // paint } // GridElement
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\GridElement.java
1
请完成以下Java代码
public static class AsyncBuilder extends AbstractBuilder<AsyncBuilder> { protected @Nullable AsyncPredicate<ServerWebExchange> predicate; @Override protected AsyncBuilder getThis() { return this; } @Override public AsyncPredicate<ServerWebExchange> getPredicate() { Objects.requireNonNull(this.predicate, "predicate can not be null"); return this.predicate; } public AsyncBuilder predicate(Predicate<ServerWebExchange> predicate) { return asyncPredicate(toAsyncPredicate(predicate)); } public AsyncBuilder asyncPredicate(AsyncPredicate<ServerWebExchange> predicate) { this.predicate = predicate; return this; } public AsyncBuilder and(AsyncPredicate<ServerWebExchange> predicate) { Objects.requireNonNull(this.predicate, "can not call and() on null predicate"); this.predicate = this.predicate.and(predicate); return this; } public AsyncBuilder or(AsyncPredicate<ServerWebExchange> predicate) { Objects.requireNonNull(this.predicate, "can not call or() on null predicate"); this.predicate = this.predicate.or(predicate); return this; } public AsyncBuilder negate() { Objects.requireNonNull(this.predicate, "can not call negate() on null predicate"); this.predicate = this.predicate.negate(); return this; } }
public static class Builder extends AbstractBuilder<Builder> { protected @Nullable Predicate<ServerWebExchange> predicate; @Override protected Builder getThis() { return this; } @Override public AsyncPredicate<ServerWebExchange> getPredicate() { return ServerWebExchangeUtils.toAsyncPredicate(this.predicate); } public Builder and(Predicate<ServerWebExchange> predicate) { Objects.requireNonNull(this.predicate, "can not call and() on null predicate"); this.predicate = this.predicate.and(predicate); return this; } public Builder or(Predicate<ServerWebExchange> predicate) { Objects.requireNonNull(this.predicate, "can not call or() on null predicate"); this.predicate = this.predicate.or(predicate); return this; } public Builder negate() { Objects.requireNonNull(this.predicate, "can not call negate() on null predicate"); this.predicate = this.predicate.negate(); return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\route\Route.java
1
请完成以下Java代码
public int getDD_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_DD_OrderLine_ID); } @Override public void setM_HU_Reservation_ID (final int M_HU_Reservation_ID) { if (M_HU_Reservation_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Reservation_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Reservation_ID, M_HU_Reservation_ID); } @Override public int getM_HU_Reservation_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Reservation_ID); } @Override public de.metas.handlingunits.model.I_M_Picking_Job_Step getM_Picking_Job_Step() { return get_ValueAsPO(COLUMNNAME_M_Picking_Job_Step_ID, de.metas.handlingunits.model.I_M_Picking_Job_Step.class); } @Override public void setM_Picking_Job_Step(final de.metas.handlingunits.model.I_M_Picking_Job_Step M_Picking_Job_Step) { set_ValueFromPO(COLUMNNAME_M_Picking_Job_Step_ID, de.metas.handlingunits.model.I_M_Picking_Job_Step.class, M_Picking_Job_Step); } @Override public void setM_Picking_Job_Step_ID (final int M_Picking_Job_Step_ID) { if (M_Picking_Job_Step_ID < 1) set_Value (COLUMNNAME_M_Picking_Job_Step_ID, null); else set_Value (COLUMNNAME_M_Picking_Job_Step_ID, M_Picking_Job_Step_ID); } @Override public int getM_Picking_Job_Step_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Step_ID); } @Override public void setQtyReserved (final BigDecimal QtyReserved) {
set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } @Override public de.metas.handlingunits.model.I_M_HU getVHU() { return get_ValueAsPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override public void setVHU(final de.metas.handlingunits.model.I_M_HU VHU) { set_ValueFromPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class, VHU); } @Override public void setVHU_ID (final int VHU_ID) { if (VHU_ID < 1) set_Value (COLUMNNAME_VHU_ID, null); else set_Value (COLUMNNAME_VHU_ID, VHU_ID); } @Override public int getVHU_ID() { return get_ValueAsInt(COLUMNNAME_VHU_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Reservation.java
1
请在Spring Boot框架中完成以下Java代码
public Result<AiragMcp> queryById(@RequestParam(name = "id", required = true) String id) { AiragMcp airagMcp = airagMcpService.getById(id); if (airagMcp == null) { return Result.error("未找到对应数据"); } return Result.OK(airagMcp); } /** * 导出excel * * @param request * @param airagMcp */ // @RequiresPermissions("llm:airag_mcp:exportXls") @RequestMapping(value = "/exportXls") public ModelAndView exportXls(HttpServletRequest request, AiragMcp airagMcp) { return super.exportXls(request, airagMcp, AiragMcp.class, "MCP"); }
/** * 通过excel导入数据 * * @param request * @param response * @return */ // @RequiresPermissions("llm:airag_mcp:importExcel") @RequestMapping(value = "/importExcel", method = RequestMethod.POST) public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) { return super.importExcel(request, response, AiragMcp.class); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\llm\controller\AiragMcpController.java
2
请完成以下Java代码
public int read() throws IOException { return in().read(); } @Override public int read(byte[] b) throws IOException { return in().read(b); } @Override public int read(byte[] b, int off, int len) throws IOException { return in().read(b, off, len); } @Override public long skip(long n) throws IOException { return in().skip(n); } @Override public int available() throws IOException { return in().available(); } @Override public boolean markSupported() { try { return in().markSupported(); } catch (IOException ex) { return false; } } @Override public synchronized void mark(int readLimit) { try { in().mark(readLimit); }
catch (IOException ex) { // Ignore } } @Override public synchronized void reset() throws IOException { in().reset(); } private InputStream in() throws IOException { InputStream in = this.in; if (in == null) { synchronized (this) { in = this.in; if (in == null) { in = getDelegateInputStream(); this.in = in; } } } return in; } @Override public void close() throws IOException { InputStream in = this.in; if (in != null) { synchronized (this) { in = this.in; if (in != null) { in.close(); } } } } protected abstract InputStream getDelegateInputStream() throws IOException; }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\LazyDelegatingInputStream.java
1
请在Spring Boot框架中完成以下Java代码
public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private int id; @Column(name = "name") private String name; @ManyToOne @Cascade(CascadeType.SAVE_UPDATE) @JoinColumn(name = "department_id") private Department department; // standard getters and setters public Employee() { } public Employee(String name) { this.name = name; } public int getId() {
return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } }
repos\tutorials-master\persistence-modules\hibernate-exceptions\src\main\java\com\baeldung\hibernate\exception\transientobject\entity\Employee.java
2
请完成以下Java代码
public void setTargetQty (java.math.BigDecimal TargetQty) { set_Value (COLUMNNAME_TargetQty, TargetQty); } /** Get Zielmenge. @return Target Movement Quantity */ @Override public java.math.BigDecimal getTargetQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty); if (bd == null) return Env.ZERO; return bd; } /** Set Suchschlüssel.
@param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { throw new IllegalArgumentException ("Value is virtual column"); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MovementLine.java
1
请完成以下Java代码
public Map<String, String> getInitParams() { Map<String, String> initParams = new HashMap<>(); if (enableSecureCookie) { // only add param if it's true; default is false initParams.put("enableSecureCookie", String.valueOf(enableSecureCookie)); } if (!enableSameSiteCookie) { // only add param if it's false; default is true initParams.put("enableSameSiteCookie", String.valueOf(enableSameSiteCookie)); } if (StringUtils.isNotBlank(sameSiteCookieOption)) { initParams.put("sameSiteCookieOption", sameSiteCookieOption); } if (StringUtils.isNotBlank(sameSiteCookieValue)) { initParams.put("sameSiteCookieValue", sameSiteCookieValue); } if (StringUtils.isNotBlank(cookieName)) { initParams.put("cookieName", cookieName);
} return initParams; } @Override public String toString() { return joinOn(this.getClass()) .add("enableSecureCookie='" + enableSecureCookie + '\'') .add("enableSameSiteCookie='" + enableSameSiteCookie + '\'') .add("sameSiteCookieOption='" + sameSiteCookieOption + '\'') .add("sameSiteCookieValue='" + sameSiteCookieValue + '\'') .add("cookieName='" + cookieName + '\'') .toString(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\SessionCookieProperties.java
1
请完成以下Java代码
private ListenableFuture<Void> addToQueue(EdgeEventEntity entity) { return queue.add(entity); } @Override public PageData<EdgeEvent> findEdgeEvents(UUID tenantId, EdgeId edgeId, Long seqIdStart, Long seqIdEnd, TimePageLink pageLink) { return DaoUtil.toPageData( edgeEventRepository .findEdgeEventsByTenantIdAndEdgeId( tenantId, edgeId.getId(), pageLink.getTextSearch(), pageLink.getStartTime(), pageLink.getEndTime(), seqIdStart,
seqIdEnd, DaoUtil.toPageable(pageLink, SORT_ORDERS))); } @Override public void cleanupEvents(long ttl) { partitioningRepository.dropPartitionsBefore(TABLE_NAME, ttl, TimeUnit.HOURS.toMillis(partitionSizeInHours)); } @Override public void createPartition(EdgeEventEntity entity) { partitioningRepository.createPartitionIfNotExists(TABLE_NAME, entity.getCreatedTime(), TimeUnit.HOURS.toMillis(partitionSizeInHours)); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\edge\JpaBaseEdgeEventDao.java
1
请完成以下Java代码
public boolean isSuspended() { return SuspensionState.SUSPENDED.getStateCode() == suspensionState; } @Override public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } @Override public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } @Override public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } @Override public String getJobConfiguration() { return jobConfiguration; } public void setJobConfiguration(String jobConfiguration) { this.jobConfiguration = jobConfiguration; } @Override public String getProcessDefinitionKey() { return processDefinitionKey; } public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } public int getSuspensionState() { return suspensionState; }
public void setSuspensionState(int state) { this.suspensionState = state; } public Long getOverridingJobPriority() { return jobPriority; } public void setJobPriority(Long jobPriority) { this.jobPriority = jobPriority; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<>(); return referenceIdAndClass; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\JobDefinitionEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class SchedulerDao { private final IQueryBL queryBL = Services.get(IQueryBL.class); @NonNull public Optional<I_AD_Scheduler> getSchedulerByProcessIdIfUnique(@NonNull final AdProcessId processId) { final List<I_AD_Scheduler> records = queryBL.createQueryBuilder(I_AD_Scheduler.class) .addEqualsFilter(I_AD_Scheduler.COLUMNNAME_AD_Process_ID, processId.getRepoId()) .create() .list(I_AD_Scheduler.class); if (!Check.isSingleElement(records)) { return Optional.empty();
} return Optional.of(records.get(0)); } @NonNull public I_AD_Scheduler getById(@NonNull final AdSchedulerId adSchedulerId) { return InterfaceWrapperHelper.load(adSchedulerId, I_AD_Scheduler.class); } public void save(@NonNull final I_AD_Scheduler scheduler) { InterfaceWrapperHelper.save(scheduler); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scheduler\SchedulerDao.java
2
请完成以下Java代码
public class RandomHexGenerator { public String generateUnboundedRandomHexUsingRandomNextInt() { Random random = new Random(); int randomInt = random.nextInt(); return Integer.toHexString(randomInt); } public String generateRandomHexUsingRandomNextIntWithInRange(int lower, int upper) { Random random = new Random(); int randomInt = random.nextInt(upper - lower) + lower; return Integer.toHexString(randomInt); } public String generateRandomHexUsingSecureRandomNextInt() { SecureRandom secureRandom = new SecureRandom(); int randomInt = secureRandom.nextInt(); return Integer.toHexString(randomInt); } public String generateRandomHexUsingSecureRandomNextIntWithInRange(int lower, int upper) { SecureRandom secureRandom = new SecureRandom(); int randomInt = secureRandom.nextInt(upper - lower) + lower; return Integer.toHexString(randomInt); } public String generateUnboundedRandomHexUsingRandomNextLong() { Random random = new Random(); long randomLong = random.nextLong(); return Long.toHexString(randomLong); } public String generateRandomHexUsingSecureRandomNextLong() { SecureRandom secureRandom = new SecureRandom(); long randomLong = secureRandom.nextLong(); return Long.toHexString(randomLong); } public String generateRandomHexWithStringFormatter() { Random random = new Random(); int randomInt = random.nextInt(); return String.format("%02x", randomInt); }
public String generateRandomHexWithCommonsMathRandomDataGenerator(int len) { RandomDataGenerator randomDataGenerator = new RandomDataGenerator(); return randomDataGenerator.nextHexString(len); } public String generateSecureRandomHexWithCommonsMathRandomDataGenerator(int len) { RandomDataGenerator randomDataGenerator = new RandomDataGenerator(); return randomDataGenerator.nextSecureHexString(len); } public String generateRandomHexWithCommonsMathRandomDataGeneratorNextIntWithRange(int lower, int upper) { RandomDataGenerator randomDataGenerator = new RandomDataGenerator(); int randomInt = randomDataGenerator.nextInt(lower, upper); return Integer.toHexString(randomInt); } public String generateRandomHexWithCommonsMathRandomDataGeneratorSecureNextIntWithRange(int lower, int upper) { RandomDataGenerator randomDataGenerator = new RandomDataGenerator(); int randomInt = randomDataGenerator.nextSecureInt(lower, upper); return Integer.toHexString(randomInt); } }
repos\tutorials-master\core-java-modules\core-java-hex\src\main\java\com\baeldung\randomhexnumber\RandomHexGenerator.java
1
请完成以下Java代码
private boolean containsInvalidUrlEncodedSlash(String uri) { if (this.allowUrlEncodedSlash || uri == null) { return false; } return uri.contains("%2f") || uri.contains("%2F"); } /** * Checks whether a path is normalized (doesn't contain path traversal sequences like * "./", "/../" or "/.") * @param path the path to test * @return true if the path doesn't contain any path-traversal character sequences. */ private boolean isNormalized(String path) { if (path == null) { return true; }
for (int i = path.length(); i > 0;) { int slashIndex = path.lastIndexOf('/', i - 1); int gap = i - slashIndex; if (gap == 2 && path.charAt(slashIndex + 1) == '.') { // ".", "/./" or "/." return false; } if (gap == 3 && path.charAt(slashIndex + 1) == '.' && path.charAt(slashIndex + 2) == '.') { return false; } i = slashIndex; } return true; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\firewall\DefaultHttpFirewall.java
1
请完成以下Java代码
public class WEBUI_C_OrderLineSO_Delete_HUReservation extends HUEditorProcessTemplate implements IProcessPrecondition { private final HUReservationService huReservationService = SpringContextHolder.instance.getBean(HUReservationService.class); private final SalesOrderLineRepository salesOrderLineRepository = SpringContextHolder.instance.getBean(SalesOrderLineRepository.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable() { final SalesOrderLine salesOrderLine = WEBUI_C_OrderLineSO_Util.retrieveSalesOrderLine(getView(), salesOrderLineRepository) .orElse(null); if (salesOrderLine == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("No sales order was set"); } final ProductId productId = salesOrderLine.getProductId(); final Quantity unreservableQty = retrieveUnreservableQuantity(productId); if (unreservableQty.signum() <= 0) { return ProcessPreconditionsResolution.rejectWithInternalReason("No unreservableQty quantity for productId=" + productId); } return ProcessPreconditionsResolution.accept();
} private Quantity retrieveUnreservableQuantity(final ProductId productId) { final RetrieveHUsQtyRequest request = WEBUI_C_OrderLineSO_Util.createHuQuantityRequest( streamSelectedHUIds(Select.ALL), productId); return huReservationService.retrieveUnreservableQty(request); } @Override @RunOutOfTrx // the service we invoke creates its own transaction protected String doIt() { final ImmutableSet<HuId> selectedReservedHUs = streamSelectedHUIds(HUEditorRowFilter.ALL) .collect(ImmutableSet.toImmutableSet()); huReservationService.deleteReservationsByVHUIds(selectedReservedHUs); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\hu\reservation\process\WEBUI_C_OrderLineSO_Delete_HUReservation.java
1
请完成以下Java代码
public int getM_DiscountSchema_ID() { return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_ID); } @Override public void setM_DiscountSchemaBreak_V_ID (final int M_DiscountSchemaBreak_V_ID) { if (M_DiscountSchemaBreak_V_ID < 1) set_ValueNoCheck (COLUMNNAME_M_DiscountSchemaBreak_V_ID, null); else set_ValueNoCheck (COLUMNNAME_M_DiscountSchemaBreak_V_ID, M_DiscountSchemaBreak_V_ID); } @Override public int getM_DiscountSchemaBreak_V_ID() { return get_ValueAsInt(COLUMNNAME_M_DiscountSchemaBreak_V_ID);
} @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchemaBreak_V.java
1
请在Spring Boot框架中完成以下Java代码
final class RegisterMissingBeanPostProcessor implements BeanDefinitionRegistryPostProcessor, BeanFactoryAware { private final AnnotationBeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator(); private final List<AbstractBeanDefinition> beanDefinitions = new ArrayList<>(); private BeanFactory beanFactory; @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { for (AbstractBeanDefinition beanDefinition : this.beanDefinitions) { String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( (ListableBeanFactory) this.beanFactory, beanDefinition.getBeanClass(), false, false); if (beanNames.length == 0) { String beanName = this.beanNameGenerator.generateBeanName(beanDefinition, registry); registry.registerBeanDefinition(beanName, beanDefinition); } }
} @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } <T> void addBeanDefinition(Class<T> beanClass, Supplier<T> beanSupplier) { this.beanDefinitions.add(new RootBeanDefinition(beanClass, beanSupplier)); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configuration\RegisterMissingBeanPostProcessor.java
2
请在Spring Boot框架中完成以下Java代码
public class FileUploadController implements HandlerExceptionResolver { @RequestMapping(value = "/uploadFile", method = RequestMethod.GET) public String getImageView() { return "file"; } @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public ModelAndView uploadFile(MultipartFile file) throws IOException { ModelAndView modelAndView = new ModelAndView("file"); InputStream in = file.getInputStream(); File currDir = new File("."); String path = currDir.getAbsolutePath(); FileOutputStream f = new FileOutputStream(path.substring(0, path.length() - 1) + file.getOriginalFilename()); int ch = 0; while ((ch = in.read()) != -1) { f.write(ch); } f.flush(); f.close();
modelAndView.getModel() .put("message", "File uploaded successfully!"); return modelAndView; } @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exc) { ModelAndView modelAndView = new ModelAndView("file"); if (exc instanceof MaxUploadSizeExceededException) { modelAndView.getModel() .put("message", "File size exceeds limit!"); } return modelAndView; } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\controller\FileUploadController.java
2
请完成以下Java代码
private void fillProcessDefinitionData(HistoricJobLogEventEntity event, JobEntity jobEntity) { String processDefinitionId = jobEntity.getProcessDefinitionId(); if (processDefinitionId != null) { fillProcessDefinitionData(event, processDefinitionId); } else { event.setProcessDefinitionId(jobEntity.getProcessDefinitionId()); event.setProcessDefinitionKey(jobEntity.getProcessDefinitionKey()); } } private void fillProcessDefinitionData(HistoricIdentityLinkLogEventEntity event, IdentityLink identityLink) { String processDefinitionId = identityLink.getProcessDefId(); if (processDefinitionId != null) { fillProcessDefinitionData(event, processDefinitionId); } else { event.setProcessDefinitionId(identityLink.getProcessDefId()); } } private void fillProcessDefinitionData(HistoryEvent event, ExecutionEntity execution) { String processDefinitionId = execution.getProcessDefinitionId(); if (processDefinitionId != null) { fillProcessDefinitionData(event, processDefinitionId); } else { event.setProcessDefinitionId(execution.getProcessDefinitionId()); event.setProcessDefinitionKey(execution.getProcessDefinitionKey()); } } private void fillProcessDefinitionData(HistoricIncidentEventEntity event, Incident incident) { String processDefinitionId = incident.getProcessDefinitionId(); if (processDefinitionId != null) { fillProcessDefinitionData(event, processDefinitionId); } else { event.setProcessDefinitionId(incident.getProcessDefinitionId()); } } private void fillProcessDefinitionData(HistoryEvent event, UserOperationLogContextEntry userOperationLogContextEntry) { String processDefinitionId = userOperationLogContextEntry.getProcessDefinitionId(); if (processDefinitionId != null) { fillProcessDefinitionData(event, processDefinitionId); } else { event.setProcessDefinitionId(userOperationLogContextEntry.getProcessDefinitionId()); event.setProcessDefinitionKey(userOperationLogContextEntry.getProcessDefinitionKey()); }
} private void fillProcessDefinitionData(HistoryEvent event, String processDefinitionId) { ProcessDefinitionEntity entity = this.getProcessDefinitionEntity(processDefinitionId); if (entity != null) { event.setProcessDefinitionId(entity.getId()); event.setProcessDefinitionKey(entity.getKey()); event.setProcessDefinitionVersion(entity.getVersion()); event.setProcessDefinitionName(entity.getName()); } } protected ProcessDefinitionEntity getProcessDefinitionEntity(String processDefinitionId) { DbEntityManager dbEntityManager = (Context.getCommandContext() != null) ? Context.getCommandContext().getDbEntityManager() : null; if (dbEntityManager != null) { return dbEntityManager .selectById(ProcessDefinitionEntity.class, processDefinitionId); } return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\DefaultHistoryEventProducer.java
1
请完成以下Java代码
public List<PrinterHWMediaTray> getPrinterHWMediaTrays() { return this.printerHWMediaTrays; } public void setPrinterHWMediaTrays(List<PrinterHWMediaTray> printerHWMediaTrays) { this.printerHWMediaTrays = printerHWMediaTrays; } @Override public String toString() { return "PrinterHW [name=" + name + ", printerHWMediaSizes=" + printerHWMediaSizes + ", printerHWMediaTrays=" + printerHWMediaTrays + "]"; } /** * Printer HW Media Size Object * * @author al */ public static class PrinterHWMediaSize implements Serializable { /** * */ private static final long serialVersionUID = 5962990173434911764L; private String name; private String isDefault; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIsDefault() { return isDefault; } public void setIsDefault(String isDefault) { this.isDefault = isDefault; } @Override public String toString() { return "PrinterHWMediaSize [name=" + name + ", isDefault=" + isDefault + "]"; } } /** * Printer HW Media Tray Object * * @author al */ public static class PrinterHWMediaTray implements Serializable { /** * */ private static final long serialVersionUID = -1833627999553124042L; private String name; private String trayNumber;
private String isDefault; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTrayNumber() { return trayNumber; } public void setTrayNumber(String trayNumber) { this.trayNumber = trayNumber; } public String getIsDefault() { return isDefault; } public void setIsDefault(String isDefault) { this.isDefault = isDefault; } @Override public String toString() { return "PrinterHWMediaTray [name=" + name + ", trayNumber=" + trayNumber + ", isDefault=" + isDefault + "]"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrinterHW.java
1
请完成以下Java代码
public String getSummary(final DocumentTableFields docFields) { return extractProductBom(docFields).getDocumentNo(); } @Override public String getDocumentInfo(final DocumentTableFields docFields) { return getSummary(docFields); } @Override public int getDoc_User_ID(final DocumentTableFields docFields) { return extractProductBom(docFields).getCreatedBy(); } @Nullable @Override public LocalDate getDocumentDate(final DocumentTableFields docFields) { final I_PP_Product_BOM productBom = extractProductBom(docFields); final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(productBom.getAD_Org_ID())); return TimeUtil.asLocalDate(productBom.getDateDoc(), timeZone); } @Override public String completeIt(final DocumentTableFields docFields) { final I_PP_Product_BOM productBomRecord = extractProductBom(docFields); productBomRecord.setDocAction(X_C_RemittanceAdvice.DOCACTION_Re_Activate); productBomRecord.setProcessed(true); return X_PP_Product_BOM.DOCSTATUS_Completed;
} @Override public void reactivateIt(final DocumentTableFields docFields) { final I_PP_Product_BOM productBom = extractProductBom(docFields); productBom.setProcessed(false); productBom.setDocAction(X_PP_Product_BOM.DOCACTION_Complete); } private static I_PP_Product_BOM extractProductBom(final DocumentTableFields docFields) { return InterfaceWrapperHelper.create(docFields, I_PP_Product_BOM.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\document\PP_Product_BOM_DocHandler.java
1
请完成以下Java代码
private void setUserFieldsAndSave(@NonNull final I_AD_User user, @NonNull final I_I_User importRecord) { user.setFirstname(importRecord.getFirstname()); user.setLastname(importRecord.getLastname()); // set value after we set first name and last name user.setValue(importRecord.getUserValue()); user.setEMail(importRecord.getEMail()); user.setIsNewsletter(importRecord.isNewsletter()); user.setPhone(importRecord.getPhone()); user.setFax(importRecord.getFax()); user.setMobilePhone(importRecord.getMobilePhone()); // user.gen final I_AD_User loginUser = InterfaceWrapperHelper.create(user, I_AD_User.class);
loginUser.setLogin(importRecord.getLogin()); loginUser.setIsSystemUser(importRecord.isSystemUser()); final IUserBL userBL = Services.get(IUserBL.class); userBL.changePasswordAndSave(loginUser, RandomStringUtils.randomAlphanumeric(8)); } @Override protected void markImported(final I_I_User importRecord) { importRecord.setI_IsImported(X_I_User.I_ISIMPORTED_Imported); importRecord.setProcessed(true); InterfaceWrapperHelper.save(importRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\impexp\ADUserImportProcess.java
1
请在Spring Boot框架中完成以下Java代码
public String index(HttpServletRequest request, Model model) { // 获取登录的用户 RpUserInfo rpUserInfo = (RpUserInfo) request.getSession().getAttribute(ConstantClass.USER); if (rpUserInfo != null) { return "system/index"; } String mobile = request.getParameter("mobile"); String password = request.getParameter("password"); String msg = ""; if (StringUtil.isEmpty(mobile)) { msg = "请输入手机号/密码"; model.addAttribute("msg", msg); return "system/login"; } if (StringUtil.isEmpty(password)) { msg = "请输入手机号/密码"; model.addAttribute("msg", msg); return "system/login"; } rpUserInfo = rpUserInfoService.getDataByMobile(mobile);
if (rpUserInfo == null) { msg = "用户名/密码错误"; } else if (!EncryptUtil.encodeMD5String(password).equals(rpUserInfo.getPassword())) { msg = "用户名/密码错误"; } model.addAttribute("mobile", mobile); model.addAttribute("password", password); request.getSession().setAttribute(ConstantClass.USER, rpUserInfo); if (!StringUtil.isEmpty(msg)) { model.addAttribute("msg", msg); return "system/login"; } return "system/index"; } }
repos\roncoo-pay-master\roncoo-pay-web-merchant\src\main\java\com\roncoo\pay\controller\login\LoginController.java
2
请在Spring Boot框架中完成以下Java代码
public static String getPurchaseOrdersFromLocalFileRouteId(@NonNull final JsonExternalSystemRequest externalSystemRequest) { return "GetPurchaseOrderFromLocalFile#" + externalSystemRequest.getExternalSystemChildConfigValue(); } @Override public String getServiceValue() { return "LocalFileSyncPurchaseOrders"; } @Override public String getExternalSystemTypeCode() { return PCM_SYSTEM_NAME; } @Override public String getEnableCommand() { return START_PURCHASE_ORDER_SYNC_LOCAL_FILE_ROUTE;
} @Override public String getDisableCommand() { return STOP_PURCHASE_ORDER_SYNC_LOCAL_FILE_ROUTE; } @NonNull public String getStartPurchaseOrderRouteId() { return getExternalSystemTypeCode() + "-" + getEnableCommand(); } @NonNull public String getStopPurchaseOrderRouteId() { return getExternalSystemTypeCode() + "-" + getDisableCommand(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\purchaseorder\LocalFilePurchaseOrderSyncServicePCMRouteBuilder.java
2