instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Spring Boot application配置
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect spring.application.name = spring-boot-bootstrap spring.datasource.username = ${SPRING_DATAS
OURCE_USER} spring.datasource.password = ${SPRING_DATASOURCE_PASSWORD}
repos\tutorials-master\spring-boot-modules\spring-boot-bootstrap\src\main\resources\application-mysql.properties
2
请在Spring Boot框架中完成以下Java代码
public BigInteger getTimeForPayment() { return timeForPayment; } /** * Sets the value of the timeForPayment property. * * @param value * allowed object is * {@link BigInteger } * */ public void setTimeForPayment(BigInteger value) { this.timeForPayment = value; } /** * Additional free text.Gets the value of the freeText property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the freeText property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFreeText().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FreeTextType } * * */ public List<FreeTextType> getFreeText() { if (freeText == null) { freeText = new ArrayList<FreeTextType>(); } return this.freeText; }
/** * Reference to the consignment. * * @return * possible object is * {@link String } * */ public String getConsignmentReference() { return consignmentReference; } /** * Sets the value of the consignmentReference property. * * @param value * allowed object is * {@link String } * */ public void setConsignmentReference(String value) { this.consignmentReference = 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\ORDERSExtensionType.java
2
请完成以下Java代码
public boolean checkResourceExists(Locale locale) throws Exception { return resolveResource() != null; } @Override protected Mono<Void> renderInternal(Map<String, Object> model, @Nullable MediaType contentType, ServerWebExchange exchange) { Resource resource = resolveResource(); if (resource == null) { return Mono .error(new IllegalStateException("Could not find Mustache template with URL [" + getUrl() + "]")); } DataBuffer dataBuffer = exchange.getResponse() .bufferFactory() .allocateBuffer(DefaultDataBufferFactory.DEFAULT_INITIAL_CAPACITY); try (Reader reader = getReader(resource)) { Assert.state(this.compiler != null, "'compiler' must not be null"); Template template = this.compiler.compile(reader); Charset charset = getCharset(contentType).orElseGet(this::getDefaultCharset); try (Writer writer = new OutputStreamWriter(dataBuffer.asOutputStream(), charset)) { template.execute(model, writer); writer.flush(); } } catch (Exception ex) { DataBufferUtils.release(dataBuffer); return Mono.error(ex); } return exchange.getResponse().writeWith(Flux.just(dataBuffer)); } private @Nullable Resource resolveResource() { ApplicationContext applicationContext = getApplicationContext(); String url = getUrl(); if (applicationContext == null || url == null) { return null;
} Resource resource = applicationContext.getResource(url); if (resource == null || !resource.exists()) { return null; } return resource; } private Reader getReader(Resource resource) throws IOException { if (this.charset != null) { return new InputStreamReader(resource.getInputStream(), this.charset); } return new InputStreamReader(resource.getInputStream()); } private Optional<Charset> getCharset(@Nullable MediaType mediaType) { return Optional.ofNullable((mediaType != null) ? mediaType.getCharset() : null); } }
repos\spring-boot-4.0.1\module\spring-boot-mustache\src\main\java\org\springframework\boot\mustache\reactive\view\MustacheView.java
1
请完成以下Java代码
private void processInTrx(@NonNull final PickingCandidate pickingCandidate) { if (pickingCandidate.isRejectedToPick()) { // TODO: impl throw new AdempiereException("Unprocessing not supported"); } else if (pickingCandidate.getPickFrom().isPickFromHU()) { processInTrx_unpackHU(pickingCandidate); } else if (pickingCandidate.getPickFrom().isPickFromPickingOrder()) { // TODO: impl throw new AdempiereException("Unprocessing not supported"); } else { throw new AdempiereException("Unknown " + pickingCandidate.getPickFrom()); } } private void processInTrx_unpackHU(@NonNull final PickingCandidate pickingCandidate) { final HuId packedToHUId = pickingCandidate.getPackedToHuId(); if (packedToHUId == null) { return; } final I_M_HU packedToHU = handlingUnitsBL.getById(packedToHUId); if (handlingUnitsBL.isDestroyed(packedToHU)) {
// shall not happen return; } if (X_M_HU.HUSTATUS_Picked.equals(packedToHU.getHUStatus())) { handlingUnitsBL.setHUStatus(packedToHU, PlainContextAware.newWithThreadInheritedTrx(), X_M_HU.HUSTATUS_Active); } pickingCandidate.changeStatusToDraft(); pickingCandidateRepository.save(pickingCandidate); huShipmentScheduleBL.deleteByTopLevelHUAndShipmentScheduleId(packedToHUId, pickingCandidate.getShipmentScheduleId()); } @NonNull private ProductId getProductId(final PickingCandidate pickingCandidate) { final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(pickingCandidate.getShipmentScheduleId()); return ProductId.ofRepoId(shipmentSchedule.getM_Product_ID()); } private I_M_ShipmentSchedule getShipmentScheduleById(@NonNull final ShipmentScheduleId shipmentScheduleId) { return shipmentSchedulesCache.computeIfAbsent(shipmentScheduleId, huShipmentScheduleBL::getById); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\UnProcessPickingCandidatesCommand.java
1
请完成以下Java代码
private void setValueForProcessorMap(Map<ProcessReqEnum, Processor> processorMap, Field processorMapField) throws IllegalAccessException { // 获取ProcessEngine对象 ProcessEngine processEngine = applicationContext.getBean(ProcessEngine.class); // 将processorMapField设为public processorMapField.setAccessible(true); // 赋值 processorMapField.set(processEngine, processorMap); } /** * 创建ProcessorMap * @param injectProcessors injectProcessors注解对象 * @return ProcessorMap */ private Map<ProcessReqEnum, Processor> createProcessorMap(InjectProcessors injectProcessors) { // 初始化容器 Map<ProcessReqEnum, Processor> processorMap = Maps.newHashMap(); // 获取注解中的值 Class[] processorClazzList = injectProcessors.value(); if (processorClazzList==null || processorClazzList.length<=0) { return processorMap; } // 遍历 for (Class<Processor> processorClazz : processorClazzList) { // 获取Processor Processor processor = applicationContext.getBean(processorClazz); // 获取枚举 ProcessReqEnum processReqEnum = EnumUtil.msgOf(ProcessReqEnum.class, processorClazz.getSimpleName()); // 加入map processorMap.put(processReqEnum, processor); System.out.println(processor); System.out.println("------------");
} System.out.println(processorMap); return processorMap; } /** * 获取需要扫描的包名 */ private String getPackage() { PackageScan packageScan = AnnotationUtil.getAnnotationValueByClass(this.getClass(), PackageScan.class); return packageScan.value(); } @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\init\InitProcessorMap.java
1
请完成以下Java代码
public ReadWriteLock getLock() { return lock; } public String getFactoryClassName() { return className; } public void setFactoryClassName(String className) { this.className = className; } public Class<?> getFactoryClass() { return ref != null ? ref.get() : null; } 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 boolean containsValue(Object value) { return this.session.getAttributeNames() .stream() .anyMatch((attrName) -> this.session.getAttribute(attrName) != null); } @Override @Nullable public Object get(Object key) { if (key instanceof String) { return this.session.getAttribute((String) key); } return null; } @Override public Object put(String key, Object value) { Object original = this.session.getAttribute(key); this.session.setAttribute(key, value); return original; } @Override @Nullable public Object remove(Object key) { if (key instanceof String) { String attrName = (String) key; Object original = this.session.getAttribute(attrName); this.session.removeAttribute(attrName); return original; } return null; } @Override public void putAll(Map<? extends String, ?> m) { for (Entry<? extends String, ?> entry : m.entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public void clear() { for (String attrName : this.session.getAttributeNames()) { remove(attrName); } } @Override public Set<String> keySet() { return this.session.getAttributeNames(); } @Override public Collection<Object> values() { return this.values; } @Override public Set<Entry<String, Object>> entrySet() { Set<String> attrNames = keySet(); Set<Entry<String, Object>> entries = new HashSet<>(attrNames.size()); for (String attrName : attrNames) { Object value = this.session.getAttribute(attrName); entries.add(new AbstractMap.SimpleEntry<>(attrName, value)); } return Collections.unmodifiableSet(entries); } private class SessionValues extends AbstractCollection<Object> { @Override public Iterator<Object> iterator() { return new Iterator<Object>() { private Iterator<Entry<String, Object>> i = entrySet().iterator(); @Override public boolean hasNext() { return this.i.hasNext(); }
@Override public Object next() { return this.i.next().getValue(); } @Override public void remove() { this.i.remove(); } }; } @Override public int size() { return SpringSessionMap.this.size(); } @Override public boolean isEmpty() { return SpringSessionMap.this.isEmpty(); } @Override public void clear() { SpringSessionMap.this.clear(); } @Override public boolean contains(Object v) { return SpringSessionMap.this.containsValue(v); } } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\server\session\SpringSessionWebSessionStore.java
1
请在Spring Boot框架中完成以下Java代码
public class ReadPluFileProcessor implements Processor { private final ProcessLogger processLogger; public ReadPluFileProcessor(@NonNull final ProcessLogger processLogger) { this.processLogger = processLogger; } @Override public void process(@NonNull final Exchange exchange) { final ExportPPOrderRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_EXPORT_PP_ORDER_CONTEXT, ExportPPOrderRouteContext.class); final String content = updatePluFile(context); final DispatchMessageRequest request = DispatchMessageRequest.builder() .destinationDetails(context.getDestinationDetails()) .payload(content) .build(); exchange.getIn().setBody(request, DispatchMessageRequest.class); } @NonNull private String updatePluFile(@NonNull final ExportPPOrderRouteContext context) { final String productBaseFolderName = context.getPluTemplateFileBaseFolderName(); final JsonExternalSystemLeichMehlConfigProductMapping mapping = context.getProductMapping(); try { final Path filePath = getPluFilePath(productBaseFolderName, mapping.getPluFile()); final Document pluDocument = XMLUtil.readFromPath(filePath); final JsonPluFileAudit jsonPluFileAudit = updateDocument(pluDocument, filePath, context); final String fileContentWithoutXMLDeclaration = XMLUtil.toString(pluDocument); context.setJsonPluFileAudit(jsonPluFileAudit); context.setPluFileXmlContent(addXMLDeclarationIfNeeded(fileContentWithoutXMLDeclaration)); context.setPluTemplateFilename(filePath.getFileName().toString());
return fileContentWithoutXMLDeclaration; } catch (final Exception e) { throw new RuntimeCamelException(e); } } @NonNull private JsonPluFileAudit updateDocument( @NonNull final Document pluDocument, @NonNull final Path filepath, @NonNull final ExportPPOrderRouteContext context) throws TransformerException { final FileUpdater fileUpdater = FileUpdater.builder() .fileName(filepath.getFileName().toString()) .document(pluDocument) .context(context) .processLogger(processLogger) .build(); return fileUpdater.updateDocument(); } @NonNull private static Path getPluFilePath(@NonNull final String productBaseFolderName, @NonNull final String pluFilepath) { return Paths.get(productBaseFolderName, FileUtil.normalizeAndValidateFilePath(pluFilepath)); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\pporder\processor\ReadPluFileProcessor.java
2
请完成以下Java代码
public boolean isCanAdjust() { return (getQty().compareTo(getMinQty()) > 0); } // isCanAdjust /** * Get Actual Allocation Qty * @return the greater of the min/qty */ public BigDecimal getActualAllocation() { if (getQty().compareTo(getMinQty()) > 0) return getQty(); else return getMinQty(); } // getActualAllocation /** * Adjust the Quantity maintaining UOM precision * @param difference difference * @return remaining difference (because under Min or rounding) */ public BigDecimal adjustQty (BigDecimal difference) { BigDecimal diff = difference.setScale(m_precision, BigDecimal.ROUND_HALF_UP); BigDecimal qty = getQty(); BigDecimal max = getMinQty().subtract(qty); BigDecimal remaining = Env.ZERO; if (max.compareTo(diff) > 0) // diff+max are negative { remaining = diff.subtract(max); setQty(qty.add(max)); } else setQty(qty.add(diff)); log.debug("Qty=" + qty + ", Min=" + getMinQty() + ", Max=" + max + ", Diff=" + diff + ", newQty=" + getQty() + ", Remaining=" + remaining); return remaining;
} // adjustQty /** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("MDistributionRunDetail[") .append (get_ID ()) .append (";M_DistributionListLine_ID=").append (getM_DistributionListLine_ID()) .append(";Qty=").append(getQty()) .append(";Ratio=").append(getRatio()) .append(";MinQty=").append(getMinQty()) .append ("]"); return sb.toString (); } // toString } // DistributionRunDetail
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MDistributionRunDetail.java
1
请完成以下Java代码
public boolean reverseAccrualIt() { throw new UnsupportedOperationException(); } @Override public boolean reActivateIt() { throw new UnsupportedOperationException(); } private boolean isReversal() { final int reversalId = getReversal_ID(); return reversalId > 0 && reversalId > getPP_Cost_Collector_ID(); } @Override public String getSummary() { return getDescription(); } @Override public LocalDate getDocumentDate() { return TimeUtil.asLocalDate(getMovementDate()); } @Override public String getProcessMsg() { return null; } @Override public int getDoc_User_ID() { return getCreatedBy(); } @Override public int getC_Currency_ID() { return 0; // N/A }
@Override public BigDecimal getApprovalAmt() { return BigDecimal.ZERO; // N/A } @Override public File createPDF() { throw new UnsupportedOperationException(); // N/A } @Override public String getDocumentInfo() { final I_C_DocType dt = MDocType.get(getCtx(), getC_DocType_ID()); return dt.getName() + " " + getDocumentNo(); } private PPOrderRouting getOrderRouting() { final IPPOrderRoutingRepository orderRoutingsRepo = Services.get(IPPOrderRoutingRepository.class); final PPOrderId orderId = PPOrderId.ofRepoId(getPP_Order_ID()); return orderRoutingsRepo.getByOrderId(orderId); } private PPOrderRoutingActivityId getActivityId() { final PPOrderId orderId = PPOrderId.ofRepoId(getPP_Order_ID()); return PPOrderRoutingActivityId.ofRepoId(orderId, getPP_Order_Node_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\MPPCostCollector.java
1
请完成以下Java代码
public ImmutableList<List<String>> getSQL_ResultRowsAsListsOfStrings(final String sqlStatement, final List<Object> parameters, final String trxName) { List<List<String>> result = null; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = prepareStatement(sqlStatement, trxName); setParameters(pstmt, parameters); rs = pstmt.executeQuery(); final int columnsCount = rs.getMetaData().getColumnCount(); if (columnsCount > 0) { result = new ArrayList<>(); while (rs.next()) { final List<String> row = new ArrayList<>(); for (int i = 1; i <= columnsCount; i++) { row.add(rs.getString(i)); } result.add(row);
} } } catch (final SQLException sqlException) { throw new DBException(sqlException, sqlStatement, parameters); } finally { DB.close(rs, pstmt); } return result != null ? ImmutableList.copyOf(result) : ImmutableList.of(); } } // DB
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\DB.java
1
请在Spring Boot框架中完成以下Java代码
public class InMemoryHttpExchangeRepository implements HttpExchangeRepository { private int capacity = 100; private boolean reverse = true; private final List<HttpExchange> httpExchanges = new LinkedList<>(); /** * Flag to say that the repository lists exchanges in reverse order. * @param reverse flag value (default true) */ public void setReverse(boolean reverse) { synchronized (this.httpExchanges) { this.reverse = reverse; } } /** * Set the capacity of the in-memory repository. * @param capacity the capacity */ public void setCapacity(int capacity) { synchronized (this.httpExchanges) { this.capacity = capacity; } } @Override public List<HttpExchange> findAll() { synchronized (this.httpExchanges) { return List.copyOf(this.httpExchanges);
} } @Override public void add(HttpExchange exchange) { synchronized (this.httpExchanges) { while (this.httpExchanges.size() >= this.capacity) { this.httpExchanges.remove(this.reverse ? this.capacity - 1 : 0); } if (this.reverse) { this.httpExchanges.add(0, exchange); } else { this.httpExchanges.add(exchange); } } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\web\exchanges\InMemoryHttpExchangeRepository.java
2
请完成以下Java代码
public void copy(Path source, Path target, CopyOption... options) throws IOException { throw new ReadOnlyFileSystemException(); } @Override public void move(Path source, Path target, CopyOption... options) throws IOException { throw new ReadOnlyFileSystemException(); } @Override public boolean isSameFile(Path path, Path path2) throws IOException { return path.equals(path2); } @Override public boolean isHidden(Path path) throws IOException { return false; } @Override public FileStore getFileStore(Path path) throws IOException { NestedPath nestedPath = NestedPath.cast(path); nestedPath.assertExists(); return new NestedFileStore(nestedPath.getFileSystem()); } @Override public void checkAccess(Path path, AccessMode... modes) throws IOException { Path jarPath = getJarPath(path); jarPath.getFileSystem().provider().checkAccess(jarPath, modes); } @Override public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) { Path jarPath = getJarPath(path); return jarPath.getFileSystem().provider().getFileAttributeView(jarPath, type, options); } @Override public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options) throws IOException {
Path jarPath = getJarPath(path); return jarPath.getFileSystem().provider().readAttributes(jarPath, type, options); } @Override public Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException { Path jarPath = getJarPath(path); return jarPath.getFileSystem().provider().readAttributes(jarPath, attributes, options); } protected Path getJarPath(Path path) { return NestedPath.cast(path).getJarPath(); } @Override public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException { throw new ReadOnlyFileSystemException(); } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileSystemProvider.java
1
请完成以下Java代码
private void addExecutionListener(final ActivityImpl activity) { if (executionListener != null) { for (String event : EXECUTION_EVENTS) { addListenerOnCoreModelElement(activity, executionListener, event); } } } private void addExecutionListener(final TransitionImpl transition) { if (executionListener != null) { addListenerOnCoreModelElement(transition, executionListener, EVENTNAME_TAKE); } } private void addListenerOnCoreModelElement(CoreModelElement element, DelegateListener<?> listener, String event) { if (skippable) { element.addListener(event, listener); } else { element.addBuiltInListener(event, listener); } } private void addTaskListener(TaskDefinition taskDefinition) { if (taskListener != null) { for (String event : TASK_EVENTS) {
if (skippable) { taskDefinition.addTaskListener(event, taskListener); } else { taskDefinition.addBuiltInTaskListener(event, taskListener); } } } } /** * Retrieves task definition. * * @param activity the taskActivity * @return taskDefinition for activity */ private TaskDefinition taskDefinition(final ActivityImpl activity) { final UserTaskActivityBehavior activityBehavior = (UserTaskActivityBehavior) activity.getActivityBehavior(); return activityBehavior.getTaskDefinition(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\PublishDelegateParseListener.java
1
请完成以下Java代码
protected boolean isChildOfMultiInstanceExecution( DelegateExecution executionEntity, DelegateExecution multiInstanceExecution ) { boolean isChild = false; DelegateExecution parentExecution = executionEntity.getParent(); if (parentExecution != null) { if (parentExecution.getId().equals(multiInstanceExecution.getId())) { isChild = true; } else { boolean isNestedChild = isChildOfMultiInstanceExecution(parentExecution, multiInstanceExecution); if (isNestedChild) { isChild = true; } } } return isChild; } protected boolean hasMultiInstanceParent(FlowNode flowNode) { boolean hasMultiInstanceParent = false; if (flowNode.getSubProcess() != null) { if (flowNode.getSubProcess().getLoopCharacteristics() != null) { hasMultiInstanceParent = true; } else { boolean hasNestedMultiInstanceParent = hasMultiInstanceParent(flowNode.getSubProcess()); if (hasNestedMultiInstanceParent) { hasMultiInstanceParent = true; } } } return hasMultiInstanceParent; } protected DelegateExecution findMultiInstanceParentExecution(DelegateExecution execution) { DelegateExecution multiInstanceExecution = null;
DelegateExecution parentExecution = execution.getParent(); if (parentExecution != null && parentExecution.getCurrentFlowElement() != null) { FlowElement flowElement = parentExecution.getCurrentFlowElement(); if (flowElement instanceof Activity) { Activity activity = (Activity) flowElement; if (activity.getLoopCharacteristics() != null) { multiInstanceExecution = parentExecution; } } if (multiInstanceExecution == null) { DelegateExecution potentialMultiInstanceExecution = findMultiInstanceParentExecution(parentExecution); if (potentialMultiInstanceExecution != null) { multiInstanceExecution = potentialMultiInstanceExecution; } } } return multiInstanceExecution; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\ParallelGatewayActivityBehavior.java
1
请完成以下Java代码
public void setC_Flatrate_RefundConfig(de.metas.contracts.model.I_C_Flatrate_RefundConfig C_Flatrate_RefundConfig) { set_ValueFromPO(COLUMNNAME_C_Flatrate_RefundConfig_ID, de.metas.contracts.model.I_C_Flatrate_RefundConfig.class, C_Flatrate_RefundConfig); } /** Set C_Flatrate_RefundConfig. @param C_Flatrate_RefundConfig_ID C_Flatrate_RefundConfig */ @Override public void setC_Flatrate_RefundConfig_ID (int C_Flatrate_RefundConfig_ID) { if (C_Flatrate_RefundConfig_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Flatrate_RefundConfig_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Flatrate_RefundConfig_ID, Integer.valueOf(C_Flatrate_RefundConfig_ID)); } /** Get C_Flatrate_RefundConfig. @return C_Flatrate_RefundConfig */ @Override public int getC_Flatrate_RefundConfig_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Flatrate_RefundConfig_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Vertrag-Rechnungskandidat. @param C_Invoice_Candidate_Term_ID Vertrag-Rechnungskandidat */ @Override public void setC_Invoice_Candidate_Term_ID (int C_Invoice_Candidate_Term_ID) {
if (C_Invoice_Candidate_Term_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, Integer.valueOf(C_Invoice_Candidate_Term_ID)); } /** Get Vertrag-Rechnungskandidat. @return Vertrag-Rechnungskandidat */ @Override public int getC_Invoice_Candidate_Term_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Term_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Invoice_Candidate_Assignment_Aggregate_V.java
1
请在Spring Boot框架中完成以下Java代码
public void onFailure(Throwable t) { log.warn("[{}][{}] Failed to process websocket command: {}:{}", ctx.getSessionId(), ctx.getCmdId(), ctx.getQuery(), latestCmd, t); ctx.sendWsMsg(new EntityDataUpdate(ctx.getCmdId(), SubscriptionErrorCode.INTERNAL_ERROR.getCode(), "Failed to process websocket command!")); } }, wsCallBackExecutor); } else { ctx.getWsLock().lock(); try { ctx.createLatestValuesSubscriptions(latestCmd.getKeys()); checkAndSendInitialData(ctx); } finally { ctx.getWsLock().unlock(); } } } private Map<String, TsValue> toTsValue(List<TsKvEntry> data) { return data.stream().collect(Collectors.toMap(TsKvEntry::getKey, value -> new TsValue(value.getTs(), value.getValueAsString()))); } @Override public void cancelSubscription(String sessionId, UnsubscribeCmd cmd) { cleanupAndCancel(getSubCtx(sessionId, cmd.getCmdId())); } private void cleanupAndCancel(TbAbstractSubCtx ctx) { if (ctx != null) { ctx.stop(); if (ctx.getSessionId() != null) { Map<Integer, TbAbstractSubCtx> sessionSubs = subscriptionsBySessionId.get(ctx.getSessionId()); if (sessionSubs != null) { sessionSubs.remove(ctx.getCmdId()); } } } }
@Override public void cancelAllSessionSubscriptions(String sessionId) { Map<Integer, TbAbstractSubCtx> sessionSubs = subscriptionsBySessionId.remove(sessionId); if (sessionSubs != null) { sessionSubs.values().forEach(sub -> { try { cleanupAndCancel(sub); } catch (Exception e) { log.warn("[{}] Failed to remove subscription {} due to ", sub.getTenantId(), sub, e); } } ); } } private int getLimit(int limit) { return limit == 0 ? DEFAULT_LIMIT : limit; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\DefaultTbEntityDataSubscriptionService.java
2
请在Spring Boot框架中完成以下Java代码
protected Specification<User> resolveSpecificationFromInfixExpr(String searchParameters) { CriteriaParser parser = new CriteriaParser(); GenericSpecificationsBuilder<User> specBuilder = new GenericSpecificationsBuilder<>(); return specBuilder.build(parser.parse(searchParameters), UserSpecification::new); } protected Specification<User> resolveSpecification(String searchParameters) { UserSpecificationsBuilder builder = new UserSpecificationsBuilder(); String operationSetExper = Joiner.on("|") .join(SearchOperation.SIMPLE_OPERATION_SET); Pattern pattern = Pattern.compile("(\\p{Punct}?)(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),"); Matcher matcher = pattern.matcher(searchParameters + ","); while (matcher.find()) { builder.with(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(5), matcher.group(4), matcher.group(6)); } return builder.build(); } @RequestMapping(method = RequestMethod.GET, value = "/myusers") @ResponseBody public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search") String search) { MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder(); if (search != null) { Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); Matcher matcher = pattern.matcher(search + ","); while (matcher.find()) { builder.with(matcher.group(1), matcher.group(2), matcher.group(3)); } } BooleanExpression exp = builder.build(); return myUserRepository.findAll(exp); } @RequestMapping(method = RequestMethod.GET, value = "/users/rsql") @ResponseBody public List<User> findAllByRsql(@RequestParam(value = "search") String search) { Node rootNode = new RSQLParser().parse(search); Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>()); return dao.findAll(spec);
} @RequestMapping(method = RequestMethod.GET, value = "/api/myusers") @ResponseBody public Iterable<MyUser> findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) Predicate predicate) { return myUserRepository.findAll(predicate); } // API - WRITE @RequestMapping(method = RequestMethod.POST, value = "/users") @ResponseStatus(HttpStatus.CREATED) public void create(@RequestBody User resource) { Preconditions.checkNotNull(resource); dao.save(resource); } @RequestMapping(method = RequestMethod.POST, value = "/myusers") @ResponseStatus(HttpStatus.CREATED) public void addMyUser(@RequestBody MyUser resource) { Preconditions.checkNotNull(resource); myUserRepository.save(resource); } }
repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\web\controller\UserController.java
2
请在Spring Boot框架中完成以下Java代码
public class RoncooPayGoodsDetails { /** 构造函数 传入所需参数 **/ public RoncooPayGoodsDetails (String goodsId , String goodsName ,Long singlePrice , Integer nums){ this.goodsId = goodsId; this.goodsName = goodsName; this.singlePrice = singlePrice; this.nums = nums; } /** 商品ID **/ private String goodsId; /** 名称 **/ private String goodsName; /** 单价 **/ private Long singlePrice; /** 数量 **/ private Integer nums; public String getGoodsId() { return goodsId; } public void setGoodsId(String goodsId) { this.goodsId = goodsId; } public String getGoodsName() { return goodsName; } public void setGoodsName(String goodsName) {
this.goodsName = goodsName; } public Long getSinglePrice() { return singlePrice; } public void setSinglePrice(Long singlePrice) { this.singlePrice = singlePrice; } public Integer getNums() { return nums; } public void setNums(Integer nums) { this.nums = nums; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\RoncooPayGoodsDetails.java
2
请完成以下Java代码
protected void runJobLogic(ExternalWorkerJobEntity externalWorkerJob, CommandContext commandContext) { externalWorkerJob.setJobHandlerConfiguration("terminate:"); if (variables != null && !variables.isEmpty()) { CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext); VariableServiceConfiguration variableServiceConfiguration = cmmnEngineConfiguration.getVariableServiceConfiguration(); VariableService variableService = variableServiceConfiguration.getVariableService(); for (Map.Entry<String, Object> variableEntry : variables.entrySet()) { String varName = variableEntry.getKey(); Object varValue = variableEntry.getValue(); VariableInstanceEntity variableInstance = variableService.createVariableInstance(varName); variableInstance.setScopeId(externalWorkerJob.getScopeId()); variableInstance.setSubScopeId(externalWorkerJob.getSubScopeId()); variableInstance.setScopeType(ScopeTypes.CMMN_EXTERNAL_WORKER);
variableService.insertVariableInstanceWithValue(variableInstance, varValue, externalWorkerJob.getTenantId()); } PlanItemInstanceEntity planItemInstanceEntity = cmmnEngineConfiguration.getPlanItemInstanceEntityManager() .findById(externalWorkerJob.getSubScopeId()); if (planItemInstanceEntity instanceof CountingPlanItemInstanceEntity) { ((CountingPlanItemInstanceEntity) planItemInstanceEntity) .setVariableCount(((CountingPlanItemInstanceEntity) planItemInstanceEntity).getVariableCount() + variables.size()); } } moveExternalWorkerJobToExecutableJob(externalWorkerJob, commandContext); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\ExternalWorkerJobTerminateCmd.java
1
请在Spring Boot框架中完成以下Java代码
private static WorkPackagesProgress getWPsProgress(@NonNull final AsyncBatchNotifyRequest request) { return WorkPackagesProgress.builder() .noOfProcessedWPs(request.getNoOfProcessedWPs()) .noOfEnqueuedWPs(request.getNoOfEnqueuedWPs()) .noOfErrorWPs(request.getNoOfErrorWPs()) .build(); } private static class WorkPackagesProgress { @NonNull Integer noOfEnqueuedWPs; @NonNull Integer noOfProcessedWPs; @NonNull Integer noOfErrorWPs; @Builder public WorkPackagesProgress( @NonNull final Integer noOfEnqueuedWPs, @Nullable final Integer noOfProcessedWPs, @Nullable final Integer noOfErrorWPs) { this.noOfEnqueuedWPs = noOfEnqueuedWPs; this.noOfProcessedWPs = CoalesceUtil.coalesceNotNull(noOfProcessedWPs, 0); this.noOfErrorWPs = CoalesceUtil.coalesceNotNull(noOfErrorWPs, 0);
Check.assumeGreaterThanZero(noOfEnqueuedWPs, "noOfEnqueuedWPs"); Check.assumeGreaterOrEqualToZero(this.noOfProcessedWPs, this.noOfErrorWPs); } public boolean isProcessedSuccessfully() { return noOfErrorWPs == 0 && noOfProcessedWPs >= noOfEnqueuedWPs; } public boolean isProcessedWithError() { return noOfErrorWPs > 0 && (noOfProcessedWPs + noOfErrorWPs >= noOfEnqueuedWPs); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\service\AsyncBatchObserver.java
2
请完成以下Java代码
public List<String> findAllNamesUsingCriteriaBuilder() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<String> query = builder.createQuery(String.class); Root<Product> product = query.from(Product.class); query.select(product.get("name")); List<String> resultList = entityManager.createQuery(query).getResultList(); return resultList; } @SuppressWarnings("unchecked") public List<Object[]> findAllIdAndNamesUsingJPQL() { Query query = entityManager.createQuery("select id, name from Product"); List<Object[]> resultList = query.getResultList(); return resultList; } public List<Object[]> findAllIdAndNamesUsingCriteriaBuilderArray() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Object[]> query = builder.createQuery(Object[].class); Root<Product> product = query.from(Product.class); query.select(builder.array(product.get("id"), product.get("name"))); List<Object[]> resultList = entityManager.createQuery(query).getResultList(); return resultList; } public List<Object[]> findAllIdNameUnitPriceUsingCriteriaQueryMultiselect() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Object[]> query = builder.createQuery(Object[].class); Root<Product> product = query.from(Product.class); query.multiselect(product.get("id"), product.get("name"), product.get("unitPrice")); List<Object[]> resultList = entityManager.createQuery(query).getResultList(); return resultList; } public List<Tuple> findAllIdAndNamesUsingCriteriaBuilderTuple() { CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> query = builder.createQuery(Tuple.class); Root<Product> product = query.from(Product.class); query.select(builder.tuple(product.get("id"), product.get("name"))); List<Tuple> resultList = entityManager.createQuery(query).getResultList(); return resultList; } public List<Object[]> findCountByCategoryUsingJPQL() { Query query = entityManager.createQuery("select p.category, count(p) from Product p group by p.category"); return query.getResultList(); } public List<Object[]> findCountByCategoryUsingCriteriaBuilder() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Object[]> query = builder.createQuery(Object[].class); Root<Product> product = query.from(Product.class); query.multiselect(product.get("category"), builder.count(product)); query.groupBy(product.get("category")); List<Object[]> resultList = entityManager.createQuery(query).getResultList(); return resultList; } }
repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\projections\ProductRepository.java
1
请完成以下Java代码
public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToEdgeNotificationMsg>> createEdgeNotificationsMsgProducer() { return new InMemoryTbQueueProducer<>(storage, topicService.getEdgeNotificationsTopic(serviceInfoProvider.getServiceId()).getFullTopicName()); } @Override public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToEdgeEventNotificationMsg>> createEdgeEventMsgProducer() { return null; } @Override public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCalculatedFieldNotificationMsg>> createToCalculatedFieldNotificationMsgProducer() { return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(calculatedFieldSettings.getEventTopic())); } @Override public TbQueueProducer<TbProtoQueueMsg<ToEdqsMsg>> createEdqsEventsProducer() { return new InMemoryTbQueueProducer<>(storage, edqsConfig.getEventsTopic()); } @Override public TbQueueRequestTemplate<TbProtoQueueMsg<ToEdqsMsg>, TbProtoQueueMsg<FromEdqsMsg>> createEdqsRequestTemplate() { TbQueueProducer<TbProtoQueueMsg<ToEdqsMsg>> requestProducer = new InMemoryTbQueueProducer<>(storage, edqsConfig.getRequestsTopic()); TbQueueConsumer<TbProtoQueueMsg<FromEdqsMsg>> responseConsumer = new InMemoryTbQueueConsumer<>(storage, edqsConfig.getResponsesTopic()); return DefaultTbQueueRequestTemplate.<TbProtoQueueMsg<ToEdqsMsg>, TbProtoQueueMsg<FromEdqsMsg>>builder()
.queueAdmin(queueAdmin) .requestTemplate(requestProducer) .responseTemplate(responseConsumer) .maxPendingRequests(edqsConfig.getMaxPendingRequests()) .maxRequestTimeout(edqsConfig.getMaxRequestTimeout()) .pollInterval(edqsConfig.getPollInterval()) .build(); } @Override public TbQueueConsumer<TbProtoQueueMsg<JobStatsMsg>> createJobStatsConsumer() { return new InMemoryTbQueueConsumer<>(storage, tasksQueueConfig.getStatsTopic()); } @Scheduled(fixedRateString = "${queue.in_memory.stats.print-interval-ms:60000}") private void printInMemoryStats() { storage.printStats(); } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\InMemoryMonolithQueueFactory.java
1
请在Spring Boot框架中完成以下Java代码
static class CachingConnectionFactoryConfiguration { @Bean CachingConnectionFactory jmsConnectionFactory(JmsProperties jmsProperties, ActiveMQProperties properties, ObjectProvider<ActiveMQConnectionFactoryCustomizer> factoryCustomizers, ActiveMQConnectionDetails connectionDetails) { JmsProperties.Cache cacheProperties = jmsProperties.getCache(); CachingConnectionFactory connectionFactory = new CachingConnectionFactory( createJmsConnectionFactory(properties, factoryCustomizers, connectionDetails)); connectionFactory.setCacheConsumers(cacheProperties.isConsumers()); connectionFactory.setCacheProducers(cacheProperties.isProducers()); connectionFactory.setSessionCacheSize(cacheProperties.getSessionCacheSize()); return connectionFactory; } } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ JmsPoolConnectionFactory.class, PooledObject.class }) static class PooledConnectionFactoryConfiguration {
@Bean(destroyMethod = "stop") @ConditionalOnBooleanProperty("spring.activemq.pool.enabled") JmsPoolConnectionFactory jmsConnectionFactory(ActiveMQProperties properties, ObjectProvider<ActiveMQConnectionFactoryCustomizer> factoryCustomizers, ActiveMQConnectionDetails connectionDetails) { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionDetails.getUser(), connectionDetails.getPassword(), connectionDetails.getBrokerUrl()); new ActiveMQConnectionFactoryConfigurer(properties, factoryCustomizers.orderedStream().toList()) .configure(connectionFactory); return new JmsPoolConnectionFactoryFactory(properties.getPool()) .createPooledConnectionFactory(connectionFactory); } } }
repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\autoconfigure\ActiveMQConnectionFactoryConfiguration.java
2
请完成以下Java代码
public ScriptBindingsFactory getScriptBindingsFactory() { return scriptBindingsFactory; } public void setScriptBindingsFactory(ScriptBindingsFactory scriptBindingsFactory) { this.scriptBindingsFactory = scriptBindingsFactory; } public ScriptTraceEnhancer getDefaultTraceEnhancer() { return defaultTraceEnhancer; } public void setDefaultTraceEnhancer(ScriptTraceEnhancer defaultTraceEnhancer) { this.defaultTraceEnhancer = defaultTraceEnhancer; } public ScriptTraceListener getScriptErrorListener() { return scriptErrorListener;
} public void setScriptErrorListener(ScriptTraceListener scriptErrorListener) { this.scriptErrorListener = scriptErrorListener; } public ScriptTraceListener getScriptSuccessListener() { return scriptSuccessListener; } public void setScriptSuccessListener(ScriptTraceListener scriptSuccessListener) { this.scriptSuccessListener = scriptSuccessListener; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\ScriptingEngines.java
1
请完成以下Java代码
protected I_M_HU_PI getM_HU_PI() { return huPI; } @Override protected IAllocationResult loadHU(final I_M_HU hu, final IAllocationRequest request) { final IAllocationStrategy allocationStrategy = allocationStrategyFactory.createAllocationStrategy(AllocationDirection.INBOUND_ALLOCATION); return allocationStrategy.execute(hu, request); } @Override protected ArrayKey extractCurrentHUKey(final IAllocationRequest request) { // NOTE: in case of maxHUsToCreate == 1 try to load all products in one HU return maxHUsToCreate == 1 ? SHARED_CurrentHUKey : super.extractCurrentHUKey(request); } @Override public boolean isAllowCreateNewHU() { // Check if we already reached the maximum number of HUs that we are allowed to create return getCreatedHUsCount() < maxHUsToCreate; } public HUProducerDestination setMaxHUsToCreate(final int maxHUsToCreate) { Check.assumeGreaterOrEqualToZero(maxHUsToCreate, "maxHUsToCreate"); this.maxHUsToCreate = maxHUsToCreate;
return this; } /** * Then this producer creates a new HU, than i uses the given {@code parentHUItem} for the new HU's {@link I_M_HU#COLUMN_M_HU_Item_Parent_ID}. * * @param parentHUItem */ public HUProducerDestination setParent_HU_Item(final I_M_HU_Item parentHUItem) { this.parentHUItem = parentHUItem; return this; } @Override protected I_M_HU_Item getParent_HU_Item() { return parentHUItem; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\HUProducerDestination.java
1
请完成以下Java代码
static Resource toResource(@NonNull final I_S_Resource record) { final IModelTranslationMap trl = InterfaceWrapperHelper.getModelTranslationMap(record); return Resource.builder() .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .resourceId(ResourceId.ofRepoId(record.getS_Resource_ID())) .isActive(record.isActive()) .value(record.getValue()) .name(trl.getColumnTrl(I_S_Resource.COLUMNNAME_Name, record.getName())) .description(record.getDescription()) .resourceTypeId(ResourceTypeId.ofRepoId(record.getS_ResourceType_ID())) .manufacturingResourceType(ManufacturingResourceType.ofNullableCode(record.getManufacturingResourceType())) .responsibleId(UserId.ofRepoIdOrNull(record.getAD_User_ID())) .workplaceId(WorkplaceId.ofRepoIdOrNull(record.getC_Workplace_ID())) .externalSystemParentConfigId(record.getExternalSystem_Config_ID() > 0 ? record.getExternalSystem_Config_ID() : null) .build(); } public ImmutableSet<ResourceId> getActivePlantIds() { return getResourcesMap().getActivePlantIds(); } // // // // // private static final class ResourcesMap { @Getter private final ImmutableList<Resource> allActive; private final ImmutableMap<ResourceId, Resource> byId; ResourcesMap(final List<Resource> list) { this.allActive = list.stream().filter(Resource::isActive).collect(ImmutableList.toImmutableList()); this.byId = Maps.uniqueIndex(list, Resource::getResourceId); } public Resource getById(@NonNull final ResourceId id) { final Resource resource = byId.get(id); if (resource == null) { throw new AdempiereException("Resource not found by ID: " + id); } return resource; }
public Stream<Resource> streamAllActive() { return allActive.stream(); } public List<Resource> getByIds(final Set<ResourceId> ids) { return ids.stream() .map(byId::get) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } public ImmutableSet<ResourceId> getActivePlantIds() { return streamAllActive() .filter(resource -> resource.isActive() && resource.isPlant()) .map(Resource::getResourceId) .collect(ImmutableSet.toImmutableSet()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\resource\ResourceRepository.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((left == null) ? 0 : left.hashCode()); result = prime * result + ((right == null) ? 0 : right.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ImmutablePair<?, ?> other = (ImmutablePair<?, ?>)obj; if (left == null) { if (other.left != null) return false; } else if (!left.equals(other.left)) return false; if (right == null) {
if (other.right != null) return false; } else if (!right.equals(other.right)) return false; return true; } @Override public LT getLeft() { return left; } @Override public RT getRight() { return right; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\pair\ImmutablePair.java
1
请完成以下Java代码
public int getDhl_LenghtUOM_ID() { return get_ValueAsInt(COLUMNNAME_Dhl_LenghtUOM_ID); } @Override public void setDHL_Shipper_Config_ID (final int DHL_Shipper_Config_ID) { if (DHL_Shipper_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_DHL_Shipper_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_DHL_Shipper_Config_ID, DHL_Shipper_Config_ID); } @Override public int getDHL_Shipper_Config_ID() { return get_ValueAsInt(COLUMNNAME_DHL_Shipper_Config_ID); } @Override public org.compiere.model.I_M_Shipper getM_Shipper() { return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class); } @Override public void setM_Shipper(final org.compiere.model.I_M_Shipper M_Shipper) { set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper); } @Override public void setM_Shipper_ID (final int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); }
@Override public int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_ID); } @Override public void setSignature (final @Nullable java.lang.String Signature) { set_Value (COLUMNNAME_Signature, Signature); } @Override public java.lang.String getSignature() { return get_ValueAsString(COLUMNNAME_Signature); } @Override public void setUserName (final @Nullable java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } @Override public java.lang.String getUserName() { return get_ValueAsString(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_DHL_Shipper_Config.java
1
请在Spring Boot框架中完成以下Java代码
public static class Config { private String fields; private String replacement; public String getFields() { return fields; } public void setFields(String fields) { this.fields = fields; } public String getReplacement() { return replacement; } public void setReplacement(String replacement) { this.replacement = replacement; } } public static class Scrubber implements RewriteFunction<JsonNode,JsonNode> { private final Pattern fields; private final String replacement; public Scrubber(Config config) { this.fields = Pattern.compile(config.getFields()); this.replacement = config.getReplacement(); } @Override public Publisher<JsonNode> apply(ServerWebExchange t, JsonNode u) { return Mono.just(scrubRecursively(u)); }
private JsonNode scrubRecursively(JsonNode u) { if ( !u.isContainerNode()) { return u; } if ( u.isObject()) { ObjectNode node = (ObjectNode)u; node.fields().forEachRemaining((f) -> { if ( fields.matcher(f.getKey()).matches() && f.getValue().isTextual()) { f.setValue(TextNode.valueOf(replacement)); } else { f.setValue(scrubRecursively(f.getValue())); } }); } else if ( u.isArray()) { ArrayNode array = (ArrayNode)u; for ( int i = 0 ; i < array.size() ; i++ ) { array.set(i, scrubRecursively(array.get(i))); } } return u; } } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway-2\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\factories\ScrubResponseGatewayFilterFactory.java
2
请完成以下Java代码
private void createOrUpdateDisposeCandidate( @NonNull final IHUProductStorage huProductStorage, @NonNull final QtyRejectedReasonCode reasonCode, @Nullable final I_M_Inventory_Candidate existingRecord) { final I_M_Inventory_Candidate record; if (existingRecord == null) { record = InterfaceWrapperHelper.newInstance(I_M_Inventory_Candidate.class); record.setM_HU_ID(huProductStorage.getHuId().getRepoId()); record.setM_Product_ID(huProductStorage.getProductId().getRepoId()); } else { record = existingRecord; } final Quantity qty = huProductStorage.getQty(); record.setC_UOM_ID(qty.getUomId().getRepoId()); record.setQtyToDispose(qty.toBigDecimal()); record.setIsWholeHU(true); record.setDisposeReason(reasonCode.getCode()); InterfaceWrapperHelper.save(record); } private IQueryBuilder<I_M_Inventory_Candidate> queryByHuIdAndNotProcessed(final @NonNull HuId huId)
{ return queryBL.createQueryBuilder(I_M_Inventory_Candidate.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_Inventory_Candidate.COLUMNNAME_M_HU_ID, huId) .addEqualsFilter(I_M_Inventory_Candidate.COLUMNNAME_Processed, false); } public boolean isDisposalPending(final @NonNull HuId huId) { return queryByHuIdAndNotProcessed(huId) .addNotNull(I_M_Inventory_Candidate.COLUMNNAME_DisposeReason) .create() .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inventory\InventoryCandidateService.java
1
请完成以下Java代码
public ProcessDefinitionBuilder transition(String destinationActivityId, String transitionId) { startTransition(destinationActivityId, transitionId); endTransition(); return this; } public ProcessDefinitionBuilder behavior(ActivityBehavior activityBehaviour) { getActivity().setActivityBehavior(activityBehaviour); return this; } public ProcessDefinitionBuilder property(String name, Object value) { processElement.setProperty(name, value); return this; } public PvmProcessDefinition buildProcessDefinition() { for (Object[] unresolvedTransition: unresolvedTransitions) { TransitionImpl transition = (TransitionImpl) unresolvedTransition[0]; String destinationActivityName = (String) unresolvedTransition[1]; ActivityImpl destination = processDefinition.findActivity(destinationActivityName); if (destination == null) { throw new RuntimeException("destination '"+destinationActivityName+"' not found. (referenced from transition in '"+transition.getSource().getId()+"')"); } transition.setDestination(destination); } return processDefinition; }
protected ActivityImpl getActivity() { return (ActivityImpl) scopeStack.peek(); } public ProcessDefinitionBuilder scope() { getActivity().setScope(true); return this; } public ProcessDefinitionBuilder executionListener(ExecutionListener executionListener) { if (transition!=null) { transition.addExecutionListener(executionListener); } else { throw new PvmException("not in a transition scope"); } return this; } public ProcessDefinitionBuilder executionListener(String eventName, ExecutionListener executionListener) { if (transition==null) { scopeStack.peek().addExecutionListener(eventName, executionListener); } else { transition.addExecutionListener(executionListener); } return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\ProcessDefinitionBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public class ReceiptCandidatesRestController { private final static transient Logger logger = LogManager.getLogger(ReceiptCandidatesRestController.class); private final ReceiptCandidateAPIService receiptCandidateAPIService; public ReceiptCandidatesRestController(@NonNull final ReceiptCandidateAPIService receiptCandidateAPIService) { this.receiptCandidateAPIService = receiptCandidateAPIService; } @GetMapping("receiptCandidates") public ResponseEntity<JsonResponseReceiptCandidates> getReceiptCandidates( @ApiParam("Max number of items to be returned in one request.") // @RequestParam(name = "limit", required = false, defaultValue = "500") // @Nullable final Integer limit) { final QueryLimit limitEff = QueryLimit.ofNullableOrNoLimit(limit).ifNoLimitUse(500); final JsonResponseReceiptCandidates result = receiptCandidateAPIService.exportReceiptCandidates(limitEff);
Loggables.withLogger(logger, Level.DEBUG).addLog("Number of exported receiptCandidates: {}", result.getItems().size()); return ResponseEntity.ok(result); } @PostMapping("receiptCandidatesResult") public ResponseEntity<String> postReceiptCandidatesStatus(@RequestBody @NonNull final JsonRequestCandidateResults status) { try (final MDC.MDCCloseable ignore = MDC.putCloseable("TransactionIdAPI", status.getTransactionKey())) { receiptCandidateAPIService.updateStatus(status); Loggables.withLogger(logger, Level.DEBUG).addLog("ReceiptCandidates status updated"); return ResponseEntity.accepted().body("ReceiptCandidates updated"); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\shipping\ReceiptCandidatesRestController.java
2
请在Spring Boot框架中完成以下Java代码
public Filter getFilter() { return this.filter; } public Servlet getServlet() { return this.servlet; } public Type getType() { return this.type; } public void setType(Type type) { this.type = type; } public Map<String, String> getInit() { return this.init; } public void setInit(Map<String, String> init) { this.init = init; } public @Nullable String getApplicationPath() { return this.applicationPath; } public void setApplicationPath(@Nullable String applicationPath) { this.applicationPath = applicationPath; } public enum Type { SERVLET, FILTER } public static class Filter {
/** * Jersey filter chain order. */ private int order; public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } } public static class Servlet { /** * Load on startup priority of the Jersey servlet. */ private int loadOnStartup = -1; public int getLoadOnStartup() { return this.loadOnStartup; } public void setLoadOnStartup(int loadOnStartup) { this.loadOnStartup = loadOnStartup; } } }
repos\spring-boot-4.0.1\module\spring-boot-jersey\src\main\java\org\springframework\boot\jersey\autoconfigure\JerseyProperties.java
2
请完成以下Java代码
public class JtaTransactionInterceptor extends AbstractTransactionInterceptor { protected final static CommandLogger LOG = ProcessEngineLogger.CMD_LOGGER; protected final TransactionManager transactionManager; public JtaTransactionInterceptor(TransactionManager transactionManager, boolean requiresNew, ProcessEngineConfigurationImpl processEngineConfiguration) { super(requiresNew, processEngineConfiguration); this.transactionManager = transactionManager; } @Override protected void doBegin() { try { transactionManager.begin(); } catch (NotSupportedException e) { throw new TransactionException("Unable to begin transaction", e); } catch (SystemException e) { throw new TransactionException("Unable to begin transaction", e); } } @Override protected boolean isExisting() { try { return transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION; } catch (SystemException e) { throw new TransactionException("Unable to retrieve transaction status", e); } } @Override protected Transaction doSuspend() { try { return transactionManager.suspend(); } catch (SystemException e) { throw new TransactionException("Unable to suspend transaction", e); } } @Override protected void doResume(Object tx) { if (tx != null) { try { transactionManager.resume((Transaction) tx); } catch (SystemException e) { throw new TransactionException("Unable to resume transaction", e); } catch (InvalidTransactionException e) { throw new TransactionException("Unable to resume transaction", e); } } } @Override protected void doCommit() { try {
transactionManager.commit(); } catch (HeuristicMixedException e) { throw new TransactionException("Unable to commit transaction", e); } catch (HeuristicRollbackException e) { throw new TransactionException("Unable to commit transaction", e); } catch (RollbackException e) { handleRollbackException(e); } catch (SystemException e) { throw new TransactionException("Unable to commit transaction", e); } catch (RuntimeException e) { doRollback(true); throw e; } catch (Error e) { doRollback(true); throw e; } } @Override protected void doRollback(boolean isNew) { try { if (isNew) { transactionManager.rollback(); } else { transactionManager.setRollbackOnly(); } } catch (SystemException e) { LOG.exceptionWhileRollingBackTransaction(e); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\JtaTransactionInterceptor.java
1
请完成以下Java代码
protected void updateEntity(DbEntityOperation operation) { final DbEntity dbEntity = operation.getEntity(); String updateStatement = dbSqlSessionFactory.getUpdateStatement(dbEntity); ensureNotNull("no update statement for " + dbEntity.getClass() + " in the ibatis mapping files", "updateStatement", updateStatement); LOG.executeDatabaseOperation("UPDATE", dbEntity); executeUpdate(updateStatement, dbEntity); } @Override protected void updateBulk(DbBulkOperation operation) { String statement = operation.getStatement(); Object parameter = operation.getParameter(); LOG.executeDatabaseBulkOperation("UPDATE", statement, parameter); executeUpdate(statement, parameter); } @Override protected void deleteBulk(DbBulkOperation operation) { String statement = operation.getStatement(); Object parameter = operation.getParameter(); LOG.executeDatabaseBulkOperation("DELETE", statement, parameter); executeDelete(statement, parameter); } @Override protected void deleteEntity(DbEntityOperation operation) { final DbEntity dbEntity = operation.getEntity();
// get statement String deleteStatement = dbSqlSessionFactory.getDeleteStatement(dbEntity.getClass()); ensureNotNull("no delete statement for " + dbEntity.getClass() + " in the ibatis mapping files", "deleteStatement", deleteStatement); LOG.executeDatabaseOperation("DELETE", dbEntity); // execute the delete executeDelete(deleteStatement, dbEntity); } @Override protected void executeSelectForUpdate(String statement, Object parameter) { executeSelectList(statement, parameter); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\sql\BatchDbSqlSession.java
1
请完成以下Java代码
public int getAD_Rule_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Rule_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Validation code. @param Code Validation Code */ @Override public void setCode (java.lang.String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validation code. @return Validation Code */ @Override public java.lang.String getCode () { return (java.lang.String)get_Value(COLUMNNAME_Code); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** * Type AD_Reference_ID=540047 * Reference name: AD_BoilerPlate_VarType */ public static final int TYPE_AD_Reference_ID=540047; /** SQL = S */ public static final String TYPE_SQL = "S"; /** Rule Engine = R */ public static final String TYPE_RuleEngine = "R"; /** Set Type. @param Type Type of Validation (SQL, Java Script, Java Language) */ @Override
public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Type. @return Type of Validation (SQL, Java Script, Java Language) */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate_Var.java
1
请在Spring Boot框架中完成以下Java代码
private void removeProductQtyFromHU( final IHUContext huContext, final I_M_HU hu, final PackingItemPart part) { final ShipmentScheduleId shipmentScheduleId = part.getShipmentScheduleId(); final I_M_ShipmentSchedule schedule = Services.get(IShipmentSchedulePA.class).getById(shipmentScheduleId); // // Allocation Request final IAllocationRequest request = AllocationUtils.createQtyRequest( huContext, part.getProductId(), part.getQty(), SystemTime.asZonedDateTime(), schedule, // reference model false // forceQtyAllocation ); // // Allocation Destination final ShipmentScheduleQtyPickedProductStorage shipmentScheduleQtyPickedStorage = new ShipmentScheduleQtyPickedProductStorage(schedule); final IAllocationDestination destination = new GenericAllocationSourceDestination(shipmentScheduleQtyPickedStorage, schedule); //
// Allocation Source final IAllocationSource source = HUListAllocationSourceDestination.of(hu); // // Move Qty from HU to shipment schedule (i.e. un-pick) final IAllocationResult result = HULoader.of(source, destination) .load(request); // Make sure result is completed // NOTE: this issue could happen if we want to take out more then we have in our HU if (!result.isCompleted()) { final String errmsg = MessageFormat.format(PackingService.ERR_CANNOT_FULLY_UNLOAD_RESULT, hu, result); throw new AdempiereException(errmsg); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\impl\PackingService.java
2
请在Spring Boot框架中完成以下Java代码
public AuthorizationManagerRequestMatcherRegistry anonymous() { return access(this.authorizationManagerFactory.anonymous()); } /** * Specify that a path variable in URL to be compared. * * <p> * For example, <pre> * requestMatchers("/user/{username}").hasVariable("username").equalTo(Authentication::getName) * </pre> * @param variable the variable in URL template to compare. * @return {@link AuthorizedUrlVariable} for further customization. * @since 6.3 */ public AuthorizedUrlVariable hasVariable(String variable) { return new AuthorizedUrlVariable(variable); } /** * Allows specifying a custom {@link AuthorizationManager}. * @param manager the {@link AuthorizationManager} to use * @return the {@link AuthorizationManagerRequestMatcherRegistry} for further * customizations */ public AuthorizationManagerRequestMatcherRegistry access( AuthorizationManager<? super RequestAuthorizationContext> manager) { Assert.notNull(manager, "manager cannot be null"); return (this.not) ? AuthorizeHttpRequestsConfigurer.this.addMapping(this.matchers, AuthorizationManagers.not(manager)) : AuthorizeHttpRequestsConfigurer.this.addMapping(this.matchers, manager); } /** * An object that allows configuring {@link RequestMatcher}s with URI path * variables * * @author Taehong Kim * @since 6.3 */ public final class AuthorizedUrlVariable { private final String variable; private AuthorizedUrlVariable(String variable) { this.variable = variable; }
/** * Compares the value of a path variable in the URI with an `Authentication` * attribute * <p> * For example, <pre> * requestMatchers("/user/{username}").hasVariable("username").equalTo(Authentication::getName)); * </pre> * @param function a function to get value from {@link Authentication}. * @return the {@link AuthorizationManagerRequestMatcherRegistry} for further * customization. */ public AuthorizationManagerRequestMatcherRegistry equalTo(Function<Authentication, String> function) { return access((auth, requestContext) -> { String value = requestContext.getVariables().get(this.variable); return new AuthorizationDecision(function.apply(auth.get()).equals(value)); }); } } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\AuthorizeHttpRequestsConfigurer.java
2
请完成以下Java代码
public class AiAppConsts { /** * 状态:启用 */ public static final String STATUS_ENABLE = "enable"; /** * 状态:禁用 */ public static final String STATUS_DISABLE = "disable"; /** * 状态:发布 */ public static final String STATUS_RELEASE = "release"; /** * 默认应用id */ public static final String DEFAULT_APP_ID = "default"; /** * 应用类型:简单聊天
*/ public static final String APP_TYPE_CHAT_SIMPLE = "chatSimple"; /** * 应用类型:聊天流(高级编排) */ public static final String APP_TYPE_CHAT_FLOW = "chatFLow"; /** * 应用元数据:流程输入参数 * for [issues/8545]新建AI应用的时候只能选择没有自定义参数的AI流程 */ public static final String APP_METADATA_FLOW_INPUTS = "flowInputs"; }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\app\consts\AiAppConsts.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Account other = (Account) obj; if (branchId == null) { if (other.branchId != null) return false; } else if (!branchId.equals(other.branchId)) return false; if (customerId == null) { if (other.customerId != null) return false; } else if (!customerId.equals(other.customerId))
return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-vault\src\main\java\com\baeldung\spring\cloud\vaultsample\domain\Account.java
1
请完成以下Java代码
public LocalDate getDocumentDate(@NonNull final DocumentTableFields docFields) { final I_C_PaySelection paySelection = extractPaySelection(docFields); return TimeUtil.asLocalDate(paySelection.getPayDate()); } @Override public int getDoc_User_ID(DocumentTableFields docFields) { return extractPaySelection(docFields).getCreatedBy(); } @Override public String completeIt(DocumentTableFields docFields) { final I_C_PaySelection paySelection = extractPaySelection(docFields); Services.get(IPaySelectionBL.class).completePaySelection(paySelection);
return IDocument.STATUS_Completed; } @Override public void reactivateIt(DocumentTableFields docFields) { final I_C_PaySelection paySelection = extractPaySelection(docFields); Services.get(IPaySelectionBL.class).reactivatePaySelection(paySelection); } private static I_C_PaySelection extractPaySelection(final DocumentTableFields docFields) { return InterfaceWrapperHelper.create(docFields, I_C_PaySelection.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\PaySelectionDocumentHandler.java
1
请完成以下Java代码
public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; }
public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "UserDto [id=" + id + ", username=" + username + ", age=" + age + "]"; } }
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\jmapper\UserDto.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getTimePeriod() { return timePeriod; } public void setTimePeriod(BigDecimal timePeriod) { this.timePeriod = timePeriod; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderedArticleLineDuration orderedArticleLineDuration = (OrderedArticleLineDuration) o; return Objects.equals(this.amount, orderedArticleLineDuration.amount) && Objects.equals(this.timePeriod, orderedArticleLineDuration.timePeriod); } @Override public int hashCode() { return Objects.hash(amount, timePeriod); } @Override public String toString() {
StringBuilder sb = new StringBuilder(); sb.append("class OrderedArticleLineDuration {\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" timePeriod: ").append(toIndentedString(timePeriod)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderedArticleLineDuration.java
2
请完成以下Java代码
public String[] getServerContext() { final Properties ctx = Env.getCtx(); String[] context = Env.getEntireContext(ctx); Arrays.sort(context); return context; } @ManagedOperation public void setLogLevel(String levelName) { LogManager.setLevel(levelName); } @ManagedOperation public String getLogLevel() { final Level level = LogManager.getLevel(); return level == null ? null : level.toString(); } @ManagedOperation public void runFinalization() {
System.runFinalization(); } @ManagedOperation public void resetLocalCache() { CacheMgt.get().reset(); } @ManagedOperation public void rotateMigrationScriptFile() { MigrationScriptFileLoggerHolder.closeMigrationScriptFiles(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\jmx\Metasfresh.java
1
请完成以下Java代码
public TbResultSet get() throws InterruptedException, ExecutionException { return mainFuture.get(); } @Override public TbResultSet get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return mainFuture.get(timeout, unit); } @Override public void addListener(Runnable listener, Executor executor) { mainFuture.addListener(listener, executor); } private TbResultSet getSafe() {
try { return mainFuture.get(); } catch (InterruptedException | ExecutionException e) { throw new IllegalStateException(e); } } private TbResultSet getSafe(long timeout, TimeUnit unit) throws TimeoutException { try { return mainFuture.get(timeout, unit); } catch (InterruptedException | ExecutionException e) { throw new IllegalStateException(e); } } }
repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\nosql\TbResultSetFuture.java
1
请完成以下Java代码
public void updateShipToColumn(final I_C_BPartner_Location location, final ICalloutField field) { if (location == null) { return; } // 07224 // In case the isBillToDefault flag is set on true, the IsBillTo must be true, as well // The field will also be read only (set readonly logic in database) final boolean isShipToDefault = location.isShipToDefault(); if (!isShipToDefault) { return; } location.setIsShipTo(true); } @CalloutMethod(columnNames = { I_C_BPartner_Location.COLUMNNAME_C_Location_ID, I_C_BPartner_Location.COLUMNNAME_Name }) public void updateAddressString(final I_C_BPartner_Location bpLocation) { final int locationId = bpLocation.getC_Location_ID(); if (locationId <= 0) { return; } final int bPartnerId = bpLocation.getC_BPartner_ID(); if (bPartnerId <= 0) { return; } final IBPartnerBL bpartnerBL = Services.get(IBPartnerBL.class); bpartnerBL.setAddress(bpLocation); }
@CalloutMethod(columnNames = { I_C_BPartner_Location.COLUMNNAME_ValidFrom}) public void updatePreviousId(final I_C_BPartner_Location bpLocation) { final int bPartnerId = bpLocation.getC_BPartner_ID(); if (bPartnerId <= 0) { return; } if (bpLocation.getValidFrom() == null) { return; } final IBPartnerBL bpartnerBL = Services.get(IBPartnerBL.class); bpartnerBL.setPreviousIdIfPossible(bpLocation); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\bpartner\callout\C_BPartner_Location.java
1
请完成以下Java代码
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 getAuthor() { return author;
} public void setAuthor(String author) { this.author = author; } static Specification<Book> hasAuthor(String author) { return (book, cq, cb) -> cb.equal(book.get("author"), author); } static Specification<Book> titleContains(String title) { return (book, cq, cb) -> cb.like(book.get("title"), "%" + title + "%"); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\criteriaquery\Book.java
1
请完成以下Java代码
public class AgeAttributeCreator { private final transient IAttributeSetInstanceAwareFactoryService attributeSetInstanceAwareFactoryService = Services.get(IAttributeSetInstanceAwareFactoryService.class); private final transient IAttributeSetInstanceBL attributeSetInstanceBL = Services.get(IAttributeSetInstanceBL.class); private final transient IAttributesBL attributesBL = Services.get(IAttributesBL.class); private final transient IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class); private final transient AgeAttributesService ageAttributesService = Adempiere.getBean(AgeAttributesService.class); private final Object sourceModel; public AgeAttributeCreator(final @NonNull Object sourceModel) { this.sourceModel = sourceModel; } /** * Note: this explanation may not be 100% correct * ASI = AttributeSetInstance * AttributeSet is the dataType * AttributeSetInstance is the instance (a new object) of an AttributeSet */ @SuppressWarnings({ "Duplicates" }) public void createASI() { final Object sourceModel = getSourceModel(); final IAttributeSetInstanceAware asiAware = attributeSetInstanceAwareFactoryService.createOrNull(sourceModel); if (asiAware == null) { return; } if (asiAware.getM_Product_ID() <= 0) { return; } final AttributeId ageAttributeId = attributesRepo.retrieveActiveAttributeIdByValueOrNull(HUAttributeConstants.ATTR_Age);
if (ageAttributeId == null) { return; } final ProductId productId = ProductId.ofRepoId(asiAware.getM_Product_ID()); final I_M_Attribute attribute = attributesBL.getAttributeOrNull(productId, ageAttributeId); if (attribute == null) { return; } attributeSetInstanceBL.getCreateASI(asiAware); final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(asiAware.getM_AttributeSetInstance_ID()); final I_M_AttributeInstance ai = attributeSetInstanceBL.getAttributeInstance(asiId, ageAttributeId); if (ai != null) { // If it was set, just leave it as it is return; } attributeSetInstanceBL.getCreateAttributeInstance(asiId, ageAttributeId); attributeSetInstanceBL.setAttributeInstanceValue(asiId, ageAttributeId, ageAttributesService.computeDefaultAgeOrNull()); } private @NonNull Object getSourceModel() { Check.assumeNotNull(sourceModel, "sourceModel not null"); return sourceModel; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\AgeAttributeCreator.java
1
请完成以下Java代码
public void setM_InOutConfirm_ID (int M_InOutConfirm_ID) { if (M_InOutConfirm_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InOutConfirm_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InOutConfirm_ID, Integer.valueOf(M_InOutConfirm_ID)); } /** Get Bestätigung Versand/Wareneingang. @return Material Shipment or Receipt Confirmation */ @Override public int getM_InOutConfirm_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutConfirm_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Inventory getM_Inventory() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Inventory_ID, org.compiere.model.I_M_Inventory.class); } @Override public void setM_Inventory(org.compiere.model.I_M_Inventory M_Inventory) { set_ValueFromPO(COLUMNNAME_M_Inventory_ID, org.compiere.model.I_M_Inventory.class, M_Inventory); } /** Set Inventur. @param M_Inventory_ID Parameters for a Physical Inventory */ @Override public void setM_Inventory_ID (int M_Inventory_ID) { if (M_Inventory_ID < 1) set_Value (COLUMNNAME_M_Inventory_ID, null); else set_Value (COLUMNNAME_M_Inventory_ID, Integer.valueOf(M_Inventory_ID)); } /** Get Inventur. @return Parameters for a Physical Inventory */ @Override public int getM_Inventory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Inventory_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) {
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutConfirm.java
1
请完成以下Java代码
public String getPmtInfId() { return pmtInfId; } /** * Sets the value of the pmtInfId property. * * @param value * allowed object is * {@link String } * */ public void setPmtInfId(String value) { this.pmtInfId = value; } /** * Gets the value of the nbOfTxs property. * * @return * possible object is * {@link String } * */ public String getNbOfTxs() { return nbOfTxs; } /** * Sets the value of the nbOfTxs property. * * @param value * allowed object is * {@link String } * */ public void setNbOfTxs(String value) { this.nbOfTxs = value; } /** * Gets the value of the ttlAmt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getTtlAmt() { return ttlAmt; } /** * Sets the value of the ttlAmt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setTtlAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.ttlAmt = value; } /** * Gets the value of the cdtDbtInd property. * * @return * possible object is * {@link CreditDebitCode } * */ public CreditDebitCode getCdtDbtInd() { return cdtDbtInd; } /** * Sets the value of the cdtDbtInd property. * * @param value * allowed object is * {@link CreditDebitCode } * */ public void setCdtDbtInd(CreditDebitCode value) { this.cdtDbtInd = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\BatchInformation2.java
1
请完成以下Java代码
public int getRecordId() { GridTab gridTab = getGridTab(); return gridTab == null ? -1 : gridTab.getRecord_ID(); } @Override public boolean canImport(TransferHandler.TransferSupport support) { final GridTab gridTab = getGridTab(); if (gridTab == null) return false; // if (!support.isDataFlavorSupported(DataFlavor.javaFileListFlavor) // && !support.isDataFlavorSupported(DataFlavor.getTextPlainUnicodeFlavor())) { // return false; // } return true; } @Override public boolean importData(TransferHandler.TransferSupport support) { final GridTab gridTab = getGridTab(); if (gridTab == null) { return false; } if (!canImport(support)) { return false; } Transferable t = support.getTransferable(); DataFlavor[] flavors = t.getTransferDataFlavors(); final TableRecordReference tableRecordReference =TableRecordReference.of(getTableId(), getRecordId()); final AttachmentEntryService attachmentEntryService = Adempiere.getBean(AttachmentEntryService.class); for (int i = 0; i < flavors.length; i++) { DataFlavor flavor = flavors[i]; try { if (flavor.equals(DataFlavor.javaFileListFlavor)) { @SuppressWarnings("unchecked") List<File> files = (List<File>)t.getTransferData(DataFlavor.javaFileListFlavor); attachmentEntryService.createNewAttachments(tableRecordReference, AttachmentEntryCreateRequest.fromFiles(files)); } else if (flavor.getMimeType().startsWith("text")) { final Object data = t.getTransferData(DataFlavor.stringFlavor);
if (data == null) continue; final String text = data.toString(); final DateFormat df = DisplayType.getDateFormat(DisplayType.DateTime); final String name = "Text " + df.format(new Timestamp(System.currentTimeMillis())); attachmentEntryService.createNewAttachment(tableRecordReference, name, text.getBytes(StandardCharsets.UTF_8)); } } catch (Exception ex) { log.error(ex.getLocalizedMessage(), ex); ADialog.error(gridTab.getWindowNo(), null, "Error", ex.getLocalizedMessage()); return false; } } // inform APanel/.. -> dataStatus with row updated gridTab.loadAttachments(); final DataStatusEvent dataStatusEvent = DataStatusEvent.builder() .source(gridTab) .totalRows(gridTab.getRowCount()) .changed(false) .autoSave(true) .inserting(false) .build(); dataStatusEvent.setCurrentRow(gridTab.getCurrentRow()); final String status = dataStatusEvent.getAD_Message(); if (status == null || status.length() == 0) dataStatusEvent.setInfo("NavigateOrUpdate", null, false, false); gridTab.fireDataStatusChanged(dataStatusEvent); return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\de\schaeffer\compiere\tools\AttachmentDnDTransferHandler.java
1
请完成以下Java代码
public class BatchResourceImpl implements BatchResource { protected ProcessEngine processEngine; protected String batchId; public BatchResourceImpl(ProcessEngine processEngine, String batchId) { this.processEngine = processEngine; this.batchId = batchId; } public BatchDto getBatch() { Batch batch = processEngine.getManagementService() .createBatchQuery() .batchId(batchId) .singleResult(); if (batch == null) { throw new InvalidRequestException(Status.NOT_FOUND, "Batch with id '" + batchId + "' does not exist"); } return BatchDto.fromBatch(batch); } public void updateSuspensionState(SuspensionStateDto suspensionState) { if (suspensionState.getSuspended()) { suspendBatch(); } else { activateBatch(); } } protected void suspendBatch() { try { processEngine.getManagementService().suspendBatchById(batchId); } catch (BadUserRequestException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, "Unable to suspend batch with id '" + batchId + "'"); }
} protected void activateBatch() { try { processEngine.getManagementService().activateBatchById(batchId); } catch (BadUserRequestException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, "Unable to activate batch with id '" + batchId + "'"); } } public void deleteBatch(boolean cascade) { try { processEngine.getManagementService() .deleteBatch(batchId, cascade); } catch (BadUserRequestException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, "Unable to delete batch with id '" + batchId + "'"); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\batch\impl\BatchResourceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { private static final Logger log = LoggerFactory.getLogger(NettyServer.class); /** * 一旦连接,第一个被执行 */ @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { log.info("有新的客户端链接:[{}]", ctx.channel().id().asLongText()); // 添加到channelGroup 通道组 NettyConfig.getChannelGroup().add(ctx.channel()); } /** * 读取数据 */ @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { log.info("服务器收到消息:{}", msg.text()); // 获取用户ID,关联channel JSONObject jsonObject = JSONUtil.parseObj(msg.text()); String uid = jsonObject.getStr("uid"); NettyConfig.getChannelMap().put(uid, ctx.channel()); // 将用户ID作为自定义属性加入到channel中,方便随时channel中获取用户ID AttributeKey<String> key = AttributeKey.valueOf("userId"); ctx.channel().attr(key).setIfAbsent(uid); // 回复消息 ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器收到消息啦")); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { log.info("用户下线了:{}", ctx.channel().id().asLongText()); // 删除通道
NettyConfig.getChannelGroup().remove(ctx.channel()); removeUserId(ctx); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { log.info("异常:{}", cause.getMessage()); // 删除通道 NettyConfig.getChannelGroup().remove(ctx.channel()); removeUserId(ctx); ctx.close(); } /** * 删除用户与channel的对应关系 */ private void removeUserId(ChannelHandlerContext ctx) { AttributeKey<String> key = AttributeKey.valueOf("userId"); String userId = ctx.channel().attr(key).get(); NettyConfig.getChannelMap().remove(userId); } }
repos\springboot-demo-master\netty\src\main\java\com\et\netty\handler\WebSocketHandler.java
2
请在Spring Boot框架中完成以下Java代码
public class VehicleController { private final InventoryService inventoryService; public VehicleController(InventoryService inventoryService) { this.inventoryService = inventoryService; } @QueryMapping public List<Vehicle> searchAll() { return this.inventoryService.searchAll(); } @QueryMapping public List<Vehicle> searchByLocation(@Argument String zipcode) {
return this.inventoryService.searchByLocation(zipcode); } @QueryMapping public Vehicle searchByVin(@Argument String vin) { return this.inventoryService.searchByVin(vin); } @MutationMapping public Vehicle addVehicle(@Argument("vin") String vin, @Argument("year") Integer year, @Argument("make") String make, @Argument("model") String model, @Argument("trim") String trim, @Argument("location") Location location) { return this.inventoryService.addVehicle(vin, year, make, model, trim, location); } }
repos\tutorials-master\spring-boot-modules\spring-boot-graphql\src\main\java\com\baeldung\graphql\error\handling\controller\VehicleController.java
2
请完成以下Java代码
protected IMigrationExecutorContext getMigrationExecutorContext() { return migrationExecutorContext; } /** * Get current properties context. * * @return {@link Properties} ctx */ protected Properties getCtx() { return migrationExecutorContext.getCtx(); } /** * Log error messages as WARNING and normal ones as INFO. * * @param msg * @param resolution * @param isError */ protected final void log(final String msg, final String resolution, final boolean isError) { final StringBuilder sb = new StringBuilder(); sb.append("Step ").append(step.getSeqNo());
if (!Check.isEmpty(msg, true)) { sb.append(": ").append(msg.trim()); } if (resolution != null) { sb.append(" [").append(resolution).append("]"); } if(isError) { logger.error(sb.toString()); } else { logger.info(sb.toString()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\AbstractMigrationStepExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonDataImportResponse { @Value @Builder @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) public static class JsonInsertIntoImportTable { String fromResource; String toImportTableName; String importFormatName; DataImportConfigId dataImportConfigId; String duration; DataImportRunId dataImportRunId; int countTotalRows; int countValidRows; @JsonInclude(JsonInclude.Include.NON_EMPTY) List<JsonErrorItem> errors; } @JsonInclude(JsonInclude.Include.NON_EMPTY) JsonInsertIntoImportTable insertIntoImportTable; @Value @Builder @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) public static class JsonImportRecordsValidation { String importTableName; String duration; int countImportRecordsDeleted; int countErrors;
} @JsonInclude(JsonInclude.Include.NON_EMPTY) JsonImportRecordsValidation importRecordsValidation; @Value @Builder @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) public static class JsonActualImport { String importTableName; String targetTableName; int countImportRecordsConsidered; int countInsertsIntoTargetTable; int countUpdatesIntoTargetTable; @JsonInclude(JsonInclude.Include.NON_EMPTY) List<JsonErrorItem> errors; } @JsonInclude(JsonInclude.Include.NON_EMPTY) JsonActualImport actualImport; @Value @Builder @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) public static class JsonActualImportAsync { int workpackageId; } @JsonInclude(JsonInclude.Include.NON_EMPTY) JsonActualImportAsync actualImportAsync; }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\data_import\JsonDataImportResponse.java
2
请完成以下Java代码
public void unlockAll(final Collection<I_M_HU> hus, final LockOwner lockOwner) { if (hus.isEmpty()) { return; } Preconditions.checkNotNull(lockOwner, "lockOwner is null"); Preconditions.checkArgument(!lockOwner.isAnyOwner(), "{} not allowed", lockOwner); Services.get(ILockManager.class) .unlock() .setOwner(lockOwner) .setRecordsByModels(hus) .release(); if (isUseVirtualColumn()) {
InterfaceWrapperHelper.refresh(hus); } } @Override public IQueryFilter<I_M_HU> isLockedFilter() { return Services.get(ILockManager.class).getLockedByFilter(I_M_HU.class, LockOwner.ANY); } @Override public IQueryFilter<I_M_HU> isNotLockedFilter() { return Services.get(ILockManager.class).getNotLockedFilter(I_M_HU.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HULockBL.java
1
请完成以下Java代码
public IQueryBuilder<ModelType> createQueryBuilder(final Predicate<IFacetCategory> onlyFacetCategoriesPredicate) { final IQueryBuilder<ModelType> queryBuilder = queryBL.createQueryBuilder(modelClass, getCtx(), ITrx.TRXNAME_None); // queryBuilder.filter(gridTabBaseQueryFilter); final IQueryFilter<ModelType> facetCategoriesFilter = createFacetCategoriesFilter(onlyFacetCategoriesPredicate); queryBuilder.filter(facetCategoriesFilter); return queryBuilder; } private final ICompositeQueryFilter<ModelType> createFacetCategoriesFilter(final Predicate<IFacetCategory> onlyFacetCategoriesPredicate) { final ICompositeQueryFilter<ModelType> facetCategoriesFilter = queryBL.createCompositeQueryFilter(modelClass) // We are joining facet category filters by "AND" .setJoinAnd() // If there is no facet category filters, we accept everything .setDefaultAccept(true);
for (final Map.Entry<IFacetCategory, IQueryFilter<ModelType>> facetCategory2filter : facetCategoryFilters.entrySet()) { final IFacetCategory facetCategory = facetCategory2filter.getKey(); if (onlyFacetCategoriesPredicate != null && !onlyFacetCategoriesPredicate.test(facetCategory)) { continue; } final IQueryFilter<ModelType> filter = facetCategory2filter.getValue(); facetCategoriesFilter.addFilter(filter); } return facetCategoriesFilter; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\GridTabFacetFilterable.java
1
请完成以下Java代码
private static @Nullable Object initFieldValue(List<Object> path, GraphQlResponse response) { Object value = (response.isValid() ? response.getData() : null); for (Object segment : path) { if (value == null) { return null; } if (segment instanceof String) { Assert.isTrue(value instanceof Map, () -> "Invalid path " + path + ", data: " + response.getData()); value = ((Map<?, ?>) value).getOrDefault(segment, null); } else { Assert.isTrue(value instanceof List, () -> "Invalid path " + path + ", data: " + response.getData()); int index = (int) segment; value = (index < ((List<?>) value).size()) ? ((List<?>) value).get(index) : null; } } return value; } /** * Return errors whose path is at, above, or below the given path. * @param path the field path to match * @return errors whose path starts with the dataPath */ private static List<ResponseError> initFieldErrors(String path, GraphQlResponse response) { if (path.isEmpty() || response.getErrors().isEmpty()) { return Collections.emptyList(); } return response.getErrors().stream() .filter((error) -> { String errorPath = error.getPath(); return (!errorPath.isEmpty() && (errorPath.startsWith(path) || path.startsWith(errorPath))); }) .collect(Collectors.toList()); }
@Override public String getPath() { return this.path; } @Override public List<Object> getParsedPath() { return this.parsedPath; } @SuppressWarnings("unchecked") @Override public @Nullable <T> T getValue() { return (T) this.value; } @Override public List<ResponseError> getErrors() { return this.fieldErrors; } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\support\AbstractGraphQlResponse.java
1
请完成以下Java代码
private List<String> createUpdateSqls(String classname) { final List<String> updateSqls = new ArrayList<>(); final Class<?> clazz = loadClass(classname); final Field[] classFields = clazz.getFields(); for (final Field field : classFields) { final String fieldName = field.getName(); if (!fieldName.endsWith(SUFFIX_AD_Reference_ID)) { continue; } final int adReferenceId = getFieldValueAsInt(field); final String prefix = fieldName.substring(0, fieldName.length() - SUFFIX_AD_Reference_ID.length()); final Map<String, String> name2value = extractNameAndValueForPrefix(prefix, classFields); updateSqls.add("\n\n-- " + prefix); updateSqls.addAll(createUpdateSqls(adReferenceId, name2value)); } return updateSqls; } private List<String> createUpdateSqls(int adReferenceId, Map<String, String> name2valuesMap) { final List<String> updateSqls = new ArrayList<>(name2valuesMap.size()); for (final Map.Entry<String, String> name2value : name2valuesMap.entrySet()) { final String name = name2value.getKey(); final String value = name2value.getValue(); final String sql = "UPDATE AD_Ref_List SET ValueName='" + name + "'" + " WHERE AD_Reference_ID=" + adReferenceId + " AND Value='" + value + "'" + ";"; updateSqls.add(sql); } return updateSqls; } private Map<String, String> extractNameAndValueForPrefix(String prefix, Field[] classFields) { final Map<String, String> name2value = new LinkedHashMap<>(); for (final Field field : classFields) { final String fieldName = field.getName(); if (!fieldName.startsWith(prefix)) { continue; } if (fieldName.endsWith(SUFFIX_AD_Reference_ID)) { continue; } final String name = fieldName.substring(prefix.length()); final String value = getFieldValueAsString(field); name2value.put(name, value); } return name2value; }
private final String getFieldValueAsString(final Field field) { try { return (String)field.get(null); } catch (Exception e) { throw new RuntimeException("Cannot get value of " + field); } } private final int getFieldValueAsInt(final Field field) { try { return (int)field.get(null); } catch (Exception e) { throw new RuntimeException("Cannot get value of " + field); } } private Class<?> loadClass(String classname) { final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { return classLoader.loadClass(classname); } catch (ClassNotFoundException e) { throw new RuntimeException("Cannot load class: " + classname, e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\tools\AD_Ref_List_ValueName_UpdateFromClass.java
1
请完成以下Java代码
public boolean isSecure() { // TODO: move to map if ("https".equals(this.overrideScheme) || "wss".equals(this.overrideScheme)) { return true; } return delegate.isSecure(); } @Override public URI getUri() { return delegate.getUri(); } @Override public @Nullable Map<String, String> getMetadata() {
return delegate.getMetadata(); } @Override public String getScheme() { String scheme = delegate.getScheme(); if (scheme != null) { return scheme; } return this.overrideScheme; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\LoadBalancerFilterFunctions.java
1
请在Spring Boot框架中完成以下Java代码
public class BPartnerCompositeLookupKey { public static BPartnerCompositeLookupKey ofMetasfreshId(@NonNull final MetasfreshId metasfreshId) { return new BPartnerCompositeLookupKey(metasfreshId, null, null, null, null); } public static <T extends RepoIdAware> BPartnerCompositeLookupKey ofMetasfreshId(@NonNull final T id) { return ofMetasfreshId(MetasfreshId.of(id)); } public static BPartnerCompositeLookupKey ofJsonExternalId(@NonNull final JsonExternalId jsonExternalId) { return new BPartnerCompositeLookupKey(null, jsonExternalId, null, null, null); } public static BPartnerCompositeLookupKey ofExternalId(@NonNull final ExternalId externalId) { return ofJsonExternalId(JsonExternalIds.of(externalId)); } public static BPartnerCompositeLookupKey ofCode(@NonNull final String code) { assumeNotEmpty(code, "Given parameter 'code' may not be empty"); return new BPartnerCompositeLookupKey(null, null, code.trim(), null, null); } public static BPartnerCompositeLookupKey ofGln(@NonNull final GLN gln) { return new BPartnerCompositeLookupKey(null, null, null, gln, null); } public static BPartnerCompositeLookupKey ofGlnWithLabel(@NonNull final GlnWithLabel glnWithLabel) { return new BPartnerCompositeLookupKey(null, null, null, null, glnWithLabel); } public static BPartnerCompositeLookupKey ofIdentifierString(@NonNull final IdentifierString bpartnerIdentifier) { switch (bpartnerIdentifier.getType()) { case EXTERNAL_ID: return BPartnerCompositeLookupKey.ofJsonExternalId(bpartnerIdentifier.asJsonExternalId()); case VALUE: return BPartnerCompositeLookupKey.ofCode(bpartnerIdentifier.asValue()); case GLN:
return BPartnerCompositeLookupKey.ofGln(bpartnerIdentifier.asGLN()); case GLN_WITH_LABEL: return BPartnerCompositeLookupKey.ofGlnWithLabel(bpartnerIdentifier.asGlnWithLabel()); case METASFRESH_ID: return BPartnerCompositeLookupKey.ofMetasfreshId(bpartnerIdentifier.asMetasfreshId()); default: throw new AdempiereException("Unexpected type=" + bpartnerIdentifier.getType()); } } MetasfreshId metasfreshId; JsonExternalId jsonExternalId; String code; GLN gln; GlnWithLabel glnWithLabel; private BPartnerCompositeLookupKey( @Nullable final MetasfreshId metasfreshId, @Nullable final JsonExternalId jsonExternalId, @Nullable final String code, @Nullable final GLN gln, @Nullable final GlnWithLabel glnWithLabel) { this.metasfreshId = metasfreshId; this.jsonExternalId = jsonExternalId; this.code = code; this.gln = gln; this.glnWithLabel = glnWithLabel; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\BPartnerCompositeLookupKey.java
2
请完成以下Java代码
public LocalInstrumentSEPA getLclInstrm() { return lclInstrm; } /** * Sets the value of the lclInstrm property. * * @param value * allowed object is * {@link LocalInstrumentSEPA } * */ public void setLclInstrm(LocalInstrumentSEPA value) { this.lclInstrm = value; } /** * Gets the value of the seqTp property. * * @return * possible object is * {@link SequenceType1Code } * */ public SequenceType1Code getSeqTp() { return seqTp; } /** * Sets the value of the seqTp property. * * @param value * allowed object is * {@link SequenceType1Code }
* */ public void setSeqTp(SequenceType1Code value) { this.seqTp = value; } /** * Gets the value of the ctgyPurp property. * * @return * possible object is * {@link CategoryPurposeSEPA } * */ public CategoryPurposeSEPA getCtgyPurp() { return ctgyPurp; } /** * Sets the value of the ctgyPurp property. * * @param value * allowed object is * {@link CategoryPurposeSEPA } * */ public void setCtgyPurp(CategoryPurposeSEPA value) { this.ctgyPurp = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\PaymentTypeInformationSDD.java
1
请在Spring Boot框架中完成以下Java代码
public class AuthProgramInitResultVo implements Serializable { private static final long serialVersionUID = -5167161500901848253L; private String mchOrderNo; /** * 交易状态 YES 成功,其他失败 */ private String errCode; /** * 支付信息 */ private String payMessage; /** * 银行返回信息 */ private String bankReturnMsg; /** * 订单状态 */ private TradeStatusEnum tradeStatus = TradeStatusEnum.WAITING_PAYMENT; /** * 是否鉴权 */ private boolean isAuth = false; /** * 签名结果 */ private String sign; public String getMchOrderNo() { return mchOrderNo; } public void setMchOrderNo(String mchOrderNo) { this.mchOrderNo = mchOrderNo; } public String getErrCode() { return errCode; } public void setErrCode(String errCode) { this.errCode = errCode; } public String getPayMessage() { return payMessage; } public void setPayMessage(String payMessage) { this.payMessage = payMessage; } public String getBankReturnMsg() {
return bankReturnMsg; } public void setBankReturnMsg(String bankReturnMsg) { this.bankReturnMsg = bankReturnMsg; } public TradeStatusEnum getTradeStatus() { return tradeStatus; } public void setTradeStatus(TradeStatusEnum tradeStatus) { this.tradeStatus = tradeStatus; } public boolean isAuth() { return isAuth; } public void setAuth(boolean auth) { isAuth = auth; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\AuthProgramInitResultVo.java
2
请完成以下Java代码
public class CreateIndexService { /** 设置集合名称 */ private static final String COLLECTION_NAME = "users"; @Resource private MongoTemplate mongoTemplate; /** * 创建升序索引 * * @return 索引信息 */ public Object createAscendingIndex() { // 设置字段名称 String field = "name"; // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(field)); } /** * 创建降序索引 * * @return 索引信息 */ public Object createDescendingIndex() { // 设置字段名称 String field = "name"; // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.descending(field)); } /** * 创建升序复合索引 * * @return 索引信息 */ public Object createCompositeIndex() { // 设置字段名称 String field1 = "name"; String field2 = "age"; // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(field1, field2)); } /** * 创建文字索引 * * @return 索引信息 */ public Object createTextIndex() { // 设置字段名称 String field = "name";
// 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.text(field)); } /** * 创建哈希索引 * * @return 索引信息 */ public Object createHashIndex() { // 设置字段名称 String field = "name"; // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.hashed(field)); } /** * 创建升序唯一索引 * * @return 索引信息 */ public Object createUniqueIndex() { // 设置字段名称 String indexName = "name"; // 配置索引选项 IndexOptions options = new IndexOptions(); // 设置为唯一索引 options.unique(true); // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(indexName), options); } /** * 创建局部索引 * * @return 索引信息 */ public Object createPartialIndex() { // 设置字段名称 String field = "name"; // 配置索引选项 IndexOptions options = new IndexOptions(); // 设置过滤条件 options.partialFilterExpression(Filters.exists("name", true)); // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(field), options); } }
repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\CreateIndexService.java
1
请在Spring Boot框架中完成以下Java代码
public class WebDriverConfig { @Bean @ConditionalOnProperty(name = "browser", havingValue = "edge") public WebDriver edgeDriver() { // this is the bean class for edge driver if (System.getenv("CLOUD_RUN_FLAG") == null) { WebDriverManager.edgedriver().setup(); } return new EdgeDriver(); } @Bean // @Primary // this will be the default browser @ConditionalOnMissingBean // to catch invalid browser values @Scope("browserscope") // use custom scope public WebDriver chromeDriver() { // this is the bean class for chrome driver
if (System.getenv("CLOUD_RUN_FLAG") == null) { WebDriverManager.chromedriver().setup(); return new ChromeDriver(); } else { WebDriverManager.chromedriver().setup(); ChromeOptions options = new ChromeOptions(); options.addArguments("--no-sandbox"); options.addArguments("--headless"); return new ChromeDriver(options = options); } } }
repos\springboot-demo-master\Selenium\src\main\java\com\et\selenium\config\WebDriverConfig.java
2
请完成以下Java代码
public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @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; } /** * Type AD_Reference_ID=540534
* Reference name: GL_JournalLine_Type */ public static final int TYPE_AD_Reference_ID=540534; /** Normal = N */ public static final String TYPE_Normal = "N"; /** Tax = T */ public static final String TYPE_Tax = "T"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_JournalLine.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(articleDescription, articleNumber, batchNumber, technicalServiceCompletionDate, dueDate, name, additionalName, inspectionType, inspectionCompleted, serialNumber, serviceOriginType, serviceDescription, serviceLocation, serviceCompleted, deviceAppraisalLines, active, archived); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DeviceInformationLine {\n"); sb.append(" articleDescription: ").append(toIndentedString(articleDescription)).append("\n"); sb.append(" articleNumber: ").append(toIndentedString(articleNumber)).append("\n"); sb.append(" batchNumber: ").append(toIndentedString(batchNumber)).append("\n"); sb.append(" technicalServiceCompletionDate: ").append(toIndentedString(technicalServiceCompletionDate)).append("\n"); sb.append(" dueDate: ").append(toIndentedString(dueDate)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" additionalName: ").append(toIndentedString(additionalName)).append("\n"); sb.append(" inspectionType: ").append(toIndentedString(inspectionType)).append("\n"); sb.append(" inspectionCompleted: ").append(toIndentedString(inspectionCompleted)).append("\n"); sb.append(" serialNumber: ").append(toIndentedString(serialNumber)).append("\n"); sb.append(" serviceOriginType: ").append(toIndentedString(serviceOriginType)).append("\n"); sb.append(" serviceDescription: ").append(toIndentedString(serviceDescription)).append("\n");
sb.append(" serviceLocation: ").append(toIndentedString(serviceLocation)).append("\n"); sb.append(" serviceCompleted: ").append(toIndentedString(serviceCompleted)).append("\n"); sb.append(" deviceAppraisalLines: ").append(toIndentedString(deviceAppraisalLines)).append("\n"); sb.append(" active: ").append(toIndentedString(active)).append("\n"); sb.append(" archived: ").append(toIndentedString(archived)).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\DeviceInformationLine.java
2
请完成以下Java代码
public final class AuthenticatorAttachment implements Serializable { @Serial private static final long serialVersionUID = 8446133215195918090L; /** * Indicates <a href= * "https://www.w3.org/TR/2021/REC-webauthn-2-20210408/#cross-platform-attachment">cross-platform * attachment</a>. * * <p> * Authenticators of this class are removable from, and can "roam" among, client * platforms. */ public static final AuthenticatorAttachment CROSS_PLATFORM = new AuthenticatorAttachment("cross-platform"); /** * Indicates <a href= * "https://www.w3.org/TR/2021/REC-webauthn-2-20210408/#platform-attachment">platform * attachment</a>. * * <p> * Usually, authenticators of this class are not removable from the platform. */ public static final AuthenticatorAttachment PLATFORM = new AuthenticatorAttachment("platform"); private final String value; AuthenticatorAttachment(String value) { this.value = value; } /** * Gets the value. * @return the value.
*/ public String getValue() { return this.value; } @Override public String toString() { return "AuthenticatorAttachment [" + this.value + "]"; } /** * Gets an instance of {@link AuthenticatorAttachment} based upon the value passed in. * @param value the value to obtain the {@link AuthenticatorAttachment} * @return the {@link AuthenticatorAttachment} */ public static AuthenticatorAttachment valueOf(String value) { switch (value) { case "cross-platform": return CROSS_PLATFORM; case "platform": return PLATFORM; default: return new AuthenticatorAttachment(value); } } public static AuthenticatorAttachment[] values() { return new AuthenticatorAttachment[] { CROSS_PLATFORM, PLATFORM }; } @Serial private Object readResolve() throws ObjectStreamException { return valueOf(this.value); } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\AuthenticatorAttachment.java
1
请完成以下Java代码
public static List<Integer> findPairsWithForLoop(int[] input, int sum) { final List<Integer> allExistingPairs = new ArrayList<>(); for (int i = 0; i < input.length; i++) { for (int j = 0; j < input.length; j++) { if (j != i && (input[i] + input[j]) == sum) { allExistingPairs.add(input[i]); } } } return allExistingPairs; } /** * Show all existing pairs using Java 8 stream API *
* @param input - number's array * @param sum - given sum * @return - number's array with all existing pairs. This list will contain just one pair's element because * the other one can be calculated with SUM - element_1 = element_2 */ public static List<Integer> findPairsWithStreamApi(int[] input, int sum) { final List<Integer> allExistingPairs = new ArrayList<>(); IntStream.range(0, input.length).forEach(i -> IntStream.range(0, input.length) .filter(j -> i != j && input[i] + input[j] == sum) .forEach(j -> allExistingPairs.add(input[i])) ); return allExistingPairs; } }
repos\tutorials-master\core-java-modules\core-java-numbers-9\src\main\java\com\baeldung\pairsaddupnumber\ExistingPairs.java
1
请在Spring Boot框架中完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQtyConsumed (final BigDecimal QtyConsumed) { set_Value (COLUMNNAME_QtyConsumed, QtyConsumed); } @Override public BigDecimal getQtyConsumed() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyConsumed); return bd != null ? bd : BigDecimal.ZERO;
} @Override public void setQtyReserved (final BigDecimal QtyReserved) { set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_Consumption_Summary.java
2
请在Spring Boot框架中完成以下Java代码
public List<EntityLink> findEntityLinksWithSameRootScopeForScopeIdAndScopeType(String scopeId, String scopeType, String linkType) { return getEntityLinkEntityManager().findEntityLinksWithSameRootScopeForScopeIdAndScopeType(scopeId, scopeType, linkType); } @Override @SuppressWarnings("unchecked") public InternalEntityLinkQuery<EntityLink> createInternalEntityLinkQuery() { return (InternalEntityLinkQuery) getEntityLinkEntityManager().createInternalEntityLinkQuery(); } @Override public EntityLinkEntity createEntityLink() { return getEntityLinkEntityManager().create(); } @Override public void insertEntityLink(EntityLink entityLink) { getEntityLinkEntityManager().insert((EntityLinkEntity) entityLink); }
@Override public void deleteEntityLinksByScopeIdAndType(String scopeId, String scopeType) { getEntityLinkEntityManager().deleteEntityLinksByScopeIdAndScopeType(scopeId, scopeType); } @Override public void deleteEntityLinksByRootScopeIdAndType(String scopeId, String scopeType) { getEntityLinkEntityManager().deleteEntityLinksByRootScopeIdAndType(scopeId, scopeType); } public EntityLinkEntityManager getEntityLinkEntityManager() { return configuration.getEntityLinkEntityManager(); } }
repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\EntityLinkServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class SslCredentialsWebServerCustomizer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> { @Bean @ConfigurationProperties(prefix = "server.ssl.credentials") public SslCredentialsConfig httpServerSslCredentials() { return new SslCredentialsConfig("HTTP Server SSL Credentials", false); } @Autowired @Qualifier("httpServerSslCredentials") private SslCredentialsConfig httpServerSslCredentialsConfig; @Autowired SslBundles sslBundles; private final ServerProperties serverProperties; public SslCredentialsWebServerCustomizer(ServerProperties serverProperties) { this.serverProperties = serverProperties; } @Override public void customize(ConfigurableServletWebServerFactory factory) { SslCredentials sslCredentials = this.httpServerSslCredentialsConfig.getCredentials(); Ssl ssl = serverProperties.getSsl(); ssl.setBundle("default"); ssl.setKeyAlias(sslCredentials.getKeyAlias()); ssl.setKeyPassword(sslCredentials.getKeyPassword()); factory.setSsl(ssl); factory.setSslBundles(sslBundles); } @Bean public SslBundles sslBundles() { SslStoreBundle storeBundle = SslStoreBundle.of( httpServerSslCredentialsConfig.getCredentials().getKeyStore(),
httpServerSslCredentialsConfig.getCredentials().getKeyPassword(), null ); return new SslBundles() { @Override public SslBundle getBundle(String name) { return SslBundle.of(storeBundle); } @Override public List<String> getBundleNames() { return List.of("default"); } @Override public void addBundleUpdateHandler(String name, Consumer<SslBundle> handler) { // no-op } }; } }
repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\config\ssl\SslCredentialsWebServerCustomizer.java
2
请完成以下Java代码
public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler authenticationSuccessHandler) { this.authenticationSuccessHandler = authenticationSuccessHandler; } /** * Sets the strategy used to handle a failed authentication. */ public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) { this.authenticationFailureHandler = authenticationFailureHandler; } /** * Sets the request matcher to check whether to proceed the request further. */ public void setRequiresAuthenticationRequestMatcher(RequestMatcher requiresAuthenticationRequestMatcher) { Assert.notNull(requiresAuthenticationRequestMatcher, "requestMatcher cannot be null"); this.requiresAuthenticationRequestMatcher = requiresAuthenticationRequestMatcher; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } /** * Override to extract the principal information from the current request */ protected abstract @Nullable Object getPreAuthenticatedPrincipal(HttpServletRequest request); /** * Override to extract the credentials (if applicable) from the current request. * Should not return null for a valid principal, though some implementations may * return a dummy value. */ protected abstract @Nullable Object getPreAuthenticatedCredentials(HttpServletRequest request); /** * Request matcher for default auth check logic */ private class PreAuthenticatedProcessingRequestMatcher implements RequestMatcher {
@Override public boolean matches(HttpServletRequest request) { Authentication currentUser = AbstractPreAuthenticatedProcessingFilter.this.securityContextHolderStrategy .getContext() .getAuthentication(); if (currentUser == null) { return true; } if (!AbstractPreAuthenticatedProcessingFilter.this.checkForPrincipalChanges) { return false; } if (!principalChanged(request, currentUser)) { return false; } AbstractPreAuthenticatedProcessingFilter.this.logger .debug("Pre-authenticated principal has changed and will be reauthenticated"); if (AbstractPreAuthenticatedProcessingFilter.this.invalidateSessionOnPrincipalChange) { AbstractPreAuthenticatedProcessingFilter.this.securityContextHolderStrategy.clearContext(); HttpSession session = request.getSession(false); if (session != null) { AbstractPreAuthenticatedProcessingFilter.this.logger.debug("Invalidating existing session"); session.invalidate(); request.getSession(); } } return true; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\preauth\AbstractPreAuthenticatedProcessingFilter.java
1
请在Spring Boot框架中完成以下Java代码
public PickingJobOptions getPickingJobOptions(@Nullable final BPartnerId customerId, @NonNull PickingJobOptionsCollection pickingJobOptionsCollection) { final PickingJobOptions customerPickingJobOptions = customerId != null ? customerConfigs.getPickingJobOptionsId(customerId).map(pickingJobOptionsCollection::getById).orElse(null) : null; if (customerPickingJobOptions != null) { return customerPickingJobOptions.fallbackTo(defaultPickingJobOptions); } else { return defaultPickingJobOptions; } } public PickingJobAggregationType getAggregationType(@Nullable final BPartnerId customerId, @NonNull PickingJobOptionsCollection pickingJobOptionsCollection) { return getPickingJobOption(customerId, pickingJobOptionsCollection, PickingJobOptions::getAggregationType, PickingJobAggregationType.DEFAULT); } @SuppressWarnings("SameParameterValue") private <T> T getPickingJobOption( @Nullable final BPartnerId customerId, @NonNull final PickingJobOptionsCollection pickingJobOptionsCollection, @NonNull final Function<PickingJobOptions, T> extractOption, @NonNull final T defaultValue) { if (customerId != null) { final PickingJobOptions pickingJobOptions = customerConfigs.getPickingJobOptionsId(customerId) .map(pickingJobOptionsCollection::getById) .orElse(null); if (pickingJobOptions != null) {
final T option = extractOption.apply(pickingJobOptions); if (option != null) { return option; } } } final T option = extractOption.apply(defaultPickingJobOptions); if (option != null) { return option; } return defaultValue; } @NonNull public ImmutableSet<BPartnerId> getPickOnlyCustomerIds() { if (isAllowPickingAnyCustomer) { return ImmutableSet.of(); } return customerConfigs.getCustomerIds(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\config\mobileui\MobileUIPickingUserProfile.java
2
请完成以下Java代码
public static ConcurrentHashMap<Integer, String[]> groupByObjectIdVersionedIds(Set<String> targetIds) { return targetIds.stream() .collect(Collectors.groupingBy( id -> new LwM2mPath(fromVersionedIdToObjectId(id)).getObjectId(), ConcurrentHashMap::new, Collectors.collectingAndThen( Collectors.toList(), list -> list.toArray(new String[0]) ) )); } public static boolean areArraysStringEqual(String[] oldValue, String[] newValue) { if (oldValue == null || newValue == null) return false; if (oldValue.length != newValue.length) return false; String[] sorted1 = oldValue.clone(); String[] sorted2 = newValue.clone(); Arrays.sort(sorted1); Arrays.sort(sorted2); return Arrays.equals(sorted1, sorted2); } public static ConcurrentHashMap<Integer, String[]> deepCopyConcurrentMap(Map<Integer, String[]> original) { return original.isEmpty() ? new ConcurrentHashMap<>() : original.entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, entry -> entry.getValue() != null ? entry.getValue().clone() : null, (v1, v2) -> v1, // merge function in case of duplicate keys ConcurrentHashMap::new )); } public static boolean areMapsEqual(Map<Integer, String[]> m1, Map<Integer, String[]> m2) { if (m1.size() != m2.size()) return false; for (Integer key : m1.keySet()) {
if (!m2.containsKey(key)) return false; String[] arr1 = m1.get(key); String[] arr2 = m2.get(key); if (arr1 == null || arr2 == null) { if (arr1 != arr2) return false; String[] sorted1 = arr1.clone(); String[] sorted2 = arr2.clone(); Arrays.sort(sorted1); Arrays.sort(sorted2); if (!Arrays.equals(sorted1, sorted2)) return false; } } return true; } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\utils\LwM2MTransportUtil.java
1
请在Spring Boot框架中完成以下Java代码
JWTAuthenticationProvider jwtAuthenticationProvider(JWTDeserializer jwtDeserializer) { return new JWTAuthenticationProvider(jwtDeserializer); } @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedMethods("GET", "HEAD", "POST", "DELETE", "PUT") .allowedOrigins(properties.getAllowedOrigins().toArray(new String[0])) .allowedHeaders("*") .allowCredentials(true); }
} @ConstructorBinding @ConfigurationProperties("security") class SecurityConfigurationProperties { private final List<String> allowedOrigins; SecurityConfigurationProperties(List<String> allowedOrigins) { this.allowedOrigins = allowedOrigins; } public List<String> getAllowedOrigins() { return allowedOrigins; } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\application\security\SecurityConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public String passwordUpdate(HttpServletRequest request, @RequestParam("originalPassword") String originalPassword, @RequestParam("newPassword") String newPassword) { if (!StringUtils.hasText(originalPassword) || !StringUtils.hasText(newPassword)) { return "参数不能为空"; } Long loginUserId = (long) request.getSession().getAttribute("loginUserId"); if (adminService.updatePassword(loginUserId, originalPassword, newPassword)) { //修改成功后清空session中的数据,前端控制跳转至登录页 request.getSession().removeAttribute("loginUserId"); request.getSession().removeAttribute("loginUser"); request.getSession().removeAttribute("errorMsg"); return "success"; } else { return "修改失败"; } } @PostMapping("/profile/name") @ResponseBody public String nameUpdate(HttpServletRequest request, @RequestParam("loginUserName") String loginUserName, @RequestParam("nickName") String nickName) { if (!StringUtils.hasText(loginUserName) || !StringUtils.hasText(nickName)) { return "参数不能为空"; }
Long loginUserId = (long) request.getSession().getAttribute("loginUserId"); if (adminService.updateName(loginUserId, loginUserName, nickName)) { return "success"; } else { return "修改失败"; } } @GetMapping("/logout") public String logout(HttpServletRequest request) { request.getSession().removeAttribute("loginUserId"); request.getSession().removeAttribute("loginUser"); request.getSession().removeAttribute("errorMsg"); return "admin/login"; } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\controller\admin\AdminController.java
2
请完成以下Java代码
public void setC_BPartner_Location_Value_ID(final int C_BPartner_Location_Value_ID) { delegate.setC_BPartner_Location_Value_ID(C_BPartner_Location_Value_ID); } @Override public int getAD_User_ID() { return delegate.getAD_User_ID(); } @Override public void setAD_User_ID(final int AD_User_ID) { delegate.setAD_User_ID(AD_User_ID); } @Override public String getBPartnerAddress() { return delegate.getBPartnerAddress(); } @Override public void setBPartnerAddress(String address) { delegate.setBPartnerAddress(address); } @Override public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentLocationAdapter.super.setRenderedAddress(from); } public void setFrom(@NonNull final I_M_InOut from) { setFrom(new DocumentLocationAdapter(from).toDocumentLocation()); }
public void setFrom(@NonNull final I_C_Order from) { setFrom(OrderDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation()); } public void setFrom(@NonNull final I_C_Invoice from) { setFrom(InvoiceDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation()); } @Override public I_M_InOut getWrappedRecord() { return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public DocumentLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new DocumentLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_M_InOut.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\location\adapter\DocumentLocationAdapter.java
1
请完成以下Java代码
public class AuthorId implements Serializable { private static final long serialVersionUID = 1L; @ManyToOne @JoinColumn(name = "publisher") private Publisher publisher; @Column(name = "name") private String name; public AuthorId() { } public AuthorId(Publisher publisher, String name) { this.publisher = publisher; this.name = name; } public Publisher getPublisher() { return publisher; } public String getName() { return name; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.publisher); hash = 97 * hash + Objects.hashCode(this.name); return hash; } @Override
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final AuthorId other = (AuthorId) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.publisher, other.publisher)) { return false; } return true; } @Override public String toString() { return "AuthorId{ " + "publisher=" + publisher + ", name=" + name + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCompositeKeyEmbeddableMapRel\src\main\java\com\bookstore\entity\AuthorId.java
1
请完成以下Java代码
protected final ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!isHUEditorView()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view"); } if (!streamSelectedHUIds(HUEditorRowFilter.Select.ONLY_TOPLEVEL).findAny().isPresent()) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(WEBUI_HU_Constants.MSG_WEBUI_ONLY_TOP_LEVEL_HU)); } if (streamSelectedHUs(HUEditorRowFilter.Select.ONLY_TOPLEVEL).noneMatch(huStatusBL::isPhysicalHU)) { return ProcessPreconditionsResolution.rejectWithInternalReason("only 'physical' HUs are eligible"); } return ProcessPreconditionsResolution.accept(); } @Override protected final String doIt() { final HUInternalUseInventoryCreateResponse result = inventoryService.moveToGarbage(createHUInternalUseInventoryCreateRequest()); somethingWasProcessed = !result.getInventories().isEmpty(); return MSG_OK; } protected abstract HUInternalUseInventoryCreateRequest createHUInternalUseInventoryCreateRequest(); @NonNull protected final List<I_M_HU> getHUsToInternalUse()
{ final List<I_M_HU> hus = streamSelectedHUs(HUEditorRowFilter.Select.ONLY_TOPLEVEL).collect(ImmutableList.toImmutableList()); if (hus.isEmpty()) { throw new AdempiereException("@NoSelection@"); } return hus; } @Override protected final void postProcess(final boolean success) { if (somethingWasProcessed) { getView().invalidateAll(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_InternalUse_Template.java
1
请完成以下Java代码
public @Nullable String getId() { return this.id; } public void setId(String id) { this.id = id; } @Override public @Nullable Tag getParent() { return this.parent; } @Override public void setParent(Tag parent) { this.parent = parent; } public @Nullable String getVar() { return this.var; } public void setVar(String var) { this.var = var; } @Override public void release() { this.parent = null; this.id = null; } @Override public void setPageContext(PageContext pageContext) { this.pageContext = pageContext; } @Override protected ServletRequest getRequest() { return this.pageContext.getRequest(); } @Override protected ServletResponse getResponse() { return this.pageContext.getResponse(); } @Override protected ServletContext getServletContext() { return this.pageContext.getServletContext(); } private final class PageContextVariableLookupEvaluationContext implements EvaluationContext { private EvaluationContext delegate; private PageContextVariableLookupEvaluationContext(EvaluationContext delegate) { this.delegate = delegate; } @Override public TypedValue getRootObject() { return this.delegate.getRootObject(); } @Override
public List<ConstructorResolver> getConstructorResolvers() { return this.delegate.getConstructorResolvers(); } @Override public List<MethodResolver> getMethodResolvers() { return this.delegate.getMethodResolvers(); } @Override public List<PropertyAccessor> getPropertyAccessors() { return this.delegate.getPropertyAccessors(); } @Override public TypeLocator getTypeLocator() { return this.delegate.getTypeLocator(); } @Override public TypeConverter getTypeConverter() { return this.delegate.getTypeConverter(); } @Override public TypeComparator getTypeComparator() { return this.delegate.getTypeComparator(); } @Override public OperatorOverloader getOperatorOverloader() { return this.delegate.getOperatorOverloader(); } @Override public @Nullable BeanResolver getBeanResolver() { return this.delegate.getBeanResolver(); } @Override public void setVariable(String name, @Nullable Object value) { this.delegate.setVariable(name, value); } @Override public Object lookupVariable(String name) { Object result = this.delegate.lookupVariable(name); if (result == null) { result = JspAuthorizeTag.this.pageContext.findAttribute(name); } return result; } } }
repos\spring-security-main\taglibs\src\main\java\org\springframework\security\taglibs\authz\JspAuthorizeTag.java
1
请完成以下Java代码
public class CamundaFormDefinitionCache extends ResourceDefinitionCache<CamundaFormDefinitionEntity> { public CamundaFormDefinitionCache(CacheFactory factory, int cacheCapacity, CacheDeployer cacheDeployer) { super(factory, cacheCapacity, cacheDeployer); } @Override protected AbstractResourceDefinitionManager<CamundaFormDefinitionEntity> getManager() { return Context.getCommandContext().getCamundaFormDefinitionManager(); } @Override protected void checkInvalidDefinitionId(String definitionId) { ensureNotNull("Invalid camunda form definition id", "camundaFormDefinitionId", definitionId); } @Override protected void checkDefinitionFound(String definitionId, CamundaFormDefinitionEntity definition) { ensureNotNull("no deployed camunda form definition found with id '" + definitionId + "'", "camundaFormDefinition", definition); } @Override protected void checkInvalidDefinitionByKey(String definitionKey, CamundaFormDefinitionEntity definition) { ensureNotNull("no deployed camunda form definition found with key '" + definitionKey + "'", "camundaFormDefinition", definition); } @Override protected void checkInvalidDefinitionByKeyAndTenantId(String definitionKey, String tenantId, CamundaFormDefinitionEntity definition) {
ensureNotNull("no deployed camunda form definition found with key '" + definitionKey + "' and tenant-id '" + tenantId + "'", "camundaFormDefinition", definition); } @Override protected void checkInvalidDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId, CamundaFormDefinitionEntity definition) { ensureNotNull("no deployed camunda form definition found with key '" + definitionKey + "', version '" + definitionVersion + "' and tenant-id '" + tenantId + "'", "camundaFormDefinition", definition); } @Override protected void checkInvalidDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId, CamundaFormDefinitionEntity definition) { // version tag is currently not supported for CamundaFormDefinition } @Override protected void checkInvalidDefinitionByDeploymentAndKey(String deploymentId, String definitionKey, CamundaFormDefinitionEntity definition) { ensureNotNull("no deployed camunda form definition found with key '" + definitionKey + "' in deployment '" + deploymentId + "'", "camundaFormDefinition", definition); } @Override protected void checkInvalidDefinitionWasCached(String deploymentId, String definitionId, CamundaFormDefinitionEntity definition) { ensureNotNull("deployment '" + deploymentId + "' didn't put camunda form definition '" + definitionId + "' in the cache", "cachedProcessDefinition", definition); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\CamundaFormDefinitionCache.java
1
请完成以下Java代码
public String getPhone() { return super.getPhone(); } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Email", example = "example@company.com") @Override public String getEmail() { return super.getEmail(); } @Schema(description = "Additional parameters of the device",implementation = com.fasterxml.jackson.databind.JsonNode.class) @Override public JsonNode getAdditionalInfo() { return super.getAdditionalInfo(); } @JsonIgnore public boolean isPublic() { if (getAdditionalInfo() != null && getAdditionalInfo().has("isPublic")) { return getAdditionalInfo().get("isPublic").asBoolean(); } return false; } @JsonIgnore public ShortCustomerInfo toShortCustomerInfo() { return new ShortCustomerInfo(id, title, isPublic()); } @Override @JsonProperty(access = Access.READ_ONLY) @Schema(description = "Name of the customer. Read-only, duplicated from title for backward compatibility", example = "Company A", accessMode = Schema.AccessMode.READ_ONLY) public String getName() { return title; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Customer [title=");
builder.append(title); builder.append(", tenantId="); builder.append(tenantId); builder.append(", additionalInfo="); builder.append(getAdditionalInfo()); builder.append(", country="); builder.append(country); builder.append(", state="); builder.append(state); builder.append(", city="); builder.append(city); builder.append(", address="); builder.append(address); builder.append(", address2="); builder.append(address2); builder.append(", zip="); builder.append(zip); builder.append(", phone="); builder.append(phone); builder.append(", email="); builder.append(email); builder.append(", createdTime="); builder.append(createdTime); builder.append(", id="); builder.append(id); builder.append("]"); return builder.toString(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\Customer.java
1
请完成以下Java代码
public static boolean isEditable(Component c) { if (c == null) return false; if (!c.isEnabled()) return false; if (c instanceof CEditor) return ((CEditor)c).isReadWrite(); if (c instanceof JTextComponent) return ((JTextComponent)c).isEditable(); // log.warn("Unknown component type - "+c.getClass()); return false; } public static void focusNextNotEmpty(Component component, Collection<Component> editors) { boolean found = false; Component last = null; for (Component c : editors) {
last = c; if (found) { if (isEditable(c) && isEmpty(c)) { c.requestFocus(); return; } } else if (c == component) { found = true; } } // if (!found) log.warn("Component not found - "+component); if (found && last != null) last.requestFocus(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\form\swing\SwingFieldsUtil.java
1
请完成以下Java代码
public List<EmailAttachment> getEmailAttachments( @NonNull final DocumentPath documentPath, @NonNull final String tagName) { final TableRecordReference recordRef = documentDescriptorFactory.getTableRecordReference(documentPath); final WebuiDocumentPrintRequest printRequest = WebuiDocumentPrintRequest.builder() .flavor(DocumentReportFlavor.EMAIL) .documentPath(documentPath) .userId(userSession.getLoggedUserId()) .roleId(userSession.getLoggedRoleId()) .build(); final Stream<EmailAttachment> emailAttachments = documentPrintService.createDocumentPrint(printRequest) .map(MailRestService::toEmailAttachment)
.map(Stream::of).orElseGet(Stream::empty); return Stream.concat(emailAttachments, attachmentEntryService.streamEmailAttachments(recordRef, tagName)) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } private static EmailAttachment toEmailAttachment(final ReportResultData contextDocumentPrint) { return EmailAttachment.builder() .filename(contextDocumentPrint.getReportFilename()) .attachmentDataSupplier(contextDocumentPrint::getReportDataByteArray) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\mail\MailRestService.java
1
请完成以下Java代码
public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } @Override protected void applyFilters(HistoricIdentityLinkLogQuery query) { if (dateBefore != null) { query.dateBefore(dateBefore); } if (dateAfter != null) { query.dateAfter(dateAfter); } if (type != null) { query.type(type); } if (userId != null) { query.userId(userId); } if (groupId != null) { query.groupId(groupId); } if (taskId != null) { query.taskId(taskId); } if (processDefinitionId != null) { query.processDefinitionId(processDefinitionId); } if (processDefinitionKey != null) { query.processDefinitionKey(processDefinitionKey); } if (operationType != null) { query.operationType(operationType); } if (assignerId != null) { query.assignerId(assignerId); }
if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } } @Override protected void applySortBy(HistoricIdentityLinkLogQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_TIME)) { query.orderByTime(); } else if (sortBy.equals(SORT_BY_TYPE)) { query.orderByType(); } else if (sortBy.equals(SORT_BY_USER_ID)) { query.orderByUserId(); } else if (sortBy.equals(SORT_BY_GROUP_ID)) { query.orderByGroupId(); } else if (sortBy.equals(SORT_BY_TASK_ID)) { query.orderByTaskId(); } else if (sortBy.equals(SORT_BY_OPERATION_TYPE)) { query.orderByOperationType(); } else if (sortBy.equals(SORT_BY_ASSIGNER_ID)) { query.orderByAssignerId(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) { query.orderByProcessDefinitionId(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) { query.orderByProcessDefinitionKey(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIdentityLinkLogQueryDto.java
1
请完成以下Java代码
private static void addContentToDocument(PdfDocument pdfDocument) throws MalformedURLException { // 4.1. add form PdfFormField personal = PdfFormField.createEmptyField(pdfDocument); personal.setFieldName("information"); PdfTextFormField name = PdfFormField.createText(pdfDocument, new Rectangle(35, 400, 100, 30), "name", ""); personal.addKid(name); PdfAcroForm.getAcroForm(pdfDocument, true) .addField(personal, pdfDocument.getFirstPage()); // 4.2. add new page pdfDocument.addNewPage(1); // 4.3. add annotation PdfAnnotation ann = new PdfTextAnnotation(new Rectangle(40, 435, 0, 0)).setTitle(new PdfString("name")) .setContents("Your name"); pdfDocument.getPage(2) .addAnnotation(ann); // create document form pdf document Document document = new Document(pdfDocument); // 4.4. add an image ImageData imageData = ImageDataFactory.create("src/main/resources/baeldung.png"); Image image = new Image(imageData).scaleAbsolute(550, 100) .setFixedPosition(1, 10, 50); document.add(image); // 4.5. add a paragraph
Text title = new Text("This is a demo").setFontSize(16); Text author = new Text("Baeldung tutorials."); Paragraph p = new Paragraph().setFontSize(8) .add(title) .add(" from ") .add(author); document.add(p); // 4.6. add a table Table table = new Table(UnitValue.createPercentArray(2)); table.addHeaderCell("#"); table.addHeaderCell("company"); table.addCell("name"); table.addCell("baeldung"); document.add(table); // close the document // this automatically closes the pdfDocument, which then closes automatically the pdfReader and pdfWriter document.close(); } }
repos\tutorials-master\text-processing-libraries-modules\pdf-2\src\main\java\com\baeldung\pdfedition\PdfEditor.java
1
请完成以下Java代码
public LoginContext getLoginContext() { return this.loginContext; } @Override public Builder<?> toBuilder() { return new Builder<>(this); } /** * A builder of {@link JaasAuthenticationToken} instances * * @since 7.0 */ public static class Builder<B extends Builder<B>> extends UsernamePasswordAuthenticationToken.Builder<B> { private LoginContext loginContext; protected Builder(JaasAuthenticationToken token) { super(token); this.loginContext = token.getLoginContext(); } /**
* Use this {@link LoginContext} * @param loginContext the {@link LoginContext} to use * @return the {@link Builder} for further configurations */ public B loginContext(LoginContext loginContext) { this.loginContext = loginContext; return (B) this; } @Override public JaasAuthenticationToken build() { return new JaasAuthenticationToken(this); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\jaas\JaasAuthenticationToken.java
1
请完成以下Java代码
public static Object getFieldValue(Object bean, String fieldName) throws IllegalAccessException { Assert.notNull(bean, "Bean cannot be null"); Assert.hasText(fieldName, "Field name required"); String[] nestedFields = StringUtils.tokenizeToStringArray(fieldName, "."); Class<?> componentClass = bean.getClass(); Object value = bean; for (String nestedField : nestedFields) { Field field = getField(componentClass, nestedField); field.setAccessible(true); value = field.get(value); if (value != null) { componentClass = value.getClass(); } } return value; } public static @Nullable Object getProtectedFieldValue(String protectedField, Object object) { Field field = FieldUtils.getField(object.getClass(), protectedField); try { field.setAccessible(true); return field.get(object); }
catch (Exception ex) { ReflectionUtils.handleReflectionException(ex); return null; // unreachable - previous line throws exception } } public static void setProtectedFieldValue(String protectedField, Object object, Object newValue) { Field field = FieldUtils.getField(object.getClass(), protectedField); try { field.setAccessible(true); field.set(object, newValue); } catch (Exception ex) { ReflectionUtils.handleReflectionException(ex); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\util\FieldUtils.java
1
请在Spring Boot框架中完成以下Java代码
public class Organization { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(nullable = false, unique = true) private String name; public Organization() { } public Organization(String name) { this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Organization [id=").append(id).append(", name=").append(name).append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31;
int result = 1; result = (prime * result) + ((id == null) ? 0 : id.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; } final Organization other = (Organization) obj; if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\persistence\model\Organization.java
2
请完成以下Java代码
private Map<ProductEntity, Integer> buildProductEntityIntegerMap(List<ProductEntity> productEntityList, Map<String, Integer> prodIdCountMap) { Map<ProductEntity, Integer> map = Maps.newHashMap(); if (CollectionUtils.isEmpty(productEntityList)) { return map; } for (ProductEntity productEntity : productEntityList) { Integer count = prodIdCountMap.get(productEntity.getId()); map.put(productEntity, count); } return map; } /** * 获取Context中的ProdIdCountMap * @param orderProcessContext 上下文 * @return ProdIdCountMap */ private Map<String, Integer> getProdIdCountMap(OrderProcessContext orderProcessContext) { OrderInsertReq orderInsertReq = (OrderInsertReq) orderProcessContext.getOrderProcessReq().getReqData(); return orderInsertReq.getProdIdCountMap(); } /** * 查询产品详情 * @param prodIdCountMap 产品ID-库存 映射 * @return 产品列表 */ private List<ProductEntity> queryProduct(Map<String, Integer> prodIdCountMap) { // 查询结果集 List<ProductEntity> productEntityList = Lists.newArrayList(); // 构建查询请求 List<ProdQueryReq> prodQueryReqList = buildProdQueryReq(prodIdCountMap); // 批量查询 for (ProdQueryReq prodQueryReq : prodQueryReqList) { List<ProductEntity> productEntitys = productService.findProducts(prodQueryReq).getData(); // 产品ID不存在 if (productEntitys.size() <= 0) { logger.error("查询产品详情时,上线中 & 产品ID=" + prodQueryReq.getId() + "的产品不存在!"); throw new CommonBizException(ExpCodeEnum.PRODUCT_NO_EXISTENT);
} productEntityList.add(productEntitys.get(0)); } return productEntityList; } /** * 构建产品查询请求 * @param prodIdCountMap 产品ID-库存 映射 * @return 产品查询请求列表 */ private List<ProdQueryReq> buildProdQueryReq(Map<String, Integer> prodIdCountMap) { List<ProdQueryReq> prodQueryReqList = Lists.newArrayList(); for (String prodId : prodIdCountMap.keySet()) { ProdQueryReq prodQueryReq = new ProdQueryReq(); prodQueryReq.setId(prodId); // 必须是"上线中"的产品 prodQueryReq.setProdStateCode(ProdStateEnum.OPEN.getCode()); prodQueryReqList.add(prodQueryReq); } return prodQueryReqList; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\datatransfer\ProdCountMapTransferComponent.java
1
请完成以下Java代码
public int getC_OLCand_ID() { return get_ValueAsInt(COLUMNNAME_C_OLCand_ID); } @Override public void setDurationAmount (final @Nullable BigDecimal DurationAmount) { set_Value (COLUMNNAME_DurationAmount, DurationAmount); } @Override public BigDecimal getDurationAmount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DurationAmount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setExternalId (final String ExternalId) { set_Value (COLUMNNAME_ExternalId, ExternalId); } @Override public String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } @Override public void setExternallyUpdatedAt (final @Nullable java.sql.Timestamp ExternallyUpdatedAt) { set_Value (COLUMNNAME_ExternallyUpdatedAt, ExternallyUpdatedAt); } @Override public java.sql.Timestamp getExternallyUpdatedAt() { return get_ValueAsTimestamp(COLUMNNAME_ExternallyUpdatedAt); } @Override public void setIsPrivateSale (final boolean IsPrivateSale) { set_Value (COLUMNNAME_IsPrivateSale, IsPrivateSale); } @Override public boolean isPrivateSale() { return get_ValueAsBoolean(COLUMNNAME_IsPrivateSale); } @Override public void setIsRentalEquipment (final boolean IsRentalEquipment) { set_Value (COLUMNNAME_IsRentalEquipment, IsRentalEquipment); } @Override public boolean isRentalEquipment() { return get_ValueAsBoolean(COLUMNNAME_IsRentalEquipment); } @Override public void setSalesLineId (final @Nullable String SalesLineId) { set_Value (COLUMNNAME_SalesLineId, SalesLineId); }
@Override public String getSalesLineId() { return get_ValueAsString(COLUMNNAME_SalesLineId); } @Override public void setTimePeriod (final @Nullable BigDecimal TimePeriod) { set_Value (COLUMNNAME_TimePeriod, TimePeriod); } @Override public BigDecimal getTimePeriod() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TimePeriod); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUnit (final @Nullable String Unit) { set_Value (COLUMNNAME_Unit, Unit); } @Override public String getUnit() { return get_ValueAsString(COLUMNNAME_Unit); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_Alberta_OrderedArticleLine.java
1
请完成以下Java代码
public void removeEventListener(ActivitiEventListener listenerToRemove) { eventSupport.removeEventListener(listenerToRemove); } @Override public void dispatchEvent(ActivitiEvent event) { if (enabled) { eventSupport.dispatchEvent(event); } if (event.getType() == ActivitiEventType.ENTITY_DELETED && event instanceof ActivitiEntityEvent) { ActivitiEntityEvent entityEvent = (ActivitiEntityEvent) event; if (entityEvent.getEntity() instanceof ProcessDefinition) { // process definition deleted event doesn't need to be dispatched to event listeners return; } } // Try getting hold of the Process definition, based on the process definition key, if a context is active CommandContext commandContext = Context.getCommandContext(); if (commandContext != null) { BpmnModel bpmnModel = extractBpmnModelFromEvent(event); if (bpmnModel != null) { ((ActivitiEventSupport) bpmnModel.getEventSupport()).dispatchEvent(event); } } } /** * In case no process-context is active, this method attempts to extract a process-definition based on the event. In case it's an event related to an entity, this can be deducted by inspecting the * entity, without additional queries to the database. * * If not an entity-related event, the process-definition will be retrieved based on the processDefinitionId (if filled in). This requires an additional query to the database in case not already * cached. However, queries will only occur when the definition is not yet in the cache, which is very unlikely to happen, unless evicted. * * @param event
* @return */ protected BpmnModel extractBpmnModelFromEvent(ActivitiEvent event) { BpmnModel result = null; if (result == null && event.getProcessDefinitionId() != null) { ProcessDefinition processDefinition = ProcessDefinitionUtil.getProcessDefinition( event.getProcessDefinitionId(), true ); if (processDefinition != null) { result = Context.getProcessEngineConfiguration() .getDeploymentManager() .resolveProcessDefinition(processDefinition) .getBpmnModel(); } } return result; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiEventDispatcherImpl.java
1
请完成以下Java代码
public class ElasticsearchException extends RuntimeException { @Getter private int errcode; @Getter private String errmsg; public ElasticsearchException(ResultCode resultCode) { this(resultCode.getCode(), resultCode.getMsg()); } public ElasticsearchException(String message) { super(message); } public ElasticsearchException(Integer errcode, String errmsg) {
super(errmsg); this.errcode = errcode; this.errmsg = errmsg; } public ElasticsearchException(String message, Throwable cause) { super(message, cause); } public ElasticsearchException(Throwable cause) { super(cause); } public ElasticsearchException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
repos\spring-boot-demo-master\demo-elasticsearch-rest-high-level-client\src\main\java\com\xkcoding\elasticsearch\exception\ElasticsearchException.java
1
请完成以下Java代码
abstract class JsonNodeUtils { static final TypeReference<Set<String>> STRING_SET = new TypeReference<>() { }; static final TypeReference<Map<String, Object>> STRING_OBJECT_MAP = new TypeReference<>() { }; static String findStringValue(JsonNode jsonNode, String fieldName) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isString()) ? value.stringValue() : null; } static <T> T findValue(JsonNode jsonNode, String fieldName, TypeReference<T> valueTypeReference, DeserializationContext context) {
if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isContainer()) ? context.readTreeAsValue(value, context.getTypeFactory().constructType(valueTypeReference)) : null; } static JsonNode findObjectNode(JsonNode jsonNode, String fieldName) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isObject()) ? value : null; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\jackson\JsonNodeUtils.java
1
请完成以下Java代码
public int hashCode() { return new HashcodeBuilder() .append(columnName) .append(direction) .toHashcode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } final QueryOrderByItem other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(this.columnName, other.columnName) .append(this.direction, other.direction) .isEqual(); } /** * @return the columnName
*/ public String getColumnName() { return columnName; } public Direction getDirection() { return direction; } public Nulls getNulls() { return nulls; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryOrderByItem.java
1
请完成以下Java代码
public static Mono<Author> findAuthorByName(String authorName) { Optional<Author> author = authors.stream() .filter(it -> it.getName() .equals(authorName)) .findFirst(); return Mono.justOrEmpty(author); } public static Mono<Book> findLatestBookByAuthorId(Long authorId) { Optional<Author> author = authors.stream() .filter(it -> it.getAuthorId() .equals(authorId)) .findFirst(); Optional<Book> book = author.flatMap(it -> it.getBooks() .stream() .findFirst()); return Mono.justOrEmpty(book); } public static Author findById(Long authorId) { return authors.stream() .filter(author -> author.getAuthorId().equals(authorId)) .findFirst() .orElse(null); }
public static class AuthorNotFoundException extends RuntimeException { public AuthorNotFoundException(String message) { super(message); } public AuthorNotFoundException() { super(); } } static <T> List<T> listOf(T... items) { List<T> list = new ArrayList<>(); for (T item : items) { list.add(item); } return list; } }
repos\tutorials-master\core-java-modules\core-java-functional\src\main\java\com\baeldung\monads\AuthorsRepository.java
1
请在Spring Boot框架中完成以下Java代码
public List<ItemListType> getItemList() { if (itemList == null) { itemList = new ArrayList<ItemListType>(); } return this.itemList; } /** * A free-text footer description with suceeds the details section. * * @return * possible object is * {@link String } * */ public String getFooterDescription() {
return footerDescription; } /** * Sets the value of the footerDescription property. * * @param value * allowed object is * {@link String } * */ public void setFooterDescription(String value) { this.footerDescription = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DetailsType.java
2