instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
class MyMBean implements DynamicMBean { @Override public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { return null; } @Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { } @Override public AttributeList getAttributes(String[] attributes) { return null; } @Override public AttributeList setAttributes(AttributeList attributes) {
return null; } @Override public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException { return null; } @Override public MBeanInfo getMBeanInfo() { MBeanAttributeInfo[] attributes = new MBeanAttributeInfo[0]; MBeanConstructorInfo[] constructors = new MBeanConstructorInfo[0]; MBeanOperationInfo[] operations = new MBeanOperationInfo[0]; MBeanNotificationInfo[] notifications = new MBeanNotificationInfo[0]; return new MBeanInfo(MyMBean.class.getName(), "My MBean", attributes, constructors, operations, notifications); } }
repos\tutorials-master\spring-kafka-3\src\main\java\com\baeldung\spring\kafka\kafkaexception\SimulateInstanceAlreadyExistsException.java
1
请在Spring Boot框架中完成以下Java代码
public class BookList implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String isbn; @ManyToMany(mappedBy = "books") private List<AuthorList> authors = new ArrayList<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public List<AuthorList> getAuthors() { return authors; } public void setAuthors(List<AuthorList> authors) { this.authors = authors; }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((BookList) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootManyToManyBidirectionalListVsSet\src\main\java\com\bookstore\entity\BookList.java
2
请完成以下Java代码
public void markStale(@NonNull final DocumentIdsSelection rowIds) { // TODO: implement staling only given rowId markStaleAll(); } @Override public boolean isStale() { return staled; } @Override public int getNextLineNo() { final int lastLineNo = DocumentQuery.builder(entityDescriptor) .setParentDocument(parentDocument) .setExistingDocumentsSupplier(this::getChangedDocumentOrNull) .setChangesCollector(NullDocumentChangesCollector.instance) .retrieveLastLineNo(); final int nextLineNo = lastLineNo / 10 * 10 + 10; return nextLineNo; } // // // @AllArgsConstructor private final class ActionsContext implements IncludedDocumentsCollectionActionsContext { @Override public boolean isParentDocumentProcessed() { return parentDocument.isProcessed(); } @Override public boolean isParentDocumentActive() { return parentDocument.isActive(); } @Override public boolean isParentDocumentNew() { return parentDocument.isNew(); } @Override public boolean isParentDocumentInvalid() { return !parentDocument.getValidStatus().isValid(); } @Override
public Collection<Document> getIncludedDocuments() { return getChangedDocuments(); } @Override public Evaluatee toEvaluatee() { return parentDocument.asEvaluatee(); } @Override public void collectAllowNew(final DocumentPath parentDocumentPath, final DetailId detailId, final LogicExpressionResult allowNew) { parentDocument.getChangesCollector().collectAllowNew(parentDocumentPath, detailId, allowNew); } @Override public void collectAllowDelete(final DocumentPath parentDocumentPath, final DetailId detailId, final LogicExpressionResult allowDelete) { parentDocument.getChangesCollector().collectAllowDelete(parentDocumentPath, detailId, allowDelete); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\HighVolumeReadWriteIncludedDocumentsCollection.java
1
请完成以下Java代码
public Set<Object> keySet() { // TODO: implement for GridField values too return ctx.keySet(); } @Override public synchronized Object put(Object key, Object value) { if (gridTab == null) throw new IllegalStateException("Method not supported (gridTab is null)"); if (gridTab.getCurrentRow() != row) { return ctx.put(key, value); } String columnName = getColumnName(key); if (columnName == null) { return ctx.put(key, value); } GridField field = gridTab.getField(columnName); if (field == null) { return ctx.put(key, value); } Object valueOld = field.getValue(); field.setValue(value, false); // inserting=false return valueOld; } @Override public synchronized void putAll(Map<? extends Object, ? extends Object> t) { for (Map.Entry<? extends Object, ? extends Object> e : t.entrySet()) put(e.getKey(), e.getValue()); } @Override public synchronized Object remove(Object key) { // TODO: implement for GridField values too return ctx.remove(key); } @Override public synchronized int size() { // TODO: implement for GridField values too return ctx.size(); }
@Override public synchronized String toString() { // TODO: implement for GridField values too return ctx.toString(); } @Override public Collection<Object> values() { return ctx.values(); } @Override public String getProperty(String key) { // I need to override this method, because Properties.getProperty method // is calling super.get() instead of get() Object oval = get(key); return oval == null ? null : oval.toString(); } @Override public String get_ValueAsString(String variableName) { final int windowNo = getWindowNo(); final int tabNo = getTabNo(); // Check value at Tab level, fallback to Window level final String value = Env.getContext(this, windowNo, tabNo, variableName, Scope.Window); return value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\GridRowCtx.java
1
请在Spring Boot框架中完成以下Java代码
public class JSONLoginAuthRequest { public enum Type { password, token } @JsonProperty("type") Type type; @JsonProperty("username") String username; @JsonProperty("password") String password; @JsonProperty("token") String token; @JsonCreator @Builder private JSONLoginAuthRequest( @JsonProperty("type") @Nullable final Type type,
@JsonProperty("username") @Nullable final String username, @JsonProperty("password") @Nullable final String password, @JsonProperty("token") final String token) { // Tolerate null/empty values; we will validate them later and we will throw nice error messages // Check.assumeNotEmpty(username, "username is not empty"); // Check.assumeNotEmpty(password, "password is not empty"); this.type = type != null ? type : Type.password; this.username = username; this.password = password; this.token = token; } public HashableString getPasswordAsEncryptableString() { return HashableString.ofPlainValue(password); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\login\json\JSONLoginAuthRequest.java
2
请完成以下Java代码
public I_M_InOutLine getM_InOutLine() { if (iciol == null) { return null; } return iciol.getM_InOutLine(); } public StockQtyAndUOMQty getQtysAlreadyInvoiced() { final StockQtyAndUOMQty zero = StockQtyAndUOMQtys.createZero(productId, icUomId); if (iciol == null) { return zero; } else { final InOutLineId inoutLineId = InOutLineId.ofRepoId(iciol.getM_InOutLine_ID()); return matchInvoiceService.getMaterialQtyMatched(inoutLineId, zero); } } public StockQtyAndUOMQty getQtysAlreadyShipped() { final I_M_InOutLine inOutLine = getM_InOutLine(); if (inOutLine == null) { return StockQtyAndUOMQtys.createZero(productId, icUomId); } final InvoicableQtyBasedOn invoicableQtyBasedOn = InvoicableQtyBasedOn.ofNullableCodeOrNominal(ic.getInvoicableQtyBasedOn()); final BigDecimal uomQty; if (!isNull(iciol, I_C_InvoiceCandidate_InOutLine.COLUMNNAME_QtyDeliveredInUOM_Override)) { uomQty = iciol.getQtyDeliveredInUOM_Override(); } else { switch (invoicableQtyBasedOn) { case CatchWeight: uomQty = coalesceNotNull(iciol.getQtyDeliveredInUOM_Catch(), iciol.getQtyDeliveredInUOM_Nominal()); break; case NominalWeight: uomQty = iciol.getQtyDeliveredInUOM_Nominal(); break; default: throw fail("Unexpected invoicableQtyBasedOn={}", invoicableQtyBasedOn); } }
final Quantity shippedUomQuantityInIcUOM = uomConversionBL.convertQuantityTo(Quantitys.of(uomQty, UomId.ofRepoId(iciol.getC_UOM_ID())), productId, icUomId); final BigDecimal stockQty = inOutLine.getMovementQty(); final StockQtyAndUOMQty deliveredQty = StockQtyAndUOMQtys .create( stockQty, productId, shippedUomQuantityInIcUOM.toBigDecimal(), shippedUomQuantityInIcUOM.getUomId()); if (inOutBL.isReturnMovementType(inOutLine.getM_InOut().getMovementType())) { return deliveredQty.negate(); } return deliveredQty; } public boolean isShipped() { return getM_InOutLine() != null; } public I_C_InvoiceCandidate_InOutLine getC_InvoiceCandidate_InOutLine() { return iciol; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\aggregator\standard\InvoiceCandidateWithInOutLine.java
1
请完成以下Java代码
public void setJobDuedate(JobDuedateDto dto) { try { ManagementService managementService = engine.getManagementService(); managementService.setJobDuedate(jobId, dto.getDuedate(), dto.isCascade()); } catch (AuthorizationException e) { throw e; } catch (ProcessEngineException e) { throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); } } @Override public void recalculateDuedate(boolean creationDateBased) { try { ManagementService managementService = engine.getManagementService(); managementService.recalculateJobDuedate(jobId, creationDateBased); } catch (AuthorizationException e) { throw e; } catch(NotFoundException e) {// rewrite status code from bad request (400) to not found (404) throw new InvalidRequestException(Status.NOT_FOUND, e, e.getMessage()); } catch (ProcessEngineException e) { throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); } } public void updateSuspensionState(JobSuspensionStateDto dto) { dto.setJobId(jobId); dto.updateSuspensionState(engine); } @Override
public void setJobPriority(PriorityDto dto) { if (dto.getPriority() == null) { throw new RestException(Status.BAD_REQUEST, "Priority for job '" + jobId + "' cannot be null."); } try { ManagementService managementService = engine.getManagementService(); managementService.setJobPriority(jobId, dto.getPriority()); } catch (AuthorizationException e) { throw e; } catch (NotFoundException e) { throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); } catch (ProcessEngineException e) { throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); } } public void deleteJob() { try { engine.getManagementService() .deleteJob(jobId); } catch (AuthorizationException e) { throw e; } catch (NullValueException e) { throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); } catch (ProcessEngineException e) { throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\JobResourceImpl.java
1
请完成以下Java代码
public class TimerIconType extends IconType { @Override public String getFillValue() { return "#585858"; } @Override public String getStrokeValue() { return "none"; } @Override public String getDValue() { return "M 10 0 C 4.4771525 0 0 4.4771525 0 10 C 0 15.522847 4.4771525 20 10 20 C 15.522847 20 20 15.522847 20 10 C 20 4.4771525 15.522847 1.1842379e-15 10 0 z M 9.09375 1.03125 C 9.2292164 1.0174926 9.362825 1.0389311 9.5 1.03125 L 9.5 3.5 L 10.5 3.5 L 10.5 1.03125 C 15.063526 1.2867831 18.713217 4.9364738 18.96875 9.5 L 16.5 9.5 L 16.5 10.5 L 18.96875 10.5 C 18.713217 15.063526 15.063526 18.713217 10.5 18.96875 L 10.5 16.5 L 9.5 16.5 L 9.5 18.96875 C 4.9364738 18.713217 1.2867831 15.063526 1.03125 10.5 L 3.5 10.5 L 3.5 9.5 L 1.03125 9.5 C 1.279102 5.0736488 4.7225326 1.4751713 9.09375 1.03125 z M 9.5 5 L 9.5 8.0625 C 8.6373007 8.2844627 8 9.0680195 8 10 C 8 11.104569 8.8954305 12 10 12 C 10.931981 12 11.715537 11.362699 11.9375 10.5 L 14 10.5 L 14 9.5 L 11.9375 9.5 C 11.756642 8.7970599 11.20294 8.2433585 10.5 8.0625 L 10.5 5 L 9.5 5 z "; } public void drawIcon( final int imageX, final int imageYo, final int iconPadding, final ProcessDiagramSVGGraphics2D svgGenerator ) { Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG); gTag.setAttributeNS(null, "transform", "translate(" + (imageX) + "," + (imageYo) + ")"); Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG); pathTag.setAttributeNS(null, "d", this.getDValue()); pathTag.setAttributeNS(null, "fill", this.getFillValue()); pathTag.setAttributeNS(null, "stroke", this.getStrokeValue()); gTag.appendChild(pathTag); svgGenerator.getExtendDOMGroupManager().addElement(gTag);
} @Override public String getAnchorValue() { return null; } @Override public String getStyleValue() { return null; } @Override public Integer getWidth() { return 20; } @Override public Integer getHeight() { return 20; } @Override public String getStrokeWidth() { return null; } }
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\TimerIconType.java
1
请在Spring Boot框架中完成以下Java代码
public class WebuiImageService { private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmmss"); private static final String EMPTY_PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; private final AdImageRepository adImageRepository; public WebuiImageService(final AdImageRepository adImageRepository) {this.adImageRepository = adImageRepository;} public WebuiImageId uploadImage(final MultipartFile file) throws IOException { final String name = file.getOriginalFilename(); final byte[] data = file.getBytes(); final String contentType = file.getContentType(); final String filenameNorm = normalizeUploadFilename(name, contentType); final MImage adImage = new MImage(Env.getCtx(), 0, ITrx.TRXNAME_None); adImage.setName(filenameNorm); adImage.setBinaryData(data); // TODO: introduce adImage.setTemporary(true); InterfaceWrapperHelper.save(adImage); return WebuiImageId.ofRepoId(adImage.getAD_Image_ID()); } @VisibleForTesting static String normalizeUploadFilename(final String name, final String contentType) { final String fileExtension = MimeType.getExtensionByType(contentType); final String nameNormalized; if (Check.isEmpty(name, true) || "blob".equals(name) // HARDCODED: this happens when the image is taken from webcam ) { nameNormalized = DATE_FORMAT.format(SystemTime.asZonedDateTime());
} else { nameNormalized = name.trim(); } return FileUtil.changeFileExtension(nameNormalized, fileExtension); } public WebuiImage getWebuiImage(@NonNull final WebuiImageId imageId, final int maxWidth, final int maxHeight) { final AdImage adImage = adImageRepository.getById(imageId.toAdImageId()); return WebuiImage.of(adImage, maxWidth, maxHeight); } public ResponseEntity<byte[]> getEmptyImage() { return ResponseEntity.status(HttpStatus.OK) .contentType(MediaType.IMAGE_PNG) .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"\"") .body(BaseEncoding.base64().decode(EMPTY_PNG_BASE64)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\upload\WebuiImageService.java
2
请在Spring Boot框架中完成以下Java代码
public class Book { @Id @GeneratedValue private Long id; private String title; @ManyToOne private Category category; public Book() { } public Book(String title) { this.title = title; } public Book(String title, Category category) { this.title = title; this.category = category; } public Long getId() { return id; }
public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-crud\src\main\java\com\baeldung\datajpadelete\entity\Book.java
2
请完成以下Java代码
public Criteria andInsertdateNotIn(List<Date> values) { addCriterion("InsertDate not in", values, "insertdate"); return (Criteria) this; } public Criteria andInsertdateBetween(Date value1, Date value2) { addCriterion("InsertDate between", value1, value2, "insertdate"); return (Criteria) this; } public Criteria andInsertdateNotBetween(Date value1, Date value2) { addCriterion("InsertDate not between", value1, value2, "insertdate"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue;
} public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\spring-boot-quick-master\quick-package-assembly\src\main\java\com\quick\entity\CityExample.java
1
请完成以下Java代码
public Optional<ReceiptScheduleId> getIdByQuery(@NonNull final ReceiptScheduleQuery query) { return buildQuery(query) .firstIdOnlyOptional(ReceiptScheduleId::ofRepoId); } @NonNull private IQuery<I_M_ReceiptSchedule> buildQuery(@NonNull final ReceiptScheduleQuery query) { final IQueryBuilder<I_M_ReceiptSchedule> builder = queryBL.createQueryBuilder(I_M_ReceiptSchedule.class) .addOnlyActiveRecordsFilter(); final ExternalSystemIdWithExternalIds externalSystemIdWithExternalIds = query.getExternalSystemIdWithExternalIds(); if (externalSystemIdWithExternalIds != null) { builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_ExternalSystem_ID, externalSystemIdWithExternalIds.getExternalSystemId().getRepoId()); final ExternalHeaderIdWithExternalLineIds externalIds = externalSystemIdWithExternalIds.getExternalHeaderIdWithExternalLineIds(); builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_ExternalHeaderId, externalIds.getExternalHeaderId().getValue()); if (!Check.isEmpty(externalIds.getExternalLineIdsAsString())) { builder.addInArrayFilter(I_M_ReceiptSchedule.COLUMNNAME_ExternalLineId, externalIds.getExternalLineIdsAsString()); } } if (query.getOrderLineId() != null) { builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_C_OrderLine_ID, query.getOrderLineId()); } if (query.getProductId() != null) { builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_M_Product_ID, query.getProductId()); } if (query.getWarehouseId() != null) { builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_M_Warehouse_ID, query.getWarehouseId()); }
if (query.getOrgId() != null) { builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_AD_Org_ID, query.getOrgId()); } if (query.getAttributesKey() != null) { builder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_M_AttributeSetInstance_ID, query.getAttributesKey().getAsString(), ASIQueryFilterModifier.instance); } // Filter by quantity if (query.isOnlyNonZeroQty()) { builder.addNotEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_QtyToMove, 0); } return builder.create(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptScheduleDAO.java
1
请完成以下Java代码
public WFActivityType getHandledActivityType() { return HANDLED_ACTIVITY_TYPE; } @Override public UIComponent getUIComponent( final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts) { return UserConfirmationSupportUtil.createUIComponent( UserConfirmationSupportUtil.UIComponentProps.builderFrom(wfActivity) .question(getQuestion(wfProcess, jsonOpts.getAdLanguage())) .build()); } @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity completePickingWFActivity) { final PickingJob pickingJob = getPickingJob(wfProcess); return computeActivityState(pickingJob); } public static WFActivityStatus computeActivityState(final PickingJob pickingJob) { return pickingJob.getDocStatus().isCompleted() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } @Override public WFProcess userConfirmed(final UserConfirmationRequest request) { request.getWfActivity().getWfActivityType().assertExpected(HANDLED_ACTIVITY_TYPE); return PickingMobileApplication.mapPickingJob( request.getWfProcess(), pickingJobRestService::complete );
} private String getQuestion(@NonNull final WFProcess wfProcess, @NonNull final String language) { final PickingJob pickingJob = wfProcess.getDocumentAs(PickingJob.class); if (pickingJob.getProgress().isDone()) { return msgBL.getMsg(language, ARE_YOU_SURE); } final PickingJobOptions options = pickingJobRestService.getPickingJobOptions(pickingJob.getCustomerId()); if (!options.isAllowCompletingPartialPickingJob()) { return msgBL.getMsg(language, ARE_YOU_SURE); } return msgBL.getMsg(language, NOT_ALL_LINES_ARE_COMPLETED_WARNING); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\CompletePickingWFActivityHandler.java
1
请完成以下Java代码
public Object getValue() { return variableValue; } @Override public void setValue(Object value) { variableValue = value; } @Override public String getTypeName() { return TYPE_TRANSIENT; } @Override public void setTypeName(String typeName) {}
@Override public String getProcessInstanceId() { return null; } @Override public String getTaskId() { return null; } @Override public void setTaskId(String taskId) {} @Override public String getExecutionId() { return null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TransientVariableInstance.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("values", values) .add("error", error) .add("properties", otherProperties == null || otherProperties.isEmpty() ? null : otherProperties) .toString(); } public List<JSONLookupValue> getValues() { return values; } @JsonAnyGetter public Map<String, Object> getOtherProperties() { return otherProperties == null ? ImmutableMap.of() : otherProperties; } @JsonAnySetter public void putOtherProperty(final String name, final String jsonValue) { if (otherProperties == null) { otherProperties = new LinkedHashMap<>();
} otherProperties.put(name, jsonValue); } @JsonSetter public JSONLookupValuesList setDefaultId(final String defaultId) { this.defaultId = defaultId; return this; } public String getDefaultId() { return defaultId; } @Nullable public JsonErrorItem getError() { return error; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONLookupValuesList.java
1
请完成以下Java代码
protected final boolean setRowValueOrNull(final IRModelMetadata metadata, final List<Object> row, final String columnName, final Object value) { final int columnIndex = metadata.getRColumnIndex(columnName); if (columnIndex < 0) { return false; } if (columnIndex >= row.size()) { return false; } row.set(columnIndex, value); return true; } protected final Object getRowValueOrNull(final IRModelMetadata metadata, final List<Object> row, final String columnName) { if (row == null) { return null; } final int columnIndex = metadata.getRColumnIndex(columnName); if (columnIndex < 0) { return null; } if (columnIndex >= row.size()) { return null; } final Object value = row.get(columnIndex); return value; } protected final <T> T getRowValueOrNull(final IRModelMetadata metadata, final List<Object> row, final String columnName, final Class<T> valueClass) { final Object valueObj = getRowValueOrNull(metadata, row, columnName); if (valueObj == null) { return null; } if (!valueClass.isAssignableFrom(valueObj.getClass())) { return null; } final T value = valueClass.cast(valueObj);
return value; } /** * * @param calculationCtx * @param columnName * @return true if the status of current calculation is about calculating the row for "columnName" group (subtotals) */ protected final boolean isGroupBy(final RModelCalculationContext calculationCtx, final String columnName) { final int groupColumnIndex = calculationCtx.getGroupColumnIndex(); if (groupColumnIndex < 0) { // no grouping return false; } final IRModelMetadata metadata = calculationCtx.getMetadata(); final int columnIndex = metadata.getRColumnIndex(columnName); if (columnIndex < 0) { return false; } return columnIndex == groupColumnIndex; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\compiere\report\core\AbstractRModelAggregatedValue.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((country == null) ? 0 : country.hashCode()); result = prime * result + ((genre == null) ? 0 : genre.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj)
return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Artist other = (Artist) obj; if (country == null) { if (other.country != null) return false; } else if (!country.equals(other.country)) return false; if (genre == null) { if (other.genre != null) return false; } else if (!genre.equals(other.genre)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
repos\tutorials-master\persistence-modules\hibernate-libraries\src\main\java\com\baeldung\hibernate\types\Artist.java
1
请完成以下Java代码
public class XssFilter implements Filter { /** * excludes link */ List<String> excludes = new ArrayList<String>(); /** * xss filter switch */ public boolean enabled = false; @Override public void init(FilterConfig filterConfig) throws ServletException { String tempExcludes = filterConfig.getInitParameter("excludes"); String tempEnabled = filterConfig.getInitParameter("enabled"); if (StringUtils.isNotEmpty(tempExcludes)) { String[] url = tempExcludes.split(","); for (int i = 0; url != null && i < url.length; i++) { excludes.add(url[i]); } } if (StringUtils.isNotEmpty(tempEnabled)) { enabled = Boolean.valueOf(tempEnabled); } } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; if (handleExcludeURL(req, resp)) { chain.doFilter(request, response);
return; } XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request); chain.doFilter(xssRequest, response); } private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) { if (!enabled) { return true; } if (excludes == null || excludes.isEmpty()) { return false; } String url = request.getServletPath(); for (String pattern : excludes) { Pattern p = Pattern.compile("^" + pattern); Matcher m = p.matcher(url); if (m.find()) { return true; } } return false; } @Override public void destroy() { } }
repos\springboot-demo-master\xss\src\main\java\com\et\filter\XssFilter.java
1
请完成以下Java代码
public int getAD_Client_ID() { return orderLine.getAD_Client_ID(); } @Override public int getAD_Org_ID() { return orderLine.getAD_Org_ID(); } @Override public boolean isSOTrx() { final I_C_Order order = getOrder(); return order.isSOTrx(); } @Override
public I_C_BPartner getC_BPartner() { final I_C_Order order = getOrder(); return InterfaceWrapperHelper.create(Services.get(IOrderBL.class).getBPartnerOrNull(order), I_C_BPartner.class); } private I_C_Order getOrder() { final I_C_Order order = orderLine.getC_Order(); if (order == null) { throw new AdempiereException("Order not set for" + orderLine); } return order; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\OrderLineBPartnerAware.java
1
请完成以下Java代码
private void commitTransactionIfNeeded(EntityTransaction newTransaction) { if (newTransaction != null && newTransaction.isActive()) { if (!newTransaction.getRollbackOnly()) { newTransaction.commit(); } } } private void saveUsingManualTransaction(InvoiceEntity invoiceEntity, EntityManager em) { if (invoiceEntity.getId() == null) { em.persist(invoiceEntity); } else { em.merge(invoiceEntity); } em.flush(); logger.info("Entity is saved: {}", invoiceEntity.getSerialNumber()); } private EntityManager em() { return entityManagerFactory.createEntityManager();
} @Transactional public void saveBatchOnly(List<InvoiceEntity> testEntities) { testEntities.forEach(entityManager::persist); entityManager.flush(); } public List<InvoiceEntity> findAll() { TypedQuery<InvoiceEntity> query = entityManager.createQuery("SELECT i From InvoiceEntity i", InvoiceEntity.class); return query.getResultList(); } @Transactional public void deleteAll() { Query query = entityManager.createQuery("DELETE FROM InvoiceEntity"); query.executeUpdate(); } }
repos\tutorials-master\persistence-modules\spring-jpa-3\src\main\java\com\baeldung\continuetransactionafterexception\InvoiceRepository.java
1
请完成以下Java代码
public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) { this.authoritiesMapper = authoritiesMapper; } private class DefaultPreAuthenticationChecks implements UserDetailsChecker { @Override public void check(UserDetails user) { if (!user.isAccountNonLocked()) { AbstractUserDetailsAuthenticationProvider.this.logger .debug("Failed to authenticate since user account is locked"); throw new LockedException(AbstractUserDetailsAuthenticationProvider.this.messages .getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked")); } if (!user.isEnabled()) { AbstractUserDetailsAuthenticationProvider.this.logger .debug("Failed to authenticate since user account is disabled"); throw new DisabledException(AbstractUserDetailsAuthenticationProvider.this.messages .getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled")); } if (!user.isAccountNonExpired()) { AbstractUserDetailsAuthenticationProvider.this.logger .debug("Failed to authenticate since user account has expired"); throw new AccountExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages .getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired")); } } } private class DefaultPostAuthenticationChecks implements UserDetailsChecker {
@Override public void check(UserDetails user) { if (!user.isCredentialsNonExpired()) { AbstractUserDetailsAuthenticationProvider.this.logger .debug("Failed to authenticate since user account credentials have expired"); throw new CredentialsExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages .getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired", "User credentials have expired")); } } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\dao\AbstractUserDetailsAuthenticationProvider.java
1
请完成以下Java代码
public static void writeCase(CmmnModel model, Case caseModel, XMLStreamWriter xtw) throws Exception { xtw.writeStartElement(ELEMENT_CASE); xtw.writeAttribute(ATTRIBUTE_ID, caseModel.getId()); if (StringUtils.isNotEmpty(caseModel.getName())) { xtw.writeAttribute(ATTRIBUTE_NAME, caseModel.getName()); } if (StringUtils.isNotEmpty(caseModel.getInitiatorVariableName())) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_INITIATOR_VARIABLE_NAME, caseModel.getInitiatorVariableName()); } if (!caseModel.getCandidateStarterUsers().isEmpty()) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_CASE_CANDIDATE_USERS, CmmnXmlUtil.convertToDelimitedString(caseModel.getCandidateStarterUsers())); } if (!caseModel.getCandidateStarterGroups().isEmpty()) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_CASE_CANDIDATE_GROUPS, CmmnXmlUtil.convertToDelimitedString(caseModel.getCandidateStarterGroups())); } if (caseModel.isAsync()) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_IS_ASYNCHRONOUS, "true"); }
if (StringUtils.isNotEmpty(caseModel.getDocumentation())) { xtw.writeStartElement(ELEMENT_DOCUMENTATION); xtw.writeCharacters(caseModel.getDocumentation()); xtw.writeEndElement(); } if (StringUtils.isNotEmpty(caseModel.getStartEventType()) && caseModel.getExtensionElements().get("eventType") == null) { ExtensionElement extensionElement = new ExtensionElement(); extensionElement.setNamespace(FLOWABLE_EXTENSIONS_NAMESPACE); extensionElement.setNamespacePrefix(FLOWABLE_EXTENSIONS_PREFIX); extensionElement.setName("eventType"); extensionElement.setElementText(caseModel.getStartEventType()); caseModel.addExtensionElement(extensionElement); } boolean didWriteExtensionStartElement = CmmnXmlUtil.writeExtensionElements(caseModel, false, model.getNamespaces(), xtw); didWriteExtensionStartElement = FlowableListenerExport.writeFlowableListeners(xtw, CmmnXmlConstants.ELEMENT_CASE_LIFECYCLE_LISTENER, caseModel.getLifecycleListeners(), didWriteExtensionStartElement); if (didWriteExtensionStartElement) { xtw.writeEndElement(); } } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\CaseExport.java
1
请完成以下Java代码
public int hashCode() { if (m_value == null) return m_columnName.hashCode(); return m_columnName.hashCode() + m_value.hashCode(); } // hashCode /** * Equals * @param compare compare object * @return true if equals */ public boolean equals (Object compare) { if (compare instanceof PrintDataElement) { PrintDataElement pde = (PrintDataElement)compare; if (pde.getColumnName().equals(m_columnName)) { if (pde.getValue() != null && pde.getValue().equals(m_value)) return true; if (pde.getValue() == null && m_value == null) return true; } } return false; } // equals /** * String representation * @return info */ public String toString() { StringBuffer sb = new StringBuffer(m_columnName).append("=").append(m_value); if (m_isPKey) sb.append("(PK)"); return sb.toString(); } // toString /** * Value Has Key * @return true if value has a key */ public boolean hasKey() { return m_value instanceof NamePair;
} // hasKey /** * String representation with key info * @return info */ public String toStringX() { if (m_value instanceof NamePair) { NamePair pp = (NamePair)m_value; StringBuffer sb = new StringBuffer(m_columnName); sb.append("(").append(pp.getID()).append(")") .append("=").append(pp.getName()); if (m_isPKey) sb.append("(PK)"); return sb.toString(); } else return toString(); } // toStringX public String getM_formatPattern() { return m_formatPattern; } public void setM_formatPattern(String pattern) { m_formatPattern = pattern; } } // PrintDataElement
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataElement.java
1
请完成以下Java代码
public String getAppliesOnlyToTableName() { return appliesOnTableName; } @Override public @NonNull ViewHeaderProperties computeHeaderProperties(@NonNull final IView view) { ViewHeaderProperties result = ViewHeaderProperties.EMPTY; for (final ViewHeaderPropertiesProvider provider : providers) { final ViewHeaderProperties properties = provider.computeHeaderProperties(view); result = result.combine(properties); } return result; } @Override public ViewHeaderPropertiesIncrementalResult computeIncrementallyOnRowsChanged( @NonNull final ViewHeaderProperties currentHeaderProperties, @NonNull final IView view, @NonNull final Set<DocumentId> changedRowIds, final boolean watchedByFrontend) { ViewHeaderProperties computedHeaderProperties = currentHeaderProperties; for (final ViewHeaderPropertiesProvider provider : providers) { final ViewHeaderPropertiesIncrementalResult partialResult = provider.computeIncrementallyOnRowsChanged( computedHeaderProperties, view, changedRowIds, watchedByFrontend);
if (partialResult.isComputed()) { computedHeaderProperties = partialResult.getComputeHeaderProperties(); } else if (partialResult.isFullRecomputeRequired()) { return ViewHeaderPropertiesIncrementalResult.fullRecomputeRequired(); } else { throw new AdempiereException("Unknow partial result type: " + partialResult); } } return ViewHeaderPropertiesIncrementalResult.computed(computedHeaderProperties); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\CompositeViewHeaderPropertiesProvider.java
1
请完成以下Java代码
public Collection<MultiValuePart> getMultiValueParts() { return multiValueParts; } public void addMultiValuePart(MultiValuePart part) { if (body != null) { throw new FlowableIllegalStateException("Cannot set both body and multi value parts"); } else if (formParameters != null && !formParameters.isEmpty()) { throw new FlowableIllegalStateException("Cannot set both form parameters and multi value parts"); } if (multiValueParts == null) { multiValueParts = new ArrayList<>(); } multiValueParts.add(part); } public Map<String, List<String>> getFormParameters() { return formParameters; } public void addFormParameter(String key, String value) { if (body != null) { throw new FlowableIllegalStateException("Cannot set both body and form parameters"); } else if (multiValueParts != null && !multiValueParts.isEmpty()) { throw new FlowableIllegalStateException("Cannot set both multi value parts and form parameters"); } if (formParameters == null) { formParameters = new LinkedHashMap<>(); } formParameters.computeIfAbsent(key, k -> new ArrayList<>()).add(value); } public int getTimeout() {
return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public boolean isNoRedirects() { return noRedirects; } public void setNoRedirects(boolean noRedirects) { this.noRedirects = noRedirects; } }
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\api\HttpRequest.java
1
请在Spring Boot框架中完成以下Java代码
public String getTransportVehicleLicenseNumber() { return transportVehicleLicenseNumber; } /** * Sets the value of the transportVehicleLicenseNumber property. * * @param value * allowed object is * {@link String } * */ public void setTransportVehicleLicenseNumber(String value) { this.transportVehicleLicenseNumber = value; } /** * Gets the value of the deliveryDetailsExtension property. * * @return * possible object is * {@link DeliveryDetailsExtensionType }
* */ public DeliveryDetailsExtensionType getDeliveryDetailsExtension() { return deliveryDetailsExtension; } /** * Sets the value of the deliveryDetailsExtension property. * * @param value * allowed object is * {@link DeliveryDetailsExtensionType } * */ public void setDeliveryDetailsExtension(DeliveryDetailsExtensionType value) { this.deliveryDetailsExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DeliveryDetailsType.java
2
请完成以下Java代码
public int getPO_PaymentTerm_ID() { return get_ValueAsInt(COLUMNNAME_PO_PaymentTerm_ID); } @Override public void setPO_PricingSystem_ID (final int PO_PricingSystem_ID) { if (PO_PricingSystem_ID < 1) set_Value (COLUMNNAME_PO_PricingSystem_ID, null); else set_Value (COLUMNNAME_PO_PricingSystem_ID, PO_PricingSystem_ID); } @Override public int getPO_PricingSystem_ID() { return get_ValueAsInt(COLUMNNAME_PO_PricingSystem_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed);
} @Override public void setReferrer (final @Nullable java.lang.String Referrer) { set_Value (COLUMNNAME_Referrer, Referrer); } @Override public java.lang.String getReferrer() { return get_ValueAsString(COLUMNNAME_Referrer); } @Override public void setVATaxID (final @Nullable java.lang.String VATaxID) { set_Value (COLUMNNAME_VATaxID, VATaxID); } @Override public java.lang.String getVATaxID() { return get_ValueAsString(COLUMNNAME_VATaxID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_QuickInput.java
1
请完成以下Java代码
protected BatchElementConfiguration collectExternalTaskIds(CommandContext commandContext) { BatchElementConfiguration elementConfiguration = new BatchElementConfiguration(); List<String> externalTaskIds = builder.getExternalTaskIds(); if (!CollectionUtil.isEmpty(externalTaskIds)) { ensureNotContainsNull(BadUserRequestException.class, "External task id cannot be null", "externalTaskIds", externalTaskIds); ExternalTaskQueryImpl taskQuery = new ExternalTaskQueryImpl(); taskQuery.externalTaskIdIn(new HashSet<>(externalTaskIds)); elementConfiguration.addDeploymentMappings(commandContext.runWithoutAuthorization( taskQuery::listDeploymentIdMappings), externalTaskIds); } ExternalTaskQueryImpl externalTaskQuery = (ExternalTaskQueryImpl) builder.getExternalTaskQuery(); if (externalTaskQuery != null) { elementConfiguration.addDeploymentMappings(externalTaskQuery.listDeploymentIdMappings()); } final List<String> collectedProcessInstanceIds = collectProcessInstanceIds(); if (!collectedProcessInstanceIds.isEmpty()) { ExternalTaskQueryImpl query = new ExternalTaskQueryImpl(); query.processInstanceIdIn(collectedProcessInstanceIds.toArray(new String[0])); elementConfiguration.addDeploymentMappings(commandContext.runWithoutAuthorization(query::listDeploymentIdMappings)); } return elementConfiguration; }
protected void writeUserOperationLog(CommandContext commandContext, int numInstances, boolean async) { List<PropertyChange> propertyChanges = new ArrayList<>(); propertyChanges.add(new PropertyChange("nrOfInstances", null, numInstances)); propertyChanges.add(new PropertyChange("async", null, async)); propertyChanges.add(new PropertyChange("retries", null, builder.getRetries())); commandContext.getOperationLogManager().logExternalTaskOperation( UserOperationLogEntry.OPERATION_TYPE_SET_EXTERNAL_TASK_RETRIES, null, propertyChanges); } protected void writeUserOperationLogAsync(CommandContext commandContext, int numInstances) { writeUserOperationLog(commandContext, numInstances, true); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractSetExternalTaskRetriesCmd.java
1
请完成以下Java代码
public ByteArrayEntity getContent() { return content; } public void setContent(ByteArrayEntity content) { this.content = content; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime;
} public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", name=" + name + ", description=" + description + ", type=" + type + ", taskId=" + taskId + ", processInstanceId=" + processInstanceId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + ", url=" + url + ", contentId=" + contentId + ", content=" + content + ", tenantId=" + tenantId + ", createTime=" + createTime + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AttachmentEntity.java
1
请在Spring Boot框架中完成以下Java代码
public JAXBElement<String> createZIP(String value) { return new JAXBElement<String>(_ZIP_QNAME, String.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link String }{@code >} */ @XmlElementDecl(namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact", name = "PointOfSales", scope = SLSRPTExtensionType.class) public JAXBElement<String> createSLSRPTExtensionTypePointOfSales(String value) { return new JAXBElement<String>(_SLSRPTExtensionTypePointOfSales_QNAME, String.class, SLSRPTExtensionType.class, value); }
/** * Create an instance of {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} */ @XmlElementDecl(namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact", name = "SalesDate", scope = SLSRPTExtensionType.class) public JAXBElement<XMLGregorianCalendar> createSLSRPTExtensionTypeSalesDate(XMLGregorianCalendar value) { return new JAXBElement<XMLGregorianCalendar>(_SLSRPTExtensionTypeSalesDate_QNAME, XMLGregorianCalendar.class, SLSRPTExtensionType.class, value); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ObjectFactory.java
2
请完成以下Java代码
public static TUPickingTarget ofPackingInstructions(@NonNull final HuPackingInstructionsId tuPIId, @NonNull final String caption) { return builder().tuPIId(tuPIId).caption(caption).build(); } public static TUPickingTarget ofExistingHU(@NonNull final HuId luId, @NonNull final HUQRCode qrCode) { return builder().tuId(luId).tuQRCode(qrCode).caption(qrCode.toDisplayableQRCode()).build(); } public boolean isExistingTU() { return tuId != null; } public boolean isNewTU()
{ return tuId == null && tuPIId != null; } public HuPackingInstructionsId getTuPIIdNotNull() { return Check.assumeNotNull(tuPIId, "TU PI shall be set for {}", this); } public HuId getTuIdNotNull() { return Check.assumeNotNull(tuId, "TU shall be set for {}", this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\TUPickingTarget.java
1
请完成以下Java代码
public void invalidateByRecord(final TableRecordReference recordRef) { final String tableName = recordRef.getTableName(); final int recordId = recordRef.getRecord_ID(); // // Get table's cache map. final IDCache<PO> cache = getByTableNameIfExists(tableName); if (cache == null) { return; } // Invalidate the cache final boolean invalidated = cache.remove(recordId) != null; // Logging if (invalidated && logger.isTraceEnabled()) { logger.trace("Model removed from cache {}: record={}/{}, trx={} ", cache.getCacheName(), tableName, recordId, trxName); } } public void put(@NonNull final PO po, @NonNull final ITableCacheConfig cacheConfig) { // // Get table's cache map. // If does not exist, create one. final IDCache<PO> cache = getByTableNameOrCreate(cacheConfig); //
// Add our PO to cache final int recordId = po.get_ID(); final PO poCopy = copyPO(po, trxName); if (poCopy == null) { logger.warn("Failed to add {} to cache because copy failed. Ignored.", po); return; } cache.put(recordId, poCopy); // Logging if (logger.isTraceEnabled()) { logger.trace("Model added to cache {}: {} ", cache.getCacheName(), poCopy); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\ModelCacheService.java
1
请完成以下Java代码
public List<String> getEvenIndexedStringsVersionTwo(List<String> names) { List<String> evenIndexedNames = EntryStream.of(names) .filterKeyValue((index, name) -> index % 2 == 0) .values() .toList(); return evenIndexedNames; } public static List<Indexed<String>> getEvenIndexedStrings(List<String> names) { List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream()) .filter(i -> i.getIndex() % 2 == 0) .collect(Collectors.toList()); return list; } public static List<Indexed<String>> getOddIndexedStrings(List<String> names) { List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream()) .filter(i -> i.getIndex() % 2 == 1) .collect(Collectors.toList()); return list; } public static List<String> getOddIndexedStrings(String[] names) { List<String> oddIndexedNames = IntStream.range(0, names.length) .filter(i -> i % 2 == 1) .mapToObj(i -> names[i]) .collect(Collectors.toList()); return oddIndexedNames; }
public static List<String> getOddIndexedStringsVersionTwo(String[] names) { List<String> oddIndexedNames = Stream.of(names) .zipWithIndex() .filter(tuple -> tuple._2 % 2 == 1) .map(tuple -> tuple._1) .toJavaList(); return oddIndexedNames; } public static List<String> getEvenIndexedStringsUsingAtomicInteger(String[] names) { AtomicInteger index = new AtomicInteger(0); return Arrays.stream(names) .filter(name -> index.getAndIncrement() % 2 == 0) .collect(Collectors.toList()); } public static List<String> getEvenIndexedStringsAtomicIntegerParallel(String[] names) { AtomicInteger index = new AtomicInteger(0); return Arrays.stream(names) .parallel() .filter(name -> index.getAndIncrement() % 2 == 0) .collect(Collectors.toList()); } }
repos\tutorials-master\core-java-modules\core-java-streams\src\main\java\com\baeldung\stream\StreamIndices.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @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 setIsDefaultForPicking (final boolean IsDefaultForPicking) { set_Value (COLUMNNAME_IsDefaultForPicking, IsDefaultForPicking); } @Override public boolean isDefaultForPicking() { return get_ValueAsBoolean(COLUMNNAME_IsDefaultForPicking); } @Override public void setIsDefaultLU (final boolean IsDefaultLU) { set_Value (COLUMNNAME_IsDefaultLU, IsDefaultLU); } @Override public boolean isDefaultLU() { return get_ValueAsBoolean(COLUMNNAME_IsDefaultLU); } @Override public void setM_HU_PI_ID (final int M_HU_PI_ID) { if (M_HU_PI_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, null); else
set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, M_HU_PI_ID); } @Override public int getM_HU_PI_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI.java
1
请完成以下Java代码
public static CmmnCaseDefinition getCaseDefinitionToCall(VariableScope execution, String defaultTenantId, BaseCallableElement callableElement) { String caseDefinitionKey = callableElement.getDefinitionKey(execution); String tenantId = callableElement.getDefinitionTenantId(execution, defaultTenantId); DeploymentCache deploymentCache = getDeploymentCache(); CmmnCaseDefinition caseDefinition = null; if (callableElement.isLatestBinding()) { caseDefinition = deploymentCache.findDeployedLatestCaseDefinitionByKeyAndTenantId(caseDefinitionKey, tenantId); } else if (callableElement.isDeploymentBinding()) { String deploymentId = callableElement.getDeploymentId(); caseDefinition = deploymentCache.findDeployedCaseDefinitionByDeploymentAndKey(deploymentId, caseDefinitionKey); } else if (callableElement.isVersionBinding()) { Integer version = callableElement.getVersion(execution); caseDefinition = deploymentCache.findDeployedCaseDefinitionByKeyVersionAndTenantId(caseDefinitionKey, version, tenantId); } return caseDefinition; } public static DecisionDefinition getDecisionDefinitionToCall(VariableScope execution, String defaultTenantId, BaseCallableElement callableElement) { String decisionDefinitionKey = callableElement.getDefinitionKey(execution); String tenantId = callableElement.getDefinitionTenantId(execution, defaultTenantId);
DeploymentCache deploymentCache = getDeploymentCache(); DecisionDefinition decisionDefinition = null; if (callableElement.isLatestBinding()) { decisionDefinition = deploymentCache.findDeployedLatestDecisionDefinitionByKeyAndTenantId(decisionDefinitionKey, tenantId); } else if (callableElement.isDeploymentBinding()) { String deploymentId = callableElement.getDeploymentId(); decisionDefinition = deploymentCache.findDeployedDecisionDefinitionByDeploymentAndKey(deploymentId, decisionDefinitionKey); } else if (callableElement.isVersionBinding()) { Integer version = callableElement.getVersion(execution); decisionDefinition = deploymentCache.findDeployedDecisionDefinitionByKeyVersionAndTenantId(decisionDefinitionKey, version, tenantId); } else if (callableElement.isVersionTagBinding()) { String versionTag = callableElement.getVersionTag(execution); decisionDefinition = deploymentCache.findDeployedDecisionDefinitionByKeyVersionTagAndTenantId(decisionDefinitionKey, versionTag, tenantId); } return decisionDefinition; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\CallableElementUtil.java
1
请完成以下Java代码
public class DmnExpressionTransformHelper { public static DmnTypeDefinition createTypeDefinition(DmnElementTransformContext context, LiteralExpression expression) { return createTypeDefinition(context, expression.getTypeRef()); } public static DmnTypeDefinition createTypeDefinition(DmnElementTransformContext context, InformationItem informationItem) { return createTypeDefinition(context, informationItem.getTypeRef()); } protected static DmnTypeDefinition createTypeDefinition(DmnElementTransformContext context, String typeRef) { if (typeRef != null) { DmnDataTypeTransformer transformer = context.getDataTypeTransformerRegistry().getTransformer(typeRef); return new DmnTypeDefinitionImpl(typeRef, transformer); } else { return new DefaultTypeDefinition(); } } public static String getExpressionLanguage(DmnElementTransformContext context, LiteralExpression expression) { return getExpressionLanguage(context, expression.getExpressionLanguage()); } public static String getExpressionLanguage(DmnElementTransformContext context, UnaryTests expression) { return getExpressionLanguage(context, expression.getExpressionLanguage()); } protected static String getExpressionLanguage(DmnElementTransformContext context, String expressionLanguage) { if (expressionLanguage != null) { return expressionLanguage; } else { return getGlobalExpressionLanguage(context); } } protected static String getGlobalExpressionLanguage(DmnElementTransformContext context) { String expressionLanguage = context.getModelInstance().getDefinitions().getExpressionLanguage(); if (!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE.equals(expressionLanguage) && !DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN12.equals(expressionLanguage) && !DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN13.equals(expressionLanguage) && !DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN14.equals(expressionLanguage) && !DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN15.equals(expressionLanguage)) { return expressionLanguage; } else { return null;
} } public static String getExpression(LiteralExpression expression) { return getExpression(expression.getText()); } public static String getExpression(UnaryTests expression) { return getExpression(expression.getText()); } protected static String getExpression(Text text) { if (text != null) { String textContent = text.getTextContent(); if (textContent != null && !textContent.isEmpty()) { return textContent; } } return null; } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\transform\DmnExpressionTransformHelper.java
1
请完成以下Java代码
public String getNote () { return (String)get_Value(COLUMNNAME_Note); } /** Set Achievement. @param PA_Achievement_ID Performance Achievement */ public void setPA_Achievement_ID (int PA_Achievement_ID) { if (PA_Achievement_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Achievement_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Achievement_ID, Integer.valueOf(PA_Achievement_ID)); } /** Get Achievement. @return Performance Achievement */ public int getPA_Achievement_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Achievement_ID); if (ii == null) return 0; return ii.intValue(); } public I_PA_Measure getPA_Measure() throws RuntimeException { return (I_PA_Measure)MTable.get(getCtx(), I_PA_Measure.Table_Name) .getPO(getPA_Measure_ID(), get_TrxName()); } /** Set Measure. @param PA_Measure_ID Concrete Performance Measurement */ public void setPA_Measure_ID (int PA_Measure_ID) { if (PA_Measure_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID)); } /** Get Measure. @return Concrete Performance Measurement
*/ public int getPA_Measure_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Achievement.java
1
请在Spring Boot框架中完成以下Java代码
public final void addParts(final PackingItemParts toAdd) { final boolean removeExistingOnes = false; addParts(toAdd, removeExistingOnes); } private final void addParts( @NonNull final PackingItemParts partsToAdd, final boolean removeExistingOnes) { partsToAdd.forEach(this::assertCanAddPart); // NOTE: we remove existing ones AFTER we validate because "canAddSchedule" always returns true in case there are no schedules if (removeExistingOnes) { parts.clear(); } parts.addQtys(partsToAdd); } @Override public final void addParts(final IPackingItem packingItem) { addParts(packingItem.getParts()); } @Override public final IPackingItem addPartsAndReturn(final IPackingItem packingItem) { addParts(packingItem.getParts()); return this; } @Override public final void setPartsFrom(final IPackingItem packingItem) { final PackingItemParts toAdd = packingItem.getParts(); final boolean removeExistingOnes = true; addParts(toAdd, removeExistingOnes); } private final void assertCanAddPart(final PackingItemPart part) { if (parts.isEmpty()) { return; } if (!PackingItemGroupingKey.equals(groupingKey, computeGroupingKey(part))) { throw new AdempiereException(part + " can't be added to " + this); } } @Override public final PackingItemGroupingKey getGroupingKey() { return groupingKey; } @Override public final ProductId getProductId() { return groupingKey.getProductId(); } @Override public final I_C_UOM getC_UOM() { return uom; } @Override public boolean isSameAs(final IPackingItem item) {
return Util.same(this, item); } @Override public BPartnerId getBPartnerId() { return getBPartnerLocationId().getBpartnerId(); } @Override public BPartnerLocationId getBPartnerLocationId() { return groupingKey.getBpartnerLocationId(); } @Override public HUPIItemProductId getPackingMaterialId() { return groupingKey.getPackingMaterialId(); } @Override public Set<WarehouseId> getWarehouseIds() { return parts.map(PackingItemPart::getWarehouseId).collect(ImmutableSet.toImmutableSet()); } @Override public Set<ShipmentScheduleId> getShipmentScheduleIds() { return parts.map(PackingItemPart::getShipmentScheduleId).collect(ImmutableSet.toImmutableSet()); } @Override public IPackingItem subtractToPackingItem( @NonNull final Quantity subtrahent, @Nullable final Predicate<PackingItemPart> acceptPartPredicate) { final PackingItemParts subtractedParts = subtract(subtrahent, acceptPartPredicate); return PackingItems.newPackingItem(subtractedParts); } @Override public PackingItem copy() { return new PackingItem(this); } @Override public String toString() { return "FreshPackingItem [" + "qtySum=" + getQtySum() + ", productId=" + getProductId() + ", uom=" + getC_UOM() + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\PackingItem.java
2
请完成以下Java代码
public boolean isNavigateToJobsListAfterPickFromComplete() { return get_ValueAsBoolean(COLUMNNAME_IsNavigateToJobsListAfterPickFromComplete); } @Override public void setIsRequireScanningProductCode (final boolean IsRequireScanningProductCode) { set_Value (COLUMNNAME_IsRequireScanningProductCode, IsRequireScanningProductCode); } @Override public boolean isRequireScanningProductCode() { return get_ValueAsBoolean(COLUMNNAME_IsRequireScanningProductCode); } @Override public void setIsRequireTrolley (final boolean IsRequireTrolley) { set_Value (COLUMNNAME_IsRequireTrolley, IsRequireTrolley); } @Override public boolean isRequireTrolley() { return get_ValueAsBoolean(COLUMNNAME_IsRequireTrolley); } @Override public void setMaxLaunchers (final int MaxLaunchers) { set_Value (COLUMNNAME_MaxLaunchers, MaxLaunchers); } @Override public int getMaxLaunchers() { return get_ValueAsInt(COLUMNNAME_MaxLaunchers); } @Override public void setMaxStartedLaunchers (final int MaxStartedLaunchers)
{ set_Value (COLUMNNAME_MaxStartedLaunchers, MaxStartedLaunchers); } @Override public int getMaxStartedLaunchers() { return get_ValueAsInt(COLUMNNAME_MaxStartedLaunchers); } @Override public void setMobileUI_UserProfile_DD_ID (final int MobileUI_UserProfile_DD_ID) { if (MobileUI_UserProfile_DD_ID < 1) set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_DD_ID, null); else set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_DD_ID, MobileUI_UserProfile_DD_ID); } @Override public int getMobileUI_UserProfile_DD_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_DD_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_DD.java
1
请在Spring Boot框架中完成以下Java代码
public List<RestIdentityLink> getIdentityLinks(@ApiParam(name = "caseDefinitionId") @PathVariable String caseDefinitionId) { CaseDefinition caseDefinition = getCaseDefinitionFromRequestWithoutAccessCheck(caseDefinitionId); if (restApiInterceptor != null) { restApiInterceptor.accessCaseDefinitionIdentityLinks(caseDefinition); } return restResponseFactory.createRestIdentityLinks(repositoryService.getIdentityLinksForCaseDefinition(caseDefinition.getId())); } @ApiOperation(value = "Add a candidate starter to a case definition", tags = { "Case Definitions" }, notes = "It is possible to add either a user or a group.", code = 201) @ApiResponses(value = { @ApiResponse(code = 201, message = "Indicates the case definition was found and the identity link was created."), @ApiResponse(code = 400, message = "Indicates the body does not contain the correct information."), @ApiResponse(code = 404, message = "Indicates the requested case definition was not found.") }) @PostMapping(value = "/cmmn-repository/case-definitions/{caseDefinitionId}/identitylinks", produces = "application/json") @ResponseStatus(HttpStatus.CREATED) public RestIdentityLink createIdentityLink(@ApiParam(name = "caseDefinitionId") @PathVariable String caseDefinitionId, @RequestBody RestIdentityLink identityLink) { CaseDefinition caseDefinition = getCaseDefinitionFromRequestWithoutAccessCheck(caseDefinitionId); if (identityLink.getGroup() == null && identityLink.getUser() == null) { throw new FlowableIllegalArgumentException("A group or a user is required to create an identity link.");
} if (identityLink.getGroup() != null && identityLink.getUser() != null) { throw new FlowableIllegalArgumentException("Only one of user or group can be used to create an identity link."); } if (restApiInterceptor != null) { restApiInterceptor.createCaseDefinitionIdentityLink(caseDefinition, identityLink); } if (identityLink.getGroup() != null) { repositoryService.addCandidateStarterGroup(caseDefinition.getId(), identityLink.getGroup()); } else { repositoryService.addCandidateStarterUser(caseDefinition.getId(), identityLink.getUser()); } // Always candidate for case definition. User-provided value is ignored identityLink.setType(IdentityLinkType.CANDIDATE); return restResponseFactory.createRestIdentityLink(identityLink.getType(), identityLink.getUser(), identityLink.getGroup(), null, caseDefinition.getId(), null); } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\CaseDefinitionIdentityLinkCollectionResource.java
2
请完成以下Java代码
public boolean deploy (MMedia[] media) { // i don't want an outdated commons-net version in our dependencies just so that this unused feature compiles without errors throw new UnsupportedOperationException("This method is currently not implemented"); // @formatter:off // // Check whether the host is our example localhost, we will not deploy locally, but this is no error // if (this.getIP_Address().equals("127.0.0.1") || this.getName().equals("localhost")) { // log.warn("You have not defined your own server, we will not really deploy to localhost!"); // return true; // } // // FTPClient ftp = new FTPClient(); // try // { // ftp.connect (getIP_Address()); // if (ftp.login (getUserName(), getPassword())) // log.info("Connected to " + getIP_Address() + " as " + getUserName()); // else // { // log.warn("Could NOT connect to " + getIP_Address() + " as " + getUserName()); // return false; // } // } // catch (Exception e) // { // log.warn("Could NOT connect to " + getIP_Address() // + " as " + getUserName(), e); // return false; // } // // boolean success = true; // String cmd = null; // // List the files in the directory // try // { // cmd = "cwd"; // ftp.changeWorkingDirectory (getFolder()); // // // cmd = "list"; // String[] fileNames = ftp.listNames(); // log.debug("Number of files in " + getFolder() + ": " + fileNames.length); // // /* // FTPFile[] files = ftp.listFiles(); // log.info("Number of files in " + getFolder() + ": " + files.length); // for (int i = 0; i < files.length; i++) // log.debug(files[i].getTimestamp() + " \t" + files[i].getName());*/ // // // cmd = "bin"; // ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // // // for (int i = 0; i < media.length; i++)
// { // if (!media[i].isSummary()) { // log.info(" Deploying Media Item:" + media[i].get_ID() + media[i].getExtension()); // MImage thisImage = media[i].getImage(); // // // Open the file and output streams // byte[] buffer = thisImage.getData(); // ByteArrayInputStream is = new ByteArrayInputStream(buffer); // // String fileName = media[i].get_ID() + media[i].getExtension(); // cmd = "put " + fileName; // ftp.storeFile(fileName, is); // is.close(); // } // } // } // catch (Exception e) // { // log.warn(cmd, e); // success = false; // } // // Logout from the FTP Server and disconnect // try // { // cmd = "logout"; // ftp.logout(); // cmd = "disconnect"; // ftp.disconnect(); // } // catch (Exception e) // { // log.warn(cmd, e); // } // ftp = null; // return success; // @formatter:on } // deploy } // MMediaServer
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MMediaServer.java
1
请完成以下Java代码
public static String getDefaultFileExtension() { final ISysConfigBL sysconfigs = Services.get(ISysConfigBL.class); return sysconfigs.getValue(SYSCONFIG_DefaultExcelFileExtension, ExcelOpenXMLFormat.FILE_EXTENSION); } public static ExcelFormat getDefaultFormat() { return getFormatByFileExtension(getDefaultFileExtension()); } public static Set<String> getFileExtensionsDefaultFirst() { return ImmutableSet.<String> builder() .add(getDefaultFileExtension()) // default one first .addAll(getFileExtensions()) .build(); } public static Set<String> getFileExtensions() { return ALL_FORMATS.stream() .map(ExcelFormat::getFileExtension) .collect(ImmutableSet.toImmutableSet()); }
public static ExcelFormat getFormatByFile(@NonNull final File file) { final String fileExtension = Files.getFileExtension(file.getPath()); return getFormatByFileExtension(fileExtension); } public static ExcelFormat getFormatByFileExtension(@NonNull final String fileExtension) { return ALL_FORMATS .stream() .filter(format -> fileExtension.equals(format.getFileExtension())) .findFirst() .orElseThrow(() -> new AdempiereException( "No " + ExcelFormat.class.getSimpleName() + " found for file extension '" + fileExtension + "'." + "\n Supported extensions are: " + getFileExtensions())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\ExcelFormats.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(columnDefinition = "uuid", updatable = false, nullable = false) private UUID id; private String name; private String email; // Getters and Setters public UUID getId() { return id; } public void setId(UUID id) { this.id = id; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
repos\tutorials-master\persistence-modules\spring-jpa-3\src\main\java\com\baeldung\jpa\postgres\uuid\entity\User.java
2
请完成以下Java代码
private void markRecordAsProcessed(@NonNull final BankStatementImportFile bankStatementImportFile) { bankStatementImportFileService.save(bankStatementImportFile.toBuilder() .importedTimestamp(SystemTime.asInstant()) .processed(true) .build()); } private void openImportedRecords(@NonNull final Set<BankStatementId> importedBankStatementIds) { if (importedBankStatementIds.isEmpty()) { throw new AdempiereException(MSG_NO_STATEMENT_IMPORTED) .markAsUserValidationError(); } setRecordsToOpen(importedBankStatementIds); } private void setRecordsToOpen(@NonNull final Set<BankStatementId> importedBankStatementIds) { getResult().setRecordToOpen(ProcessExecutionResult.RecordsToOpen.builder() .records(TableRecordReference.ofRecordIds(I_C_BankStatement.Table_Name, BankStatementId.toIntSet(importedBankStatementIds))) .targetTab(ProcessExecutionResult.RecordsToOpen.TargetTab.NEW_TAB) .target(importedBankStatementIds.size() == 1 ? ProcessExecutionResult.RecordsToOpen.OpenTarget.SingleDocument : ProcessExecutionResult.RecordsToOpen.OpenTarget.GridView) .build()); } private boolean isSelectedRecordProcessed(@NonNull final BankStatementImportFileId bankStatementImportFileId) { return bankStatementImportFileService.getById(bankStatementImportFileId) .isProcessed(); } private boolean isMissingAttachmentEntryForRecordId(@NonNull final BankStatementImportFileId bankStatementImportFileId) { return !getSingleAttachmentEntryId(bankStatementImportFileId).isPresent(); } @NonNull
private Optional<AttachmentEntryId> getSingleAttachmentEntryId(@NonNull final BankStatementImportFileId bankStatementImportFileId) { final List<AttachmentEntry> attachments = attachmentEntryService .getByReferencedRecord(TableRecordReference.of(I_C_BankStatement_Import_File.Table_Name, bankStatementImportFileId)); if (attachments.isEmpty()) { return Optional.empty(); } if (attachments.size() != 1) { throw new AdempiereException(MSG_MULTIPLE_ATTACHMENTS) .markAsUserValidationError(); } return Optional.of(attachments.get(0).getId()); } @NonNull private AttachmentEntryDataResource retrieveAttachmentResource(@NonNull final BankStatementImportFileId bankStatementImportFileId) { final AttachmentEntryId attachmentEntryId = getSingleAttachmentEntryId(bankStatementImportFileId) .orElseThrow(() -> new AdempiereException(MSG_NO_ATTACHMENT) .markAsUserValidationError()); return attachmentEntryService.retrieveDataResource(attachmentEntryId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\process\C_BankStatement_Import_File_Camt53_ImportAttachment.java
1
请在Spring Boot框架中完成以下Java代码
public class DedicatedEventsJpaDaoConfig { public static final String EVENTS_PERSISTENCE_UNIT = "events"; public static final String EVENTS_DATA_SOURCE = EVENTS_PERSISTENCE_UNIT + "DataSource"; public static final String EVENTS_TRANSACTION_MANAGER = EVENTS_PERSISTENCE_UNIT + "TransactionManager"; public static final String EVENTS_TRANSACTION_TEMPLATE = EVENTS_PERSISTENCE_UNIT + "TransactionTemplate"; public static final String EVENTS_JDBC_TEMPLATE = EVENTS_PERSISTENCE_UNIT + "JdbcTemplate"; @Bean @ConfigurationProperties("spring.datasource.events") public DataSourceProperties eventsDataSourceProperties() { return new DataSourceProperties(); } @ConfigurationProperties(prefix = "spring.datasource.events.hikari") @Bean(EVENTS_DATA_SOURCE) public DataSource eventsDataSource(@Qualifier("eventsDataSourceProperties") DataSourceProperties eventsDataSourceProperties) { return eventsDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build(); } @Bean public LocalContainerEntityManagerFactoryBean eventsEntityManagerFactory(@Qualifier(EVENTS_DATA_SOURCE) DataSource eventsDataSource, EntityManagerFactoryBuilder builder) { return builder .dataSource(eventsDataSource)
.packages(LifecycleEventEntity.class, StatisticsEventEntity.class, ErrorEventEntity.class, RuleNodeDebugEventEntity.class, RuleChainDebugEventEntity.class, AuditLogEntity.class, CalculatedFieldDebugEventEntity.class) .persistenceUnit(EVENTS_PERSISTENCE_UNIT) .build(); } @Bean(EVENTS_TRANSACTION_MANAGER) public JpaTransactionManager eventsTransactionManager(@Qualifier("eventsEntityManagerFactory") LocalContainerEntityManagerFactoryBean eventsEntityManagerFactory) { return new JpaTransactionManager(Objects.requireNonNull(eventsEntityManagerFactory.getObject())); } @Bean(EVENTS_TRANSACTION_TEMPLATE) public TransactionTemplate eventsTransactionTemplate(@Qualifier(EVENTS_TRANSACTION_MANAGER) JpaTransactionManager eventsTransactionManager) { return new TransactionTemplate(eventsTransactionManager); } @Bean(EVENTS_JDBC_TEMPLATE) public JdbcTemplate eventsJdbcTemplate(@Qualifier(EVENTS_DATA_SOURCE) DataSource eventsDataSource) { return new JdbcTemplate(eventsDataSource); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\config\DedicatedEventsJpaDaoConfig.java
2
请完成以下Java代码
private void put(EntityId entityId, AttributeScope scope, AttributeKvEntry attribute) { String key = attribute.getKey(); log.trace("[{}][{}][{}] Before cache put: {}", entityId, scope, key, attribute); cache.put(new AttributeCacheKey(scope, entityId, key), attribute); log.trace("[{}][{}][{}] after cache put.", entityId, scope, key); } @Override public ListenableFuture<List<String>> removeAll(TenantId tenantId, EntityId entityId, AttributeScope scope, List<String> attributeKeys) { validate(entityId, scope); List<ListenableFuture<TbPair<String, Long>>> futures = attributesDao.removeAllWithVersions(tenantId, entityId, scope, attributeKeys); return Futures.allAsList(futures.stream().map(future -> Futures.transform(future, keyVersionPair -> { String key = keyVersionPair.getFirst(); Long version = keyVersionPair.getSecond(); cache.evict(new AttributeCacheKey(scope, entityId, key), version); if (version != null) { TenantId edqsTenantId = entityId.getEntityType() == EntityType.TENANT ? (TenantId) entityId : tenantId; edqsService.onDelete(edqsTenantId, ObjectType.ATTRIBUTE_KV, new AttributeKv(entityId, scope, key, version)); } return key;
}, cacheExecutor)).toList()); } @Override public int removeAllByEntityId(TenantId tenantId, EntityId entityId) { List<Pair<AttributeScope, String>> result = attributesDao.removeAllByEntityId(tenantId, entityId); result.forEach(deleted -> { AttributeScope scope = deleted.getKey(); String key = deleted.getValue(); if (scope != null && key != null) { cache.evict(new AttributeCacheKey(scope, entityId, key)); // using version as Long.MAX_VALUE because we expect that the entity is deleted and there won't be any attributes after this edqsService.onDelete(tenantId, ObjectType.ATTRIBUTE_KV, new AttributeKv(entityId, scope, key, Long.MAX_VALUE)); } }); return result.size(); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\attributes\CachedAttributesService.java
1
请在Spring Boot框架中完成以下Java代码
public void configure() { //@formatter:off from(fileEndpointConfig.getProductFileEndpoint()) .id(routeId) .streamCache("true") .log("Product Sync Route Started with Id=" + routeId) .process(exchange -> PInstanceUtil.setPInstanceHeader(exchange, enabledByExternalSystemRequest)) .split(body().tokenize("\n")) .streaming() .process(exchange -> PInstanceUtil.setPInstanceHeader(exchange, enabledByExternalSystemRequest)) .filter(new SkipFirstLinePredicate()) .doTry() .unmarshal(new BindyCsvDataFormat(ProductRow.class)) .process(getProductUpsertProcessor()).id(UPSERT_PRODUCT_PROCESSOR_ID) .choice() .when(bodyAs(ProductUpsertCamelRequest.class).isNull()) .log(LoggingLevel.INFO, "Nothing to do! No product to upsert!") .otherwise() .log(LoggingLevel.DEBUG, "Calling metasfresh-api to upsert Product: ${body}") .to(direct(MF_UPSERT_PRODUCT_V2_CAMEL_URI)).id(UPSERT_PRODUCT_ENDPOINT_ID)
.endChoice() .end() .endDoTry() .doCatch(Throwable.class) .to(direct(ERROR_WRITE_TO_ADISSUE)) .end() .end(); //@formatter:on } @NonNull private ProductUpsertProcessor getProductUpsertProcessor() { return ProductUpsertProcessor.builder() .externalSystemRequest(enabledByExternalSystemRequest) .pInstanceLogger(pInstanceLogger) .build(); } }
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\product\GetProductFromFileRouteBuilder.java
2
请完成以下Spring Boot application配置
spring: cloud: gateway: routes: - id: golden_route uri: https://httpbin.org predicates: - Path=/api/** - GoldenCustomer=true filters: - StripPrefix=1 - AddRequestHeader=GoldenCustomer,true - id: common_route uri: https://httpbin.org predicates: - Path=/api/** - name: GoldenCustomer
args: golden: false customerIdCookie: customerId filters: - StripPrefix=1 - AddRequestHeader=GoldenCustomer,false
repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\spring-cloud-gateway-intro\src\main\resources\application-customroutes.yml
2
请完成以下Java代码
public void onApplicationEvent(RefreshRoutesEvent event) { try { if (this.cache.containsKey(CACHE_KEY) && event.isScoped()) { final Mono<List<Route>> scopedRoutes = fetch(event.getMetadata()).collect(Collectors.toList()) .onErrorResume(s -> Mono.just(List.of())); scopedRoutes.subscribe(scopedRoutesList -> { updateCache(Flux.concat(Flux.fromIterable(scopedRoutesList), getNonScopedRoutes(event)) .sort(AnnotationAwareOrderComparator.INSTANCE)); }, this::handleRefreshError); } else { final Mono<List<Route>> allRoutes = fetch().collect(Collectors.toList()); allRoutes.subscribe(list -> updateCache(Flux.fromIterable(list)), this::handleRefreshError); } } catch (Throwable e) { handleRefreshError(e); } } private synchronized void updateCache(Flux<Route> routes) { routes.materialize() .collect(Collectors.toList()) .subscribe(this::publishRefreshEvent, this::handleRefreshError); } private void publishRefreshEvent(List<Signal<Route>> signals) { cache.put(CACHE_KEY, signals); Objects.requireNonNull(applicationEventPublisher, "ApplicationEventPublisher is required"); applicationEventPublisher.publishEvent(new RefreshRoutesResultEvent(this)); } private Flux<Route> getNonScopedRoutes(RefreshRoutesEvent scopedEvent) { return this.getRoutes() .filter(route -> !RouteLocator.matchMetadata(route.getMetadata(), scopedEvent.getMetadata())); }
private void handleRefreshError(Throwable throwable) { if (log.isErrorEnabled()) { log.error("Refresh routes error !!!", throwable); } Objects.requireNonNull(applicationEventPublisher, "ApplicationEventPublisher is required"); applicationEventPublisher.publishEvent(new RefreshRoutesResultEvent(this, throwable)); } @Override public int getOrder() { return 0; } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\route\CachingRouteLocator.java
1
请完成以下Java代码
private static void addIndividualAttributeValuestoMap( @NonNull final I_DIM_Dimension_Spec_Attribute dimensionSpecAttribute, @NonNull final Multimap<IPair<String, AttributeId>, AttributeValueId> groupName2AttributeValues) { final IQueryBL queryBL = Services.get(IQueryBL.class); final List<I_DIM_Dimension_Spec_AttributeValue> attrValues = queryBL .createQueryBuilder(I_DIM_Dimension_Spec_AttributeValue.class) .addOnlyActiveRecordsFilter() .addEqualsFilter( I_DIM_Dimension_Spec_AttributeValue.COLUMN_DIM_Dimension_Spec_Attribute_ID, dimensionSpecAttribute.getDIM_Dimension_Spec_Attribute_ID()) .create() .list(); final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class); final AttributeId attributeId = AttributeId.ofRepoId(dimensionSpecAttribute.getM_Attribute_ID()); for (final I_DIM_Dimension_Spec_AttributeValue attrValue : attrValues) { final AttributeValueId attributeValueId = AttributeValueId.ofRepoId(attrValue.getM_AttributeValue_ID()); final String groupName; if (dimensionSpecAttribute.isValueAggregate()) { groupName = dimensionSpecAttribute.getValueAggregateName(); } else { final AttributeListValue attributeListValue = attributesRepo.retrieveAttributeValueOrNull(attributeId, attributeValueId); groupName = attributeListValue.getName(); } final ImmutablePair<String, AttributeId> key = ImmutablePair.of(groupName, attributeId); groupName2AttributeValues.put(key, attributeValueId); } } private static void sortAndAddMapEntriesToList( @NonNull final Multimap<IPair<String, AttributeId>, AttributeValueId> groupNameToAttributeValueIds, @NonNull final Builder<DimensionSpecGroup> list) { final Collection<Entry<IPair<String, AttributeId>, Collection<AttributeValueId>>> // entrySet = groupNameToAttributeValueIds.asMap().entrySet();
final ArrayList<DimensionSpecGroup> newGroups = new ArrayList<>(); for (final Entry<IPair<String, AttributeId>, Collection<AttributeValueId>> entry : entrySet) { final String groupName = entry.getKey().getLeft(); final ITranslatableString groupNameTrl = TranslatableStrings.constant(groupName); final Optional<AttributeId> groupAttributeId = Optional.ofNullable(entry.getKey().getRight()); final AttributesKey attributesKey = createAttributesKey(entry.getValue()); final DimensionSpecGroup newGroup = new DimensionSpecGroup( () -> groupNameTrl, attributesKey, groupAttributeId); newGroups.add(newGroup); } newGroups.sort(Comparator.comparing(DimensionSpecGroup::getAttributesKey)); list.addAll(newGroups); } private static AttributesKey createAttributesKey(final Collection<AttributeValueId> values) { return AttributesKey.ofParts( values.stream() .map(AttributesKeyPart::ofAttributeValueId) .collect(ImmutableSet.toImmutableSet())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java\de\metas\dimension\DimensionSpec.java
1
请完成以下Java代码
public void setup() { src = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"; dest = "eiusmod"; pattern = Pattern.compile(Pattern.quote(dest), Pattern.CASE_INSENSITIVE); } // toLowerCase() and contains() @Benchmark public boolean lowerCaseContains() { return src.toLowerCase() .contains(dest.toLowerCase()); } // matches() with Regular Expressions @Benchmark public boolean matchesRegularExpression() { return src.matches("(?i).*" + dest + ".*"); } public boolean processRegionMatches(String localSrc, String localDest) { for (int i = localSrc.length() - localDest.length(); i >= 0; i--) if (localSrc.regionMatches(true, i, localDest, 0, localDest.length())) return true; return false; } // String regionMatches()
@Benchmark public boolean regionMatches() { return processRegionMatches(src, dest); } // Pattern CASE_INSENSITIVE with regexp @Benchmark public boolean patternCaseInsensitiveRegexp() { return pattern.matcher(src) .find(); } // Apache Commons StringUtils containsIgnoreCase @Benchmark public boolean apacheCommonsStringUtils() { return org.apache.commons.lang3.StringUtils.containsIgnoreCase(src, dest); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-2\src\main\java\com\baeldung\contains\CaseInsensitiveWorkarounds.java
1
请完成以下Java代码
public int getAD_Field_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Field_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Tab getAD_Tab() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Tab_ID, org.compiere.model.I_AD_Tab.class); } @Override public void setAD_Tab(org.compiere.model.I_AD_Tab AD_Tab) { set_ValueFromPO(COLUMNNAME_AD_Tab_ID, org.compiere.model.I_AD_Tab.class, AD_Tab); } /** Set Register. @param AD_Tab_ID Register auf einem Fenster */ @Override public void setAD_Tab_ID (int AD_Tab_ID) { if (AD_Tab_ID < 1) set_Value (COLUMNNAME_AD_Tab_ID, null); else set_Value (COLUMNNAME_AD_Tab_ID, Integer.valueOf(AD_Tab_ID)); } /** Get Register. @return Register auf einem Fenster */ @Override public int getAD_Tab_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tab_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class); }
@Override public void setAD_Window(org.compiere.model.I_AD_Window AD_Window) { set_ValueFromPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class, AD_Window); } /** Set Fenster. @param AD_Window_ID Eingabe- oder Anzeige-Fenster */ @Override public void setAD_Window_ID (int AD_Window_ID) { if (AD_Window_ID < 1) set_Value (COLUMNNAME_AD_Window_ID, null); else set_Value (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID)); } /** Get Fenster. @return Eingabe- oder Anzeige-Fenster */ @Override public int getAD_Window_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Element_Link.java
1
请完成以下Java代码
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; String path = httpRequest.getRequestURI(); if (path.endsWith("/")) { String newPath = path.substring(0, path.length() - 1); HttpServletRequest newRequest = new CustomHttpServletRequestWrapper(httpRequest, newPath); chain.doFilter(newRequest, response); } else { chain.doFilter(request, response); } } private static class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper { private final String newPath;
public CustomHttpServletRequestWrapper(HttpServletRequest request, String newPath) { super(request); this.newPath = newPath; } @Override public String getRequestURI() { return newPath; } @Override public StringBuffer getRequestURL() { StringBuffer url = new StringBuffer(); url.append(getScheme()).append("://").append(getServerName()).append(":").append(getServerPort()) .append(newPath); return url; } } }
repos\tutorials-master\spring-boot-modules\spring-boot-3-url-matching\src\main\java\com\baeldung\sample\filters\TrailingSlashRedirectFilter.java
1
请在Spring Boot框架中完成以下Java代码
public String getSuppliersCustomerID() { return suppliersCustomerID; } /** * Sets the value of the suppliersCustomerID property. * * @param value * allowed object is * {@link String } * */ public void setSuppliersCustomerID(String value) { this.suppliersCustomerID = value; } /** * The accounting area at the document recipient's side. Used to associate a given document to a certain accounting area. * * @return * possible object is * {@link String } * */ public String getAccountingArea() { return accountingArea; } /** * Sets the value of the accountingArea property. * * @param value * allowed object is * {@link String } * */ public void setAccountingArea(String value) { this.accountingArea = value; } /** * The ID of an internal sub organization to which the document shall be associated to at the document recipient's side. * * @return * possible object is * {@link String } * */ public String getSubOrganizationID() { return subOrganizationID; } /**
* Sets the value of the subOrganizationID property. * * @param value * allowed object is * {@link String } * */ public void setSubOrganizationID(String value) { this.subOrganizationID = value; } /** * Gets the value of the customerExtension property. * * @return * possible object is * {@link CustomerExtensionType } * */ public CustomerExtensionType getCustomerExtension() { return customerExtension; } /** * Sets the value of the customerExtension property. * * @param value * allowed object is * {@link CustomerExtensionType } * */ public void setCustomerExtension(CustomerExtensionType value) { this.customerExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\CustomerType.java
2
请完成以下Java代码
public Set<ProductId> getProductIdsMatchingQueryString( @NonNull final String queryString, @NonNull final ClientId clientId, @NonNull QueryLimit limit) { final IQueryBuilder<I_M_Product> queryBuilder = queryBL.createQueryBuilder(I_M_Product.class) .setLimit(limit) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_Product.COLUMNNAME_AD_Client_ID, clientId); queryBuilder.addCompositeQueryFilter() .setJoinOr() .addStringLikeFilter(I_M_Product.COLUMNNAME_Value, queryString, true) .addStringLikeFilter(I_M_Product.COLUMNNAME_Name, queryString, true); return queryBuilder.create().idsAsSet(ProductId::ofRepoIdOrNull); } @Override
public void save(I_M_Product record) { InterfaceWrapperHelper.save(record); } @Override public boolean isExistingValue(@NonNull final String value, @NonNull final ClientId clientId) { return queryBL.createQueryBuilder(I_M_Product.class) //.addOnlyActiveRecordsFilter() // check inactive records too .addEqualsFilter(I_M_Product.COLUMNNAME_Value, value) .addEqualsFilter(I_M_Product.COLUMNNAME_AD_Client_ID, clientId) .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\impl\ProductDAO.java
1
请在Spring Boot框架中完成以下Java代码
public class BatchEntityManagerImpl extends AbstractServiceEngineEntityManager<BatchServiceConfiguration, BatchEntity, BatchDataManager> implements BatchEntityManager { public BatchEntityManagerImpl(BatchServiceConfiguration batchServiceConfiguration, BatchDataManager batchDataManager) { super(batchServiceConfiguration, batchServiceConfiguration.getEngineName(), batchDataManager); } @Override public List<Batch> findBatchesBySearchKey(String searchKey) { return dataManager.findBatchesBySearchKey(searchKey); } @Override public List<Batch> findAllBatches() { return dataManager.findAllBatches(); } @Override public List<Batch> findBatchesByQueryCriteria(BatchQueryImpl batchQuery) { return dataManager.findBatchesByQueryCriteria(batchQuery); } @Override public long findBatchCountByQueryCriteria(BatchQueryImpl batchQuery) { return dataManager.findBatchCountByQueryCriteria(batchQuery); } @Override public BatchEntity createBatch(BatchBuilder batchBuilder) { BatchEntity batchEntity = dataManager.create(); batchEntity.setBatchType(batchBuilder.getBatchType()); batchEntity.setBatchSearchKey(batchBuilder.getSearchKey()); batchEntity.setBatchSearchKey2(batchBuilder.getSearchKey2()); batchEntity.setCreateTime(getClock().getCurrentTime()); batchEntity.setStatus(batchBuilder.getStatus()); batchEntity.setBatchDocumentJson(batchBuilder.getBatchDocumentJson(), serviceConfiguration.getEngineName()); batchEntity.setTenantId(batchBuilder.getTenantId()); dataManager.insert(batchEntity); return batchEntity; }
@Override public Batch completeBatch(String batchId, String status) { BatchEntity batchEntity = findById(batchId); batchEntity.setCompleteTime(getClock().getCurrentTime()); batchEntity.setStatus(status); return batchEntity; } @Override public void deleteBatches(BatchQueryImpl batchQuery) { dataManager.deleteBatches(batchQuery); } @Override public void delete(String batchId) { BatchEntity batch = dataManager.findById(batchId); List<BatchPart> batchParts = getBatchPartEntityManager().findBatchPartsByBatchId(batch.getId()); if (batchParts != null && batchParts.size() > 0) { for (BatchPart batchPart : batchParts) { getBatchPartEntityManager().deleteBatchPartEntityAndResources((BatchPartEntity) batchPart); } } ByteArrayRef batchDocRefId = batch.getBatchDocRefId(); if (batchDocRefId != null && batchDocRefId.getId() != null) { batchDocRefId.delete(serviceConfiguration.getEngineName()); } delete(batch); } protected BatchPartEntityManager getBatchPartEntityManager() { return serviceConfiguration.getBatchPartEntityManager(); } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\persistence\entity\BatchEntityManagerImpl.java
2
请完成以下Java代码
public void afterPropertiesSet() { Assert.notEmpty(this.channelProcessors, "A list of ChannelProcessors is required"); } @Override public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException, ServletException { for (ConfigAttribute attribute : config) { if (ANY_CHANNEL.equals(attribute.getAttribute())) { return; } } for (ChannelProcessor processor : this.channelProcessors) { processor.decide(invocation, config); if (invocation.getResponse().isCommitted()) { break; } } } protected @Nullable List<ChannelProcessor> getChannelProcessors() { return this.channelProcessors; } @SuppressWarnings("cast")
public void setChannelProcessors(List<?> channelProcessors) { Assert.notEmpty(channelProcessors, "A list of ChannelProcessors is required"); this.channelProcessors = new ArrayList<>(channelProcessors.size()); for (Object currentObject : channelProcessors) { Assert.isInstanceOf(ChannelProcessor.class, currentObject, () -> "ChannelProcessor " + currentObject.getClass().getName() + " must implement ChannelProcessor"); this.channelProcessors.add((ChannelProcessor) currentObject); } } @Override public boolean supports(ConfigAttribute attribute) { if (ANY_CHANNEL.equals(attribute.getAttribute())) { return true; } for (ChannelProcessor processor : this.channelProcessors) { if (processor.supports(attribute)) { return true; } } return false; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\channel\ChannelDecisionManagerImpl.java
1
请完成以下Java代码
protected void registerTabCallouts(final ITabCalloutFactory tabCalloutsRegistry) { tabCalloutsRegistry.registerTabCalloutForTable(I_C_Invoice_Candidate.Table_Name, C_Invoice_Candidate_TabCallout.class); } @Override protected void registerCallouts(final IProgramaticCalloutProvider calloutsRegistry) { calloutsRegistry.registerAnnotatedCallout(new de.metas.invoicecandidate.callout.C_Invoice_Candidate()); calloutsRegistry.registerAnnotatedCallout(new de.metas.invoicecandidate.callout.C_Invoice_Candidate_Agg()); calloutsRegistry.registerAnnotatedCallout(new de.metas.invoicecandidate.callout.C_ILCandHandler()); } /** * Setup de.metas.aggregation */ private void setupAggregations() { // // In case there was no aggregation found, fallback to our legacy IC header/line aggregation key builders final IAggregationFactory aggregationFactory = Services.get(IAggregationFactory.class); aggregationFactory.setDefaultAggregationKeyBuilder(I_C_Invoice_Candidate.class, X_C_Aggregation.AGGREGATIONUSAGELEVEL_Header, ICHeaderAggregationKeyBuilder_OLD.instance); aggregationFactory.setDefaultAggregationKeyBuilder(I_C_Invoice_Candidate.class, X_C_Aggregation.AGGREGATIONUSAGELEVEL_Line, ICLineAggregationKeyBuilder_OLD.instance); // // On C_Aggregation master data change => invalidate candidates for that aggregation
Services.get(IAggregationListeners.class).addListener(aggregationListener); } private void ensureDataDestExists() { final Properties ctx = Env.getCtx(); final I_AD_InputDataSource dest = Services.get(IInputDataSourceDAO.class).retrieveInputDataSource(ctx, InvoiceCandidate_Constants.DATA_DESTINATION_INTERNAL_NAME, false, ITrx.TRXNAME_None); if (dest == null) { final I_AD_InputDataSource newDest = InterfaceWrapperHelper.create(ctx, I_AD_InputDataSource.class, ITrx.TRXNAME_None); newDest.setEntityType(InvoiceCandidate_Constants.ENTITY_TYPE); newDest.setInternalName(InvoiceCandidate_Constants.DATA_DESTINATION_INTERNAL_NAME); newDest.setIsDestination(true); newDest.setValue(InvoiceCandidate_Constants.DATA_DESTINATION_INTERNAL_NAME); newDest.setName(Services.get(IMsgBL.class).translate(ctx, "C_Invoice_ID")); InterfaceWrapperHelper.save(newDest); } } @Override protected void setupCaching(final IModelCacheService cachingService) { CacheMgt.get().enableRemoteCacheInvalidationForTableName(I_C_Invoice_Candidate.Table_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\ConfigValidator.java
1
请完成以下Java代码
public void onClose() { if (webSocketMap.containsKey(userId)) { webSocketMap.remove(userId); subOnlineCount(); } log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount()); } /** * 收到客户端消息后调用的方法 * * @param message 客户端发送过来的消息 */ @OnMessage public void onMessage(String message, Session session) { log.info("用户消息:" + userId + ",报文:" + message); if (!StringUtils.isEmpty(message)) { try { JSONObject jsonObject = JSON.parseObject(message); jsonObject.put("fromUserId", this.userId); String toUserId = jsonObject.getString("toUserId"); if (!StringUtils.isEmpty(toUserId) && webSocketMap.containsKey(toUserId)) { webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString()); } else { log.error("请求的 userId:" + toUserId + "不在该服务器上"); } } catch (Exception e) { e.printStackTrace(); } } } /** * 发生错误时调用
* * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error("用户错误:" + this.userId + ",原因:" + error.getMessage()); error.printStackTrace(); } /** * 实现服务器主动推送 */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } public static synchronized AtomicInteger getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocketServer.onlineCount.getAndIncrement(); } public static synchronized void subOnlineCount() { WebSocketServer.onlineCount.getAndDecrement(); } }
repos\springboot-demo-master\websocket\src\main\java\com\et\websocket\channel\WebSocketServer.java
1
请完成以下Java代码
private String escapeHtml(HttpServletRequest request) throws IOException { StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = null; try (InputStream inputStream = request.getInputStream()) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); char[] charBuffer = new char[128]; int bytesRead = -1; while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { stringBuilder.append(charBuffer, 0, bytesRead); } } String input = stringBuilder.toString(); // Escape HTML characters return input.replaceAll("&", "&amp;") .replaceAll("<", "&lt;") .replaceAll(">", "&gt;") .replaceAll("'", "&#39;"); } @Override public ServletInputStream getInputStream() { final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes()); ServletInputStream servletInputStream = new ServletInputStream() { @Override public int read() { return byteArrayInputStream.read(); } @Override public boolean isFinished() { return false; } @Override public boolean isReady() { return false; } @Override public void setReadListener(ReadListener listener) {
} }; return servletInputStream; } @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(this.getInputStream())); } @Override public Enumeration<String> getHeaders(String name) { if(HttpHeaders.CONTENT_LENGTH.equals(name)) { return Collections.enumeration(Collections.singletonList(String.valueOf(body.length()))); } return super.getHeaders(name); } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc\src\main\java\com\baeldung\modifyrequest\requestwrapper\EscapeHtmlRequestWrapper.java
1
请完成以下Java代码
public void warn(final int WindowNo, final String AD_Message) { getCurrentInstance().warn(WindowNo, AD_Message); } @Override public void warn(final int WindowNo, final String AD_Message, final String message) { getCurrentInstance().warn(WindowNo, AD_Message, message); } @Override public void warn(final int WindowNo, final Throwable e) { getCurrentInstance().warn(WindowNo, e); } @Override public void error(final int WindowNo, final String AD_Message) { getCurrentInstance().error(WindowNo, AD_Message); } @Override public void error(final int WindowNo, final String AD_Message, final String message) { getCurrentInstance().error(WindowNo, AD_Message, message); } @Override public void error(int WindowNo, Throwable e) { getCurrentInstance().error(WindowNo, e); } @Override public void download(final byte[] data, final String contentType, final String filename) { getCurrentInstance().download(data, contentType, filename); } @Override public void downloadNow(final InputStream content, final String contentType, final String filename) { getCurrentInstance().downloadNow(content, contentType, filename); } @Override public void invokeLater(final int windowNo, final Runnable runnable) { getCurrentInstance().invokeLater(windowNo, runnable); } @Override public Thread createUserThread(final Runnable runnable, final String threadName) { return getCurrentInstance().createUserThread(runnable, threadName); } @Override public String getClientInfo() { return getCurrentInstance().getClientInfo(); } /** * This method does nothing. * * @deprecated please check out the deprecation notice in {@link IClientUIInstance#hideBusyDialog()}. */ @Deprecated @Override
public void hideBusyDialog() { // nothing } @Override public void showWindow(final Object model) { getCurrentInstance().showWindow(model); } @Override public void executeLongOperation(final Object component, final Runnable runnable) { getCurrentInstance().executeLongOperation(component, runnable); } @Override public IClientUIInvoker invoke() { return getCurrentInstance().invoke(); } @Override public IClientUIAsyncInvoker invokeAsync() { return getCurrentInstance().invokeAsync(); } @Override public void showURL(String url) { getCurrentInstance().showURL(url); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\AbstractClientUI.java
1
请完成以下Java代码
public void addLaneSet(LaneSet newLaneSet) { getLaneSets().add(newLaneSet); } public Lane getLaneForId(String id) { if(laneSets != null && laneSets.size() > 0) { Lane lane; for(LaneSet set : laneSets) { lane = set.getLaneForId(id); if(lane != null) { return lane; } } } return null; } @Override public CoreActivityBehavior<? extends BaseDelegateExecution> getActivityBehavior() { // unsupported in PVM return null; } // getters and setters ////////////////////////////////////////////////////// public ActivityImpl getInitial() { return initial; } public void setInitial(ActivityImpl initial) { this.initial = initial; } @Override public String toString() { return "ProcessDefinition("+id+")"; } public String getDescription() { return (String) getProperty("documentation"); }
/** * @return all lane-sets defined on this process-instance. Returns an empty list if none are defined. */ public List<LaneSet> getLaneSets() { if(laneSets == null) { laneSets = new ArrayList<LaneSet>(); } return laneSets; } public void setParticipantProcess(ParticipantProcess participantProcess) { this.participantProcess = participantProcess; } public ParticipantProcess getParticipantProcess() { return participantProcess; } public boolean isScope() { return true; } public PvmScope getEventScope() { return null; } public ScopeImpl getFlowScope() { return null; } public PvmScope getLevelOfSubprocessScope() { return null; } @Override public boolean isSubProcessScope() { return true; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\ProcessDefinitionImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class DeviceMapping { @SerializedName("_id") private UUID _id = null; @SerializedName("serialNumber") private String serialNumber = null; @SerializedName("updated") private OffsetDateTime updated = null; public DeviceMapping _id(UUID _id) { this._id = _id; return this; } /** * Alberta-Id des Geräts * @return _id **/ @Schema(example = "c496a0f9-ab4e-47b1-9f76-42f363e0420f", required = true, description = "Alberta-Id des Geräts") public UUID getId() { return _id; } public void setId(UUID _id) { this._id = _id; } public DeviceMapping serialNumber(String serialNumber) { this.serialNumber = serialNumber; return this; } /** * eindeutige Seriennumer aus WaWi * @return serialNumber **/ @Schema(example = "2005-F540053-EB-0430", required = true, description = "eindeutige Seriennumer aus WaWi") public String getSerialNumber() { return serialNumber; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } public DeviceMapping updated(OffsetDateTime updated) { this.updated = updated; return this; } /** * Der Zeitstempel der letzten Änderung * @return updated
**/ @Schema(example = "2020-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getUpdated() { return updated; } public void setUpdated(OffsetDateTime updated) { this.updated = updated; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DeviceMapping deviceMapping = (DeviceMapping) o; return Objects.equals(this._id, deviceMapping._id) && Objects.equals(this.serialNumber, deviceMapping.serialNumber) && Objects.equals(this.updated, deviceMapping.updated); } @Override public int hashCode() { return Objects.hash(_id, serialNumber, updated); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DeviceMapping {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" serialNumber: ").append(toIndentedString(serialNumber)).append("\n"); sb.append(" updated: ").append(toIndentedString(updated)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\DeviceMapping.java
2
请完成以下Java代码
public static Object convertValueToPO(final Object value, final String columnName, final DocumentFieldWidgetType widgetType, final Class<?> targetClass) { return SqlValueConverters.convertToPOValue(value, columnName, widgetType, targetClass); } @Override public void delete(@NonNull final Document document) { trxManager.assertThreadInheritedTrxExists(); assertThisRepository(document.getEntityDescriptor()); DocumentPermissionsHelper.assertCanEdit(document, UserSession.getCurrentPermissions()); if (document.isNew()) { throw new IllegalArgumentException("Cannot delete new document: " + document); } saveHandlers.delete(document); } @Override public String retrieveVersion(final DocumentEntityDescriptor entityDescriptor, final int documentIdAsInt) { final SqlDocumentEntityDataBindingDescriptor binding = SqlDocumentEntityDataBindingDescriptor.cast(entityDescriptor.getDataBinding()); final String sql = binding.getSqlSelectVersionById() .orElseThrow(() -> new AdempiereException("Versioning is not supported for " + entityDescriptor)); final Timestamp version = DB.getSQLValueTSEx(ITrx.TRXNAME_ThreadInherited, sql, documentIdAsInt); return version == null ? VERSION_DEFAULT : String.valueOf(version.getTime()); } @Override public int retrieveLastLineNo(final DocumentQuery query) {
logger.debug("Retrieving last LineNo: query={}", query); final DocumentEntityDescriptor entityDescriptor = query.getEntityDescriptor(); assertThisRepository(entityDescriptor); final SqlDocumentQueryBuilder sqlBuilder = SqlDocumentQueryBuilder.of(query); final SqlAndParams sql = sqlBuilder.getSqlMaxLineNo(); return DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql.getSql(), sql.getSqlParams()); } public boolean isReadonly(@NonNull final GridTabVO gridTabVO) { return saveHandlers.isReadonly(gridTabVO); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlDocumentsRepository.java
1
请完成以下Java代码
private boolean hasDuplicates(Long thisBackOffValue) { return amountOfDuplicates(thisBackOffValue) > 1; } private int amountOfDuplicates(Long thisBackOffValue) { return Long.valueOf(this.backOffValues .stream() .filter(thisBackOffValue::equals) .count()) .intValue(); } private DestinationTopic.Properties createProperties(long delayMs, String suffix) { return new DestinationTopic.Properties(delayMs, suffix, getDestinationTopicType(delayMs), this.maxAttempts, this.numPartitions, this.dltStrategy, this.kafkaOperations, this.shouldRetryOn, this.timeout); } private String joinWithRetrySuffix(long parameter) { return String.join("-", this.destinationTopicSuffixes.getRetrySuffix(), String.valueOf(parameter)); } public static class DestinationTopicSuffixes {
private final String retryTopicSuffix; private final String dltSuffix; public DestinationTopicSuffixes(@Nullable String retryTopicSuffix, @Nullable String dltSuffix) { this.retryTopicSuffix = StringUtils.hasText(retryTopicSuffix) ? retryTopicSuffix : RetryTopicConstants.DEFAULT_RETRY_SUFFIX; this.dltSuffix = StringUtils.hasText(dltSuffix) ? dltSuffix : RetryTopicConstants.DEFAULT_DLT_SUFFIX; } public String getRetrySuffix() { return this.retryTopicSuffix; } public String getDltSuffix() { return this.dltSuffix; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\DestinationTopicPropertiesFactory.java
1
请完成以下Java代码
private Path parseWindowsLocalPath(@NonNull final URL url) { try { final String normalizedPath = Stream.concat(Stream.of(url.getAuthority()), Arrays.stream(url.getPath().split("/"))) .filter(Check::isNotBlank) .collect(Collectors.joining("/")); return Paths.get(normalizedPath); } catch (final Throwable throwable) { return null; } } @Nullable private Path parseNonLocalWindowsFileURL(@NonNull final URL url) { try { final String normalizedPath = Stream.of(url.getAuthority(), url.getPath()) .filter(Check::isNotBlank) .collect(Collectors.joining()); return Paths.get("//" + normalizedPath); } catch (final Throwable throwable) { return null; } } /** * Creates a file path for the given {@code baseDirectory} and {@code subdirectory}. * * @throws RuntimeException if the resulting file path is not within the given {@code baseDirectory}. */ @NonNull public static Path createAndValidatePath(@NonNull final Path baseDirectory, @NonNull final Path subdirectory) { final Path baseDirectoryAbs = baseDirectory.normalize().toAbsolutePath(); final Path outputFilePath = baseDirectoryAbs.resolve( subdirectory).normalize().toAbsolutePath(); // Validate that the outputFilePath is within the base directory if (!outputFilePath.startsWith(baseDirectoryAbs)) { throw new RuntimeException("Invalid path " + outputFilePath + "! The result of baseDirectory=" + baseDirectory + " and subdirectory=" + subdirectory + " needs to be within baseDirectory"); } return outputFilePath;
} public static void copy(@NonNull final File from, @NonNull final OutputStream out) throws IOException { try (final InputStream in = Files.newInputStream(from.toPath())) { copy(in, out); } } /** * Copies the content from a given {@link InputStream} to the specified {@link File}. * The method writes the data to a temporary file first, and then renames it to the target file. * This ensures that we don'T end up with a partially written file that's then already processed by some other component. * * @throws IOException if an I/O error occurs during reading, writing, or renaming the file */ public static void copy(@NonNull final InputStream in, @NonNull final File to) throws IOException { final File tempFile = new File(to.getAbsolutePath() + ".part"); try (final FileOutputStream out = new FileOutputStream(tempFile)) { copy(in, out); } // rename the temporary file to the final destination if (!tempFile.renameTo(to)) { throw new IOException("Failed to rename the temporary file " + tempFile.getAbsolutePath() + " to " + to.getAbsolutePath()); } } public static void copy(@NonNull final InputStream in, @NonNull final OutputStream out) throws IOException { final byte[] buf = new byte[4096]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.flush(); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\FileUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class WsSessionMetaData { private WebSocketSessionRef sessionRef; private long lastActivityTime; public WsSessionMetaData(WebSocketSessionRef sessionRef) { super(); this.sessionRef = sessionRef; this.lastActivityTime = System.currentTimeMillis(); } public WebSocketSessionRef getSessionRef() { return sessionRef; } public void setSessionRef(WebSocketSessionRef sessionRef) {
this.sessionRef = sessionRef; } public long getLastActivityTime() { return lastActivityTime; } public void setLastActivityTime(long lastActivityTime) { this.lastActivityTime = lastActivityTime; } @Override public String toString() { return "WsSessionMetaData [sessionRef=" + sessionRef + ", lastActivityTime=" + lastActivityTime + "]"; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ws\WsSessionMetaData.java
2
请完成以下Java代码
public static Path twoColumnCsvPath() throws URISyntaxException { URI uri = ClassLoader.getSystemResource(Constants.TWO_COLUMN_CSV).toURI(); return Paths.get(uri); } public static Path fourColumnCsvPath() throws URISyntaxException { URI uri = ClassLoader.getSystemResource(Constants.FOUR_COLUMN_CSV).toURI(); return Paths.get(uri); } public static Path namedColumnCsvPath() throws URISyntaxException { URI uri = ClassLoader.getSystemResource(Constants.NAMED_COLUMN_CSV).toURI(); return Paths.get(uri); } public static String readFile(Path path) throws IOException { return IOUtils.toString(path.toUri()); }
// Dummy Data for Writing public static List<String[]> twoColumnCsvString() { List<String[]> list = new ArrayList<>(); list.add(new String[]{"ColA", "ColB"}); list.add(new String[]{"A", "B"}); return list; } public static List<String[]> fourColumnCsvString() { List<String[]> list = new ArrayList<>(); list.add(new String[]{"ColA", "ColB", "ColC", "ColD"}); list.add(new String[]{"A", "B", "A", "B"}); list.add(new String[]{"BB", "AB", "AA", "B"}); return list; } }
repos\tutorials-master\libraries-data-io\src\main\java\com\baeldung\libraries\opencsv\helpers\Helpers.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonQtyToleranceSpec { @Nullable BigDecimal percentage; @Nullable BigDecimal qty; @Nullable String uom; @Nullable public static JsonQtyToleranceSpec ofNullable(@Nullable IssuingToleranceSpec spec) { if (spec == null) { return null; } final IssuingToleranceValueType valueType = spec.getValueType();
if (valueType == IssuingToleranceValueType.PERCENTAGE) { final Percent percent = spec.getPercent(); return builder().percentage(percent.toBigDecimal()).build(); } else if (valueType == IssuingToleranceValueType.QUANTITY) { final Quantity qty = spec.getQty(); return builder().qty(qty.toBigDecimal()).uom(qty.getUOMSymbol()).build(); } else { throw new AdempiereException("Unknown valueType: " + valueType); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\issue\json\JsonQtyToleranceSpec.java
2
请在Spring Boot框架中完成以下Java代码
protected void toString(final MoreObjects.ToStringHelper toStringHelper) { toStringHelper .omitNullValues() .add("product", product) .add("bpartner", bpartner) .add("day", day) .add("qtyUserEntered", qtyUserEntered) .add("qty", qty) .add("contractLine", contractLine); } public String getBpartnerUUID() { return bpartner.getUuid(); } public String getProductUUID() { return product.getUuid(); }
public Long getProductId() { return product.getId(); } public LocalDate getDay() { return day.toLocalDate(); } public boolean isQtyConfirmedByUser() { return getQty().compareTo(getQtyUserEntered()) == 0; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\ProductSupply.java
2
请完成以下Java代码
public void update(Edge edge) { this.tenantId = edge.getTenantId(); this.customerId = edge.getCustomerId(); this.rootRuleChainId = edge.getRootRuleChainId(); this.name = edge.getName(); this.type = edge.getType(); this.label = edge.getLabel(); this.routingKey = edge.getRoutingKey(); this.secret = edge.getSecret(); this.version = edge.getVersion(); } @Schema(description = "JSON object with the Edge Id. " + "Specify this field to update the Edge. " + "Referencing non-existing Edge Id will cause error. " + "Omit this field to create new Edge." ) @Override public EdgeId getId() { return super.getId(); } @Schema(description = "Timestamp of the edge creation, in milliseconds", example = "1609459200000", accessMode = Schema.AccessMode.READ_ONLY) @Override public long getCreatedTime() { return super.getCreatedTime(); } @Schema(description = "JSON object with Tenant Id. Use 'assignDeviceToTenant' to change the Tenant Id.", accessMode = Schema.AccessMode.READ_ONLY) @Override public TenantId getTenantId() { return this.tenantId; } @Schema(description = "JSON object with Customer Id. Use 'assignEdgeToCustomer' to change the Customer Id.", accessMode = Schema.AccessMode.READ_ONLY) @Override public CustomerId getCustomerId() { return this.customerId; } @Schema(description = "JSON object with Root Rule Chain Id. Use 'setEdgeRootRuleChain' to change the Root Rule Chain Id.", accessMode = Schema.AccessMode.READ_ONLY) public RuleChainId getRootRuleChainId() { return this.rootRuleChainId; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Unique Edge Name in scope of Tenant", example = "Silo_A_Edge") @Override public String getName() { return this.name;
} @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge type", example = "Silos") public String getType() { return this.type; } @Schema(description = "Label that may be used in widgets", example = "Silo Edge on far field") public String getLabel() { return this.label; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge routing key ('username') to authorize on cloud") public String getRoutingKey() { return this.routingKey; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge secret ('password') to authorize on cloud") public String getSecret() { return this.secret; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\edge\Edge.java
1
请完成以下Java代码
public class Book { @Id private String id; private String name; private String yearPublished; private Vector embedding; public Book() {} public Book(String id, String name, String yearPublished, Vector theEmbedding) { this.id = id; this.name = name; this.yearPublished = yearPublished; this.embedding = theEmbedding; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getYearPublished() {
return yearPublished; } public void setYearPublished(String yearPublished) { this.yearPublished = yearPublished; } public Vector getEmbedding() { return embedding; } public void setEmbedding(Vector embedding) { this.embedding = embedding; } }
repos\tutorials-master\persistence-modules\spring-data-vector\src\main\java\com\baeldung\springdata\mongodb\Book.java
1
请完成以下Java代码
public List<Document> searchIndex(Query query) { try { IndexReader indexReader = DirectoryReader.open(memoryIndex); IndexSearcher searcher = new IndexSearcher(indexReader); TopDocs topDocs = searcher.search(query, 10); List<Document> documents = new ArrayList<>(); for (ScoreDoc scoreDoc : topDocs.scoreDocs) { documents.add(searcher.doc(scoreDoc.doc)); } return documents; } catch (IOException e) { e.printStackTrace(); } return null; } public List<Document> searchIndex(Query query, Sort sort) { try { IndexReader indexReader = DirectoryReader.open(memoryIndex); IndexSearcher searcher = new IndexSearcher(indexReader);
TopDocs topDocs = searcher.search(query, 10, sort); List<Document> documents = new ArrayList<>(); for (ScoreDoc scoreDoc : topDocs.scoreDocs) { documents.add(searcher.doc(scoreDoc.doc)); } return documents; } catch (IOException e) { e.printStackTrace(); } return null; } }
repos\tutorials-master\lucene\src\main\java\com\baeldung\lucene\InMemoryLuceneIndex.java
1
请完成以下Java代码
public void setHR_Concept_Category_ID (int HR_Concept_Category_ID) { if (HR_Concept_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_Concept_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_Concept_Category_ID, Integer.valueOf(HR_Concept_Category_ID)); } /** Get Payroll Concept Category. @return Payroll Concept Category */ public int getHR_Concept_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Concept_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Default. @param IsDefault Default value */ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name.
@return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Concept_Category.java
1
请完成以下Java代码
public void stop() { isStopping = true; try { Loggables.withLogger(logger, Level.TRACE).addLog("Closing AMQP Connection!"); if (connectionFactory != null) { connectionFactory.destroy(); connectionFactory = null; } } finally { isStopping = false; // 02486 make sure that we inform 'replicationProcessor' so there is a change of being restarted replicationProcessor.setProcessRunning(false); } } private void logException(final Throwable e, final String messageText) { log("Error: " + e.getLocalizedMessage(), messageText, // text null, // reference e// isError ); } private void log(final String summary, final String text, final String reference, final Throwable error) { final I_IMP_Processor impProcessor = replicationProcessor.getMImportProcessor(); Services.get(IIMPProcessorBL.class).createLog(impProcessor, summary, text, reference, error); } @Override public void onMessage(@NonNull final Message message) { String text = null; final String messageReference = "onMessage-startAt-millis-" + SystemTime.millis(); try (final IAutoCloseable ignored = setupLoggable(messageReference)) { text = extractMessageBodyAsString(message); Loggables.withLogger(logger, Level.TRACE) .addLog("Received message(text): \n{}", text); importXMLDocument(text); log("Imported Document", text, null, null); // loggable can't store the message-text for us // not sending reply if (StringUtils.isNotEmpty(message.getMessageProperties().getReplyTo())) { Loggables.withLogger(logger, Level.WARN) .addLog("Sending reply currently not supported with RabbitMQ"); } } catch (final RuntimeException e) { logException(e, text); } }
private String extractMessageBodyAsString(@NonNull final Message message) { final String encoding = message.getMessageProperties().getContentEncoding(); if (Check.isEmpty(encoding)) { Loggables.withLogger(logger, Level.WARN) .addLog("Incoming RabbitMQ message lacks content encoding info; assuming UTF-8; messageId={}", message.getMessageProperties().getMessageId()); return new String(message.getBody(), StandardCharsets.UTF_8); } try { return new String(message.getBody(), encoding); } catch (final UnsupportedEncodingException e) { throw new AdempiereException("Incoming RabbitMQ message has unsupportred encoding='" + encoding + "'; messageId=" + message.getMessageProperties().getMessageId(), e); } } private IAutoCloseable setupLoggable(@NonNull final String reference) { final IIMPProcessorBL impProcessorBL = Services.get(IIMPProcessorBL.class); final I_IMP_Processor importProcessor = replicationProcessor.getMImportProcessor(); return impProcessorBL.setupTemporaryLoggable(importProcessor, reference); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\imp\RabbitMqListener.java
1
请完成以下Java代码
public int getNetDays () { Integer ii = (Integer)get_Value(COLUMNNAME_NetDays); if (ii == null) return 0; return ii.intValue(); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); }
/** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Contract.java
1
请完成以下Java代码
public <T> T convertToType(ELContext context, Object obj, Class<T> type) { Objects.requireNonNull(context); if (obj instanceof Optional) { Object value = null; if (((Optional<?>) obj).isPresent()) { value = ((Optional<?>) obj).get(); // If the value is assignable to the required type, do so. if (type.isAssignableFrom(value.getClass())) { context.setPropertyResolved(true); @SuppressWarnings("unchecked") T result = (T) value; return result; } } try { T convertedValue = context.convertToType(value, type); context.setPropertyResolved(true); return convertedValue; } catch (ELException e) { /* * TODO: This isn't pretty but it works. Significant refactoring would be required to avoid the * exception. See also Util.isCoercibleFrom(). */ } } return null; } /** * {@inheritDoc} * * @return If the base object is an {@link Optional} and {@link Optional#isEmpty()} returns {@code true} then this * method returns {@code null}.
* <p> * If the base object is an {@link Optional} and {@link Optional#isPresent()} returns {@code true} then * this method returns the result of invoking the specified method on the object obtained by calling * {@link Optional#get()} with the specified parameters. * <p> * If the base object is not an {@link Optional} then the return value is undefined. */ @Override public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { Objects.requireNonNull(context); if (base instanceof Optional && method != null) { context.setPropertyResolved(base, method); if (((Optional<?>) base).isEmpty()) { return null; } else { Object resolvedBase = ((Optional<?>) base).get(); return context.getELResolver().invoke(context, resolvedBase, method, paramTypes, params); } } return null; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\OptionalELResolver.java
1
请在Spring Boot框架中完成以下Java代码
public void markAsPaid(@NonNull final OrderId orderId, @NonNull final OrderPayScheduleId orderPayScheduleId) { orderPayScheduleRepository.updateById(orderId, orderPaySchedule -> orderPaySchedule.markAsPaid(orderPayScheduleId)); } @NonNull public Optional<OrderPaySchedule> getByOrderId(@NonNull final OrderId orderId) {return orderPayScheduleRepository.getByOrderId(orderId);} public void deleteByOrderId(@NonNull final OrderId orderId) {orderPayScheduleRepository.deleteByOrderId(orderId);} @Nullable OrderSchedulingContext extractContext(final @NotNull org.compiere.model.I_C_Order orderRecord) { final Money grandTotal = orderBL.getGrandTotal(orderRecord); if (grandTotal.isZero()) { return null; } final PaymentTermId paymentTermId = orderBL.getPaymentTermId(orderRecord); final PaymentTerm paymentTerm = paymentTermService.getById(paymentTermId); if (!paymentTerm.isComplex()) { return null;
} return OrderSchedulingContext.builder() .orderId(OrderId.ofRepoId(orderRecord.getC_Order_ID())) .orderDate(TimeUtil.asLocalDate(orderRecord.getDateOrdered())) .letterOfCreditDate(TimeUtil.asLocalDate(orderRecord.getLC_Date())) .billOfLadingDate(TimeUtil.asLocalDate(orderRecord.getBLDate())) .ETADate(TimeUtil.asLocalDate(orderRecord.getETA())) .invoiceDate(TimeUtil.asLocalDate(orderRecord.getInvoiceDate())) .grandTotal(grandTotal) .precision(orderBL.getAmountPrecision(orderRecord)) .paymentTerm(paymentTerm) .build(); } public void create(@NonNull final OrderPayScheduleCreateRequest request) { orderPayScheduleRepository.create(request); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\service\OrderPayScheduleService.java
2
请在Spring Boot框架中完成以下Java代码
public synchronized void updateSessionId(String sid) { sessionId = sid; } /** * 服务器主动推送消息 * * @param msgType 消息类型 * @param jsonData echarts图表数据 */ public void pushMsg(String msgType, String jsonData) { SocketIOClient targetClient = this.server.getClient(UUID.fromString(sessionId)); if (targetClient == null) { logger.error("sessionId=" + sessionId + "在server中获取不到client"); } else { targetClient.sendEvent(msgType, jsonData); } // queue.offer(jsonData); } // public String popJson() { // try { // return queue.poll(100L, TimeUnit.MILLISECONDS); // } catch (InterruptedException e) { // e.printStackTrace(); // return null; // } // } /** * 解析Base64位信息并输出到某个目录下面. * * @param base64Info base64串 * @return 文件地址 */ public String saveBase64Pic(String base64Info) { if (StringUtils.isEmpty(base64Info)) { return "";
} // 数据中:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABI4AAAEsCAYAAAClh/jbAAA ... 在"base64,"之后的才是图片信息 String[] arr = base64Info.split("base64,"); // 将图片输出到系统某目录. OutputStream out = null; String now = FastDateFormat.getInstance("yyyyMMddHHmmss").format(new Date()); String destFile = p.getImageDir() + now + ".png"; try { // 使用了Apache commons codec的包来解析Base64 byte[] buffer = Base64.decodeBase64(arr[1]); out = new FileOutputStream(destFile); out.write(buffer); } catch (IOException e) { logger.error("解析Base64图片信息并保存到某目录下出错!", e); return ""; } finally { IOUtils.closeQuietly(out); } return destFile; } }
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\echarts\service\ApiService.java
2
请在Spring Boot框架中完成以下Java代码
protected String getPrefix() { return "tb-cf"; } @Override protected long getNotificationPollDuration() { return pollInterval; } @Override protected long getNotificationPackProcessingTimeout() { return packProcessingTimeout; } @Override protected int getMgmtThreadPoolSize() { return Math.max(Runtime.getRuntime().availableProcessors(), 4); } @Override protected TbQueueConsumer<TbProtoQueueMsg<ToCalculatedFieldNotificationMsg>> createNotificationsConsumer() { return queueFactory.createToCalculatedFieldNotificationMsgConsumer(); } @Override protected void handleNotification(UUID id, TbProtoQueueMsg<ToCalculatedFieldNotificationMsg> msg, TbCallback callback) { ToCalculatedFieldNotificationMsg toCfNotification = msg.getValue(); if (toCfNotification.hasLinkedTelemetryMsg()) { forwardToActorSystem(toCfNotification.getLinkedTelemetryMsg(), callback); } } @EventListener public void handleComponentLifecycleEvent(ComponentLifecycleMsg event) { if (event.getEntityId().getEntityType() == EntityType.TENANT) { if (event.getEvent() == ComponentLifecycleEvent.DELETED) { Set<TopicPartitionInfo> partitions = stateService.getPartitions(); if (CollectionUtils.isEmpty(partitions)) { return; } stateService.delete(partitions.stream() .filter(tpi -> tpi.getTenantId().isPresent() && tpi.getTenantId().get().equals(event.getTenantId())) .collect(Collectors.toSet())); } } } private void forwardToActorSystem(CalculatedFieldTelemetryMsgProto msg, TbCallback callback) {
var tenantId = toTenantId(msg.getTenantIdMSB(), msg.getTenantIdLSB()); var entityId = EntityIdFactory.getByTypeAndUuid(msg.getEntityType(), new UUID(msg.getEntityIdMSB(), msg.getEntityIdLSB())); actorContext.tell(new CalculatedFieldTelemetryMsg(tenantId, entityId, msg, callback)); } private void forwardToActorSystem(CalculatedFieldLinkedTelemetryMsgProto linkedMsg, TbCallback callback) { var msg = linkedMsg.getMsg(); var tenantId = toTenantId(msg.getTenantIdMSB(), msg.getTenantIdLSB()); var entityId = EntityIdFactory.getByTypeAndUuid(msg.getEntityType(), new UUID(msg.getEntityIdMSB(), msg.getEntityIdLSB())); actorContext.tell(new CalculatedFieldLinkedTelemetryMsg(tenantId, entityId, linkedMsg, callback)); } private TenantId toTenantId(long tenantIdMSB, long tenantIdLSB) { return TenantId.fromUUID(new UUID(tenantIdMSB, tenantIdLSB)); } @Override protected void stopConsumers() { super.stopConsumers(); stateService.stop(); // eventConsumer will be stopped by stateService } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\DefaultTbCalculatedFieldConsumerService.java
2
请完成以下Java代码
public boolean getBoolArray() { return array[ThreadLocalRandom.current().nextInt(size)]; } @Benchmark public boolean getBitSet() { return bitSet.get(ThreadLocalRandom.current().nextInt(size)); } @Benchmark public void setBoolArray() { int index = ThreadLocalRandom.current().nextInt(size); array[index] = true; } @Benchmark public void setBitSet() { int index = ThreadLocalRandom.current().nextInt(size); bitSet.set(index); }
@Benchmark public int cardinalityBoolArray() { int sum = 0; for (boolean b : array) { if (b) { sum++; } } return sum; } @Benchmark public int cardinalityBitSet() { return bitSet.cardinality(); } }
repos\tutorials-master\jmh\src\main\java\com\baeldung\bitset\VectorOfBitsBenchmark.java
1
请完成以下Java代码
public void setPackageWeight (final @Nullable BigDecimal PackageWeight) { set_Value (COLUMNNAME_PackageWeight, PackageWeight); } @Override public BigDecimal getPackageWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PackageWeight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setReceivedInfo (final @Nullable java.lang.String ReceivedInfo) { set_Value (COLUMNNAME_ReceivedInfo, ReceivedInfo); } @Override public java.lang.String getReceivedInfo() { return get_ValueAsString(COLUMNNAME_ReceivedInfo); } @Override
public void setShipDate (final @Nullable java.sql.Timestamp ShipDate) { set_Value (COLUMNNAME_ShipDate, ShipDate); } @Override public java.sql.Timestamp getShipDate() { return get_ValueAsTimestamp(COLUMNNAME_ShipDate); } @Override public void setTrackingInfo (final @Nullable java.lang.String TrackingInfo) { set_Value (COLUMNNAME_TrackingInfo, TrackingInfo); } @Override public java.lang.String getTrackingInfo() { return get_ValueAsString(COLUMNNAME_TrackingInfo); } @Override public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override public java.lang.String getTrackingURL() { return get_ValueAsString(COLUMNNAME_TrackingURL); } @Override public void setWidthInCm (final int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, WidthInCm); } @Override public int getWidthInCm() { return get_ValueAsInt(COLUMNNAME_WidthInCm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Package.java
1
请完成以下Java代码
public void setFactoryClass(Class<?> clazz) { ref = new WeakReference<>(clazz); } } /** * Discover the name of class that implements ExpressionFactory. * * @param tccl {@code ClassLoader} * @return Class name. There is default, so it is never {@code null}. */ private static String discoverClassName(ClassLoader tccl) { // First services API String className = getClassNameServices(tccl); if (className == null) { // Second el.properties file className = getClassNameJreDir(); } if (className == null) { // Third system property className = getClassNameSysProp(); } if (className == null) { // Fourth - default className = "org.flowable.common.engine.impl.de.odysseus.el.ExpressionFactoryImpl"; } return className; } private static String getClassNameServices(ClassLoader tccl) { ExpressionFactory result = null; ServiceLoader<ExpressionFactory> serviceLoader = ServiceLoader.load(ExpressionFactory.class, tccl); Iterator<ExpressionFactory> iter = serviceLoader.iterator(); while (result == null && iter.hasNext()) { result = iter.next(); }
if (result == null) { return null; } return result.getClass().getName(); } private static String getClassNameJreDir() { File file = new File(PROPERTY_FILE); if (file.canRead()) { try (InputStream is = new FileInputStream(file)) { Properties props = new Properties(); props.load(is); String value = props.getProperty(PROPERTY_NAME); if (value != null && !value.trim().isEmpty()) { return value.trim(); } } catch (FileNotFoundException e) { // Should not happen - ignore it if it does } catch (IOException ioe) { throw new ELException("Failed to read " + PROPERTY_NAME, ioe); } } return null; } private static String getClassNameSysProp() { String value = System.getProperty(PROPERTY_NAME); if (value != null && !value.trim().isEmpty()) { return value.trim(); } return null; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\ExpressionFactory.java
1
请完成以下Java代码
public void setExpression(String expression) { this.expression = expression; } public String getVariable() { return variable; } public void setVariable(String variable) { this.variable = variable; } public String getType() { return type; } public String getDefaultExpression() { return defaultExpression; } public void setDefaultExpression(String defaultExpression) { this.defaultExpression = defaultExpression; } public void setType(String type) { this.type = type; } public String getDatePattern() { return datePattern; } public void setDatePattern(String datePattern) { this.datePattern = datePattern; } public boolean isReadable() { return readable; } public void setReadable(boolean readable) { this.readable = readable; } public boolean isWriteable() { return writeable; }
public void setWriteable(boolean writeable) { this.writeable = writeable; } public boolean isRequired() { return required; } public void setRequired(boolean required) { this.required = required; } public List<FormValue> getFormValues() { return formValues; } public void setFormValues(List<FormValue> formValues) { this.formValues = formValues; } public FormProperty clone() { FormProperty clone = new FormProperty(); clone.setValues(this); return clone; } public void setValues(FormProperty otherProperty) { super.setValues(otherProperty); setName(otherProperty.getName()); setExpression(otherProperty.getExpression()); setVariable(otherProperty.getVariable()); setType(otherProperty.getType()); setDefaultExpression(otherProperty.getDefaultExpression()); setDatePattern(otherProperty.getDatePattern()); setReadable(otherProperty.isReadable()); setWriteable(otherProperty.isWriteable()); setRequired(otherProperty.isRequired()); formValues = new ArrayList<FormValue>(); if (otherProperty.getFormValues() != null && !otherProperty.getFormValues().isEmpty()) { for (FormValue formValue : otherProperty.getFormValues()) { formValues.add(formValue.clone()); } } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\FormProperty.java
1
请完成以下Java代码
private IQueryBuilder<I_MD_Cockpit> createInitialQueryBuilder() { final IQueryBL queryBL = Services.get(IQueryBL.class); final IQueryBuilder<I_MD_Cockpit> queryBuilder = queryBL .createQueryBuilder(I_MD_Cockpit.class) .addOnlyActiveRecordsFilter(); return queryBuilder; } private boolean augmentQueryBuilder(final IQueryBuilder<I_MD_Cockpit> queryBuilder, final DateFilterVO dateFilterVO) { if (dateFilterVO == null) { return false; } final LocalDate date = dateFilterVO.getDate(); if (date == null) { return false; } queryBuilder.addCompareFilter(I_MD_Cockpit.COLUMN_DateGeneral, CompareQueryFilter.Operator.GREATER_OR_EQUAL, date); queryBuilder.addCompareFilter(I_MD_Cockpit.COLUMN_DateGeneral, CompareQueryFilter.Operator.LESS, date.plusDays(1)); return true; } private boolean augmentQueryBuilder(final IQueryBuilder<I_MD_Cockpit> queryBuilder, final ProductFilterVO productFilterVO) { final IQuery<I_M_Product> productQuery = ProductFilterUtil.createProductQueryOrNull(productFilterVO); if (productQuery == null) { return false; } queryBuilder.addInSubQueryFilter(I_MD_Cockpit.COLUMNNAME_M_Product_ID, I_M_Product.COLUMNNAME_M_Product_ID, productQuery);
return true; } private IQueryBuilder<I_MD_Cockpit> augmentQueryBuilderWithOrderBy(@NonNull final IQueryBuilder<I_MD_Cockpit> queryBuilder) { return queryBuilder .orderByDescending(I_MD_Cockpit.COLUMNNAME_QtyStockEstimateSeqNo_AtDate) .orderBy(I_MD_Cockpit.COLUMNNAME_DateGeneral) .orderBy(I_MD_Cockpit.COLUMNNAME_M_Product_ID) .orderBy(I_MD_Cockpit.COLUMNNAME_AttributesKey); } public LocalDate getFilterByDate(@NonNull final DocumentFilterList filters) { final DateFilterVO dateFilterVO = DateFilterUtil.extractDateFilterVO(filters); return dateFilterVO.getDate(); } public Predicate<I_M_Product> toProductFilterPredicate(@NonNull final DocumentFilterList filters) { return ProductFilterUtil.toPredicate(filters); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\filters\MaterialCockpitFilters.java
1
请在Spring Boot框架中完成以下Java代码
public class DatabaseFile { @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") private String id; private String fileName; private String fileType; @Lob private byte[] data; public DatabaseFile() { } public DatabaseFile(String fileName, String fileType, byte[] data) { this.fileName = fileName; this.fileType = fileType; this.data = data; } public String getId() { return id; } public String getFileName() { return fileName; } public String getFileType() { return fileType; }
public byte[] getData() { return data; } public void setId(String id) { this.id = id; } public void setFileName(String fileName) { this.fileName = fileName; } public void setFileType(String fileType) { this.fileType = fileType; } public void setData(byte[] data) { this.data = data; } }
repos\Spring-Boot-Advanced-Projects-main\springboot-upload-download-file-database\src\main\java\net\alanbinu\springboot\fileuploaddownload\model\DatabaseFile.java
2
请完成以下Java代码
public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPlannedAmt (final BigDecimal PlannedAmt) { set_Value (COLUMNNAME_PlannedAmt, PlannedAmt); } @Override public BigDecimal getPlannedAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt); return bd != null ? bd : BigDecimal.ZERO; } /** * ProjInvoiceRule AD_Reference_ID=383 * Reference name: C_Project InvoiceRule */ public static final int PROJINVOICERULE_AD_Reference_ID=383; /** None = - */ public static final String PROJINVOICERULE_None = "-"; /** Committed Amount = C */ public static final String PROJINVOICERULE_CommittedAmount = "C"; /** Time&Material max Comitted = c */ public static final String PROJINVOICERULE_TimeMaterialMaxComitted = "c"; /** Time&Material = T */ public static final String PROJINVOICERULE_TimeMaterial = "T"; /** Product Quantity = P */ public static final String PROJINVOICERULE_ProductQuantity = "P"; @Override public void setProjInvoiceRule (final java.lang.String ProjInvoiceRule) { set_Value (COLUMNNAME_ProjInvoiceRule, ProjInvoiceRule); } @Override public java.lang.String getProjInvoiceRule() { return get_ValueAsString(COLUMNNAME_ProjInvoiceRule); }
@Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectTask.java
1
请在Spring Boot框架中完成以下Java代码
private List<RedisNode> getNodes(Cluster cluster) { return cluster.getNodes().stream().map(this::asRedisNode).toList(); } private RedisNode asRedisNode(Node node) { return new RedisNode(node.host(), node.port()); } protected final DataRedisProperties getProperties() { return this.properties; } protected @Nullable SslBundle getSslBundle() { return this.connectionDetails.getSslBundle(); } protected final boolean isSslEnabled() { return getProperties().getSsl().isEnabled(); } protected final boolean urlUsesSsl(String url) { return DataRedisUrl.of(url).useSsl(); } protected boolean isPoolEnabled(Pool pool) { Boolean enabled = pool.getEnabled(); return (enabled != null) ? enabled : COMMONS_POOL2_AVAILABLE; } private List<RedisNode> createSentinels(Sentinel sentinel) { List<RedisNode> nodes = new ArrayList<>();
for (Node node : sentinel.getNodes()) { nodes.add(asRedisNode(node)); } return nodes; } protected final DataRedisConnectionDetails getConnectionDetails() { return this.connectionDetails; } private Mode determineMode() { if (getSentinelConfig() != null) { return Mode.SENTINEL; } if (getClusterConfiguration() != null) { return Mode.CLUSTER; } if (getMasterReplicaConfiguration() != null) { return Mode.MASTER_REPLICA; } return Mode.STANDALONE; } enum Mode { STANDALONE, CLUSTER, MASTER_REPLICA, SENTINEL } }
repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\DataRedisConnectionConfiguration.java
2
请完成以下Java代码
public class ResourceImpl extends RootElementImpl implements Resource { protected static Attribute<String> nameAttribute; protected static ChildElementCollection<ResourceParameter> resourceParameterCollection; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Resource.class, BPMN_ELEMENT_RESOURCE) .namespaceUri(BPMN20_NS) .extendsType(RootElement.class) .instanceProvider(new ModelTypeInstanceProvider<Resource>() { public Resource newInstance(ModelTypeInstanceContext instanceContext) { return new ResourceImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .required() .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); resourceParameterCollection = sequenceBuilder.elementCollection(ResourceParameter.class) .build(); typeBuilder.build(); }
public ResourceImpl(ModelTypeInstanceContext context) { super(context); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public Collection<ResourceParameter> getResourceParameters() { return resourceParameterCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ResourceImpl.java
1
请完成以下Java代码
public boolean isEnableSafeDmnXml() { return enableSafeDmnXml; } public DmnEngineConfiguration setEnableSafeDmnXml(boolean enableSafeDmnXml) { this.enableSafeDmnXml = enableSafeDmnXml; return this; } public boolean isStrictMode() { return strictMode; } public DmnEngineConfiguration setStrictMode(boolean strictMode) { this.strictMode = strictMode; return this; } @Override public DmnEngineConfiguration setClock(Clock clock) { this.clock = clock; return this; } @Override public DmnEngineConfiguration setDatabaseSchemaUpdate(String databaseSchemaUpdate) { this.databaseSchemaUpdate = databaseSchemaUpdate; return this; } public void setHitPolicyBehaviors(Map<String, AbstractHitPolicy> hitPolicyBehaviors) { this.hitPolicyBehaviors = hitPolicyBehaviors; } public Map<String, AbstractHitPolicy> getHitPolicyBehaviors() { return hitPolicyBehaviors; } public void setCustomHitPolicyBehaviors(Map<String, AbstractHitPolicy> customHitPolicyBehaviors) { this.customHitPolicyBehaviors = customHitPolicyBehaviors; } public Map<String, AbstractHitPolicy> getCustomHitPolicyBehaviors() { return customHitPolicyBehaviors; } public DecisionRequirementsDiagramGenerator getDecisionRequirementsDiagramGenerator() { return decisionRequirementsDiagramGenerator;
} public DmnEngineConfiguration setDecisionRequirementsDiagramGenerator(DecisionRequirementsDiagramGenerator decisionRequirementsDiagramGenerator) { this.decisionRequirementsDiagramGenerator = decisionRequirementsDiagramGenerator; return this; } public boolean isCreateDiagramOnDeploy() { return isCreateDiagramOnDeploy; } public DmnEngineConfiguration setCreateDiagramOnDeploy(boolean isCreateDiagramOnDeploy) { this.isCreateDiagramOnDeploy = isCreateDiagramOnDeploy; return this; } public String getDecisionFontName() { return decisionFontName; } public DmnEngineConfiguration setDecisionFontName(String decisionFontName) { this.decisionFontName = decisionFontName; return this; } public String getLabelFontName() { return labelFontName; } public DmnEngineConfiguration setLabelFontName(String labelFontName) { this.labelFontName = labelFontName; return this; } public String getAnnotationFontName() { return annotationFontName; } public DmnEngineConfiguration setAnnotationFontName(String annotationFontName) { this.annotationFontName = annotationFontName; return this; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\DmnEngineConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Email address of the contact. * * @return * possible object is * {@link String } * */ public String getEmail() { return email; } /** * Sets the value of the email property. * * @param value * allowed object is * {@link String } * */ public void setEmail(String value) { this.email = value; } /** * Phone number of the contact. * * @return * possible object is * {@link String } * */ public String getPhone() { return phone; } /** * Sets the value of the phone property. * * @param value * allowed object is * {@link String } * */
public void setPhone(String value) { this.phone = value; } /** * Fax number of the contact. * * @return * possible object is * {@link String } * */ public String getFax() { return fax; } /** * Sets the value of the fax property. * * @param value * allowed object is * {@link String } * */ public void setFax(String value) { this.fax = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ContactType.java
2
请完成以下Java代码
private static class Pkcs7Encoder { private static final int BLOCK_SIZE = 32; private static byte[] encode(byte[] src) { int count = src.length; // 计算需要填充的位数 int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE); // 获得补位所用的字符 byte pad = (byte) (amountToPad & 0xFF); byte[] pads = new byte[amountToPad]; for (int index = 0; index < amountToPad; index++) { pads[index] = pad; } int length = count + amountToPad; byte[] dest = new byte[length]; System.arraycopy(src, 0, dest, 0, count); System.arraycopy(pads, 0, dest, count, amountToPad);
return dest; } private static byte[] decode(byte[] decrypted) { int pad = decrypted[decrypted.length - 1]; if (pad < 1 || pad > BLOCK_SIZE) { pad = 0; } if (pad > 0) { return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad); } return decrypted; } } }
repos\SpringBlade-master\blade-gateway\src\main\java\org\springblade\gateway\utils\JwtCrypto.java
1
请完成以下Java代码
public boolean isStaled () { Object oo = get_Value(COLUMNNAME_IsStaled); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Gueltig. @param IsValid Element ist gueltig */ public void setIsValid (boolean IsValid) { set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid)); } /** Get Gueltig. @return Element ist gueltig */ public boolean isValid () { Object oo = get_Value(COLUMNNAME_IsValid); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Last Refresh Date. @param LastRefreshDate Last Refresh Date */
public void setLastRefreshDate (Timestamp LastRefreshDate) { set_Value (COLUMNNAME_LastRefreshDate, LastRefreshDate); } /** Get Last Refresh Date. @return Last Refresh Date */ public Timestamp getLastRefreshDate () { return (Timestamp)get_Value(COLUMNNAME_LastRefreshDate); } /** Set Staled Since. @param StaledSinceDate Staled Since */ public void setStaledSinceDate (Timestamp StaledSinceDate) { set_Value (COLUMNNAME_StaledSinceDate, StaledSinceDate); } /** Get Staled Since. @return Staled Since */ public Timestamp getStaledSinceDate () { return (Timestamp)get_Value(COLUMNNAME_StaledSinceDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_Table_MView.java
1
请完成以下Java代码
public void setPOReference (final @Nullable java.lang.String POReference) { set_ValueNoCheck (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setProcessed (final boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_ValueNoCheck (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setSumDeliveredInStockingUOM (final @Nullable BigDecimal SumDeliveredInStockingUOM)
{ set_ValueNoCheck (COLUMNNAME_SumDeliveredInStockingUOM, SumDeliveredInStockingUOM); } @Override public BigDecimal getSumDeliveredInStockingUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumDeliveredInStockingUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSumOrderedInStockingUOM (final @Nullable BigDecimal SumOrderedInStockingUOM) { set_ValueNoCheck (COLUMNNAME_SumOrderedInStockingUOM, SumOrderedInStockingUOM); } @Override public BigDecimal getSumOrderedInStockingUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumOrderedInStockingUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUserFlag (final @Nullable java.lang.String UserFlag) { set_ValueNoCheck (COLUMNNAME_UserFlag, UserFlag); } @Override public java.lang.String getUserFlag() { return get_ValueAsString(COLUMNNAME_UserFlag); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_M_InOut_Desadv_V.java
1
请完成以下Java代码
public class BpmnErrorRequestDto extends RequestDto { protected String errorCode; protected String errorMessage; protected Map<String, TypedValueField> variables; public BpmnErrorRequestDto(String workerId, String errorCode) { super(workerId); this.errorCode = errorCode; } public BpmnErrorRequestDto(String workerId, String errorCode, String errorMessage) { this(workerId, errorCode); this.errorMessage = errorMessage; } public BpmnErrorRequestDto(String workerId, String errorCode, String errorMessage, Map<String, TypedValueField> variables) {
this(workerId, errorCode, errorMessage); this.variables = variables; } public String getErrorCode() { return errorCode; } public String getErrorMessage() { return errorMessage; } public Map<String, TypedValueField> getVariables() { return variables; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\task\impl\dto\BpmnErrorRequestDto.java
1
请完成以下Java代码
public class AuthorizationGrantedEvent<T> extends AuthorizationEvent implements ResolvableTypeProvider { @Serial private static final long serialVersionUID = -8690818228055810339L; /** * @since 6.4 */ public AuthorizationGrantedEvent(Supplier<Authentication> authentication, T object, AuthorizationResult result) { super(authentication, object, result); } /** * Get the object to which access was requested * @return the object to which access was requested * @since 5.8 */ @Override @SuppressWarnings("unchecked")
public T getObject() { return (T) getSource(); } /** * Get {@link ResolvableType} of this class. * @return {@link ResolvableType} * @since 6.5 */ @Override public ResolvableType getResolvableType() { return ResolvableType.forClassWithGenerics(getClass(), ResolvableType.forInstance(getObject())); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\event\AuthorizationGrantedEvent.java
1
请完成以下Java代码
public Map<Locale, Charset> getLocaleCharsetMappings() { return this.localeCharsetMappings; } public Map<String, String> getInitParameters() { return this.initParameters; } public List<? extends CookieSameSiteSupplier> getCookieSameSiteSuppliers() { return this.cookieSameSiteSuppliers; } public void setMimeMappings(MimeMappings mimeMappings) { Assert.notNull(mimeMappings, "'mimeMappings' must not be null"); this.mimeMappings = new MimeMappings(mimeMappings); } public void addMimeMappings(MimeMappings mimeMappings) { mimeMappings.forEach((mapping) -> this.mimeMappings.add(mapping.getExtension(), mapping.getMimeType())); } public void setInitializers(List<? extends ServletContextInitializer> initializers) { Assert.notNull(initializers, "'initializers' must not be null"); this.initializers = new ArrayList<>(initializers); } public void addInitializers(ServletContextInitializer... initializers) { Assert.notNull(initializers, "'initializers' must not be null"); this.initializers.addAll(Arrays.asList(initializers)); } public void setLocaleCharsetMappings(Map<Locale, Charset> localeCharsetMappings) { Assert.notNull(localeCharsetMappings, "'localeCharsetMappings' must not be null"); this.localeCharsetMappings = localeCharsetMappings; }
public void setInitParameters(Map<String, String> initParameters) { this.initParameters = initParameters; } public void setCookieSameSiteSuppliers(List<? extends CookieSameSiteSupplier> cookieSameSiteSuppliers) { Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null"); this.cookieSameSiteSuppliers = new ArrayList<>(cookieSameSiteSuppliers); } public void addCookieSameSiteSuppliers(CookieSameSiteSupplier... cookieSameSiteSuppliers) { Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null"); this.cookieSameSiteSuppliers.addAll(Arrays.asList(cookieSameSiteSuppliers)); } public void addWebListenerClassNames(String... webListenerClassNames) { this.webListenerClassNames.addAll(Arrays.asList(webListenerClassNames)); } public Set<String> getWebListenerClassNames() { return this.webListenerClassNames; } public List<URL> getStaticResourceUrls() { return this.staticResourceJars.getUrls(); } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ServletWebServerSettings.java
1
请在Spring Boot框架中完成以下Java代码
public String extract(@ValidFileType MultipartFile image) throws IOException { byte[] imageBytes = image.getBytes(); DetectDocumentTextResponse response = textractClient.detectDocumentText(request -> request .document(document -> document .bytes(SdkBytes.fromByteArray(imageBytes)) .build()) .build()); return transformTextDetectionResponse(response); } public String extract(String bucketName, String objectKey) { DetectDocumentTextResponse response = textractClient.detectDocumentText(request -> request .document(document -> document .s3Object(s3Object -> s3Object .bucket(bucketName) .name(objectKey) .build())
.build()) .build()); return transformTextDetectionResponse(response); } private String transformTextDetectionResponse(DetectDocumentTextResponse response) { return response.blocks() .stream() .filter(block -> block.blockType().equals(BlockType.LINE)) .map(Block::text) .collect(Collectors.joining(" ")); } }
repos\tutorials-master\aws-modules\amazon-textract\src\main\java\com\baeldung\textract\service\TextExtractor.java
2
请完成以下Java代码
class C_OLCand_HandlerDAO { public IQueryBuilder<I_C_OLCand> retrieveMissingCandidatesQuery(final Properties ctx, final String trxName) { final IQueryBL queryBL = Services.get(IQueryBL.class); final IQueryBuilder<I_C_OLCand> queryBuilder = queryBL.createQueryBuilder(I_C_OLCand.class, ctx, trxName) .addOnlyActiveRecordsFilter() .addOnlyContextClient(); // // Only those without errors queryBuilder.addEqualsFilter(I_C_OLCand.COLUMNNAME_IsError, false); // // Only which are for our data source final IInputDataSourceDAO inputDataSourceDAO = Services.get(IInputDataSourceDAO.class); final I_AD_InputDataSource dataSource = inputDataSourceDAO.retrieveInputDataSource(ctx, InvoiceCandidate_Constants.DATA_DESTINATION_INTERNAL_NAME, false/* the record might be deactivated if that case simply never happens on a particular machting */, trxName); queryBuilder.addEqualsFilter(I_C_OLCand.COLUMN_AD_DataDestination_ID, dataSource.getAD_InputDataSource_ID()); //
// Only those which were not already created final IQuery<I_C_Invoice_Candidate> existingICsQuery = queryBL.createQueryBuilder(I_C_Invoice_Candidate.class, ctx, trxName) .addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_AD_Table_ID, InterfaceWrapperHelper.getTableId(I_C_OLCand.class)) .create(); queryBuilder.addNotInSubQueryFilter(I_C_OLCand.COLUMNNAME_C_OLCand_ID, I_C_OLCand.COLUMNNAME_Record_ID, existingICsQuery); // // Order by queryBuilder.orderBy() .addColumn(I_C_OLCand.COLUMN_C_OLCand_ID); return queryBuilder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\invoicecandidate\spi\impl\C_OLCand_HandlerDAO.java
1
请完成以下Java代码
public CmmnEngine getObject() throws Exception { configureExternallyManagedTransactions(); if (cmmnEngineConfiguration.getBeans() == null) { cmmnEngineConfiguration.setBeans(new SpringBeanFactoryProxyMap(applicationContext)); } this.cmmnEngine = cmmnEngineConfiguration.buildCmmnEngine(); return this.cmmnEngine; } protected void configureExternallyManagedTransactions() { if (cmmnEngineConfiguration instanceof SpringCmmnEngineConfiguration) { // remark: any config can be injected, so we cannot have SpringConfiguration as member SpringCmmnEngineConfiguration engineConfiguration = (SpringCmmnEngineConfiguration) cmmnEngineConfiguration; if (engineConfiguration.getTransactionManager() != null) { cmmnEngineConfiguration.setTransactionsExternallyManaged(true); } } } @Override
public Class<CmmnEngine> getObjectType() { return CmmnEngine.class; } @Override public boolean isSingleton() { return true; } public CmmnEngineConfiguration getCmmnEngineConfiguration() { return cmmnEngineConfiguration; } public void setCmmnEngineConfiguration(CmmnEngineConfiguration cmmnEngineConfiguration) { this.cmmnEngineConfiguration = cmmnEngineConfiguration; } }
repos\flowable-engine-main\modules\flowable-cmmn-spring\src\main\java\org\flowable\cmmn\spring\CmmnEngineFactoryBean.java
1