instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private int getDisplayType(final Method method) { if (method == null) { return -1; } final ColumnInfo info = method.getAnnotation(ColumnInfo.class); if (info == null) { return -1; } final int displayType = info.displayType(); return displayType > 0 ? displayType : -1; } private boolean isSelectionColumn(final PropertyDescriptor pd) { Boolean selectionColumn = getSelectionColumn(pd.getReadMethod()); if (selectionColumn == null) {
selectionColumn = getSelectionColumn(pd.getWriteMethod()); } return selectionColumn != null ? selectionColumn : false; } private Boolean getSelectionColumn(final Method method) { if (method == null) { return null; } final ColumnInfo info = method.getAnnotation(ColumnInfo.class); if (info == null) { return null; } return info.selectionColumn(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\table\TableModelMetaInfo.java
1
请完成以下Java代码
public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setM_Maturing_Configuration_ID (final int M_Maturing_Configuration_ID) { if (M_Maturing_Configuration_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_ID, M_Maturing_Configuration_ID); }
@Override public int getM_Maturing_Configuration_ID() { return get_ValueAsInt(COLUMNNAME_M_Maturing_Configuration_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Maturing_Configuration.java
1
请完成以下Java代码
public final class AstEval extends AstNode { private final AstNode child; private final boolean deferred; public AstEval(AstNode child, boolean deferred) { this.child = child; this.deferred = deferred; } public boolean isDeferred() { return deferred; } public boolean isLeftValue() { return getChild(0).isLeftValue(); } public boolean isMethodInvocation() { return getChild(0).isMethodInvocation(); } public ValueReference getValueReference(Bindings bindings, ELContext context) { return child.getValueReference(bindings, context); } @Override public Object eval(Bindings bindings, ELContext context) { return child.eval(bindings, context); } @Override public String toString() { return (deferred ? "#" : "$") + "{...}"; } @Override public void appendStructure(StringBuilder b, Bindings bindings) { b.append(deferred ? "#{" : "${"); child.appendStructure(b, bindings); b.append("}"); } public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) { return child.getMethodInfo(bindings, context, returnType, paramTypes); } public Object invoke( Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] paramValues ) { return child.invoke(bindings, context, returnType, paramTypes, paramValues); }
public Class<?> getType(Bindings bindings, ELContext context) { return child.getType(bindings, context); } public boolean isLiteralText() { return child.isLiteralText(); } public boolean isReadOnly(Bindings bindings, ELContext context) { return child.isReadOnly(bindings, context); } public void setValue(Bindings bindings, ELContext context, Object value) { child.setValue(bindings, context, value); } public int getCardinality() { return 1; } public AstNode getChild(int i) { return i == 0 ? child : null; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstEval.java
1
请完成以下Java代码
public class CreatedByValueGeneration implements AnnotationValueGeneration<CreatedBy> { private final ByValueGenerator generator = new ByValueGenerator(new UserService()); @Override public void initialize(CreatedBy mby, Class<?> clazz) { } @Override public GenerationTiming getGenerationTiming() { return GenerationTiming.INSERT; }
@Override public ValueGenerator<?> getValueGenerator() { return generator; } @Override public boolean referenceColumnInSql() { return false; } @Override public String getDatabaseGeneratedReferencedColumnValue() { return null; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootTimestampGeneration\src\main\java\com\bookstore\by\CreatedByValueGeneration.java
1
请完成以下Java代码
private OrderStateTimeEntity buildOrderStateTimeEntity(String orderId, OrderStateEnum targetOrderState) { OrderStateTimeEntity orderStateTimeEntity = new OrderStateTimeEntity(); orderStateTimeEntity.setOrderId(orderId); orderStateTimeEntity.setOrderStateEnum(targetOrderState); orderStateTimeEntity.setTime(new Timestamp(System.currentTimeMillis())); return orderStateTimeEntity; } private void checkParam(OrderStateEnum targetOrderState) { if (targetOrderState == null) { throw new CommonSysException(ExpCodeEnum.TARGETSTATE_NULL); } } @Override public void handle(OrderProcessContext orderProcessContext) { // 设置目标状态 setTargetOrderState(); // 前置处理 this.preHandle(orderProcessContext);
if (this.isStop) { return; } // 改变状态 this.changeState(orderProcessContext, this.targetOrderState); if (this.isStop) { return; } // 后置处理 this.afterHandle(orderProcessContext); } public abstract void setTargetOrderState(); }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\changestate\BaseChangeStateComponent.java
1
请完成以下Java代码
public void push(E item) { deque.addFirst(item); } @Override public E pop() { return deque.removeFirst(); } @Override public E peek() { return deque.peekFirst(); } // implementing methods from the Collection interface @Override public int size() { return deque.size(); } @Override public boolean isEmpty() { return deque.isEmpty(); } @Override public boolean contains(Object o) { return deque.contains(o); } @Override public Iterator<E> iterator() { return deque.iterator(); } @Override public Object[] toArray() { return deque.toArray(); } @Override public <T> T[] toArray(T[] a) { return deque.toArray(a); } @Override public boolean add(E e) { return deque.add(e); } @Override
public boolean remove(Object o) { return deque.remove(o); } @Override public boolean containsAll(Collection<?> c) { return deque.containsAll(c); } @Override public boolean addAll(Collection<? extends E> c) { return deque.addAll(c); } @Override public boolean removeAll(Collection<?> c) { return deque.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return deque.retainAll(c); } @Override public void clear() { deque.clear(); } }
repos\tutorials-master\core-java-modules\core-java-collections-4\src\main\java\com\baeldung\collections\dequestack\ArrayLifoStack.java
1
请完成以下Java代码
public void setType(String type) { this.type = type; } public String getTitle() { return title; } @XmlElement public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } @XmlElement public void setDescription(String description) { this.description = description; }
public String getDate() { return date; } @XmlElement public void setDate(String date) { this.date = date; } public String getAuthor() { return author; } @XmlElement public void setAuthor(String author) { this.author = author; } }
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\binding\Tutorial.java
1
请完成以下Java代码
static Decoder<?> findJsonDecoder(CodecConfigurer configurer) { return findJsonDecoder(configurer.getReaders().stream() .filter((reader) -> reader instanceof DecoderHttpMessageReader) .map((reader) -> ((DecoderHttpMessageReader<?>) reader).getDecoder())); } static Encoder<?> findJsonEncoder(List<Encoder<?>> encoders) { return findJsonEncoder(encoders.stream()); } static Decoder<?> findJsonDecoder(List<Decoder<?>> decoders) { return findJsonDecoder(decoders.stream()); } private static Encoder<?> findJsonEncoder(Stream<Encoder<?>> stream) { return stream .filter((encoder) -> encoder.canEncode(MESSAGE_TYPE, MediaType.APPLICATION_JSON)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("No JSON Encoder")); } private static Decoder<?> findJsonDecoder(Stream<Decoder<?>> decoderStream) { return decoderStream .filter((decoder) -> decoder.canDecode(MESSAGE_TYPE, MediaType.APPLICATION_JSON)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("No JSON Decoder")); }
CodecConfigurer getCodecConfigurer() { return this.codecConfigurer; } @SuppressWarnings("unchecked") <T> WebSocketMessage encode(WebSocketSession session, GraphQlWebSocketMessage message) { DataBuffer buffer = ((Encoder<T>) this.encoder).encodeValue( (T) message, session.bufferFactory(), MESSAGE_TYPE, MimeTypeUtils.APPLICATION_JSON, null); return new WebSocketMessage(WebSocketMessage.Type.TEXT, buffer); } @SuppressWarnings("ConstantConditions") @Nullable GraphQlWebSocketMessage decode(WebSocketMessage webSocketMessage) { DataBuffer buffer = DataBufferUtils.retain(webSocketMessage.getPayload()); return (GraphQlWebSocketMessage) this.decoder.decode(buffer, MESSAGE_TYPE, null, null); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\CodecDelegate.java
1
请完成以下Java代码
public void setMSV3_Pzn (java.lang.String MSV3_Pzn) { set_Value (COLUMNNAME_MSV3_Pzn, MSV3_Pzn); } /** Get MSV3_Pzn. @return MSV3_Pzn */ @Override public java.lang.String getMSV3_Pzn () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Pzn); } /** Set MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel. @param MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel */ @Override public void setMSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID (int MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID) { if (MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID, Integer.valueOf(MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID)); } /** Get MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel. @return MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel */ @Override public int getMSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne getMSV3_VerfuegbarkeitsanfrageEinzelne() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne.class); } @Override
public void setMSV3_VerfuegbarkeitsanfrageEinzelne(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne MSV3_VerfuegbarkeitsanfrageEinzelne) { set_ValueFromPO(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne.class, MSV3_VerfuegbarkeitsanfrageEinzelne); } /** Set MSV3_VerfuegbarkeitsanfrageEinzelne. @param MSV3_VerfuegbarkeitsanfrageEinzelne_ID MSV3_VerfuegbarkeitsanfrageEinzelne */ @Override public void setMSV3_VerfuegbarkeitsanfrageEinzelne_ID (int MSV3_VerfuegbarkeitsanfrageEinzelne_ID) { if (MSV3_VerfuegbarkeitsanfrageEinzelne_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, Integer.valueOf(MSV3_VerfuegbarkeitsanfrageEinzelne_ID)); } /** Get MSV3_VerfuegbarkeitsanfrageEinzelne. @return MSV3_VerfuegbarkeitsanfrageEinzelne */ @Override public int getMSV3_VerfuegbarkeitsanfrageEinzelne_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel.java
1
请完成以下Java代码
public char firstChar() { return name.charAt(0); } /** * 安全地将字符串类型的词性转为Enum类型,如果未定义该词性,则返回null * * @param name 字符串词性 * @return Enum词性 */ public static final Nature fromString(String name) { Integer id = idMap.get(name); if (id == null) return null; return values[id]; } /** * 创建自定义词性,如果已有该对应词性,则直接返回已有的词性 * * @param name 字符串词性 * @return Enum词性
*/ public static final Nature create(String name) { Nature nature = fromString(name); if (nature == null) return new Nature(name); return nature; } @Override public String toString() { return name; } public int ordinal() { return ordinal; } public static Nature[] values() { return values; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\tag\Nature.java
1
请完成以下Java代码
public CaseIllegalStateTransitionException wrongChildStateException(String transition, String id, String childId, String stateList) { return new CaseIllegalStateTransitionException(exceptionMessage( "014", caseStateTransitionMessage + "Reason: There is a child case execution with id '{}' which is in one of the following states: {}", transition, id, childId, stateList )); } public PvmException transitCaseException(String transition, String id, CaseExecutionState currentState) { return new PvmException(exceptionMessage( "015", caseStateTransitionMessage + "Reason: Expected case execution state to be {terminatingOnTermination|terminatingOnExit} but it was '{}'.", transition, id, currentState )); } public PvmException suspendCaseException(String id, CaseExecutionState currentState) { return transitCaseException("suspend", id, currentState); } public PvmException terminateCaseException(String id, CaseExecutionState currentState) { return transitCaseException("terminate", id, currentState); } public ProcessEngineException missingDelegateParentClassException(String className, String parentClass) { return new ProcessEngineException( exceptionMessage("016", "Class '{}' doesn't implement '{}'.", className, parentClass)); }
public UnsupportedOperationException unsupportedTransientOperationException(String className) { return new UnsupportedOperationException( exceptionMessage("017", "Class '{}' is not supported in transient CaseExecutionImpl", className)); } public ProcessEngineException invokeVariableListenerException(Throwable cause) { return new ProcessEngineException(exceptionMessage( "018", "Variable listener invocation failed. Reason: {}", cause.getMessage()), cause ); } public ProcessEngineException decisionDefinitionEvaluationFailed(CmmnActivityExecution execution, Exception cause) { return new ProcessEngineException(exceptionMessage( "019", "Could not evaluate decision in case execution '"+execution.getId()+"'. Reason: {}", cause.getMessage()), cause ); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\CmmnBehaviorLogger.java
1
请在Spring Boot框架中完成以下Java代码
public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getPlanItemInstanceId() { return planItemInstanceId; } public void setPlanItemInstanceId(String planItemInstanceId) { this.planItemInstanceId = planItemInstanceId; } public String getCaseInstanceId() { return caseInstanceId; } public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } public String getVariableName() { return variableName; } public void setVariableName(String variableName) {
this.variableName = variableName; } public String getVariableNameLike() { return variableNameLike; } public void setVariableNameLike(String variableNameLike) { this.variableNameLike = variableNameLike; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = QueryVariable.class) public List<QueryVariable> getVariables() { return variables; } public void setVariables(List<QueryVariable> variables) { this.variables = variables; } public void setExcludeLocalVariables(Boolean excludeLocalVariables) { this.excludeLocalVariables = excludeLocalVariables; } public Boolean getExcludeLocalVariables() { return excludeLocalVariables; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\variable\HistoricVariableInstanceQueryRequest.java
2
请在Spring Boot框架中完成以下Java代码
public MetricCollectingServerInterceptor metricCollectingServerInterceptor(final MeterRegistry registry, final Collection<BindableService> services) { final MetricCollectingServerInterceptor metricCollector = new MetricCollectingServerInterceptor(registry); log.debug("Pre-Registering service metrics"); for (final BindableService service : services) { log.debug("- {}", service); metricCollector.preregisterService(service); } return metricCollector; } @ConditionalOnProperty(prefix = "grpc", name = "metricsA66Enabled", matchIfMissing = true) @Bean public GrpcServerConfigurer streamTracerFactoryConfigurer(final MeterRegistry registry) { MetricsServerStreamTracers metricsServerStreamTracers = new MetricsServerStreamTracers( Stopwatch::createUnstarted); return builder -> builder .addStreamTracerFactory(metricsServerStreamTracers.getMetricsServerTracerFactory(registry)); } @Bean @Lazy InfoContributor grpcInfoContributor(final GrpcServerProperties properties, final Collection<BindableService> grpcServices) { final Map<String, Object> details = new LinkedHashMap<>(); details.put("port", properties.getPort()); if (properties.isReflectionServiceEnabled()) { // Only expose services via web-info if we do the same via grpc. final Map<String, List<String>> services = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
details.put("services", services); for (final BindableService grpcService : grpcServices) { final ServiceDescriptor serviceDescriptor = grpcService.bindService().getServiceDescriptor(); final List<String> methods = collectMethodNamesForService(serviceDescriptor); services.put(serviceDescriptor.getName(), methods); } } return new SimpleInfoContributor("grpc.server", details); } /** * Gets all method names from the given service descriptor. * * @param serviceDescriptor The service descriptor to get the names from. * @return The newly created and sorted list of the method names. */ protected List<String> collectMethodNamesForService(final ServiceDescriptor serviceDescriptor) { final List<String> methods = new ArrayList<>(); for (final MethodDescriptor<?, ?> grpcMethod : serviceDescriptor.getMethods()) { methods.add(extractMethodName(grpcMethod)); } methods.sort(String.CASE_INSENSITIVE_ORDER); return methods; } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\autoconfigure\GrpcServerMetricAutoConfiguration.java
2
请完成以下Java代码
public void run(final String localTrxName_NOTUSED) { allocationBL.invoiceDiscountAndWriteOff( InvoiceDiscountAndWriteOffRequest.builder() .invoice(invoice) .useInvoiceDate(true) .discountAmt(discountAmt) .description(getProcessInfo().getTitle()) .build()); // Make sure it was fully allocated InterfaceWrapperHelper.refresh(invoice); Check.errorIf(!invoice.isPaid(), "C_Invoice {} still has IsPaid='N' after having allocating discountAmt={}", invoice, discountAmt); // Log the success and increase the counter addLog("@Processed@: @C_Invoice_ID@ " + invoice.getDocumentNo() + "; @DiscountAmt@=" + discountAmt); counterProcessed.incrementAndGet(); } @Override public boolean doCatch(final Throwable e) { final String errmsg = "@Error@: @C_Invoice_ID@ " + invoice.getDocumentNo() + ": " + e.getLocalizedMessage(); addLog(errmsg); log.error(errmsg, e); return true; // do rollback } }); } private Iterator<I_C_Invoice> retrieveInvoices() { final Stopwatch stopwatch = Stopwatch.createStarted(); // // Create the selection which we might need to update // note that selecting all unpaid and then skipping all whose open amount is > p_OpenAmt is acceptable performance-wise, // at least when we worked with 14.000 invoices and the client was running remote, over an internet connection final IQueryBuilder<I_C_Invoice> queryBuilder = queryBL .createQueryBuilder(I_C_Invoice.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Invoice.COLUMNNAME_AD_Client_ID, getClientId()) .addEqualsFilter(I_C_Invoice.COLUMNNAME_IsPaid, false); // not already fully allocated if (!getProcessInfo().isInvokedByScheduler()) { // user selection..if any. if none, then process all final IQueryFilter<I_C_Invoice> userSelectionFilter = getProcessInfo().getQueryFilterOrElseTrue(); queryBuilder.filter(userSelectionFilter); } if (p_SOTrx != null) { queryBuilder.addEqualsFilter(PARAM_IsSOTrx, p_SOTrx.toBoolean()); }
if (p_DateInvoicedFrom != null) { queryBuilder.addCompareFilter(PARAM_DateInvoiced, Operator.GREATER_OR_EQUAL, p_DateInvoicedFrom); } if (p_DateInvoicedTo != null) { queryBuilder.addCompareFilter(PARAM_DateInvoiced, Operator.LESS_OR_EQUAL, p_DateInvoicedTo); } final IQuery<I_C_Invoice> query = queryBuilder .orderBy(I_C_Invoice.COLUMNNAME_C_Invoice_ID) .create(); addLog("Using query: " + query); final int count = query.count(); if (count > 0) { final Iterator<I_C_Invoice> iterator = query.iterate(I_C_Invoice.class); addLog("Found " + count + " invoices to evaluate. Took " + stopwatch); return iterator; } else { addLog("No invoices found. Took " + stopwatch); return Collections.emptyIterator(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\process\C_Invoice_MassDiscountOrWriteOff.java
1
请在Spring Boot框架中完成以下Java代码
public Pet returnPet(UUID petUuid) { var pet = petsRepo.findPetByUuid(petUuid) .orElseThrow(() -> new IllegalArgumentException("Unknown pet")); pet.setOwner(null); petsRepo.save(pet); return pet; } public List<PetHistoryEntry> listPetHistory(UUID petUuid) { var pet = petsRepo.findPetByUuid(petUuid) .orElseThrow(() -> new IllegalArgumentException("No pet with UUID '" + petUuid + "' found")); return petsRepo.findRevisions(pet.getId()).stream() .map(r -> {
CustomRevisionEntity rev = r.getMetadata().getDelegate(); return new PetHistoryEntry(r.getRequiredRevisionInstant(), r.getMetadata().getRevisionType(), r.getEntity().getUuid(), r.getEntity().getSpecies().getName(), r.getEntity().getName(), r.getEntity().getOwner() != null ? r.getEntity().getOwner().getName() : null, rev.getRemoteHost(), rev.getRemoteUser()); }) .toList(); } }
repos\tutorials-master\persistence-modules\spring-data-envers\src\main\java\com\baeldung\envers\customrevision\service\AdoptionService.java
2
请完成以下Java代码
public void add(int index, E element) { } @Override public E remove(int index) { return null; } @Override public int indexOf(Object o) { return 0; } @Override public int lastIndexOf(Object o) { return 0; }
@Override public ListIterator<E> listIterator() { return null; } @Override public ListIterator<E> listIterator(int index) { return null; } @Override public List<E> subList(int fromIndex, int toIndex) { return null; } }
repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\customiterators\MyList.java
1
请完成以下Java代码
static public MPrintFormat get (final Properties ctx, final int AD_PrintFormat_ID, final boolean readFromDisk) { final Integer key = AD_PrintFormat_ID; MPrintFormat printFormat = null; if (!readFromDisk) { printFormat = s_formats.get(key); // Validate the context if (printFormat != null && !CacheCtxParamDescriptor.isSameCtx(ctx, printFormat.getCtx())) { printFormat = null; } } if (printFormat == null) { printFormat = new MPrintFormat (ctx, AD_PrintFormat_ID, ITrx.TRXNAME_None); if (printFormat.get_ID() <= 0) printFormat = null; else s_formats.put(key, printFormat); } // // Return a copy if (printFormat != null) { return (MPrintFormat)printFormat.copy(); } return null; } // get /** * Get (default) Printformat for Report View or Table * @param ctx context * @param AD_ReportView_ID id or 0 * @param AD_Table_ID id or 0 * @return first print format found or null */ static public MPrintFormat get (Properties ctx, int AD_ReportView_ID, int AD_Table_ID) { MPrintFormat retValue = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT * FROM AD_PrintFormat WHERE "; if (AD_ReportView_ID > 0) sql += "AD_ReportView_ID=?"; else sql += "AD_Table_ID=?"; sql += " ORDER BY IsDefault DESC"; try { pstmt = DB.prepareStatement (sql, null); pstmt.setInt (1, AD_ReportView_ID > 0 ? AD_ReportView_ID : AD_Table_ID); rs = pstmt.executeQuery (); if (rs.next ()) retValue = new MPrintFormat (ctx, rs, null); } catch (Exception e) { s_log.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null;
} return retValue; } // get /** * Delete Format from Cache * @param AD_PrintFormat_ID id */ static public void deleteFromCache (int AD_PrintFormat_ID) { Integer key = new Integer(AD_PrintFormat_ID); s_formats.put(key, null); } // deleteFromCache //begin vpj-cd e-evolution /** * Get ID of Print Format use Name * @param String formatName * @param AD_Table_ID * @param AD_Client_ID * @return AD_PrintFormat_ID */ public static int getPrintFormat_ID(String formatName, int AD_Table_ID, int AD_Client_ID) { final String sql = "SELECT AD_PrintFormat_ID FROM AD_PrintFormat" + " WHERE Name = ? AND AD_Table_ID = ? AND AD_Client_ID IN (0, ?)" + " ORDER BY AD_Client_ID DESC"; return DB.getSQLValue(null, sql, formatName, AD_Table_ID, AD_Client_ID); } //end vpj-cd e-evolution } // MPrintFormat
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintFormat.java
1
请在Spring Boot框架中完成以下Java代码
public Duration getAuthorizationCodeTimeToLive() { return this.authorizationCodeTimeToLive; } public void setAuthorizationCodeTimeToLive(Duration authorizationCodeTimeToLive) { this.authorizationCodeTimeToLive = authorizationCodeTimeToLive; } public Duration getAccessTokenTimeToLive() { return this.accessTokenTimeToLive; } public void setAccessTokenTimeToLive(Duration accessTokenTimeToLive) { this.accessTokenTimeToLive = accessTokenTimeToLive; } public String getAccessTokenFormat() { return this.accessTokenFormat; } public void setAccessTokenFormat(String accessTokenFormat) { this.accessTokenFormat = accessTokenFormat; } public Duration getDeviceCodeTimeToLive() { return this.deviceCodeTimeToLive; } public void setDeviceCodeTimeToLive(Duration deviceCodeTimeToLive) { this.deviceCodeTimeToLive = deviceCodeTimeToLive; }
public boolean isReuseRefreshTokens() { return this.reuseRefreshTokens; } public void setReuseRefreshTokens(boolean reuseRefreshTokens) { this.reuseRefreshTokens = reuseRefreshTokens; } public Duration getRefreshTokenTimeToLive() { return this.refreshTokenTimeToLive; } public void setRefreshTokenTimeToLive(Duration refreshTokenTimeToLive) { this.refreshTokenTimeToLive = refreshTokenTimeToLive; } public String getIdTokenSignatureAlgorithm() { return this.idTokenSignatureAlgorithm; } public void setIdTokenSignatureAlgorithm(String idTokenSignatureAlgorithm) { this.idTokenSignatureAlgorithm = idTokenSignatureAlgorithm; } } }
repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-authorization-server\src\main\java\org\springframework\boot\security\oauth2\server\authorization\autoconfigure\servlet\OAuth2AuthorizationServerProperties.java
2
请完成以下Java代码
private List<SyncProductSupply> createPlannedSyncProductSupplies(final I_C_RfQResponseLine rfqResponseLine) { final I_C_Flatrate_Term contract = rfqResponseLine.getC_Flatrate_Term(); Check.assumeNotNull(contract, "contract not null"); final List<I_C_RfQResponseLineQty> rfqResponseLineQtys = pmmRfQDAO.retrieveResponseLineQtys(rfqResponseLine); if (rfqResponseLineQtys.isEmpty()) { return ImmutableList.of(); } final I_C_BPartner dropShipPartnerRecord = bpartnerDAO.getById(contract.getBill_BPartner_ID()); final String bpartner_uuid = SyncUUIDs.toUUIDString(dropShipPartnerRecord); final String contractLine_uuid = SyncUUIDs.toUUIDString(contract); final String product_uuid = SyncUUIDs.toUUIDString(contract.getPMM_Product());
final List<SyncProductSupply> plannedSyncProductSupplies = new ArrayList<>(rfqResponseLineQtys.size()); for (final I_C_RfQResponseLineQty rfqResponseLineQty : rfqResponseLineQtys) { final SyncProductSupply syncProductSupply = SyncProductSupply.builder() .bpartner_uuid(bpartner_uuid) .contractLine_uuid(contractLine_uuid) .product_uuid(product_uuid) .day(TimeUtil.asLocalDate(rfqResponseLineQty.getDatePromised())) .qty(rfqResponseLineQty.getQtyPromised()) .build(); plannedSyncProductSupplies.add(syncProductSupply); } return plannedSyncProductSupplies; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\SyncObjectsFactory.java
1
请完成以下Java代码
public static boolean shouldSkipFlowElement( CommandContext commandContext, DelegateExecution execution, String skipExpressionString ) { Expression skipExpression = commandContext .getProcessEngineConfiguration() .getExpressionManager() .createExpression(skipExpressionString); Object value = skipExpression.getValue(execution); if (value instanceof Boolean) { return ((Boolean) value).booleanValue(); } else { throw new ActivitiIllegalArgumentException( "Skip expression does not resolve to a boolean: " + skipExpression.getExpressionText()
); } } public static boolean shouldSkipFlowElement(DelegateExecution execution, Expression skipExpression) { Object value = skipExpression.getValue(execution); if (value instanceof Boolean) { return ((Boolean) value).booleanValue(); } else { throw new ActivitiIllegalArgumentException( "Skip expression does not resolve to a boolean: " + skipExpression.getExpressionText() ); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\SkipExpressionUtil.java
1
请完成以下Java代码
public java.lang.String getReleaseNo () { return (java.lang.String)get_Value(COLUMNNAME_ReleaseNo); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** * StatusCode AD_Reference_ID=53311 * Reference name: AD_Migration Status */ public static final int STATUSCODE_AD_Reference_ID=53311; /** Applied = A */ public static final String STATUSCODE_Applied = "A"; /** Unapplied = U */ public static final String STATUSCODE_Unapplied = "U"; /** Failed = F */ public static final String STATUSCODE_Failed = "F";
/** Partially applied = P */ public static final String STATUSCODE_PartiallyApplied = "P"; /** Set Status Code. @param StatusCode Status Code */ @Override public void setStatusCode (java.lang.String StatusCode) { set_Value (COLUMNNAME_StatusCode, StatusCode); } /** Get Status Code. @return Status Code */ @Override public java.lang.String getStatusCode () { return (java.lang.String)get_Value(COLUMNNAME_StatusCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_Migration.java
1
请在Spring Boot框架中完成以下Java代码
public class DocTypeService { private final IOrgDAO orgsDAO = Services.get(IOrgDAO.class); private final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class); @NonNull public DocTypeId getDocTypeId( @NonNull final DocBaseType docBaseType, @NonNull final OrgId orgId) { return getDocTypeId(docBaseType, DocSubType.NONE, orgId); } @NonNull public DocTypeId getDocTypeId( @NonNull final DocBaseType docBaseType, @NonNull final DocSubType docSubType, @NonNull final OrgId orgId) { final I_AD_Org orgRecord = orgsDAO.getById(orgId); final DocTypeQuery query = DocTypeQuery .builder() .docBaseType(docBaseType) .docSubType(docSubType) .adClientId(orgRecord.getAD_Client_ID()) .adOrgId(orgRecord.getAD_Org_ID()) .build(); return docTypeDAO.getDocTypeId(query); } @Nullable public DocTypeId getOrderDocTypeId(@Nullable final JsonOrderDocType orderDocType, final OrgId orgId) { if (orderDocType == null) { return null; } final DocBaseType docBaseType = DocBaseType.SalesOrder; final DocSubType docSubType;
if (JsonOrderDocType.PrepayOrder.equals(orderDocType)) { docSubType = DocSubType.PrepayOrder; } else { docSubType = DocSubType.StandardOrder; } final I_AD_Org orgRecord = orgsDAO.getById(orgId); final DocTypeQuery query = DocTypeQuery .builder() .docBaseType(docBaseType) .docSubType(docSubType) .adClientId(orgRecord.getAD_Client_ID()) .adOrgId(orgRecord.getAD_Org_ID()) .build(); return docTypeDAO.getDocTypeId(query); } @NonNull public Optional<JsonOrderDocType> getOrderDocType(@Nullable final DocTypeId docTypeId) { if (docTypeId == null) { return Optional.empty(); } final I_C_DocType docType = docTypeDAO.getById(docTypeId); final DocBaseType docBaseType = DocBaseType.ofCode(docType.getDocBaseType()); if (!docBaseType.isSalesOrder()) { throw new AdempiereException("Invalid base doc type!"); } return Optional.ofNullable(JsonOrderDocType.ofCodeOrNull(docType.getDocSubType())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\DocTypeService.java
2
请在Spring Boot框架中完成以下Java代码
public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); if (ArrayUtil.isNotEmpty(cc)) { helper.setCc(cc); } FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(fileName, file); mailSender.send(message); } /** * 发送正文中有静态资源的邮件 * * @param to 收件人地址 * @param subject 邮件主题 * @param content 邮件内容 * @param rscPath 静态资源地址 * @param rscId 静态资源id * @param cc 抄送地址 * @throws MessagingException 邮件发送异常 */ @Override
public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); if (ArrayUtil.isNotEmpty(cc)) { helper.setCc(cc); } FileSystemResource res = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, res); mailSender.send(message); } }
repos\spring-boot-demo-master\demo-email\src\main\java\com\xkcoding\email\service\impl\MailServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String deletePerson(long id) { try { personRepository.delete(new Person(id)); } catch (Exception ex) { return "Error deleting the user:" + ex.toString(); } return "User succesfully deleted!"; } /** * /user/get?email=[email] -> return the user having the passed email. * * @param email The email to search in the database. * @return The user id or a message error if the user is not found. */ @RequestMapping("/user/get") @ResponseBody public String getUser(String email) { String userId = ""; String userType = ""; try { User user = userRepository.findByEmail(email); userId = String.valueOf(user.getId()); // get the user type if (user instanceof Person) userType = "Person"; else if (user instanceof Company) userType = "Company"; } catch (Exception ex) { return "User not found"; } return "The " + userType + " id is: " + userId; } /** * /user/update?id=[id]&email=[email]&name=[name] -> get the user with passed
* id and change its email and name (the firstName if the user is of type * Person). * * @param id The id of the user to update. * @param email The new email value. * @param name The new name for the user. * @return A string describing if the user is succesfully updated or not. */ @RequestMapping("/user/update") @ResponseBody public String update(Long id, String email, String name) { try { User user = userRepository.findOne(id); user.setEmail(email); // switch on the user type if (user instanceof Person) { Person person = (Person)user; person.setFirstName(name); } if (user instanceof Company) { Company company = (Company)user; company.setName(name); } // updates the user accordingly to its type (Person or Company) userRepository.save(user); } catch (Exception ex) { return "Error: " + ex.toString(); } return "User successfully updated."; } } // class UserController
repos\spring-boot-samples-master\spring-boot-springdatajpa-inheritance\src\main\java\netgloo\controllers\UserController.java
2
请完成以下Java代码
public class DocumentationImpl extends BpmnModelElementInstanceImpl implements Documentation { protected static Attribute<String> idAttribute; protected static Attribute<String> textFormatAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Documentation.class, BPMN_ELEMENT_DOCUMENTATION) .namespaceUri(BPMN20_NS) .instanceProvider(new ModelTypeInstanceProvider<Documentation>() { public Documentation newInstance(ModelTypeInstanceContext instanceContext) { return new DocumentationImpl(instanceContext); } }); idAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ID) .idAttribute() .build(); textFormatAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_TEXT_FORMAT) .defaultValue("text/plain") .build(); typeBuilder.build(); } public DocumentationImpl(ModelTypeInstanceContext context) { super(context); } public String getId() { return idAttribute.getValue(this);
} public void setId(String id) { idAttribute.setValue(this, id); } public String getTextFormat() { return textFormatAttribute.getValue(this); } public void setTextFormat(String textFormat) { textFormatAttribute.setValue(this, textFormat); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DocumentationImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Json login(@RequestBody String body) { String oper = "user login"; log.info("{}, body: {}", oper, body); JSONObject json = JSON.parseObject(body); String uname = json.getString("uname"); String pwd = json.getString("pwd"); if (StringUtils.isEmpty(uname)) { return Json.fail(oper, "用户名不能为空"); } if (StringUtils.isEmpty(pwd)) { return Json.fail(oper, "密码不能为空"); } Subject currentUser = SecurityUtils.getSubject(); try { //登录 currentUser.login(new UsernamePasswordToken(uname, pwd)); //从session取出用户信息 User user = (User) currentUser.getPrincipal(); if (user == null) throw new AuthenticationException(); //返回登录用户的信息给前台,含用户的所有角色和权限 return Json.succ(oper).data("uid", user.getUid()).data("nick", user.getNick()) .data("roles", user.getRoles()).data("perms", user.getPerms()); } catch (UnknownAccountException uae) { log.warn("用户帐号不正确"); return Json.fail(oper, "用户帐号或密码不正确"); } catch (IncorrectCredentialsException ice) {
log.warn("用户密码不正确"); return Json.fail(oper, "用户帐号或密码不正确"); } catch (LockedAccountException lae) { log.warn("用户帐号被锁定"); return Json.fail(oper, "用户帐号被锁定不可用"); } catch (AuthenticationException ae) { log.warn("登录出错"); return Json.fail(oper, "登录失败:" + ae.getMessage()); } } @RequestMapping("/success") public String methodName() { return "登陆成功"; } }
repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\controller\UserController.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getSellrank() { return sellrank; } public void setSellrank(int sellrank) { this.sellrank = sellrank; } public int getRoyalties() { return royalties; }
public void setRoyalties(int royalties) { this.royalties = royalties; } public int getRating() { return rating; } public void setRating(int rating) { this.rating = rating; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + ", sellrank=" + sellrank + ", royalties=" + royalties + ", rating=" + rating + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDatabaseViewUpdateInsertDelete\src\main\java\com\bookstore\entity\Author.java
1
请完成以下Java代码
public String getStartUserId() { return startUserId; } public void setStartUserId(String startUserId) { this.startUserId = startUserId; } @Override public String getStartActivityId() { return startActivityId; } public void setStartActivityId(String startUserId) { this.startActivityId = startUserId; } @Override public String getSuperProcessInstanceId() { return superProcessInstanceId; } public void setSuperProcessInstanceId(String superProcessInstanceId) { this.superProcessInstanceId = superProcessInstanceId; } @Override public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getName() { if (localizedName != null && localizedName.length() > 0) { return localizedName; } else { return name; } } public void setName(String name) { this.name = name; } public String getLocalizedName() { return localizedName; } @Override public void setLocalizedName(String localizedName) { this.localizedName = localizedName; } @Override public String getDescription() { if (localizedDescription != null && localizedDescription.length() > 0) { return localizedDescription; } else { return description; }
} public void setDescription(String description) { this.description = description; } public String getLocalizedDescription() { return localizedDescription; } @Override public void setLocalizedDescription(String localizedDescription) { this.localizedDescription = localizedDescription; } @Override public Map<String, Object> getProcessVariables() { Map<String, Object> variables = new HashMap<>(); if (queryVariables != null) { for (HistoricVariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() == null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } public List<HistoricVariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new HistoricVariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "HistoricProcessInstanceEntity[superProcessInstanceId=" + superProcessInstanceId + "]"; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricProcessInstanceEntity.java
1
请完成以下Java代码
public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; this.resourceCode = resource.hashCode(); } public Long getPassQps() { return passQps; } public void setPassQps(Long passQps) { this.passQps = passQps; } public Long getBlockQps() { return blockQps; } public void setBlockQps(Long blockQps) { this.blockQps = blockQps; } public Long getExceptionQps() { return exceptionQps; } public void setExceptionQps(Long exceptionQps) { this.exceptionQps = exceptionQps; } public double getRt() { return rt; } public void setRt(double rt) { this.rt = rt; } public int getCount() { return count;
} public void setCount(int count) { this.count = count; } public int getResourceCode() { return resourceCode; } public Long getSuccessQps() { return successQps; } public void setSuccessQps(Long successQps) { this.successQps = successQps; } @Override public String toString() { return "MetricEntity{" + "id=" + id + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", app='" + app + '\'' + ", timestamp=" + timestamp + ", resource='" + resource + '\'' + ", passQps=" + passQps + ", blockQps=" + blockQps + ", successQps=" + successQps + ", exceptionQps=" + exceptionQps + ", rt=" + rt + ", count=" + count + ", resourceCode=" + resourceCode + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\MetricEntity.java
1
请在Spring Boot框架中完成以下Java代码
public void addArg(String key, String value) { this.args.put(key, value); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FilterProperties that = (FilterProperties) o; return Objects.equals(name, that.name) && Objects.equals(args, that.args); }
@Override public int hashCode() { return Objects.hash(name, args); } @Override public String toString() { final StringBuilder sb = new StringBuilder("FilterDefinition{"); sb.append("name='").append(name).append('\''); sb.append(", args=").append(args); sb.append('}'); return sb.toString(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\FilterProperties.java
2
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password= spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # Spring Boot 2.5.0 init schema & data spring.sql.init.username=root spring.sql.init.password= spring.sql.init.schema-locations=classpath*:schema-all.sql #spring.sql.init.enabl
ed=true #spring.sql.init.data-locations=classpath*: #spring.sql.init.encoding=UTF-8 #spring.sql.init.separator=; #spring.sql.init.continue-on-error=true
repos\SpringBoot-Learning-master\2.x\chapter3-13\src\main\resources\application.properties
2
请完成以下Java代码
public MAccount getAccount(final TaxId taxId, final AcctSchemaId acctSchemaId, final TaxAcctType acctType) { return getAccountIfExists(taxId, acctSchemaId, acctType) .orElseThrow(() -> new AdempiereException("@NotFound@ " + acctType + " (" + taxId + ", " + acctSchemaId + ")")); } @Override public Optional<MAccount> getAccountIfExists(final TaxId taxId, final AcctSchemaId acctSchemaId, final TaxAcctType acctType) { return getAccountId(taxId, acctSchemaId, acctType) .map(accountsRepo::getById); } @Override public Optional<AccountId> getAccountId(@NonNull final TaxId taxId, @NonNull final AcctSchemaId acctSchemaId, final TaxAcctType acctType) { final I_C_Tax_Acct taxAcct = getTaxAcctRecord(acctSchemaId, taxId); if (TaxAcctType.TaxDue == acctType) { final Optional<AccountId> accountId = AccountId.optionalOfRepoId(taxAcct.getT_Due_Acct()); return accountId; } else if (TaxAcctType.TaxLiability == acctType) { final Optional<AccountId> accountId = AccountId.optionalOfRepoId(taxAcct.getT_Liability_Acct()); return accountId; } else if (TaxAcctType.TaxCredit == acctType) { final Optional<AccountId> accountId = AccountId.optionalOfRepoId(taxAcct.getT_Credit_Acct()); return accountId; } else if (TaxAcctType.TaxReceivables == acctType) { final Optional<AccountId> accountId = AccountId.optionalOfRepoId(taxAcct.getT_Receivables_Acct()); return accountId; } else if (TaxAcctType.TaxExpense == acctType) { final Optional<AccountId> accountId = AccountId.optionalOfRepoId(taxAcct.getT_Expense_Acct()); return accountId;
} else if (TaxAcctType.ProductRevenue_Override == acctType) { // might be not set return AccountId.optionalOfRepoId(taxAcct.getT_Revenue_Acct()); } else { throw new AdempiereException("Unknown tax account type: " + acctType); } } private I_C_Tax_Acct getTaxAcctRecord(final AcctSchemaId acctSchemaId, final TaxId taxId) { return taxAcctRecords.getOrLoad( TaxIdAndAcctSchemaId.of(taxId, acctSchemaId), this::retrieveTaxAcctRecord); } private I_C_Tax_Acct retrieveTaxAcctRecord(@NonNull final TaxIdAndAcctSchemaId key) { return Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_C_Tax_Acct.class) .addEqualsFilter(I_C_Tax_Acct.COLUMNNAME_C_Tax_ID, key.getTaxId()) .addEqualsFilter(I_C_Tax_Acct.COLUMNNAME_C_AcctSchema_ID, key.getAcctSchemaId()) .addOnlyActiveRecordsFilter() .create() .firstOnlyNotNull(I_C_Tax_Acct.class); } @Value(staticConstructor = "of") private static class TaxIdAndAcctSchemaId { @NonNull TaxId taxId; @NonNull AcctSchemaId acctSchemaId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\tax\impl\TaxAcctBL.java
1
请完成以下Java代码
private ImmutableList<DataEntryDetailsRow> loadRows() { return loadAllRows(); } private ImmutableList<DataEntryDetailsRow> loadAllRows() { final Predicate<FlatrateDataEntryDetail> all = detail -> true; return loadMatchingRows(all); } public ImmutableList<DataEntryDetailsRow> loadMatchingRows(@NonNull final Predicate<FlatrateDataEntryDetail> filter) { final FlatrateDataEntry entry = flatrateDataEntryRepo.getById(flatrateDataEntryId); final FlatrateDataEntry entryWithAllDetails; if (!entry.isProcessed()) { entryWithAllDetails = flatrateDataEntryService.addMissingDetails(entry); } else { entryWithAllDetails = entry; } final LookupValue uom = Check.assumeNotNull(uomLookup.findById(entryWithAllDetails.getUomId()), "UOM lookup may not be null for C_UOM_ID={}; C_Flatrate_DataEntry_ID={}", UomId.toRepoId(entryWithAllDetails.getUomId()), FlatrateDataEntryId.toRepoId(entryWithAllDetails.getId())); final ImmutableList.Builder<DataEntryDetailsRow> result = ImmutableList.builder(); for (final FlatrateDataEntryDetail detail : entryWithAllDetails.getDetails()) { if (filter.test(detail)) { final DataEntryDetailsRow row = toRow(entryWithAllDetails.isProcessed(), uom, detail); result.add(row); } }
return result.build(); } private DataEntryDetailsRow toRow( final boolean processed, @NonNull final LookupValue uom, @NonNull final FlatrateDataEntryDetail detail) { final ProductASIDescription productASIDescription = ProductASIDescription.ofString(attributeSetInstanceBL.getASIDescriptionById(detail.getAsiId())); final DocumentId documentId = DataEntryDetailsRowUtil.createDocumentId(detail); final BPartnerDepartment bPartnerDepartment = detail.getBPartnerDepartment(); final LookupValue department; if (bPartnerDepartment.isNone()) { department = null; } else { department = departmentLookup.findById(bPartnerDepartment.getId()); } final DataEntryDetailsRow.DataEntryDetailsRowBuilder row = DataEntryDetailsRow.builder() .processed(processed) .id(documentId) .asi(productASIDescription) .department(department) .uom(uom); if (detail.getQuantity() != null) { row.qty(detail.getQuantity().toBigDecimal()); } return row.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\contract\flatrate\model\DataEntryDetailsRowsLoader.java
1
请完成以下Spring Boot application配置
# ????????? spring.servlet.multipart.max-request-size=1024MB # ???????? spring.servlet.multipart.max-file-size=10MB # ????????? predict.imagefilepath=/Users/liuhaihua/Downloads/i
mages/ # ?????? predict.modelpath=/Users/liuhaihua/Downloads/minist-model.zip
repos\springboot-demo-master\Deeplearning4j\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public Duration getKeyValue() { return this.keyValue; } public void setKeyValue(Duration keyValue) { this.keyValue = keyValue; } public Duration getKeyValueDurable() { return this.keyValueDurable; } public void setKeyValueDurable(Duration keyValueDurable) { this.keyValueDurable = keyValueDurable; } public Duration getQuery() { return this.query; } public void setQuery(Duration query) { this.query = query; } public Duration getView() { return this.view; } public void setView(Duration view) { this.view = view; } public Duration getSearch() { return this.search; } public void setSearch(Duration search) { this.search = search; }
public Duration getAnalytics() { return this.analytics; } public void setAnalytics(Duration analytics) { this.analytics = analytics; } public Duration getManagement() { return this.management; } public void setManagement(Duration management) { this.management = management; } } }
repos\spring-boot-4.0.1\module\spring-boot-couchbase\src\main\java\org\springframework\boot\couchbase\autoconfigure\CouchbaseProperties.java
2
请完成以下Java代码
public int getInvocationsPerBatchJob() { return invocationsPerBatchJob; } public String getSeedJobDefinitionId() { return seedJobDefinitionId; } public String getMonitorJobDefinitionId() { return monitorJobDefinitionId; } public String getBatchJobDefinitionId() { return batchJobDefinitionId; } public String getTenantId() { return tenantId; } public String getCreateUserId() { return createUserId; } public Date getStartTime() { return startTime; } public Date getEndTime() { return endTime; } public Date getRemovalTime() { return removalTime;
} public Date getExecutionStartTime() { return executionStartTime; } public void setExecutionStartTime(final Date executionStartTime) { this.executionStartTime = executionStartTime; } public static HistoricBatchDto fromBatch(HistoricBatch historicBatch) { HistoricBatchDto dto = new HistoricBatchDto(); dto.id = historicBatch.getId(); dto.type = historicBatch.getType(); dto.totalJobs = historicBatch.getTotalJobs(); dto.batchJobsPerSeed = historicBatch.getBatchJobsPerSeed(); dto.invocationsPerBatchJob = historicBatch.getInvocationsPerBatchJob(); dto.seedJobDefinitionId = historicBatch.getSeedJobDefinitionId(); dto.monitorJobDefinitionId = historicBatch.getMonitorJobDefinitionId(); dto.batchJobDefinitionId = historicBatch.getBatchJobDefinitionId(); dto.tenantId = historicBatch.getTenantId(); dto.createUserId = historicBatch.getCreateUserId(); dto.startTime = historicBatch.getStartTime(); dto.endTime = historicBatch.getEndTime(); dto.removalTime = historicBatch.getRemovalTime(); dto.executionStartTime = historicBatch.getExecutionStartTime(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\batch\HistoricBatchDto.java
1
请完成以下Java代码
HeapNode getRootNode() { return heapNodes[0]; } void heapifyFromRoot() { heapify(0); } void swap(int i, int j) { HeapNode temp = heapNodes[i]; heapNodes[i] = heapNodes[j]; heapNodes[j] = temp; } static int[] merge(int[][] array) { HeapNode[] heapNodes = new HeapNode[array.length]; int resultingArraySize = 0; for (int i = 0; i < array.length; i++) { HeapNode node = new HeapNode(array[i][0], i); heapNodes[i] = node; resultingArraySize += array[i].length; }
MinHeap minHeap = new MinHeap(heapNodes); int[] resultingArray = new int[resultingArraySize]; for (int i = 0; i < resultingArraySize; i++) { HeapNode root = minHeap.getRootNode(); resultingArray[i] = root.element; if (root.nextElementIndex < array[root.arrayIndex].length) { root.element = array[root.arrayIndex][root.nextElementIndex++]; } else { root.element = Integer.MAX_VALUE; } minHeap.heapifyFromRoot(); } return resultingArray; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\minheapmerge\MinHeap.java
1
请在Spring Boot框架中完成以下Java代码
public Mono<Boolean> serviceInstanceExists(String instanceId) { return Mono.just(mailServices.containsKey(instanceId)); } public Mono<MailServiceInstance> getServiceInstance(String instanceId) { if (mailServices.containsKey(instanceId)) { return Mono.just(mailServices.get(instanceId)); } return Mono.empty(); } public Mono<Void> deleteServiceInstance(String instanceId) { mailServices.remove(instanceId); mailServiceBindings.remove(instanceId); return Mono.empty(); } public Mono<MailServiceBinding> createServiceBinding(String instanceId, String bindingId) { return this.serviceInstanceExists(instanceId) .flatMap(exists -> { if (exists) { MailServiceBinding mailServiceBinding = new MailServiceBinding(bindingId, buildCredentials(instanceId, bindingId)); mailServiceBindings.put(instanceId, mailServiceBinding); return Mono.just(mailServiceBinding); } else { return Mono.empty(); } }); } public Mono<Boolean> serviceBindingExists(String instanceId, String bindingId) { return Mono.just(mailServiceBindings.containsKey(instanceId) && mailServiceBindings.get(instanceId).getBindingId().equalsIgnoreCase(bindingId)); } public Mono<MailServiceBinding> getServiceBinding(String instanceId, String bindingId) {
if (mailServiceBindings.containsKey(instanceId) && mailServiceBindings.get(instanceId).getBindingId().equalsIgnoreCase(bindingId)) { return Mono.just(mailServiceBindings.get(instanceId)); } return Mono.empty(); } public Mono<Void> deleteServiceBinding(String instanceId) { mailServiceBindings.remove(instanceId); return Mono.empty(); } private Map<String, Object> buildCredentials(String instanceId, String bindingId) { Map<String, Object> credentials = new HashMap<>(); credentials.put(URI_KEY, mailSystemBaseURL + instanceId); credentials.put(USERNAME_KEY, bindingId); credentials.put(PASSWORD_KEY, UUID.randomUUID().toString()); return credentials; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-open-service-broker\src\main\java\com\baeldung\spring\cloud\openservicebroker\mail\MailService.java
2
请完成以下Java代码
public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false;
} if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((Chapter) obj).id); } @Override public int hashCode() { return 2021; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDatabaseTriggers\src\main\java\com\bookstore\entity\Chapter.java
1
请完成以下Java代码
public void init() { logger.info("Hello world from Quartz..."); } @Bean public SpringBeanJobFactory springBeanJobFactory() { AutoWiringSpringBeanJobFactory jobFactory = new AutoWiringSpringBeanJobFactory(); logger.debug("Configuring Job factory"); jobFactory.setApplicationContext(applicationContext); return jobFactory; } @Bean public Scheduler scheduler(Trigger trigger, JobDetail job, SchedulerFactoryBean factory) throws SchedulerException { logger.debug("Getting a handle to the Scheduler"); Scheduler scheduler = factory.getScheduler(); scheduler.scheduleJob(job, trigger); logger.debug("Starting Scheduler threads"); scheduler.start(); return scheduler; } @Bean public SchedulerFactoryBean schedulerFactoryBean() throws IOException { SchedulerFactoryBean factory = new SchedulerFactoryBean(); factory.setJobFactory(springBeanJobFactory()); factory.setQuartzProperties(quartzProperties()); return factory; }
public Properties quartzProperties() throws IOException { PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); propertiesFactoryBean.afterPropertiesSet(); return propertiesFactoryBean.getObject(); } @Bean public JobDetail jobDetail() { return newJob().ofType(SampleJob.class).storeDurably().withIdentity(JobKey.jobKey("Qrtz_Job_Detail")).withDescription("Invoke Sample Job service...").build(); } @Bean public Trigger trigger(JobDetail job) { int frequencyInSec = 10; logger.info("Configuring trigger to fire every {} seconds", frequencyInSec); return newTrigger().forJob(job).withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")).withDescription("Sample trigger").withSchedule(simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()).build(); } }
repos\tutorials-master\spring-quartz\src\main\java\org\baeldung\springquartz\basics\scheduler\QrtzScheduler.java
1
请完成以下Java代码
public Mono<Void> filter(@NonNull ServerWebExchange exchange, @NonNull WebFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); // 处理跨域请求 if (CorsUtils.isCorsRequest(request)) { ServerHttpResponse response = exchange.getResponse(); HttpHeaders headers = response.getHeaders(); headers.add("Access-Control-Allow-Headers", ALLOWED_HEADERS); headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS); headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN); headers.add("Access-Control-Expose-Headers", ALLOWED_EXPOSE); headers.add("Access-Control-Max-Age", MAX_AGE); headers.add("Access-Control-Allow-Credentials", "true"); if (request.getMethod() == HttpMethod.OPTIONS) { response.setStatusCode(HttpStatus.OK); return Mono.empty(); } } // 处理黑白名单与拦截请求 if (requestProperties.getEnabled()) { String path = request.getPath().value(); String ip = Objects.requireNonNull(request.getRemoteAddress()).getHostString(); if (isRequestBlock(path, ip)) { throw new RuntimeException(DEFAULT_MESSAGE); } } return chain.filter(exchange); } /** * 是否白名单 * * @param ip ip地址 * @return boolean */ private boolean isWhiteList(String ip) { List<String> whiteList = requestProperties.getWhiteList(); String[] defaultWhiteIps = defaultWhiteList.toArray(new String[0]); String[] whiteIps = whiteList.toArray(new String[0]); return PatternMatchUtils.simpleMatch(defaultWhiteIps, ip) || PatternMatchUtils.simpleMatch(whiteIps, ip); } /** * 是否黑名单 * * @param ip ip地址 * @return boolean */ private boolean isBlackList(String ip) { List<String> blackList = requestProperties.getBlackList(); String[] blackIps = blackList.toArray(new String[0]); return PatternMatchUtils.simpleMatch(blackIps, ip); } /** * 是否禁用请求访问
* * @param path 请求路径 * @return boolean */ private boolean isRequestBlock(String path) { List<String> blockUrl = requestProperties.getBlockUrl(); return defaultBlockUrl.stream().anyMatch(pattern -> antPathMatcher.match(pattern, path)) || blockUrl.stream().anyMatch(pattern -> antPathMatcher.match(pattern, path)); } /** * 是否拦截请求 * * @param path 请求路径 * @param ip ip地址 * @return boolean */ private boolean isRequestBlock(String path, String ip) { return (isRequestBlock(path) && !isWhiteList(ip)) || isBlackList(ip); } @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } }
repos\SpringBlade-master\blade-gateway\src\main\java\org\springblade\gateway\filter\GatewayFilter.java
1
请完成以下Java代码
public class TimePageLink extends PageLink { private final Long startTime; private final Long endTime; public TimePageLink(PageLink pageLink, Long startTime, Long endTime) { super(pageLink); this.startTime = startTime; this.endTime = endTime; } public TimePageLink(int pageSize) { this(pageSize, 0); } public TimePageLink(int pageSize, int page) { this(pageSize, page, null); } public TimePageLink(int pageSize, int page, String textSearch) { this(pageSize, page, textSearch, null, null, null); } public TimePageLink(int pageSize, int page, String textSearch, SortOrder sortOrder) { this(pageSize, page, textSearch, sortOrder, null, null);
} public TimePageLink(int pageSize, int page, String textSearch, SortOrder sortOrder, Long startTime, Long endTime) { super(pageSize, page, textSearch, sortOrder); this.startTime = startTime; this.endTime = endTime; } @JsonIgnore public TimePageLink nextPageLink() { return new TimePageLink(this.getPageSize(), this.getPage()+1, this.getTextSearch(), this.getSortOrder(), this.startTime, this.endTime); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\page\TimePageLink.java
1
请完成以下Java代码
public static ImageIcon getImageIcon(final String fileNameInImageDir) { if (fileNameInImageDir == null || fileNameInImageDir.isEmpty()) { return null; } try { return imageIcons.get(fileNameInImageDir).orNull(); } catch (final ExecutionException e) { logger.warn("Failed loading image for " + fileNameInImageDir, e); } return null; } // getImageIcon /** * Get ImageIcon. * * This method different from {@link #getImageIcon(String)} where the fileName parameter is with extension. * The method will first try .png and then .gif if .png does not exists. * * @param fileNameWithoutExtension file name in images folder without the extension(e.g. Bean16) * @return image or <code>null</code> */ public static ImageIcon getImageIcon2(final String fileNameWithoutExtension) { if (fileNameWithoutExtension == null || fileNameWithoutExtension.isEmpty()) { return null; } try { return imageIcons2.get(fileNameWithoutExtension).orNull(); } catch (final ExecutionException e) { logger.warn("Failed loading image for " + fileNameWithoutExtension, e); } return null; } // getImageIcon2 /** * Get Image. * * This method different from {@link #getImage(String)} where the fileName parameter is with extension. * The method will first try .png and then .gif if .png does not exists. *
* @param fileNameWithoutExtension file name in images folder without the extension(e.g. Bean16) * @return image or <code>null</code> */ public static Image getImage2(final String fileNameWithoutExtension) { final ImageIcon imageIcon = getImageIcon2(fileNameWithoutExtension); if(imageIcon == null) { return null; } return imageIcon.getImage(); } /** * Loads {@link Image} of given <code>url</code> and apply theme's RGB filter if any. * * @param url * @return {@link Image} or null */ private static final Optional<Image> loadImage(final URL url) { if (url == null) { return Optional.absent(); } final Toolkit toolkit = Toolkit.getDefaultToolkit(); Image image = toolkit.getImage(url); if (image == null) { return Optional.absent(); } return Optional.fromNullable(image); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\images\Images.java
1
请在Spring Boot框架中完成以下Java代码
public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } public void addVariable(RestVariable variable) { variables.add(variable); } @ApiModelProperty(example = "3") public String getCallbackId() { return callbackId; } public void setCallbackId(String callbackId) { this.callbackId = callbackId; } @ApiModelProperty(example = "cmmn") public String getCallbackType() { return callbackType; } public void setCallbackType(String callbackType) { this.callbackType = callbackType; } @ApiModelProperty(example = "123") public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } @ApiModelProperty(example = "event-to-bpmn-2.0-process") public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType;
} @ApiModelProperty(value = "The stage plan item instance id this process instance belongs to or null, if it is not part of a case at all or is not a child element of a stage") public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } @ApiModelProperty(example = "someTenantId") public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricProcessInstanceResponse.java
2
请完成以下Java代码
public int hashCode() { return Objects.hash(sql, sqlParams); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof TypedSqlQueryFilter) { final TypedSqlQueryFilter<?> other = (TypedSqlQueryFilter<?>)obj; return Objects.equals(sql, other.sql) && Objects.equals(sqlParams, other.sqlParams); } else { return false; } } @Override
public String getSql() { return sql; } @Override public List<Object> getSqlParams(final Properties ctx_NOTUSED) { return sqlParams; } @Override public boolean accept(final T model) { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\TypedSqlQueryFilter.java
1
请完成以下Java代码
public I_AD_Sequence getAD_Sequence() throws RuntimeException { return (I_AD_Sequence)MTable.get(getCtx(), I_AD_Sequence.Table_Name) .getPO(getAD_Sequence_ID(), get_TrxName()); } /** Set Sequence. @param AD_Sequence_ID Document Sequence */ public void setAD_Sequence_ID (int AD_Sequence_ID) { if (AD_Sequence_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Sequence_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Sequence_ID, Integer.valueOf(AD_Sequence_ID)); } /** Get Sequence. @return Document Sequence */ public int getAD_Sequence_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Sequence_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_Table getAD_Table() throws RuntimeException { return (I_AD_Table)MTable.get(getCtx(), I_AD_Table.Table_Name) .getPO(getAD_Table_ID(), get_TrxName()); } /** Set Table. @param AD_Table_ID Database Table information */ public void setAD_Table_ID (int AD_Table_ID) { if (AD_Table_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID)); } /** Get Table. @return Database Table information */ public int getAD_Table_ID () {
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Document No. @param DocumentNo Document sequence number of the document */ public void setDocumentNo (String DocumentNo) { set_ValueNoCheck (COLUMNNAME_DocumentNo, DocumentNo); } /** Get Document No. @return Document sequence number of the document */ public String getDocumentNo () { return (String)get_Value(COLUMNNAME_DocumentNo); } /** Set Record ID. @param Record_ID Direct internal record ID */ public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Record ID. @return Direct internal record ID */ public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Sequence_Audit.java
1
请完成以下Spring Boot application配置
spring: # ActiveMQ 配置项,对应 ActiveMQProperties 配置类 activemq: broker-url: tcp://127.0.0.1:61616 # ActiveMQ Broker 的地址 user: admin # 账号 pas
sword: admin # 密码 packages: trust-all: true # 可信任的反序列化包
repos\SpringBoot-Labs-master\lab-32\lab-32-activemq-demo\src\main\resources\application.yaml
2
请在Spring Boot框架中完成以下Java代码
public String getCONTROLVALUE() { return controlvalue; } /** * Sets the value of the controlvalue property. * * @param value * allowed object is * {@link String } * */ public void setCONTROLVALUE(String value) { this.controlvalue = value; } /** * Gets the value of the measurementunit property. * * @return * possible object is * {@link String } * */ public String getMEASUREMENTUNIT() { return measurementunit; } /** * Sets the value of the measurementunit property. * * @param value * allowed object is * {@link String } * */ public void setMEASUREMENTUNIT(String value) { this.measurementunit = value; } /** * Gets the value of the tamou1 property. * * @return * possible object is * {@link TAMOU1 } * */ public TAMOU1 getTAMOU1() { return tamou1; } /** * Sets the value of the tamou1 property. *
* @param value * allowed object is * {@link TAMOU1 } * */ public void setTAMOU1(TAMOU1 value) { this.tamou1 = value; } /** * Gets the value of the ttaxi1 property. * * @return * possible object is * {@link TTAXI1 } * */ public TTAXI1 getTTAXI1() { return ttaxi1; } /** * Sets the value of the ttaxi1 property. * * @param value * allowed object is * {@link TTAXI1 } * */ public void setTTAXI1(TTAXI1 value) { this.ttaxi1 = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\TRAILR.java
2
请完成以下Java代码
public void setAssignee(String taskId, String userId) { commandExecutor.execute(new AddIdentityLinkCmd(taskId, userId, AddIdentityLinkCmd.IDENTITY_USER, IdentityLinkType.ASSIGNEE)); } @Override public void setOwner(String taskId, String userId) { commandExecutor.execute(new AddIdentityLinkCmd(taskId, userId, AddIdentityLinkCmd.IDENTITY_USER, IdentityLinkType.OWNER)); } @Override public void addUserIdentityLink(String taskId, String userId, String identityLinkType) { commandExecutor.execute(new AddIdentityLinkCmd(taskId, userId, AddIdentityLinkCmd.IDENTITY_USER, identityLinkType)); } @Override public void addGroupIdentityLink(String taskId, String groupId, String identityLinkType) { commandExecutor.execute(new AddIdentityLinkCmd(taskId, groupId, AddIdentityLinkCmd.IDENTITY_GROUP, identityLinkType)); } @Override public void deleteGroupIdentityLink(String taskId, String groupId, String identityLinkType) { commandExecutor.execute(new DeleteIdentityLinkCmd(taskId, null, groupId, identityLinkType)); }
@Override public void deleteUserIdentityLink(String taskId, String userId, String identityLinkType) { commandExecutor.execute(new DeleteIdentityLinkCmd(taskId, userId, null, identityLinkType)); } @Override public List<IdentityLink> getIdentityLinksForTask(String taskId) { return commandExecutor.execute(new GetIdentityLinksForTaskCmd(taskId)); } @Override public TaskBuilder createTaskBuilder() { return new CmmnTaskBuilderImpl(commandExecutor, configuration); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnTaskServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class RedisConfiguration { @Bean public RedisTemplate<String, Session> getRedisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Session> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); return redisTemplate; } @Bean public RedisMappingContext keyValueMappingContext() { return new RedisMappingContext(new MappingConfiguration(new IndexConfiguration(), new MyKeyspaceConfiguration())); } public static class MyKeyspaceConfiguration extends KeyspaceConfiguration { @Override protected Iterable<KeyspaceSettings> initialConfiguration() {
KeyspaceSettings keyspaceSettings = new KeyspaceSettings(Session.class, "session"); keyspaceSettings.setTimeToLive(60L); return Collections.singleton(keyspaceSettings); } } @Component public static class SessionExpiredEventListener { @EventListener public void handleRedisKeyExpiredEvent(RedisKeyExpiredEvent<Session> event) { Session expiredSession = (Session) event.getValue(); assert expiredSession != null; log.info("Session with key={} has expired", expiredSession.getId()); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-redis\src\main\java\com\baelding\springbootredis\config\RedisConfiguration.java
2
请完成以下Java代码
public boolean equals(Object obj) { if (obj instanceof BuilderMethods == false) { return false; } if (this == obj) { return true; } final BuilderMethods otherObject = (BuilderMethods) obj; return new EqualsBuilder().append(this.intValue, otherObject.intValue).append(this.strSample, otherObject.strSample).isEquals(); } @Override public String toString() { return new ToStringBuilder(this).append("INTVALUE", this.intValue).append("STRINGVALUE", this.strSample).toString(); } public static void main(final String[] arguments) { final BuilderMethods simple1 = new BuilderMethods(1, "The First One"); System.out.println(simple1.getName()); System.out.println(simple1.hashCode()); System.out.println(simple1.toString()); SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer(); try { sampleLazyInitializer.get(); } catch (ConcurrentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } SampleBackgroundInitializer sampleBackgroundInitializer = new SampleBackgroundInitializer(); sampleBackgroundInitializer.start();
// Proceed with other tasks instead of waiting for the SampleBackgroundInitializer task to finish. try { Object result = sampleBackgroundInitializer.get(); } catch (ConcurrentException e) { e.printStackTrace(); } } } class SampleBackgroundInitializer extends BackgroundInitializer<String> { @Override protected String initialize() throws Exception { return null; } // Any complex task that takes some time }
repos\tutorials-master\libraries-apache-commons\src\main\java\com\baeldung\commons\lang3\BuilderMethods.java
1
请完成以下Java代码
public Object getProperty(@NonNull String name) { return encryptableDelegate.getProperty(name); } /** * {@inheritDoc} */ @Override public PropertySource<Map<String, Object>> getDelegate() { return encryptableDelegate; } /** * {@inheritDoc} */ @Override public Origin getOrigin(String key) { Origin fromSuper = EncryptablePropertySource.super.getOrigin(key); if (fromSuper != null) { return fromSuper; } String property = resolvePropertyName(key); if (super.containsProperty(property)) { return new SystemEnvironmentOrigin(property); } return null; }
/** * <p>Set whether getSource() should wrap the source Map in an EncryptableMapWrapper.</p> * * @param wrapGetSource true to wrap the source Map */ public void setWrapGetSource(boolean wrapGetSource) { encryptableDelegate.setWrapGetSource(wrapGetSource); } @Override @NonNull public Map<String, Object> getSource() { return encryptableDelegate.getSource(); } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\wrapper\EncryptableSystemEnvironmentPropertySourceWrapper.java
1
请完成以下Java代码
public class DefaultAsyncBatchListener implements IAsyncBatchListener { private static final AdMessageKey MSG_ASYNC_PROCESSED = AdMessageKey.of("DefaultAsyncBatchListener_AsyncBatch_Processed"); @Override public void createNotice(final I_C_Async_Batch asyncBatch) { final I_C_Async_Batch_Type asyncBatchType = loadOutOfTrx(asyncBatch.getC_Async_Batch_Type_ID(), I_C_Async_Batch_Type.class); if (!IAsyncBatchDAO.ASYNC_BATCH_TYPE_DEFAULT.equals(asyncBatchType.getInternalName())) { return; } final UserId recipientUserId = UserId.ofRepoId(asyncBatch.getCreatedBy()); final UserNotificationsConfig notificationsConfig = createUserNotificationsConfigOrNull(recipientUserId, asyncBatchType); if (notificationsConfig == null) { return; }
final INotificationBL notificationBL = Services.get(INotificationBL.class); notificationBL.send( UserNotificationRequest.builder() .notificationsConfig(notificationsConfig) .contentADMessage(MSG_ASYNC_PROCESSED) .contentADMessageParam(asyncBatch.getName()) .targetAction(TargetRecordAction.of(TableRecordReference.of(asyncBatch))) .build()); } private static UserNotificationsConfig createUserNotificationsConfigOrNull(final UserId recipientUserId, final I_C_Async_Batch_Type asyncBatchType) { final INotificationBL notifications = Services.get(INotificationBL.class); return notifications.getUserNotificationsConfig(recipientUserId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\impl\DefaultAsyncBatchListener.java
1
请完成以下Java代码
private static class ImmutableFactoryGroupBuilder { private final HashSet<String> tableNamesToEnableRemoveCacheInvalidation = new HashSet<>(); private final HashMultimap<String, ModelCacheInvalidateRequestFactory> factoriesByTableName = HashMultimap.create(); public ImmutableModelCacheInvalidateRequestFactoriesList build() { return ImmutableModelCacheInvalidateRequestFactoriesList.builder() .factoriesByTableName(factoriesByTableName) .tableNamesToEnableRemoveCacheInvalidation( TableNamesGroup.builder() .groupId(WindowBasedModelCacheInvalidateRequestFactoryGroup.class.getSimpleName()) .tableNames(tableNamesToEnableRemoveCacheInvalidation) .build()) .build(); } public ImmutableFactoryGroupBuilder addAll(@NonNull final Set<ParentChildInfo> parentChildInfos) { parentChildInfos.forEach(this::add); return this; } public ImmutableFactoryGroupBuilder add(@NonNull final ParentChildInfo info) { addForParentTable(info); addForChildTable(info); return this; } private void addForParentTable(final ParentChildInfo info) { final String parentTableName = info.getParentTableName(); factoriesByTableName.put(parentTableName, DirectModelCacheInvalidateRequestFactory.instance); // NOTE: always invalidate parent table name, even if info.isParentNeedsRemoteCacheInvalidation() is false tableNamesToEnableRemoveCacheInvalidation.add(parentTableName);
} private void addForChildTable(final ParentChildInfo info) { final String childTableName = info.getChildTableName(); if (childTableName == null || isBlank(childTableName)) { return; } try { final ParentChildModelCacheInvalidateRequestFactory factory = info.toGenericModelCacheInvalidateRequestFactoryOrNull(); if (factory != null) { factoriesByTableName.put(childTableName, factory); } } catch (final Exception ex) { logger.warn("Failed to create model cache invalidate for {}: {}", childTableName, info, ex); } if (info.isChildNeedsRemoteCacheInvalidation()) { tableNamesToEnableRemoveCacheInvalidation.add(childTableName); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\WindowBasedModelCacheInvalidateRequestFactoryGroup.java
1
请完成以下Java代码
private static ITranslatableString getDefaultFilterCaption() { return Services.get(IMsgBL.class).getTranslatableMsgText("Default"); } private static DocumentFilterParamDescriptor.Builder newParamDescriptor(final String fieldName) { return DocumentFilterParamDescriptor.builder() .fieldName(fieldName) .displayName(Services.get(IMsgBL.class).translatable(fieldName)); } public static ProductsProposalViewFilter extractPackageableViewFilterVO(@NonNull final JSONFilterViewRequest filterViewRequest) { final DocumentFilterList filters = filterViewRequest.getFiltersUnwrapped(getDescriptors()); return extractPackageableViewFilterVO(filters); } private static ProductsProposalViewFilter extractPackageableViewFilterVO(final DocumentFilterList filters) { return filters.getFilterById(ProductsProposalViewFilter.FILTER_ID) .map(filter -> toProductsProposalViewFilterValue(filter)) .orElse(ProductsProposalViewFilter.ANY); }
private static ProductsProposalViewFilter toProductsProposalViewFilterValue(final DocumentFilter filter) { return ProductsProposalViewFilter.builder() .productName(filter.getParameterValueAsString(ProductsProposalViewFilter.PARAM_ProductName, null)) .build(); } public static DocumentFilterList toDocumentFilters(final ProductsProposalViewFilter filter) { final DocumentFilter.DocumentFilterBuilder builder = DocumentFilter.builder() .setFilterId(ProductsProposalViewFilter.FILTER_ID) .setCaption(getDefaultFilterCaption()); if (!Check.isEmpty(filter.getProductName())) { builder.addParameter(DocumentFilterParam.ofNameEqualsValue(ProductsProposalViewFilter.PARAM_ProductName, filter.getProductName())); } if (!builder.hasParameters()) { return DocumentFilterList.EMPTY; } return DocumentFilterList.of(builder.build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\filters\ProductsProposalViewFilters.java
1
请完成以下Java代码
public class FlatrateTermInvoiceCandidateListener implements IInvoiceCandidateListener { public static final FlatrateTermInvoiceCandidateListener instance = new FlatrateTermInvoiceCandidateListener(); private FlatrateTermInvoiceCandidateListener() { super(); } @Override public void onBeforeClosed(@NonNull final I_C_Invoice_Candidate candidate) { final int tableID = candidate.getAD_Table_ID(); if (tableID != InterfaceWrapperHelper.getTableId(I_C_Flatrate_Term.class)) { return; } final I_C_Flatrate_Term term = load(candidate.getRecord_ID(), I_C_Flatrate_Term.class);
final IQuery<I_C_SubscriptionProgress> subscriptionQuery = Services.get(IQueryBL.class) .createQueryBuilder(I_C_SubscriptionProgress.class, term) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_SubscriptionProgress.COLUMNNAME_C_Flatrate_Term_ID, term.getC_Flatrate_Term_ID()) .create(); final List<I_M_ShipmentSchedule> shipmentSchedules = Services.get(IQueryBL.class) .createQueryBuilder(I_M_ShipmentSchedule.class, candidate) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_ShipmentSchedule.COLUMNNAME_AD_Table_ID, InterfaceWrapperHelper.getTableId(I_C_SubscriptionProgress.class)) .addInSubQueryFilter(I_M_ShipmentSchedule.COLUMNNAME_Record_ID, I_C_SubscriptionProgress.COLUMNNAME_C_SubscriptionProgress_ID, subscriptionQuery) .orderBy().addColumn(I_M_ShipmentSchedule.COLUMNNAME_M_ShipmentSchedule_ID).endOrderBy() .create() .list(I_M_ShipmentSchedule.class); shipmentSchedules.forEach(shipmentSchedule -> Services.get(IShipmentScheduleBL.class).closeShipmentSchedule(shipmentSchedule)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\spi\impl\FlatrateTermInvoiceCandidateListener.java
1
请在Spring Boot框架中完成以下Java代码
public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public boolean isActivated() { return activated; } public void setActivated(boolean activated) { this.activated = activated; } public String getLangKey() { return langKey; } public void setLangKey(String langKey) { this.langKey = langKey; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Instant getCreatedDate() {
return createdDate; } public void setCreatedDate(Instant createdDate) { this.createdDate = createdDate; } public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public Instant getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(Instant lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } public Set<String> getAuthorities() { return authorities; } public void setAuthorities(Set<String> authorities) { this.authorities = authorities; } @Override public String toString() { return "UserDTO{" + "login='" + login + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", imageUrl='" + imageUrl + '\'' + ", activated=" + activated + ", langKey='" + langKey + '\'' + ", createdBy=" + createdBy + ", createdDate=" + createdDate + ", lastModifiedBy='" + lastModifiedBy + '\'' + ", lastModifiedDate=" + lastModifiedDate + ", authorities=" + authorities + "}"; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\dto\UserDTO.java
2
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { // task 06058: if the document is processed, we not allowed to run this process final I_M_ShipperTransportation shipperTransportation = context.getSelectedModel(I_M_ShipperTransportation.class); return ProcessPreconditionsResolution.acceptIf(!shipperTransportation.isProcessed()); } @Override protected String doIt() throws Exception { final ShipperTransportationId shipperTransportationId = ShipperTransportationId.ofRepoId(getRecord_ID()); final I_M_ShipperTransportation shipperTransportation = shipperTransportationDAO.getById(shipperTransportationId); Check.assumeNotNull(shipperTransportation, "shipperTransportation not null"); // // If the document is processed, we not allowed to run this process (06058) if (shipperTransportation.isProcessed()) { throw new AdempiereException("@" + CreateFromPickingSlots_MSG_DOC_PROCESSED + "@"); } final I_M_Tour tour = Services.get(ITourDAO.class).getById(p_M_Tour_ID); Check.assumeNotNull(tour, "tour not null"); // // Fetch delivery days final Timestamp deliveryDate = shipperTransportation.getDateDoc(); final List<I_M_DeliveryDay> deliveryDays = deliveryDayDAO.retrieveDeliveryDays(tour, deliveryDate); if (deliveryDays.isEmpty()) { // No delivery days for tour; return "OK"; } // used to make sure no order is added more than once final Map<Integer, I_C_Order> orderId2order = new LinkedHashMap<>(); // we shall allow only those partner which are set in delivery days and that are vendors and have purchase orders for (final I_M_DeliveryDay dd : deliveryDays) { if (!dd.isToBeFetched()) {
continue; // nothing to do } // skip generic delivery days final I_C_BPartner_Location bpLocation = dd.getC_BPartner_Location(); if (bpLocation == null) { continue; } final List<I_C_Order> purchaseOrders = orderDAO.retrievePurchaseOrdersForPickup(bpLocation, dd.getDeliveryDate(), dd.getDeliveryDateTimeMax()); if (purchaseOrders.isEmpty()) { continue; // nothing to do } for (final I_C_Order purchaseOrder : purchaseOrders) { orderId2order.put(purchaseOrder.getC_Order_ID(), purchaseOrder); } } // // Iterate collected orders and create shipment packages for them for (final I_C_Order order : orderId2order.values()) { orderToShipperTransportationService.addPurchaseOrderToShipperTransportation( OrderId.ofRepoId(order.getC_Order_ID()), ShipperTransportationId.ofRepoId(shipperTransportation.getM_ShipperTransportation_ID())); } return "OK"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\process\M_ShippingPackage_CreateFromTourplanning.java
1
请完成以下Java代码
protected void executeParse(BpmnParse bpmnParse, EndEvent endEvent) { ActivityImpl endEventActivity = createActivityOnCurrentScope(bpmnParse, endEvent, BpmnXMLConstants.ELEMENT_EVENT_END); EventDefinition eventDefinition = null; if (!endEvent.getEventDefinitions().isEmpty()) { eventDefinition = endEvent.getEventDefinitions().get(0); } // Error end event if (eventDefinition instanceof org.flowable.bpmn.model.ErrorEventDefinition) { org.flowable.bpmn.model.ErrorEventDefinition errorDefinition = (org.flowable.bpmn.model.ErrorEventDefinition) eventDefinition; if (bpmnParse.getBpmnModel().containsErrorRef(errorDefinition.getErrorCode())) { String errorCode = bpmnParse.getBpmnModel().getErrors().get(errorDefinition.getErrorCode()); if (StringUtils.isEmpty(errorCode)) { LOGGER.warn("errorCode is required for an error event {}", endEvent.getId()); } endEventActivity.setProperty("type", "errorEndEvent"); errorDefinition.setErrorCode(errorCode); } endEventActivity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createErrorEndEventActivityBehavior(endEvent, errorDefinition)); // Cancel end event } else if (eventDefinition instanceof CancelEventDefinition) { ScopeImpl scope = bpmnParse.getCurrentScope(); if (scope.getProperty("type") == null || !scope.getProperty("type").equals("transaction")) { LOGGER.warn("end event with cancelEventDefinition only supported inside transaction subprocess (id={})", endEvent.getId()); } else { endEventActivity.setProperty("type", "cancelEndEvent"); endEventActivity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createCancelEndEventActivityBehavior(endEvent)); }
// Terminate end event } else if (eventDefinition instanceof TerminateEventDefinition) { endEventActivity.setAsync(endEvent.isAsynchronous()); endEventActivity.setExclusive(!endEvent.isNotExclusive()); endEventActivity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createTerminateEndEventActivityBehavior(endEvent)); // None end event } else if (eventDefinition == null) { endEventActivity.setAsync(endEvent.isAsynchronous()); endEventActivity.setExclusive(!endEvent.isNotExclusive()); endEventActivity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createNoneEndEventActivityBehavior(endEvent)); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\EndEventParseHandler.java
1
请完成以下Java代码
public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) {} /** * Key Released * if Escape restore old Text. * @param e event */ @Override public void keyReleased(KeyEvent e) { // ESC if (e.getKeyCode() == KeyEvent.VK_ESCAPE) setText(m_initialText); m_setting = true; try { fireVetoableChange(m_columnName, m_oldText, getText()); } catch (PropertyVetoException pve) {} m_setting = false; } // keyReleased /** * Set Field/WindowNo for ValuePreference (NOP) * @param mField field model */ @Override public void setField (org.compiere.model.GridField mField) { m_mField = mField; EditorContextPopupMenu.onGridFieldSet(this);
} // setField @Override public GridField getField() { return m_mField; } // metas: begin @Override public boolean isAutoCommit() { return true; } // metas: end } // VText
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VText.java
1
请完成以下Java代码
protected I_M_Material_Tracking_Report_Line createGroup( final Object itemHashKey, final MaterialTrackingReportAgregationItem items) { final IMaterialTrackingReportDAO materialTrackingReportDAO = Services.get(IMaterialTrackingReportDAO.class); final I_M_Material_Tracking_Report_Line existingLine = materialTrackingReportDAO.retrieveMaterialTrackingReportLineOrNull(report, itemHashKey.toString()); // Create a report line based on a ref if (existingLine != null) { return existingLine; } final I_M_Material_Tracking_Report_Line newLine; try { newLine = materialTrackingReportBL.createMaterialTrackingReportLine(report, items.getInOutLine(), itemHashKey.toString()); InterfaceWrapperHelper.save(newLine); } catch (final Throwable t) { Loggables.addLog("@Error@: " + t); throw AdempiereException.wrapIfNeeded(t); } return newLine; } @Override protected void closeGroup(final I_M_Material_Tracking_Report_Line reportLine) { // save the line
final BigDecimal qtyReceived = reportLine.getQtyReceived().setScale(1, RoundingMode.HALF_UP); final BigDecimal qtyIssued = reportLine.getQtyIssued().setScale(1, RoundingMode.HALF_UP); final BigDecimal qtyDifference = qtyReceived.subtract(qtyIssued).setScale(1, RoundingMode.HALF_UP); reportLine.setDifferenceQty(qtyDifference); InterfaceWrapperHelper.save(reportLine); } @Override protected void addItemToGroup(final I_M_Material_Tracking_Report_Line reportLine, final MaterialTrackingReportAgregationItem items) { materialTrackingReportBL.createMaterialTrackingReportLineAllocation(reportLine, items); if (items.getPPOrder() != null) { // issue Side reportLine.setQtyIssued(reportLine.getQtyIssued().add(items.getQty())); } else { // receipt side reportLine.setQtyReceived(reportLine.getQtyReceived().add(items.getQty())); } InterfaceWrapperHelper.save(reportLine); } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\process\CreateMaterialTrackingReportLineFromMaterialTrackingRefAggregator.java
1
请在Spring Boot框架中完成以下Java代码
public ProducerFactory<String, String> producerFactory() { Map<String, Object> configProps = new HashMap<>(); configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); configProps.put(ProducerConfig.MAX_REQUEST_SIZE_CONFIG, "20971520"); return new DefaultKafkaProducerFactory<>(configProps); } @Bean public KafkaTemplate<String, String> kafkaTemplate() { return new KafkaTemplate<>(producerFactory()); } @Bean public ProducerFactory<String, BookEvent> bookProducerFactory() {
Map<String, Object> configProps = new HashMap<>(); configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); configProps.put(JsonSerializer.TYPE_MAPPINGS, "bookEvent:com.baeldung.spring.kafka.multiplelisteners.BookEvent"); return new DefaultKafkaProducerFactory<>(configProps); } @Bean public KafkaTemplate<String, BookEvent> bookKafkaTemplate() { return new KafkaTemplate<>(bookProducerFactory()); } }
repos\tutorials-master\spring-kafka-2\src\main\java\com\baeldung\spring\kafka\multiplelisteners\KafkaProducerConfig.java
2
请完成以下Java代码
static CursorStrategy<ScrollPosition> defaultCursorStrategy() { return CursorStrategy.withEncoder(new ScrollPositionCursorStrategy(), CursorEncoder.base64()); } static int defaultScrollCount() { return 20; } static Function<Boolean, ScrollPosition> defaultScrollPosition() { return (forward) -> ScrollPosition.offset(); } static ScrollSubrange getScrollSubrange( DataFetchingEnvironment env, CursorStrategy<ScrollPosition> cursorStrategy) {
boolean forward = true; String cursor = env.getArgument("after"); Integer count = env.getArgument("first"); if (cursor == null && count == null) { cursor = env.getArgument("before"); count = env.getArgument("last"); if (cursor != null || count != null) { forward = false; } } ScrollPosition pos = (cursor != null) ? cursorStrategy.fromCursor(cursor) : null; return ScrollSubrange.create(pos, count, forward); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\query\RepositoryUtils.java
1
请在Spring Boot框架中完成以下Java代码
public String getBankAccountName() { return bankAccountName; } /** 银行卡开户名eg:张三 **/ public void setBankAccountName(String bankAccountName) { this.bankAccountName = bankAccountName; } /** 银行卡卡号 **/ public String getBankAccountNo() { return bankAccountNo; } /** 银行卡卡号 **/ public void setBankAccountNo(String bankAccountNo) { this.bankAccountNo = bankAccountNo; } /** 银行编号eg:ICBC **/ public String getBankCode() { return bankCode; } /** 银行编号eg:ICBC **/ public void setBankCode(String bankCode) { this.bankCode = bankCode; } /** 银行卡类型 **/ public String getBankAccountType() { return bankAccountType; } /** 银行卡类型 **/ public void setBankAccountType(String bankAccountType) { this.bankAccountType = bankAccountType; } /** 证件类型 **/ public String getCardType() { return cardType; } /** 证件类型 **/ public void setCardType(String cardType) { this.cardType = cardType; } /** 证件号码 **/ public String getCardNo() { return cardNo; } /** 证件号码 **/ public void setCardNo(String cardNo) { this.cardNo = cardNo; } /** 手机号码 **/ public String getMobileNo() { return mobileNo; }
/** 手机号码 **/ public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo; } /** 银行名称 **/ public String getBankName() { return bankName; } /** 银行名称 **/ public void setBankName(String bankName) { this.bankName = bankName; } /** 用户编号 **/ public String getUserNo() { return userNo; } /** 用户编号 **/ public void setUserNo(String userNo) { this.userNo = userNo; } /** 是否默认 **/ public String getIsDefault() { return isDefault; } /** 是否默认 **/ public void setIsDefault(String isDefault) { this.isDefault = isDefault; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserBankAccount.java
2
请在Spring Boot框架中完成以下Java代码
public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getIdNo() { return idNo; } public void setIdNo(String idNo) { this.idNo = idNo; } public String getBankAccountNo() { return bankAccountNo; } public void setBankAccountNo(String bankAccountNo) { this.bankAccountNo = bankAccountNo; } public String getOpenId() { return openId; } public void setOpenId(String openId) {
this.openId = openId; } public String getPayWayCode() { return payWayCode; } public void setPayWayCode(String payWayCode) { this.payWayCode = payWayCode; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } 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\AuthProgramInitParamVo.java
2
请完成以下Java代码
public int getM_Picking_Job_Step_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Step_ID); } @Override public void setQtyReserved (final BigDecimal QtyReserved) { set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } @Override public de.metas.handlingunits.model.I_M_HU getVHU() { return get_ValueAsPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override
public void setVHU(final de.metas.handlingunits.model.I_M_HU VHU) { set_ValueFromPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class, VHU); } @Override public void setVHU_ID (final int VHU_ID) { if (VHU_ID < 1) set_Value (COLUMNNAME_VHU_ID, null); else set_Value (COLUMNNAME_VHU_ID, VHU_ID); } @Override public int getVHU_ID() { return get_ValueAsInt(COLUMNNAME_VHU_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Reservation.java
1
请完成以下Java代码
public TimerJobQueryImpl jobWithoutTenantId() { this.withoutTenantId = true; return this; } // sorting ////////////////////////////////////////// public TimerJobQuery orderByJobDuedate() { return orderBy(JobQueryProperty.DUEDATE); } public TimerJobQuery orderByExecutionId() { return orderBy(JobQueryProperty.EXECUTION_ID); } public TimerJobQuery orderByJobId() { return orderBy(JobQueryProperty.JOB_ID); } public TimerJobQuery orderByProcessInstanceId() { return orderBy(JobQueryProperty.PROCESS_INSTANCE_ID); } public TimerJobQuery orderByJobRetries() { return orderBy(JobQueryProperty.RETRIES); } public TimerJobQuery orderByTenantId() { return orderBy(JobQueryProperty.TENANT_ID); } // results ////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext.getTimerJobEntityManager().findJobCountByQueryCriteria(this); } public List<Job> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext.getTimerJobEntityManager().findJobsByQueryCriteria(this, page); } // getters ////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public String getExecutionId() { return executionId; } public boolean getRetriesLeft() { return retriesLeft; } public boolean getExecutable() { return executable; } public Date getNow() { return Context.getProcessEngineConfiguration().getClock().getCurrentTime(); } public boolean isWithException() { return withException; } public String getExceptionMessage() { return exceptionMessage;
} public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public static long getSerialversionuid() { return serialVersionUID; } public String getId() { return id; } public String getProcessDefinitionId() { return processDefinitionId; } public boolean isOnlyTimers() { return onlyTimers; } public boolean isOnlyMessages() { return onlyMessages; } public Date getDuedateHigherThan() { return duedateHigherThan; } public Date getDuedateLowerThan() { return duedateLowerThan; } public Date getDuedateHigherThanOrEqual() { return duedateHigherThanOrEqual; } public Date getDuedateLowerThanOrEqual() { return duedateLowerThanOrEqual; } public boolean isNoRetriesLeft() { return noRetriesLeft; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TimerJobQueryImpl.java
1
请完成以下Java代码
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException{} public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0];} } }; public static void main(String... args) { try { new EmailService("smtp.mailtrap.io", 25, "87ba3d9555fae8", "91cb4379af43ed").sendMail(); } catch (Exception e) { e.printStackTrace(); } } public void sendMail() throws Exception { Session session = getSession(); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("from@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com")); message.setSubject("Mail Subject"); String msg = "This is my first email using JavaMailer"; message.setContent(getMultipart(msg)); Transport.send(message); } public void sendMailToMultipleRecipients() throws Exception { Session session = getSession(); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("from@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com, to1@gmail.com")); message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("to2@gmail.com, to3@gmail.com")); message.setSubject("Mail Subject"); String msg = "This is my first email using JavaMailer"; message.setContent(getMultipart(msg)); Transport.send(message); } private Multipart getMultipart(String msg) throws Exception { MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(msg, "text/html; charset=utf-8"); String msgStyled = "This is my <b style='color:red;'>bold-red email</b> using JavaMailer"; MimeBodyPart mimeBodyPartWithStyledText = new MimeBodyPart(); mimeBodyPartWithStyledText.setContent(msgStyled, "text/html; charset=utf-8"); MimeBodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.attachFile(getFile());
Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); multipart.addBodyPart(mimeBodyPartWithStyledText); multipart.addBodyPart(attachmentBodyPart); return multipart; } private Session getSession() { Session session = Session.getInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); return session; } private File getFile() throws Exception { URI uri = this.getClass() .getClassLoader() .getResource("attachment.txt") .toURI(); return new File(uri); } }
repos\tutorials-master\core-java-modules\core-java-networking\src\main\java\com\baeldung\mail\EmailService.java
1
请完成以下Java代码
public void setC_CreditLimit_Type_ID (int C_CreditLimit_Type_ID) { if (C_CreditLimit_Type_ID < 1) set_ValueNoCheck (COLUMNNAME_C_CreditLimit_Type_ID, null); else set_ValueNoCheck (COLUMNNAME_C_CreditLimit_Type_ID, Integer.valueOf(C_CreditLimit_Type_ID)); } /** Get Credit Limit Type. @return Credit Limit Type */ @Override public int getC_CreditLimit_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_CreditLimit_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Auto Approval. @param IsAutoApproval Auto Approval */ @Override public void setIsAutoApproval (boolean IsAutoApproval) { set_Value (COLUMNNAME_IsAutoApproval, Boolean.valueOf(IsAutoApproval)); } /** Get Auto Approval. @return Auto Approval */ @Override public boolean isAutoApproval () { Object oo = get_Value(COLUMNNAME_IsAutoApproval); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); }
return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CreditLimit_Type.java
1
请完成以下Java代码
public boolean isStateChangeUnprocessed() { return stateChangeUnprocessed; } @Override public void setStateChangeUnprocessed(boolean stateChangeUnprocessed) { this.stateChangeUnprocessed = stateChangeUnprocessed; } @Override public Map<String, Object> getPlanItemInstanceLocalVariables() { Map<String, Object> variables = new HashMap<>(); if (queryVariables != null) { for (VariableInstance variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getSubScopeId() != null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } @Override public List<VariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new VariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<VariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; }
@Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("PlanItemInstance with id: ") .append(id); if (getName() != null) { stringBuilder.append(", name: ").append(getName()); } stringBuilder.append(", definitionId: ") .append(planItemDefinitionId) .append(", state: ") .append(state); if (elementId != null) { stringBuilder.append(", elementId: ").append(elementId); } stringBuilder .append(", caseInstanceId: ") .append(caseInstanceId) .append(", caseDefinitionId: ") .append(caseDefinitionId); if (StringUtils.isNotEmpty(tenantId)) { stringBuilder.append(", tenantId=").append(tenantId); } return stringBuilder.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\PlanItemInstanceEntityImpl.java
1
请完成以下Java代码
public OPERATION getOperation() { return OPERATION.parse(operation); } public void setOperation(final OPERATION operation) { this.operation = operation.getValue(); } public long getTimestamp() { return timestamp; } public void setTimestamp(final long timestamp) { this.timestamp = timestamp; } public long getCreatedDate() { return createdDate; } public void setCreatedDate(final long createdDate) { this.createdDate = createdDate; } public long getModifiedDate() { return modifiedDate; } public void setModifiedDate(final long modifiedDate) { this.modifiedDate = modifiedDate; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(final String createdBy) { this.createdBy = createdBy; } public String getModifiedBy() { return modifiedBy; } public void setModifiedBy(final String modifiedBy) { this.modifiedBy = modifiedBy; } public void setOperation(final String operation) { this.operation = operation; } @Override public int hashCode() { final int prime = 31; int result = 1;
result = prime * result + ((name == null) ? 0 : name.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 Bar other = (Bar) obj; if (name == null) { return other.name == null; } else return name.equals(other.name); } @Override public String toString() { return "Bar [name=" + name + "]"; } @PrePersist public void onPrePersist() { LOGGER.info("@PrePersist"); audit(OPERATION.INSERT); } @PreUpdate public void onPreUpdate() { LOGGER.info("@PreUpdate"); audit(OPERATION.UPDATE); } @PreRemove public void onPreRemove() { LOGGER.info("@PreRemove"); audit(OPERATION.DELETE); } private void audit(final OPERATION operation) { setOperation(operation); setTimestamp((new Date()).getTime()); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\persistence\model\Bar.java
1
请完成以下Java代码
protected HttpHandler getHttpHandler() { // Use bean names so that we don't consider the hierarchy String[] beanNames = getBeanFactory().getBeanNamesForType(HttpHandler.class); if (beanNames.length == 0) { throw new ApplicationContextException( "Unable to start ReactiveWebApplicationContext due to missing HttpHandler bean."); } if (beanNames.length > 1) { throw new ApplicationContextException( "Unable to start ReactiveWebApplicationContext due to multiple HttpHandler beans : " + StringUtils.arrayToCommaDelimitedString(beanNames)); } return getBeanFactory().getBean(beanNames[0], HttpHandler.class); } @Override protected void doClose() { if (isActive()) { AvailabilityChangeEvent.publish(this, ReadinessState.REFUSING_TRAFFIC); } super.doClose(); WebServer webServer = getWebServer(); if (webServer != null) { webServer.destroy();
} } /** * Returns the {@link WebServer} that was created by the context or {@code null} if * the server has not yet been created. * @return the web server */ @Override public @Nullable WebServer getWebServer() { WebServerManager serverManager = this.serverManager; return (serverManager != null) ? serverManager.getWebServer() : null; } @Override public @Nullable String getServerNamespace() { return this.serverNamespace; } @Override public void setServerNamespace(@Nullable String serverNamespace) { this.serverNamespace = serverNamespace; } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\reactive\context\ReactiveWebServerApplicationContext.java
1
请完成以下Java代码
public class Flowable5TaskFormDataWrapper implements TaskFormData { private org.activiti.engine.form.TaskFormData activiti5TaskFormData; public Flowable5TaskFormDataWrapper(org.activiti.engine.form.TaskFormData activiti5TaskFormData) { this.activiti5TaskFormData = activiti5TaskFormData; } @Override public String getFormKey() { return activiti5TaskFormData.getFormKey(); } @Override public String getDeploymentId() { return activiti5TaskFormData.getDeploymentId();
} @Override public List<FormProperty> getFormProperties() { return activiti5TaskFormData.getFormProperties(); } @Override public Task getTask() { if (activiti5TaskFormData.getTask() != null) { return new Flowable5TaskWrapper(activiti5TaskFormData.getTask()); } return null; } }
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5TaskFormDataWrapper.java
1
请完成以下Java代码
public void setRegionName (java.lang.String RegionName) { set_Value (COLUMNNAME_RegionName, RegionName); } /** Get Region. @return Name der Region */ @Override public java.lang.String getRegionName () { return (java.lang.String)get_Value(COLUMNNAME_RegionName); } /** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override
public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Gültig bis inklusiv (letzter Tag) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Gültig bis. @return Gültig bis inklusiv (letzter Tag) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Postal.java
1
请完成以下Java代码
public class Student { private StudentGrade grade; //new data representation // private int grade; //old data representation private String name; private int age; public void setGrade(int grade) { this.grade = new StudentGrade(grade); } public int getGrade() { return this.grade.getGrade().intValue(); //int is returned for backward compatibility } public Connection getConnection() throws SQLException { final String URL = "jdbc:h2:~/test"; return DriverManager.getConnection(URL, "sa", ""); } public void setAge(int age) { if (age < 0 || age > 150) { throw new IllegalArgumentException(); } this.age = age; } public int getAge() {
return age; } @Override public String toString() { return this.name; } private class StudentGrade { private BigDecimal grade = BigDecimal.ZERO; private Date updatedAt; public StudentGrade(int grade) { this.grade = new BigDecimal(grade); this.updatedAt = new Date(); } public BigDecimal getGrade() { return grade; } public Date getDate() { return updatedAt; } } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-modifiers-2\src\main\java\com\baeldung\publicmodifier\Student.java
1
请完成以下Java代码
public long getCountErrors() { return countErrors; } @Override public void incrementCountErrors() { countErrors++; } @Override public long getQueueSize() { return queueSize; } @Override public void incrementQueueSize() { queueSize++;
} @Override public void decrementQueueSize() { queueSize--; } @Override public long getCountSkipped() { return countSkipped; } @Override public void incrementCountSkipped() { countSkipped++; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\QueueProcessorStatistics.java
1
请完成以下Java代码
public XML addElement (String element) { addElementToRegistry (element); return (this); } /** * Adds an Element to the element. * * @param hashcode * name of element for hash table * @param element * Adds an Element to the element. */ public XML addElement (String hashcode, Element element) { addElementToRegistry (hashcode, element); return (this); } /** * Adds an Element to the element. * * @param hashcode * name of element for hash table * @param element * Adds an Element to the element. */ public XML addElement (String hashcode, String element) { addElementToRegistry (hashcode, element); return (this); } /** * Add an element to the valuie of &lt;&gt;VALUE&lt;/&gt; * * @param element * the value of &lt;&gt;VALUE&lt;/&gt; */ public XML addElement (Element element) { addElementToRegistry (element); return (this); } /** * Removes an Element from the element. * * @param hashcode * the name of the element to be removed. */ public XML removeElement (String hashcode) { removeElementFromRegistry (hashcode); return (this); } public boolean getNeedLineBreak () { boolean linebreak = true; java.util.Enumeration en = elements (); // if this tag has one child, and it's a String, then don't
// do any linebreaks to preserve whitespace while (en.hasMoreElements ()) { Object obj = en.nextElement (); if (obj instanceof StringElement) { linebreak = false; break; } } return linebreak; } public boolean getBeginEndModifierDefined () { boolean answer = false; if (!this.getNeedClosingTag ()) answer = true; return answer; } public char getBeginEndModifier () { return '/'; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xml\XML.java
1
请在Spring Boot框架中完成以下Java代码
public class DelaySender { @Autowired private AmqpTemplate rabbitTemplate; /** * 在消息上设置时间 * @param msg */ public void sendDelayMsg(Msg msg) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(msg.getId() + " 延迟消息发送时间:" + sdf.format(new Date())); rabbitTemplate.convertAndSend(RabbitConfig.DELAY_EXCHANGE_NAME, "delay", msg, new MessagePostProcessor() { @Override public Message postProcessMessage(Message message) throws AmqpException { message.getMessageProperties().setExpiration(msg.getTtl() + "");
return message; } }); } /** * 在队列上设置时间,则消息不需要任何处理 * @param msg */ public void sendDelayQueue(Msg msg) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(msg.getId() + " 延迟队列消息发送时间:" + sdf.format(new Date())); rabbitTemplate.convertAndSend(RabbitConfig.DELAY_QUEUE_EXCHANGE_NAME,"delay", msg); } }
repos\spring-boot-quick-master\quick-rabbitmq\src\main\java\com\quick\mq\scenes\delayTask\DelaySender.java
2
请完成以下Java代码
public String getEventHandlerType() { return EVENT_HANDLER_TYPE; } @SuppressWarnings("unchecked") @Override public void handleEvent(EventSubscriptionEntity eventSubscription, Object payload, CommandContext commandContext) { if (eventSubscription.getExecutionId() != null) { super.handleEvent(eventSubscription, payload, commandContext); } else if (eventSubscription.getProcessDefinitionId() != null) { // Find initial flow element matching the signal start event String processDefinitionId = eventSubscription.getProcessDefinitionId(); org.flowable.bpmn.model.Process process = ProcessDefinitionUtil.getProcess(processDefinitionId); ProcessDefinition processDefinition = ProcessDefinitionUtil.getProcessDefinition(processDefinitionId); if (processDefinition.isSuspended()) { throw new FlowableException("Could not handle signal: process definition with id: " + processDefinitionId + " is suspended for " + eventSubscription); } // Start process instance via the flow element linked to the event FlowElement flowElement = process.getFlowElement(eventSubscription.getActivityId(), true); if (flowElement == null) { throw new FlowableException("Could not find matching FlowElement for " + eventSubscription); } ProcessInstanceHelper processInstanceHelper = CommandContextUtil.getProcessEngineConfiguration(commandContext).getProcessInstanceHelper();
processInstanceHelper.createAndStartProcessInstanceWithInitialFlowElement(processDefinition, null, null, null, flowElement, process, getPayloadAsMap(payload), null, null, null, true); } else if (eventSubscription.getScopeId() != null && ScopeTypes.CMMN.equals(eventSubscription.getScopeType())) { CommandContextUtil.getProcessEngineConfiguration(commandContext).getCaseInstanceService().handleSignalEvent(eventSubscription, getPayloadAsMap(payload)); } else { throw new FlowableException("Invalid signal handling: no execution nor process definition set for " + eventSubscription); } } protected Map<String, Object> getPayloadAsMap(Object payload) { Map<String, Object> variables = null; if (payload instanceof Map) { variables = (Map<String, Object>) payload; } return variables; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\event\SignalEventHandler.java
1
请完成以下Java代码
public void setRRStartDate (Timestamp RRStartDate) { set_Value (COLUMNNAME_RRStartDate, RRStartDate); } /** Get Revenue Recognition Start. @return Revenue Recognition Start Date */ public Timestamp getRRStartDate () { return (Timestamp)get_Value(COLUMNNAME_RRStartDate); } public org.compiere.model.I_C_OrderLine getRef_OrderLine() throws RuntimeException { return (org.compiere.model.I_C_OrderLine)MTable.get(getCtx(), org.compiere.model.I_C_OrderLine.Table_Name) .getPO(getRef_OrderLine_ID(), get_TrxName()); } /** Set Referenced Order Line. @param Ref_OrderLine_ID Reference to corresponding Sales/Purchase Order */ public void setRef_OrderLine_ID (int Ref_OrderLine_ID) { if (Ref_OrderLine_ID < 1) set_Value (COLUMNNAME_Ref_OrderLine_ID, null); else set_Value (COLUMNNAME_Ref_OrderLine_ID, Integer.valueOf(Ref_OrderLine_ID)); } /** Get Referenced Order Line. @return Reference to corresponding Sales/Purchase Order */ public int getRef_OrderLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Ref_OrderLine_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Ressourcenzuordnung. @param S_ResourceAssignment_ID Ressourcenzuordnung */ public void setS_ResourceAssignment_ID (int S_ResourceAssignment_ID) { if (S_ResourceAssignment_ID < 1) set_Value (COLUMNNAME_S_ResourceAssignment_ID, null); else set_Value (COLUMNNAME_S_ResourceAssignment_ID, Integer.valueOf(S_ResourceAssignment_ID)); } /** Get Ressourcenzuordnung. @return Ressourcenzuordnung */ public int getS_ResourceAssignment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceAssignment_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_C_OrderLine_Overview.java
1
请完成以下Java代码
protected void setStreamSource(StreamSource streamSource) { if (this.streamSource != null) { throw new FlowableException("invalid: multiple sources " + this.streamSource + " and " + streamSource); } this.streamSource = streamSource; } /* * ------------------- GETTERS AND SETTERS ------------------- */ public List<EventDefinitionEntity> getEventDefinitions() { return eventDefinitions; } public EventDeploymentEntity getDeployment() {
return deployment; } public void setDeployment(EventDeploymentEntity deployment) { this.deployment = deployment; } public EventModel getEventModel() { return eventModel; } public void setEventModel(EventModel eventModel) { this.eventModel = eventModel; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\parser\EventDefinitionParse.java
1
请完成以下Java代码
public class AgentLoader { private static Logger LOGGER = LoggerFactory.getLogger(AgentLoader.class); public static void run(String[] args) { String agentFilePath = "/home/adi/Desktop/agent-1.0.0-jar-with-dependencies.jar"; String applicationName = "MyAtmApplication"; //iterate all jvms and get the first one that matches our application name Optional<String> jvmProcessOpt = Optional.ofNullable(VirtualMachine.list() .stream() .filter(jvm -> { LOGGER.info("jvm:{}", jvm.displayName()); return jvm.displayName().contains(applicationName); }) .findFirst().get().id()); if(!jvmProcessOpt.isPresent()) { LOGGER.error("Target Application not found");
return; } File agentFile = new File(agentFilePath); try { String jvmPid = jvmProcessOpt.get(); LOGGER.info("Attaching to target JVM with PID: " + jvmPid); VirtualMachine jvm = VirtualMachine.attach(jvmPid); jvm.loadAgent(agentFile.getAbsolutePath()); jvm.detach(); LOGGER.info("Attached to target JVM and loaded Java agent successfully"); } catch (Exception e) { throw new RuntimeException(e); } } }
repos\tutorials-master\core-java-modules\core-java-jvm\src\main\java\com\baeldung\instrumentation\application\AgentLoader.java
1
请完成以下Java代码
public static Collector<BankStatementLineReference, ?, BankStatementLineReferenceList> collector() { return GuavaCollectors.collectUsingListAccumulator(BankStatementLineReferenceList::of); } public static final BankStatementLineReferenceList EMPTY = new BankStatementLineReferenceList(ImmutableList.of()); private final ImmutableList<BankStatementLineReference> list; private BankStatementLineReferenceList(@NonNull final Collection<BankStatementLineReference> collection) { this.list = ImmutableList.copyOf(collection); } @Override public Iterator<BankStatementLineReference> iterator() { return list.iterator(); } public Stream<BankStatementLineReference> stream() { return list.stream(); } public ImmutableSet<PaymentId> getPaymentIds() { return list.stream() .map(BankStatementLineReference::getPaymentId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet());
} public ImmutableSet<BankStatementLineId> getBankStatementLineIds() { return list.stream() .map(BankStatementLineReference::getBankStatementLineId) .collect(ImmutableSet.toImmutableSet()); } public ImmutableSet<BankStatementLineRefId> getBankStatementLineRefIds() { return list.stream() .map(BankStatementLineReference::getBankStatementLineRefId) .collect(ImmutableSet.toImmutableSet()); } public boolean isEmpty() { return list.isEmpty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\BankStatementLineReferenceList.java
1
请在Spring Boot框架中完成以下Java代码
public void execute(CommandContext commandContext) { if (isTransactionActive()) { entityManager.getTransaction().commit(); } } }; TransactionListener jpaTransactionRollbackListener = new TransactionListener() { @Override public void execute(CommandContext commandContext) { if (isTransactionActive()) { entityManager.getTransaction().rollback(); } } }; TransactionContext transactionContext = Context.getTransactionContext();
transactionContext.addTransactionListener(TransactionState.COMMITTED, jpaTransactionCommitListener); transactionContext.addTransactionListener(TransactionState.ROLLED_BACK, jpaTransactionRollbackListener); // Also, start a transaction, if one isn't started already if (!isTransactionActive()) { entityManager.getTransaction().begin(); } } } return entityManager; } private EntityManagerFactory getEntityManagerFactory() { return entityManagerFactory; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\EntityManagerSessionImpl.java
2
请完成以下Java代码
public void setC_Location(org.compiere.model.I_C_Location C_Location) { set_ValueFromPO(COLUMNNAME_C_Location_ID, org.compiere.model.I_C_Location.class, C_Location); } /** Set Anschrift. @param C_Location_ID Adresse oder Anschrift */ @Override public void setC_Location_ID (int C_Location_ID) { if (C_Location_ID < 1) set_Value (COLUMNNAME_C_Location_ID, null); else set_Value (COLUMNNAME_C_Location_ID, Integer.valueOf(C_Location_ID)); } /** Get Anschrift. @return Adresse oder Anschrift */ @Override public int getC_Location_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Location_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity
*/ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_C_Allotment.java
1
请完成以下Java代码
public final class OidcUserRefreshedEvent extends ApplicationEvent { @Serial private static final long serialVersionUID = 2657442604286019694L; private final OidcUser oldOidcUser; private final OidcUser newOidcUser; private final Authentication authentication; /** * Creates a new instance with the provided parameters. * @param accessTokenResponse the {@link OAuth2AccessTokenResponse} that triggered the * event * @param oldOidcUser the original {@link OidcUser} * @param newOidcUser the refreshed {@link OidcUser} * @param authentication the authentication result */ public OidcUserRefreshedEvent(OAuth2AccessTokenResponse accessTokenResponse, OidcUser oldOidcUser, OidcUser newOidcUser, Authentication authentication) { super(accessTokenResponse); Assert.notNull(oldOidcUser, "oldOidcUser cannot be null"); Assert.notNull(newOidcUser, "newOidcUser cannot be null"); Assert.notNull(authentication, "authentication cannot be null"); this.oldOidcUser = oldOidcUser; this.newOidcUser = newOidcUser; this.authentication = authentication; } /** * Returns the {@link OAuth2AccessTokenResponse} that triggered the event. * @return the access token response */ public OAuth2AccessTokenResponse getAccessTokenResponse() { return (OAuth2AccessTokenResponse) this.getSource(); } /** * Returns the original {@link OidcUser}. * @return the original user */ public OidcUser getOldOidcUser() { return this.oldOidcUser;
} /** * Returns the refreshed {@link OidcUser}. * @return the refreshed user */ public OidcUser getNewOidcUser() { return this.newOidcUser; } /** * Returns the authentication result. * @return the authentication result */ public Authentication getAuthentication() { return this.authentication; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\authentication\event\OidcUserRefreshedEvent.java
1
请完成以下Java代码
public class TraceHUTrxListener implements IHUTrxListener { private static final Logger logger = LogManager.getLogger(TraceHUTrxListener.class); public static TraceHUTrxListener INSTANCE = new TraceHUTrxListener(); private TraceHUTrxListener() { } @Override public void huParentChanged( @NonNull final I_M_HU hu, @Nullable final I_M_HU_Item parentHUItemOld) { final HUTraceEventsService huTraceEventService = HUTraceModuleInterceptor.INSTANCE.getHUTraceEventsService(); huTraceEventService.createAndAddForHuParentChanged(hu, parentHUItemOld); } @Override public void afterTrxProcessed( @NonNull final IReference<I_M_HU_Trx_Hdr> trxHdrRef, @NonNull final List<I_M_HU_Trx_Line> trxLines) { final I_M_HU_Trx_Hdr trxHdr = trxHdrRef.getValue(); // we'll need the record, not the reference that might be stale after the commit. if (Adempiere.isUnitTestMode()) { afterTrxProcessed0(trxLines, trxHdr); // in unit test mode, there won't be a commit return; } final ITrxManager trxManager = Services.get(ITrxManager.class); final ITrxListenerManager trxListenerManager = trxManager.getTrxListenerManager(ITrx.TRXNAME_ThreadInherited);
trxListenerManager .newEventListener(TrxEventTiming.AFTER_COMMIT) .registerHandlingMethod(innerTrx -> { // do a brand new transaction in which we execute our things, // because basically 'innerTrx' is already done and might even already be closed final ITrxManager innerTrxManager = Services.get(ITrxManager.class); innerTrxManager.runInNewTrx(localTrxName -> { // we need to update our subjects' trxNames, because the one this listener method was called with was committed and therefore is not valid anymore setTrxName(trxHdr, localTrxName); trxLines.forEach(l -> setTrxName(l, localTrxName)); afterTrxProcessed0(trxLines, trxHdr); }); }); logger.debug("Enqueued M_HU_Trx_Hdr and _M_HU_Trx_Lines for HU-tracing after the next commit; trxHdr={}; trxLines={}", trxHdr, trxLines); } private void afterTrxProcessed0( @NonNull final List<I_M_HU_Trx_Line> trxLines, @NonNull final I_M_HU_Trx_Hdr trxHdr) { logger.debug("Invoke HUTraceEventsService; trxHdr={}; trxLines={}", trxHdr, trxLines); final HUTraceEventsService huTraceEventService = HUTraceModuleInterceptor.INSTANCE.getHUTraceEventsService(); huTraceEventService.createAndAddFor(trxHdr, trxLines); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\trace\interceptor\TraceHUTrxListener.java
1
请完成以下Java代码
private static final class UserMenuFavorites { private static Builder builder() { return new Builder(); } private final UserId adUserId; private final Set<Integer> menuIds = ConcurrentHashMap.newKeySet(); private UserMenuFavorites(final Builder builder) { adUserId = builder.adUserId; Check.assumeNotNull(adUserId, "Parameter adUserId is not null"); menuIds.addAll(builder.menuIds); } public UserId getAdUserId() { return adUserId; } public boolean isFavorite(final MenuNode menuNode) { return menuIds.contains(menuNode.getAD_Menu_ID()); } public void setFavorite(final int adMenuId, final boolean favorite) { if (favorite) { menuIds.add(adMenuId); } else { menuIds.remove(adMenuId); } } public static class Builder { private UserId adUserId; private final Set<Integer> menuIds = new HashSet<>(); private Builder()
{ } public MenuTreeRepository.UserMenuFavorites build() { return new UserMenuFavorites(this); } public Builder adUserId(final UserId adUserId) { this.adUserId = adUserId; return this; } public Builder addMenuIds(final List<Integer> adMenuIds) { if (adMenuIds.isEmpty()) { return this; } menuIds.addAll(adMenuIds); return this; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\MenuTreeRepository.java
1
请完成以下Java代码
private Optional<Quantity> getProductGrossWeight(@NonNull final ProductId productId) { return productWeights.computeIfAbsent(productId, productBL::getGrossWeight); } public Optional<Quantity> calculateWeightInKg(@NonNull final I_M_HU hu) { return weightSourceTypes.calculateWeight(weightSourceType -> calculateWeightInKg(hu, weightSourceType)); } private Optional<Quantity> calculateWeightInKg(@NonNull final I_M_HU hu, @NonNull final ShippingWeightSourceType weightSourceType) { switch (weightSourceType) { case CatchWeight: return Optional.empty(); case ProductWeight: return calculateWeight_usingNominalGrossWeight(hu); case HUWeightGross: return calculateWeight_usingWeightGrossAttribute(hu); default: throw new AdempiereException("Unknown weight source type: " + weightSourceType); } } private Optional<Quantity> calculateWeight_usingNominalGrossWeight(final I_M_HU hu) { Quantity result = null; for (final IHUProductStorage huProductStorage : handlingUnitsBL.getStorageFactory().getStorage(hu).getProductStorages()) { final Quantity huProductStorageWeight = calculateWeight_usingNominalGrossWeight(huProductStorage).orElse(null); if (huProductStorageWeight == null) { return Optional.empty(); } result = Quantity.addNullables(result, huProductStorageWeight); } return Optional.ofNullable(result); } private Optional<Quantity> calculateWeight_usingNominalGrossWeight(final IHUProductStorage huProductStorage) { final ProductId productId = huProductStorage.getProductId(); final Quantity productWeight = getProductGrossWeight(productId).orElse(null); if (productWeight == null) { return Optional.empty();
} final Quantity qty = uomConversionBL.convertToProductUOM(huProductStorage.getQty(), productId); final Quantity weight = productWeight.multiply(qty.toBigDecimal()).roundToUOMPrecision(); return Optional.of(weight); } private Optional<Quantity> calculateWeight_usingWeightGrossAttribute(final I_M_HU hu) { final IMutableHUContext huContext = handlingUnitsBL.createMutableHUContext(); final IAttributeStorage huAttributes = huContext.getHUAttributeStorageFactory().getAttributeStorage(hu); final IWeightable weightable = Weightables.wrap(huAttributes); if (!weightable.hasWeightGross()) { return Optional.empty(); } final Quantity weightGross = weightable.getWeightGrossAsQuantity(); return weightGross.signum() > 0 ? Optional.of(weightGross) : Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipping\weighting\ShippingWeightCalculator.java
1
请完成以下Java代码
private static Set<HuId> extractHUIds(final Collection<I_M_HU> hus) { if (hus == null || hus.isEmpty()) { return ImmutableSet.of(); } return hus.stream() .filter(Objects::nonNull) .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(Collectors.toSet()); } @Override public void notifyRecordsChanged( @NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend) { // TODO: notifyRecordsChanged: // get M_HU_IDs from recordRefs, // find the top level records from this view which contain our HUs // invalidate those top levels only final Set<HuId> huIdsToCheck = recordRefs .streamIds(I_M_HU.Table_Name, HuId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); if (huIdsToCheck.isEmpty()) { return; } final boolean containsSomeRecords = rowsBuffer.containsAnyOfHUIds(huIdsToCheck); if (!containsSomeRecords) { return; } invalidateAll(); } @Override public Stream<HUEditorRow> streamByIds(final DocumentIdsSelection rowIds) { if (rowIds.isEmpty()) { return Stream.empty(); } return streamByIds(HUEditorRowFilter.onlyRowIds(rowIds)); } public Stream<HUEditorRow> streamByIds(final HUEditorRowFilter filter) { return rowsBuffer.streamByIdsExcludingIncludedRows(filter); } /** * @return top level rows and included rows recursive stream which are matching the given filter */ public Stream<HUEditorRow> streamAllRecursive(final HUEditorRowFilter filter)
{ return rowsBuffer.streamAllRecursive(filter); } /** * @return true if there is any top level or included row which is matching given filter */ public boolean matchesAnyRowRecursive(final HUEditorRowFilter filter) { return rowsBuffer.matchesAnyRowRecursive(filter); } @Override public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass) { final Set<HuId> huIds = streamByIds(rowIds) .filter(HUEditorRow::isPureHU) .map(HUEditorRow::getHuId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); if (huIds.isEmpty()) { return ImmutableList.of(); } final List<I_M_HU> hus = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU.class) .addInArrayFilter(I_M_HU.COLUMN_M_HU_ID, huIds) .create() .list(I_M_HU.class); return InterfaceWrapperHelper.createList(hus, modelClass); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorView.java
1
请在Spring Boot框架中完成以下Java代码
public CommandLineRunner demo(BookRepository bookRepository) { return (args) -> { Book b1 = new Book("Book A", BigDecimal.valueOf(9.99), LocalDate.of(2023, 8, 31)); Book b2 = new Book("Book B", BigDecimal.valueOf(19.99), LocalDate.of(2023, 7, 31)); Book b3 = new Book("Book C", BigDecimal.valueOf(29.99), LocalDate.of(2023, 6, 10)); Book b4 = new Book("Book D", BigDecimal.valueOf(39.99), LocalDate.of(2023, 5, 5)); // save a few books, ID auto increase, expect 1, 2, 3, 4 bookRepository.save(b1); bookRepository.save(b2); bookRepository.save(b3); bookRepository.save(b4); // find all books log.info("findAll(), expect 4 books"); log.info("-------------------------------"); for (Book book : bookRepository.findAll()) { log.info(book.toString()); } log.info("\n"); // find book by ID Optional<Book> optionalBook = bookRepository.findById(1L); optionalBook.ifPresent(obj -> { log.info("Book found with findById(1L):"); log.info("--------------------------------"); log.info(obj.toString()); log.info("\n"); }); // find book by title log.info("Book found with findByTitle('Book B')"); log.info("--------------------------------------------"); bookRepository.findByTitle("Book C").forEach(b -> { log.info(b.toString()); log.info("\n"); });
// find book by published date after log.info("Book found with findByPublishedDateAfter(), after 2023/7/1"); log.info("--------------------------------------------"); bookRepository.findByPublishedDateAfter(LocalDate.of(2023, 7, 1)).forEach(b -> { log.info(b.toString()); log.info("\n"); }); // delete a book bookRepository.deleteById(2L); log.info("Book delete where ID = 2L"); log.info("--------------------------------------------"); // find all books log.info("findAll() again, expect 3 books"); log.info("-------------------------------"); for (Book book : bookRepository.findAll()) { log.info(book.toString()); } log.info("\n"); }; } }
repos\spring-boot-master\spring-data-jpa\src\main\java\com\mkyong\MainApplication.java
2
请完成以下Java代码
private JavaMailSenderImpl createMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(this.config.getSmtpHost()); mailSender.setPort(this.config.getSmtpPort()); mailSender.setUsername(this.config.getUsername()); mailSender.setPassword(this.config.getPassword()); mailSender.setJavaMailProperties(createJavaMailProperties()); return mailSender; } private Properties createJavaMailProperties() { Properties javaMailProperties = new Properties(); String protocol = this.config.getSmtpProtocol(); javaMailProperties.put("mail.transport.protocol", protocol); javaMailProperties.put(MAIL_PROP + protocol + ".host", this.config.getSmtpHost()); javaMailProperties.put(MAIL_PROP + protocol + ".port", this.config.getSmtpPort() + ""); javaMailProperties.put(MAIL_PROP + protocol + ".timeout", this.config.getTimeout() + ""); javaMailProperties.put(MAIL_PROP + protocol + ".auth", String.valueOf(StringUtils.isNotEmpty(this.config.getUsername())));
javaMailProperties.put(MAIL_PROP + protocol + ".starttls.enable", Boolean.valueOf(this.config.isEnableTls()).toString()); if (this.config.isEnableTls() && StringUtils.isNoneEmpty(this.config.getTlsVersion())) { javaMailProperties.put(MAIL_PROP + protocol + ".ssl.protocols", this.config.getTlsVersion()); } if (this.config.isEnableProxy()) { javaMailProperties.put(MAIL_PROP + protocol + ".proxy.host", config.getProxyHost()); javaMailProperties.put(MAIL_PROP + protocol + ".proxy.port", config.getProxyPort()); if (StringUtils.isNoneEmpty(config.getProxyUser())) { javaMailProperties.put(MAIL_PROP + protocol + ".proxy.user", config.getProxyUser()); } if (StringUtils.isNoneEmpty(config.getProxyPassword())) { javaMailProperties.put(MAIL_PROP + protocol + ".proxy.password", config.getProxyPassword()); } } return javaMailProperties; } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\mail\TbSendEmailNode.java
1
请完成以下Java代码
public class DBRes_ro extends ListResourceBundle { /** Data */ static final Object[][] contents = new String[][]{ { "CConnectionDialog", "Conexiune" }, { "Name", "Nume" }, { "AppsHost", "Server de aplica\u0163ie" }, { "AppsPort", "Port de aplica\u0163ie" }, { "TestApps", "Testare a serverului de aplica\u0163ie" }, { "DBHost", "Server de baz\u0103 de date" }, { "DBPort", "Port de baz\u0103 de date" }, { "DBName", "Numele bazei de date" }, { "DBUidPwd", "Utilizator / parol\u0103" }, { "ViaFirewall", "Prin firewall" }, { "FWHost", "Gazd\u0103 de firewall" }, { "FWPort", "Port de firewall" }, { "TestConnection", "Testare a bazei de date" }, { "Type", "Tip al bazei de date" }, { "BequeathConnection", "Cedare de conexiune" },
{ "Overwrite", "Suprascriere" }, { "ConnectionProfile", "Profil conexiune" }, { "LAN", "LAN" }, { "TerminalServer", "Terminal Server" }, { "VPN", "VPN" }, { "WAN", "WAN" }, { "ConnectionError", "Eroare de conexiune" }, { "ServerNotActive", "Serverul este inactiv" } }; /** * Get Contents * @return contents */ public Object[][] getContents() { return contents; } // getContent } // Res
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\connectiondialog\i18n\DBRes_ro.java
1
请完成以下Java代码
public @Nullable PropertySource<?> apply(@Nullable PropertySource<?> propertySource) { if (propertySource instanceof EnumerablePropertySource) { EnumerablePropertySource<?> enumerablePropertySource = (EnumerablePropertySource<?>) propertySource; String[] propertyNames = enumerablePropertySource.getPropertyNames(); Arrays.sort(propertyNames); logProperties(Arrays.asList(propertyNames), enumerablePropertySource::getProperty); } return propertySource; } } // The PropertySource may not be enumerable but may use a Map as its source. protected class MapPropertySourceLoggingFunction extends AbstractPropertySourceLoggingFunction { @Override @SuppressWarnings("unchecked") public @Nullable PropertySource<?> apply(@Nullable PropertySource<?> propertySource) { if (!(propertySource instanceof EnumerablePropertySource)) {
Object source = propertySource != null ? propertySource.getSource() : null; if (source instanceof Map) { Map<String, Object> map = new TreeMap<>((Map<String, Object>) source); logProperties(map.keySet(), map::get); } } return propertySource; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\context\logging\EnvironmentLoggingApplicationListener.java
1
请完成以下Java代码
public class FormFieldImpl implements FormField { protected boolean businessKey; protected String id; protected String label; protected FormType type; protected Object defaultValue; protected TypedValue value; protected List<FormFieldValidationConstraint> validationConstraints = new ArrayList<FormFieldValidationConstraint>(); protected Map<String, String> properties = new HashMap<String, String>(); // getters / setters /////////////////////////////////////////// public String getId() { return id; } public void setId(String id) { this.id = id; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public FormType getType() { return type; } public String getTypeName() { return type.getName(); } public void setType(FormType type) { this.type = type; } public Object getDefaultValue() { return defaultValue; } public TypedValue getValue() { return value; }
public void setDefaultValue(Object defaultValue) { this.defaultValue = defaultValue; } public void setValue(TypedValue value) { this.value = value; } public Map<String, String> getProperties() { return properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; } public List<FormFieldValidationConstraint> getValidationConstraints() { return validationConstraints; } public void setValidationConstraints(List<FormFieldValidationConstraint> validationConstraints) { this.validationConstraints = validationConstraints; } @Override public boolean isBusinessKey() { return businessKey; } public void setBusinessKey(boolean businessKey) { this.businessKey = businessKey; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\FormFieldImpl.java
1
请完成以下Java代码
public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } @Override public String toString() { return this.getClass().getSimpleName() + "[taskId=" + taskId + ", deploymentId=" + deploymentId + ", processDefinitionKey=" + processDefinitionKey + ", jobId=" + jobId + ", jobDefinitionId=" + jobDefinitionId + ", batchId=" + batchId + ", operationId=" + operationId + ", operationType=" + operationType + ", userId=" + userId + ", timestamp=" + timestamp + ", property=" + property
+ ", orgValue=" + orgValue + ", newValue=" + newValue + ", id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", processInstanceId=" + processInstanceId + ", externalTaskId=" + externalTaskId + ", tenantId=" + tenantId + ", entityType=" + entityType + ", category=" + category + ", annotation=" + annotation + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\UserOperationLogEntryEventEntity.java
1
请完成以下Java代码
public class UnixTimeUtils { private UnixTimeUtils() { } public static Date dateFrom(long timestamp) { return new Date(timestamp); } public static Calendar calendarFrom(long timestamp) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(timestamp); return calendar; } public static Instant fromNanos(long timestamp) { long seconds = timestamp / 1_000_000_000; long nanos = timestamp % 1_000_000_000; return Instant.ofEpochSecond(seconds, nanos); } public static Instant fromTimestamp(long timestamp) { return Instant.ofEpochMilli(millis(timestamp)); } public static String format(Instant instant) { LocalDateTime time = localTimeUtc(instant); return time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); }
public static LocalDateTime localTimeUtc(Instant instant) { return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); } private static long millis(long timestamp) { if (timestamp >= 1E16 || timestamp <= -1E16) { return timestamp / 1_000_000; } if (timestamp >= 1E14 || timestamp <= -1E14) { return timestamp / 1_000; } if (timestamp >= 1E11 || timestamp <= -3E10) { return timestamp; } return timestamp * 1_000; } }
repos\tutorials-master\core-java-modules\core-java-date-operations-3\src\main\java\com\baeldung\unixtime\UnixTimeUtils.java
1
请完成以下Java代码
public class Employee { private Integer employeeId; private String firstName; private String lastName; private Integer age; private Role role; public Employee() { } public Employee(Integer employeeId, String firstName, String lastName, Integer age, Role role) { this.employeeId = employeeId; this.firstName = firstName; this.lastName = lastName; this.age = age; this.role = role; } public Integer getEmployeeId() { return employeeId; } public void setEmployeeId(Integer employeeId) { this.employeeId = employeeId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName;
} public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-client\src\main\java\com\baeldung\reactive\model\Employee.java
1
请完成以下Java代码
public static ExecutableScript getScriptFromResource(String language, String resource, ScriptFactory scriptFactory) { ensureNotEmpty(NotValidException.class, "Script language", language); ensureNotEmpty(NotValidException.class, "Script resource", resource); return scriptFactory.createScriptFromResource(language, resource); } /** * Creates a new {@link ExecutableScript} from a dynamic resource. Dynamic means that the source * is an expression which will be evaluated during execution. * * @param language the language of the script * @param resourceExpression the expression which evaluates to the resource path * @param scriptFactory the script factory used to create the script * @return the newly created script * @throws NotValidException if language is null or empty or resourceExpression is null */ public static ExecutableScript getScriptFromResourceExpression(String language, Expression resourceExpression, ScriptFactory scriptFactory) { ensureNotEmpty(NotValidException.class, "Script language", language); ensureNotNull(NotValidException.class, "Script resource expression", resourceExpression); return scriptFactory.createScriptFromResource(language, resourceExpression); } /** * Checks if the value is an expression for a dynamic script source or resource. * * @param language the language of the script * @param value the value to check * @return true if the value is an expression for a dynamic script source/resource, otherwise false
*/ public static boolean isDynamicScriptExpression(String language, String value) { return StringUtil.isExpression(value) && (language != null && !JuelScriptEngineFactory.names.contains(language.toLowerCase())); } /** * Returns the configured script factory in the context or a new one. */ public static ScriptFactory getScriptFactory() { ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration(); if (processEngineConfiguration != null) { return processEngineConfiguration.getScriptFactory(); } else { return new ScriptFactory(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ScriptUtil.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public long getAssigneeHash() { return assigneeHash; } public void setAssigneeHash(long assigneeHash) {
this.assigneeHash = assigneeHash; } public Object getPersistentState() { // immutable return TaskMeterLogEntity.class; } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<>(); return referenceIdAndClass; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TaskMeterLogEntity.java
1