instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public List<TopicSubscription> getSubscriptions() { return subscriptions; } public boolean isRunning() { return isRunning.get(); } public void setBackoffStrategy(BackoffStrategy backOffStrategy) { this.backoffStrategy = backOffStrategy; } protected void runBackoffStrategy(FetchAndLockResponseDto fetchAndLockResponse) { try { List<ExternalTask> externalTasks = fetchAndLockResponse.getExternalTasks(); if (backoffStrategy instanceof ErrorAwareBackoffStrategy) { ErrorAwareBackoffStrategy errorAwareBackoffStrategy = ((ErrorAwareBackoffStrategy) backoffStrategy); ExternalTaskClientException exception = fetchAndLockResponse.getError(); errorAwareBackoffStrategy.reconfigure(externalTasks, exception); } else { backoffStrategy.reconfigure(externalTasks); } long waitTime = backoffStrategy.calculateBackoffTime(); suspend(waitTime); } catch (Throwable e) { LOG.exceptionWhileExecutingBackoffStrategyMethod(e); } }
protected void suspend(long waitTime) { if (waitTime > 0 && isRunning.get()) { ACQUISITION_MONITOR.lock(); try { if (isRunning.get()) { IS_WAITING.await(waitTime, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { LOG.exceptionWhileExecutingBackoffStrategyMethod(e); } finally { ACQUISITION_MONITOR.unlock(); } } } protected void resume() { ACQUISITION_MONITOR.lock(); try { IS_WAITING.signal(); } finally { ACQUISITION_MONITOR.unlock(); } } public void disableBackoffStrategy() { this.isBackoffStrategyDisabled.set(true); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\TopicSubscriptionManager.java
1
请在Spring Boot框架中完成以下Java代码
public void setSenderID(String value) { this.senderID = value; } /** * Gets the value of the recipientID property. * * @return * possible object is * {@link String } * */ public String getRecipientID() { return recipientID; } /** * Sets the value of the recipientID property. * * @param value * allowed object is * {@link String } * */ public void setRecipientID(String value) { this.recipientID = value; } /** * Gets the value of the interchangeRef property. * * @return * possible object is * {@link String } * */ public String getInterchangeRef() { return interchangeRef; } /** * Sets the value of the interchangeRef property. * * @param value * allowed object is * {@link String } * */ public void setInterchangeRef(String value) { this.interchangeRef = value; } /** * Gets the value of the dateTime property. * * @return * possible object is * {@link XMLGregorianCalendar }
* */ public XMLGregorianCalendar getDateTime() { return dateTime; } /** * Sets the value of the dateTime property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDateTime(XMLGregorianCalendar value) { this.dateTime = value; } /** * Gets the value of the testIndicator property. * * @return * possible object is * {@link String } * */ public String getTestIndicator() { return testIndicator; } /** * Sets the value of the testIndicator property. * * @param value * allowed object is * {@link String } * */ public void setTestIndicator(String value) { this.testIndicator = value; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIMessage.java
2
请完成以下Java代码
public List<String> getResult() { return loadedDataLines; } } /** * Read file that has at least on filed with multiline text * <br> * Assumes the <code>TEXT_DELIMITER</code> is not encountered in the field * * @param file * @param charset * @return * @throws IOException */ public List<String> readMultiLines(@NonNull final File file, @NonNull final Charset charset) throws IOException { return Files.readLines(file, charset, new MultiLineProcessor()); } public List<String> readMultiLines(@NonNull final byte[] data, @NonNull final Charset charset) throws IOException { return ByteSource.wrap(data).asCharSource(charset).readLines(new MultiLineProcessor()); } /** * Read file that has not any multi-line text * * @param file * @param charset * @return * @throws IOException */ public List<String> readRegularLines(@NonNull final File file, @NonNull final Charset charset) throws IOException { return Files.readLines(file, charset, new SingleLineProcessor()); } public List<String> readRegularLines(@NonNull final byte[] data, @NonNull final Charset charset) throws IOException { return ByteSource.wrap(data).asCharSource(charset).readLines(new SingleLineProcessor()); }
/** * Build the preview from the loaded lines * * @param lines * @return */ public String buildDataPreview(@NonNull final List<String> lines) { String dataPreview = lines.stream() .limit(MAX_LOADED_LINES) .collect(Collectors.joining("\n")); if (lines.size() > MAX_LOADED_LINES) { dataPreview = dataPreview + "\n......................................................\n"; } return dataPreview; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\parser\FileImportReader.java
1
请完成以下Java代码
public String toString() { return "PropertyKey [name=" + name + "]"; } @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(Object obj) { if (this == obj)
return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PropertyKey<?> other = (PropertyKey<?>) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\PropertyKey.java
1
请完成以下Java代码
default boolean matchesAnyRowRecursive(final HUEditorRowFilter filter) { return streamAllRecursive(filter).findAny().isPresent(); } /** * Stream all rows (including children) which match any of given <code>rowIds</code>. * * If a rowId is included in another row (which will be returned by this method), then that row will be excluded. * e.g. * Consider having following structure: rowId=1 which includes rowId=2 which includes rowId=3. * <ul> * <li>When this method will be called with rowIds={1, 3}, only rowId=1 will be returned because rowId=3 is indirectly included in rowId=1. * <li>When this method will be called with rowIds={3}, rowId=3 will be returned because it's not included in any of the rowIds we asked for. * <li> * </ul> * */ Stream<HUEditorRow> streamByIdsExcludingIncludedRows(HUEditorRowFilter filter); Stream<HUEditorRow> streamPage( int firstRow, int pageLength, HUEditorRowFilter filter, @NonNull final ViewRowsOrderBy orderBys); HUEditorRow getById(DocumentId rowId) throws EntityNotFoundException;
default Optional<HUEditorRow> getParentRowByChildIdOrNull(final DocumentId childId) throws EntityNotFoundException { final HUEditorRowId childRowId = HUEditorRowId.ofDocumentId(childId); final HUEditorRowId topLevelRowId = childRowId.toTopLevelRowId(); final HUEditorRow topLevelRow = getById(topLevelRowId.toDocumentId()); return topLevelRow .streamRecursive() .map(HUEditorRow::cast) .filter(row -> row.hasDirectChild(childId)) .findFirst(); } /** @return SQL where clause using fully qualified table name (i.e. not table alias) */ SqlViewRowsWhereClause getSqlWhereClause(DocumentIdsSelection rowIds); }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorViewBuffer.java
1
请完成以下Java代码
public void setC_RfQ_Topic_ID (int C_RfQ_Topic_ID) { if (C_RfQ_Topic_ID < 1) set_ValueNoCheck (COLUMNNAME_C_RfQ_Topic_ID, null); else set_ValueNoCheck (COLUMNNAME_C_RfQ_Topic_ID, Integer.valueOf(C_RfQ_Topic_ID)); } /** Get Ausschreibungs-Thema. @return Topic for Request for Quotations */ @Override public int getC_RfQ_Topic_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_RfQ_Topic_ID); if (ii == null) return 0; return ii.intValue(); } /** Set RfQ Subscriber. @param C_RfQ_TopicSubscriber_ID Request for Quotation Topic Subscriber */ @Override public void setC_RfQ_TopicSubscriber_ID (int C_RfQ_TopicSubscriber_ID) { if (C_RfQ_TopicSubscriber_ID < 1) set_ValueNoCheck (COLUMNNAME_C_RfQ_TopicSubscriber_ID, null); else set_ValueNoCheck (COLUMNNAME_C_RfQ_TopicSubscriber_ID, Integer.valueOf(C_RfQ_TopicSubscriber_ID)); } /** Get RfQ Subscriber. @return Request for Quotation Topic Subscriber */ @Override public int getC_RfQ_TopicSubscriber_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_RfQ_TopicSubscriber_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datum der Abmeldung. @param OptOutDate Date the contact opted out */ @Override
public void setOptOutDate (java.sql.Timestamp OptOutDate) { set_Value (COLUMNNAME_OptOutDate, OptOutDate); } /** Get Datum der Abmeldung. @return Date the contact opted out */ @Override public java.sql.Timestamp getOptOutDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_OptOutDate); } /** Set Anmeldung. @param SubscribeDate Date the contact actively subscribed */ @Override public void setSubscribeDate (java.sql.Timestamp SubscribeDate) { set_Value (COLUMNNAME_SubscribeDate, SubscribeDate); } /** Get Anmeldung. @return Date the contact actively subscribed */ @Override public java.sql.Timestamp getSubscribeDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_SubscribeDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ_TopicSubscriber.java
1
请在Spring Boot框架中完成以下Java代码
public class ShipmentScheduleUpdatedHandler implements MaterialEventHandler<ShipmentScheduleUpdatedEvent> { private final CandidateChangeService candidateChangeHandler; private final CandidateRepositoryRetrieval candidateRepository; public ShipmentScheduleUpdatedHandler( @NonNull final CandidateChangeService candidateChangeHandler, @NonNull final CandidateRepositoryRetrieval candidateRepository) { this.candidateChangeHandler = candidateChangeHandler; this.candidateRepository = candidateRepository; } @Override public Collection<Class<? extends ShipmentScheduleUpdatedEvent>> getHandledEventType() { return ImmutableList.of(ShipmentScheduleUpdatedEvent.class); } @Override public void handleEvent(@NonNull final ShipmentScheduleUpdatedEvent event) { final DemandDetailsQuery demandDetailsQuery = DemandDetailsQuery.ofShipmentScheduleId(event.getShipmentScheduleId()); final CandidatesQuery candidatesQuery = CandidatesQuery .builder() .type(CandidateType.DEMAND) .businessCase(CandidateBusinessCase.SHIPMENT) .demandDetailsQuery(demandDetailsQuery) .build(); final Candidate candidate = candidateRepository.retrieveLatestMatchOrNull(candidatesQuery); final Candidate updatedCandidate; final DemandDetail demandDetail = DemandDetail.forDocumentLine( event.getShipmentScheduleId(), event.getDocumentLineDescriptor(), event.getMaterialDescriptor().getQuantity()); if (candidate == null)
{ updatedCandidate = Candidate .builderForEventDescriptor(event.getEventDescriptor()) .materialDescriptor(event.getMaterialDescriptor()) .minMaxDescriptor(event.getMinMaxDescriptor()) .type(CandidateType.DEMAND) .businessCase(CandidateBusinessCase.SHIPMENT) .businessCaseDetail(demandDetail) .build(); } else { updatedCandidate = candidate.toBuilder() .materialDescriptor(event.getMaterialDescriptor()) .minMaxDescriptor(event.getMinMaxDescriptor()) .businessCaseDetail(demandDetail) .build(); } candidateChangeHandler.onCandidateNewOrChange(updatedCandidate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\shipmentschedule\ShipmentScheduleUpdatedHandler.java
2
请完成以下Java代码
public void insert(PersonEntity personEntity) throws SQLException { String query = "INSERT INTO persons(id, name) VALUES(" + personEntity.getId() + ", '" + personEntity.getName() + "')"; Statement statement = connection.createStatement(); statement.executeUpdate(query); } public void insert(List<PersonEntity> personEntities) throws SQLException { for (PersonEntity personEntity : personEntities) { insert(personEntity); } } public void update(PersonEntity personEntity) throws SQLException { String query = "UPDATE persons SET name = '" + personEntity.getName() + "' WHERE id = " + personEntity.getId(); Statement statement = connection.createStatement(); statement.executeUpdate(query);
} public void deleteById(int id) throws SQLException { String query = "DELETE FROM persons WHERE id = " + id; Statement statement = connection.createStatement(); statement.executeUpdate(query); } public List<PersonEntity> getAll() throws SQLException { String query = "SELECT id, name, FROM persons"; Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query); List<PersonEntity> result = new ArrayList<>(); while (resultSet.next()) { result.add(new PersonEntity(resultSet.getInt("id"), resultSet.getString("name"))); } return result; } }
repos\tutorials-master\persistence-modules\core-java-persistence\src\main\java\com\baeldung\statmentVsPreparedstatment\StatementPersonDao.java
1
请完成以下Java代码
public boolean isAuthenticated() { return this.authenticated; } @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { throw new IllegalArgumentException( "Instead of calling this setter, please call toBuilder to create a new instance"); } @Override public String getName() { return (this.principal == null) ? "" : this.principal.toString(); } static final class Builder implements Authentication.Builder<Builder> { private final Log logger = LogFactory.getLog(getClass()); private final Collection<GrantedAuthority> authorities = new LinkedHashSet<>(); private @Nullable Object principal; private @Nullable Object credentials; private @Nullable Object details; private boolean authenticated; Builder(Authentication authentication) { this.logger.debug("Creating a builder which will result in exchanging an authentication of type " + authentication.getClass() + " for " + SimpleAuthentication.class.getSimpleName() + ";" + " consider implementing " + authentication.getClass().getSimpleName() + "#toBuilder"); this.authorities.addAll(authentication.getAuthorities()); this.principal = authentication.getPrincipal(); this.credentials = authentication.getCredentials(); this.details = authentication.getDetails(); this.authenticated = authentication.isAuthenticated(); } @Override public Builder authorities(Consumer<Collection<GrantedAuthority>> authorities) { authorities.accept(this.authorities);
return this; } @Override public Builder details(@Nullable Object details) { this.details = details; return this; } @Override public Builder principal(@Nullable Object principal) { this.principal = principal; return this; } @Override public Builder credentials(@Nullable Object credentials) { this.credentials = credentials; return this; } @Override public Builder authenticated(boolean authenticated) { this.authenticated = authenticated; return this; } @Override public Authentication build() { return new SimpleAuthentication(this); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\SimpleAuthentication.java
1
请完成以下Java代码
public class ConsoleScriptsApplierListener implements IScriptsApplierListener { public static final transient ConsoleScriptsApplierListener instance = new ConsoleScriptsApplierListener(); private ConsoleScriptsApplierListener() { } @Override public void onScriptApplied(final IScript script) { // nothing } @Override public ScriptFailedResolution onScriptFailed(final IScript script, final ScriptExecutionException e) throws RuntimeException { final File file = script.getLocalFile(); final String exceptionMessage = e.toStringX(false); // printStackTrace=false final PrintStream out = System.out; final BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); out.println("--------------------------------------------------------------------------------------------------"); out.println("Script failed to run: " + file.toString()); out.println(); out.println(exceptionMessage); out.println("--------------------------------------------------------------------------------------------------"); do { out.println("What shall we do?"); out.println("F - fail, I - Ignore, R - Retry"); out.flush(); String answer; try { answer = in.readLine(); } catch (final IOException ioex) { out.println("Failed reading from console. Throwing inital error."); out.flush(); e.addSuppressed(ioex); throw e;
} if ("F".equalsIgnoreCase(answer)) { return ScriptFailedResolution.Fail; } else if ("I".equalsIgnoreCase(answer)) { return ScriptFailedResolution.Ignore; } else if ("R".equalsIgnoreCase(answer)) { return ScriptFailedResolution.Retry; } else { out.println("Unknown option: " + answer); } } while (true); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\applier\impl\ConsoleScriptsApplierListener.java
1
请完成以下Java代码
public ValueExpression setVariable(String variable, ValueExpression expression) { if (map.isEmpty()) { map = new HashMap<String, ValueExpression>(); } return map.put(variable, expression); } } private Functions functions; private Variables variables; private ELResolver resolver; /** * Create a context. */ public SimpleContext() { this(null); } /** * Create a context, use the specified resolver. */ public SimpleContext(ELResolver resolver) { this.resolver = resolver; } /** * Define a function. */ public void setFunction(String prefix, String localName, Method method) { if (functions == null) { functions = new Functions(); } functions.setFunction(prefix, localName, method); } /** * Define a variable. */ public ValueExpression setVariable(String name, ValueExpression expression) { if (variables == null) { variables = new Variables(); } return variables.setVariable(name, expression); } /** * Get our function mapper. */ @Override public FunctionMapper getFunctionMapper() { if (functions == null) { functions = new Functions(); } return functions; }
/** * Get our variable mapper. */ @Override public VariableMapper getVariableMapper() { if (variables == null) { variables = new Variables(); } return variables; } /** * Get our resolver. Lazy initialize to a {@link SimpleResolver} if necessary. */ @Override public ELResolver getELResolver() { if (resolver == null) { resolver = new SimpleResolver(); } return resolver; } /** * Set our resolver. * * @param resolver */ public void setELResolver(ELResolver resolver) { this.resolver = resolver; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\util\SimpleContext.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderDetail implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue @Column(name = "ORDER_ID") private Long orderId; public OrderDetail() { } public OrderDetail(Date orderDate, String orderDesc) { super(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); return result; } @Override
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OrderDetail other = (OrderDetail) obj; if (orderId == null) { if (other.orderId != null) return false; } else if (!orderId.equals(other.orderId)) return false; return true; } public Long getOrderId() { return orderId; } public void setOrderId(Long orderId) { this.orderId = orderId; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\hibernate\fetching\model\OrderDetail.java
2
请完成以下Java代码
public static void main(final String[] args) { // Spring Java config final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.getEnvironment().addActiveProfile("spring"); context.register(SpringBatchConfig.class); context.refresh(); // Spring xml config // ApplicationContext context = new ClassPathXmlApplicationContext("spring-batch-intro.xml"); runJob(context, "parentJob"); runJob(context, "firstBatchJob"); runJob(context, "skippingBatchJob"); runJob(context, "skipPolicyBatchJob"); } private static void runJob(AnnotationConfigApplicationContext context, String batchJobName) {
final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); final Job job = (Job) context.getBean(batchJobName); LOGGER.info("Starting the batch job: {}", batchJobName); try { // To enable multiple execution of a job with the same parameters JobParameters jobParameters = new JobParametersBuilder().addString("jobID", String.valueOf(System.currentTimeMillis())) .toJobParameters(); final JobExecution execution = jobLauncher.run(job, jobParameters); LOGGER.info("Job Status : {}", execution.getStatus()); } catch (final Exception e) { e.printStackTrace(); LOGGER.error("Job failed {}", e.getMessage()); } } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batch\App.java
1
请完成以下Java代码
public class LogAdvice implements MethodInterceptor { @Override public Object invoke(MethodInvocation methodInvocation) throws Throwable { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //记录请求信息 StopWatch stopWatch = new StopWatch(); stopWatch.start(); Object result = methodInvocation.proceed(); stopWatch.stop(); Method method = methodInvocation.getMethod(); String urlStr = request.getRequestURL().toString(); log.info("===================================begin=================================================="); log.info("req path: {}", StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath())); log.info("req ip: {}", request.getRemoteUser()); log.info("req method: {}", request.getMethod()); log.info("req params: {}", getParameter(method, methodInvocation.getArguments())); log.info("req result: {}", JSONUtil.toJsonStr(result)); log.info("req uri: {}", request.getRequestURI()); log.info("req url: {}", request.getRequestURL().toString()); log.info("req cost: {}ms", stopWatch.getLastTaskTimeMillis()); log.info("===================================end==================================================="); return result; } private Object getParameter(Method method, Object[] args) { List<Object> argList = new ArrayList<>(); Parameter[] parameters = method.getParameters(); for (int i = 0; i < parameters.length; i++) { //将RequestBody注解修饰的参数作为请求参数 RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class); if (requestBody != null) { argList.add(args[i]); }
//将RequestParam注解修饰的参数作为请求参数 RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class); if (requestParam != null) { Map<String, Object> map = new HashMap<>(); String key = parameters[i].getName(); if (!StringUtils.isEmpty(requestParam.value())) { key = requestParam.value(); } map.put(key, args[i]); argList.add(map); } } if (argList.size() == 0) { return null; } else if (argList.size() == 1) { return argList.get(0); } else { return argList; } } }
repos\spring-boot-quick-master\quick-platform-component\src\main\java\com\quick\component\config\logAspect\LogAdvice.java
1
请在Spring Boot框架中完成以下Java代码
public String getAD_Client_Value() { return AD_Client_Value; } public int getAD_Org_ID() { return AD_Org_ID; } public String getADInputDataDestination_InternalName() { return ADInputDataDestination_InternalName; } public BigInteger getADInputDataSourceID() { return ADInputDataSourceID; } public BigInteger getADUserEnteredByID() { return ADUserEnteredByID;
} public String getDeliveryRule() { return DeliveryRule; } public String getDeliveryViaRule() { return DeliveryViaRule; } public String getCurrencyISOCode() { return currencyISOCode; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\excelimport\ExcelConfigurationContext.java
2
请完成以下Java代码
public int getC_RevenueRecognition_Plan_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_RevenueRecognition_Plan_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getP_Revenue_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getP_Revenue_Acct(), get_TrxName()); } /** Set Product Revenue. @param P_Revenue_Acct Account for Product Revenue (Sales Account) */ public void setP_Revenue_Acct (int P_Revenue_Acct) { set_ValueNoCheck (COLUMNNAME_P_Revenue_Acct, Integer.valueOf(P_Revenue_Acct)); } /** Get Product Revenue. @return Account for Product Revenue (Sales Account) */ public int getP_Revenue_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_P_Revenue_Acct); if (ii == null) return 0; return ii.intValue(); } /** Set Recognized Amount. @param RecognizedAmt Recognized Amount */ public void setRecognizedAmt (BigDecimal RecognizedAmt) { set_ValueNoCheck (COLUMNNAME_RecognizedAmt, RecognizedAmt); } /** Get Recognized Amount. @return Recognized Amount */ public BigDecimal getRecognizedAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RecognizedAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Total Amount. @param TotalAmt Total Amount */ public void setTotalAmt (BigDecimal TotalAmt) { set_ValueNoCheck (COLUMNNAME_TotalAmt, TotalAmt); }
/** Get Total Amount. @return Total Amount */ public BigDecimal getTotalAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt); if (bd == null) return Env.ZERO; return bd; } public I_C_ValidCombination getUnEarnedRevenue_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getUnEarnedRevenue_Acct(), get_TrxName()); } /** Set Unearned Revenue. @param UnEarnedRevenue_Acct Account for unearned revenue */ public void setUnEarnedRevenue_Acct (int UnEarnedRevenue_Acct) { set_ValueNoCheck (COLUMNNAME_UnEarnedRevenue_Acct, Integer.valueOf(UnEarnedRevenue_Acct)); } /** Get Unearned Revenue. @return Account for unearned revenue */ public int getUnEarnedRevenue_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_UnEarnedRevenue_Acct); 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_RevenueRecognition_Plan.java
1
请完成以下Java代码
public void registerScriptScannerClassesFor(final IScriptExecutorFactory scriptExecutorFactory) { for (final ScriptType scriptType : scriptExecutorFactory.getSupportedScriptTypes()) { registerScriptScannerClass(scriptType.getFileExtension(), SingletonScriptScanner.class); } } private static final String normalizeFileExtension(final String fileExtension) { return fileExtension.trim().toLowerCase(); } @Override public void setScriptFactory(final IScriptFactory scriptFactory)
{ this.scriptFactory = scriptFactory; } @Override public IScriptFactory getScriptFactoryToUse() { if (scriptFactory != null) { return scriptFactory; } return scriptFactoryDefault; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\ScriptScannerFactory.java
1
请完成以下Java代码
public static List<AttributeKvEntry> toAttributes(List<JsonNode> attributes) { if (!CollectionUtils.isEmpty(attributes)) { return attributes.stream().map(attr -> { KvEntry entry = parseValue(attr.get(KEY).asText(), attr.get(VALUE)); return new BaseAttributeKvEntry(entry, attr.get(LAST_UPDATE_TS).asLong()); } ).collect(Collectors.toList()); } else { return Collections.emptyList(); } } public static List<TsKvEntry> toTimeseries(Map<String, List<JsonNode>> timeseries) { if (!CollectionUtils.isEmpty(timeseries)) { List<TsKvEntry> result = new ArrayList<>(); timeseries.forEach((key, values) -> result.addAll(values.stream().map(ts -> { KvEntry entry = parseValue(key, ts.get(VALUE)); return new BasicTsKvEntry(ts.get(TS).asLong(), entry); } ).toList()) ); return result; } else { return Collections.emptyList(); } } private static KvEntry parseValue(String key, JsonNode value) { if (!value.isContainerNode()) { if (value.isBoolean()) { return new BooleanDataEntry(key, value.asBoolean()); } else if (value.isNumber()) {
return parseNumericValue(key, value); } else if (value.isTextual()) { return new StringDataEntry(key, value.asText()); } else { throw new RuntimeException(CAN_T_PARSE_VALUE + value); } } else { return new JsonDataEntry(key, value.toString()); } } private static KvEntry parseNumericValue(String key, JsonNode value) { if (value.isFloatingPointNumber()) { return new DoubleDataEntry(key, value.asDouble()); } else { try { long longValue = Long.parseLong(value.toString()); return new LongDataEntry(key, longValue); } catch (NumberFormatException e) { throw new IllegalArgumentException("Big integer values are not supported!"); } } } }
repos\thingsboard-master\rest-client\src\main\java\org\thingsboard\rest\client\utils\RestJsonConverter.java
1
请完成以下Java代码
class WorkflowModel { private final Workflow workflow; private final LinkedHashMap<WFNodeId, WorkflowNodeModel> nodesById = new LinkedHashMap<>(); WorkflowModel(@NonNull final Workflow workflow) { this.workflow = workflow; } public @NonNull WorkflowId getId() { return workflow.getId(); } public @NonNull ITranslatableString getName() {return workflow.getName();} public @NonNull ITranslatableString getDescription() {return workflow.getDescription();} public @NonNull ITranslatableString getHelp() {return workflow.getHelp();}
public WorkflowNodeModel getNodeById(final WFNodeId nodeId) { return nodesById.computeIfAbsent(nodeId, k -> { final WFNode node = workflow.getNodeById(nodeId); return new WorkflowNodeModel(this, node); }); } public List<WorkflowNodeModel> getNodesInOrder(final @NonNull ClientId clientId) { return workflow.getNodesInOrder(clientId) .stream() .map(node -> getNodeById(node.getId())) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WorkflowModel.java
1
请完成以下Java代码
public boolean isRequireVV () { Object oo = get_Value(COLUMNNAME_RequireVV); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set User ID. @param UserID User ID or account number */ @Override public void setUserID (java.lang.String UserID) { set_Value (COLUMNNAME_UserID, UserID); } /** Get User ID. @return User ID or account number */ @Override public java.lang.String getUserID () { return (java.lang.String)get_Value(COLUMNNAME_UserID); }
/** Set Vendor ID. @param VendorID Vendor ID for the Payment Processor */ @Override public void setVendorID (java.lang.String VendorID) { set_Value (COLUMNNAME_VendorID, VendorID); } /** Get Vendor ID. @return Vendor ID for the Payment Processor */ @Override public java.lang.String getVendorID () { return (java.lang.String)get_Value(COLUMNNAME_VendorID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaymentProcessor.java
1
请完成以下Java代码
public Optional<I_M_HU> getHUByBarcode(@NonNull final String barcodeStringParam) { final String barcodeString = StringUtils.trimBlankToNull(barcodeStringParam); if (barcodeString == null) { // shall not happen throw new AdempiereException("No barcode provided"); } final GlobalQRCode globalQRCode = GlobalQRCode.parse(barcodeString).orNullIfError(); if(globalQRCode != null) { final HUQRCode huQRCode = HUQRCode.fromGlobalQRCode(globalQRCode); return huQRCodesService.getHuIdByQRCodeIfExists(huQRCode) .map(handlingUnitsDAO::getById); } else { final I_M_HU hu = handlingUnitsDAO.createHUQueryBuilder() .setHUStatus(X_M_HU.HUSTATUS_Active) .setOnlyWithBarcode(barcodeString) .firstOnly(); return Optional.ofNullable(hu); } } public Optional<I_M_HU> getHUBySSCC18(@NonNull final String sscc18) { final I_M_HU hu = handlingUnitsDAO.createHUQueryBuilder() .setHUStatus(X_M_HU.HUSTATUS_Active) // match SSCC18 attribute .addOnlyWithAttribute(AttributeConstants.ATTR_SSCC18_Value, sscc18) // only HU's with BPartner set shall be considered (06821) .setOnlyIfAssignedToBPartner(true) .firstOnly(); return Optional.ofNullable(hu); } public Optional<ProductBarcodeFilterData> createDataFromHU( final @Nullable String barcode, final @Nullable I_M_HU hu) { if (hu == null) { return Optional.empty(); } final ImmutableSet<ProductId> productIds = extractProductIds(hu); if (productIds.isEmpty()) { return Optional.empty(); } final ICompositeQueryFilter<I_M_Packageable_V> filter = queryBL.createCompositeQueryFilter(I_M_Packageable_V.class) .addInArrayFilter(I_M_Packageable_V.COLUMNNAME_M_Product_ID, productIds);
final WarehouseId warehouseId = IHandlingUnitsBL.extractWarehouseIdOrNull(hu); if (warehouseId != null) { filter.addInArrayFilter(I_M_Packageable_V.COLUMNNAME_M_Warehouse_ID, null, warehouseId); } final BPartnerId bpartnerId = IHandlingUnitsBL.extractBPartnerIdOrNull(hu); if (bpartnerId != null) { filter.addEqualsFilter(I_M_Packageable_V.COLUMNNAME_C_BPartner_Customer_ID, bpartnerId); } return Optional.of(ProductBarcodeFilterData.builder() .barcode(barcode) .huId(HuId.ofRepoId(hu.getM_HU_ID())) .sqlWhereClause(toSqlAndParams(filter)) .build()); } private ImmutableSet<ProductId> extractProductIds(@NonNull final I_M_HU hu) { final IMutableHUContext huContext = handlingUnitsBL.createMutableHUContext(PlainContextAware.newWithThreadInheritedTrx()); return huContext.getHUStorageFactory() .getStorage(hu) .getProductStorages() .stream() .map(IHUProductStorage::getProductId) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\filters\ProductBarcodeFilterServicesFacade.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() {
return age; } public void setAge(Integer age) { this.age = age; } public Boolean getSex() { return sex; } public void setSex(Boolean sex) { this.sex = sex; } }
repos\springboot-demo-master\hikari\src\main\java\com\et\hikari\entity\User.java
1
请完成以下Java代码
private ImmutableSet<PickingCandidateId> getValidPickingCandidates() { return getRowsNotAlreadyProcessed() .stream() .filter(ProductsToPickRow::isEligibleForProcessing) .map(ProductsToPickRow::getPickingCandidateId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } private void deliverAndInvoice(final ImmutableSet<PickingCandidateId> validPickingCandidates) { final List<PickingCandidate> pickingCandidates = processAllPickingCandidates(validPickingCandidates); final Set<HuId> huIdsToDeliver = pickingCandidates .stream() .filter(PickingCandidate::isPacked) .map(PickingCandidate::getPackedToHuId) .collect(ImmutableSet.toImmutableSet()); final List<I_M_HU> husToDeliver = handlingUnitsRepo.getByIds(huIdsToDeliver); HUShippingFacade.builder() .hus(husToDeliver) .addToShipperTransportationId(shipperTransportationId) .completeShipments(true) .failIfNoShipmentCandidatesFound(true) .invoiceMode(BillAssociatedInvoiceCandidates.IF_INVOICE_SCHEDULE_PERMITS)
.createShipperDeliveryOrders(true) .build() .generateShippingDocuments(); } private List<ProductsToPickRow> getRowsNotAlreadyProcessed() { return streamAllRows() .filter(row -> !row.isProcessed()) .collect(ImmutableList.toImmutableList()); } private boolean isPartialDeliveryAllowed() { return sysConfigBL.getBooleanValue(SYSCONFIG_AllowPartialDelivery, false); } private ImmutableList<PickingCandidate> processAllPickingCandidates(final ImmutableSet<PickingCandidateId> pickingCandidateIdsToProcess) { return trxManager.callInNewTrx(() -> pickingCandidatesService .process(pickingCandidateIdsToProcess) .getPickingCandidates()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\process\ProductsToPick_4EyesReview_ProcessAll.java
1
请完成以下Java代码
public void assertHasAccess(@NonNull final UserId userId) { if (!hasAccess(userId)) { throw new AdempiereException(NO_ACCESS_ERROR_MSG); } } public boolean hasAccess(@NonNull final UserId userId) { return UserId.equals(getResponsibleId(), userId); } public <T> T getDocumentAs(@NonNull final Class<T> type) { return type.cast(document); } public WFActivity getActivityById(@NonNull final WFActivityId id) { return getActivityByIdOptional(id) .orElseThrow(() -> new AdempiereException(NO_ACTIVITY_ERROR_MSG) .appendParametersToMessage() .setParameter("ID", id) .setParameter("WFProcess", this)); } @NonNull
public Optional<WFActivity> getActivityByIdOptional(@NonNull final WFActivityId id) { return Optional.ofNullable(activitiesById.get(id)); } public WFProcess withChangedActivityStatus( @NonNull final WFActivityId wfActivityId, @NonNull final WFActivityStatus newActivityStatus) { return withChangedActivityById(wfActivityId, wfActivity -> wfActivity.withStatus(newActivityStatus)); } private WFProcess withChangedActivityById(@NonNull final WFActivityId wfActivityId, @NonNull final UnaryOperator<WFActivity> remappingFunction) { return withChangedActivities(wfActivity -> wfActivity.getId().equals(wfActivityId) ? remappingFunction.apply(wfActivity) : wfActivity); } private WFProcess withChangedActivities(@NonNull final UnaryOperator<WFActivity> remappingFunction) { final ImmutableList<WFActivity> activitiesNew = CollectionUtils.map(this.activities, remappingFunction); return !Objects.equals(this.activities, activitiesNew) ? toBuilder().activities(activitiesNew).build() : this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WFProcess.java
1
请完成以下Java代码
public class CamundaRestResources { private static final Set<Class<?>> RESOURCE_CLASSES = new HashSet<Class<?>>(); private static final Set<Class<?>> CONFIGURATION_CLASSES = new HashSet<Class<?>>(); static { RESOURCE_CLASSES.add(NamedProcessEngineRestServiceImpl.class); RESOURCE_CLASSES.add(DefaultProcessEngineRestServiceImpl.class); CONFIGURATION_CLASSES.add(JacksonConfigurator.class); CONFIGURATION_CLASSES.add(JacksonJsonProvider.class); CONFIGURATION_CLASSES.add(JsonMappingExceptionHandler.class); CONFIGURATION_CLASSES.add(JsonParseExceptionHandler.class); CONFIGURATION_CLASSES.add(ProcessEngineExceptionHandler.class); CONFIGURATION_CLASSES.add(RestExceptionHandler.class); CONFIGURATION_CLASSES.add(MultipartPayloadProvider.class); CONFIGURATION_CLASSES.add(JacksonHalJsonProvider.class); CONFIGURATION_CLASSES.add(ExceptionHandler.class); }
/** * Returns a set containing all resource classes provided by Camunda Platform. * @return a set of resource classes. */ public static Set<Class<?>> getResourceClasses() { return RESOURCE_CLASSES; } /** * Returns a set containing all provider / mapper / config classes used in the * default setup of the camunda REST api. * @return a set of provider / mapper / config classes. */ public static Set<Class<?>> getConfigurationClasses() { return CONFIGURATION_CLASSES; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\CamundaRestResources.java
1
请完成以下Java代码
public ResponseEntity<Object> handleInvalidAuthentication( InvalidAuthenticationException e, WebRequest request) { return ResponseEntity.status(UNPROCESSABLE_ENTITY) .body( new HashMap<String, Object>() { { put("message", e.getMessage()); } }); } @Override protected ResponseEntity<Object> handleMethodArgumentNotValid( MethodArgumentNotValidException e, HttpHeaders headers, HttpStatus status, WebRequest request) { List<FieldErrorResource> errorResources = e.getBindingResult().getFieldErrors().stream() .map( fieldError -> new FieldErrorResource( fieldError.getObjectName(), fieldError.getField(), fieldError.getCode(), fieldError.getDefaultMessage())) .collect(Collectors.toList()); return ResponseEntity.status(UNPROCESSABLE_ENTITY).body(new ErrorResource(errorResources)); } @ExceptionHandler({ConstraintViolationException.class}) @ResponseStatus(UNPROCESSABLE_ENTITY) @ResponseBody public ErrorResource handleConstraintViolation( ConstraintViolationException ex, WebRequest request) { List<FieldErrorResource> errors = new ArrayList<>();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) { FieldErrorResource fieldErrorResource = new FieldErrorResource( violation.getRootBeanClass().getName(), getParam(violation.getPropertyPath().toString()), violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(), violation.getMessage()); errors.add(fieldErrorResource); } return new ErrorResource(errors); } private String getParam(String s) { String[] splits = s.split("\\."); if (splits.length == 1) { return s; } else { return String.join(".", Arrays.copyOfRange(splits, 2, splits.length)); } } }
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\exception\CustomizeExceptionHandler.java
1
请完成以下Java代码
public Builder setGridView(final ViewLayout.Builder gridView) { this._gridView = gridView; return this; } public Builder setSingleRowLayout(@NonNull final DocumentLayoutSingleRow.Builder singleRowLayout) { this.singleRowLayout = singleRowLayout; return this; } private DocumentLayoutSingleRow.Builder getSingleRowLayout() { return singleRowLayout; } private ViewLayout.Builder getGridView() { return _gridView; } public Builder addDetail(@Nullable final DocumentLayoutDetailDescriptor detail) { if (detail == null) { return this; } if (detail.isEmpty()) { logger.trace("Skip adding detail to layout because it is empty; detail={}", detail); return this; } details.add(detail); return this; } public Builder setSideListView(final ViewLayout sideListViewLayout)
{ this._sideListView = sideListViewLayout; return this; } private ViewLayout getSideList() { Preconditions.checkNotNull(_sideListView, "sideList"); return _sideListView; } public Builder putDebugProperty(final String name, final String value) { debugProperties.put(name, value); return this; } public Builder setStopwatch(final Stopwatch stopwatch) { this.stopwatch = stopwatch; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutDescriptor.java
1
请完成以下Java代码
protected String getXMLElementName() { return ELEMENT_DI_WAYPOINT; } @Override protected DmnElement convertXMLToElement(XMLStreamReader xtr, ConversionHelper conversionHelper) { GraphicInfo graphicInfo = new GraphicInfo(); graphicInfo.setX(Double.valueOf(xtr.getAttributeValue(null, DmnXMLConstants.ATTRIBUTE_DI_X))); graphicInfo.setY(Double.valueOf(xtr.getAttributeValue(null, DmnXMLConstants.ATTRIBUTE_DI_Y))); // calculate width and height for output and decision service sections if (conversionHelper.getCurrentDiShape().getDecisionServiceDividerLine() == conversionHelper.getCurrentDiEdge()) { // output decisions if (conversionHelper.getCurrentDiShape().getDecisionServiceDividerLine().getWaypoints().isEmpty()) { GraphicInfo decisionServiceGraphicInfo = conversionHelper.getCurrentDiShape().getGraphicInfo(); graphicInfo.setWidth(decisionServiceGraphicInfo.getWidth()); graphicInfo.setHeight(graphicInfo.getY() - decisionServiceGraphicInfo.getY()); } else { GraphicInfo decisionServiceGraphicInfo = conversionHelper.getCurrentDiShape().getGraphicInfo(); graphicInfo.setWidth(decisionServiceGraphicInfo.getWidth()); graphicInfo.setHeight(decisionServiceGraphicInfo.getHeight() - graphicInfo.getY() + decisionServiceGraphicInfo.getY()); } }
conversionHelper.getCurrentDiEdge().addWaypoint(graphicInfo); return graphicInfo; } @Override protected void writeAdditionalAttributes(DmnElement element, DmnDefinition model, XMLStreamWriter xtw) throws Exception { } @Override protected void writeAdditionalChildElements(DmnElement element, DmnDefinition model, XMLStreamWriter xtw) throws Exception { } }
repos\flowable-engine-main\modules\flowable-dmn-xml-converter\src\main\java\org\flowable\dmn\xml\converter\DmnDiWaypointXmlConverter.java
1
请完成以下Java代码
public static void schedule(@NonNull final IInvoiceCandUpdateSchedulerRequest request) { SCHEDULER.schedule(request); } private static final UpdateInvalidInvoiceCandidatesWorkpackageProcessorScheduler // SCHEDULER = new UpdateInvalidInvoiceCandidatesWorkpackageProcessorScheduler(true/*createOneWorkpackagePerAsyncBatch*/); private static final String SYSCONFIG_MaxInvoiceCandidatesToUpdate = "de.metas.invoicecandidate.async.spi.impl.UpdateInvalidInvoiceCandidatesWorkpackageProcessor.MaxInvoiceCandidatesToUpdate"; private static final int DEFAULT_MaxInvoiceCandidatesToUpdate = 500; // services private final transient ITrxManager trxManager = Services.get(ITrxManager.class); private final transient ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); private final transient IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class); private final transient IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class); @Override public final boolean isRunInTransaction() { return false; // run out of transaction } @Override public Result processWorkPackage(@NonNull final I_C_Queue_WorkPackage workpackage, final String localTrxName) { trxManager.assertTrxNameNull(localTrxName); final Properties ctx = InterfaceWrapperHelper.getCtx(workpackage); final int adClientId = workpackage.getAD_Client_ID(); Check.assume(adClientId > 0, "No point in calling this process with AD_Client_ID=0"); // // Get parameters final int maxInvoiceCandidatesToUpdate = getMaxInvoiceCandidatesToUpdate(); // // Update invalid ICs invoiceCandBL.updateInvalid() .setContext(ctx, localTrxName) // Only those which are not locked at all .setLockedBy(ILock.NULL)
.setTaggedWithNoTag() .setLimit(maxInvoiceCandidatesToUpdate) .update(); // // If we updated just a limited set of invoice candidates, // then create a new workpackage to update the rest of them. if (maxInvoiceCandidatesToUpdate > 0) { final int countRemaining = invoiceCandDAO.tagToRecompute() .setContext(ctx, localTrxName) .setLockedBy(ILock.NULL) .setTaggedWithNoTag() .countToBeTagged(); if (countRemaining > 0) { final AsyncBatchId asyncBatchId = AsyncBatchId.ofRepoIdOrNull(getC_Queue_WorkPackage().getC_Async_Batch_ID()); final IInvoiceCandUpdateSchedulerRequest request = InvoiceCandUpdateSchedulerRequest.of(ctx, localTrxName, asyncBatchId); schedule(request); Loggables.addLog("Scheduled another workpackage for {} remaining recompute records", countRemaining); } } return Result.SUCCESS; } private int getMaxInvoiceCandidatesToUpdate() { return sysConfigBL.getIntValue(SYSCONFIG_MaxInvoiceCandidatesToUpdate, DEFAULT_MaxInvoiceCandidatesToUpdate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\async\spi\impl\UpdateInvalidInvoiceCandidatesWorkpackageProcessor.java
1
请在Spring Boot框架中完成以下Java代码
private MaterialDescriptor createDemandMaterialDescriptor( @NonNull final AbstractDDOrderEvent ddOrderEvent, @NonNull final DDOrderLine ddOrderLine) { final MaterialDescriptorBuilder materialDescriptorBuilder = initCommonDescriptorBuilder(ddOrderLine); return materialDescriptorBuilder .date(computeDate(ddOrderEvent, ddOrderLine, CandidateType.DEMAND)) .warehouseId(computeWarehouseId(ddOrderEvent, CandidateType.DEMAND)) .build(); } private MaterialDescriptor createSupplyMaterialDescriptor( @NonNull final AbstractDDOrderEvent ddOrderEvent, @NonNull final DDOrderLine ddOrderLine) { final MaterialDescriptorBuilder materialDescriptorBuilder = initCommonDescriptorBuilder(ddOrderLine); return materialDescriptorBuilder .date(computeDate(ddOrderEvent, ddOrderLine, CandidateType.SUPPLY)) .warehouseId(computeWarehouseId(ddOrderEvent, CandidateType.SUPPLY)) .build(); } private MaterialDescriptorBuilder initCommonDescriptorBuilder(final DDOrderLine ddOrderLine) { return MaterialDescriptor.builder() .productDescriptor(ddOrderLine.getProductDescriptor()) // .customerId(ddOrderLine.getBPartnerId()) // the ddOrder line's bpartner is not the customer, but probably the shipper .quantity(ddOrderLine.getQtyToMove()); } protected abstract CandidatesQuery createPreExistingCandidatesQuery( AbstractDDOrderEvent ddOrderEvent, DDOrderLine ddOrderLine, CandidateType candidateType); private DistributionDetail createCandidateDetailFromDDOrderAndLine( @NonNull final DDOrder ddOrder, @NonNull final DDOrderLine ddOrderLine) { return DistributionDetail.builder()
.ddOrderDocStatus(ddOrder.getDocStatus()) .ddOrderRef(DDOrderRef.ofNullableDDOrderAndLineId(ddOrder.getDdOrderId(), ddOrderLine.getDdOrderLineId())) .forwardPPOrderRef(ddOrder.getForwardPPOrderRef()) .distributionNetworkAndLineId(ddOrderLine.getDistributionNetworkAndLineId()) .qty(ddOrderLine.getQtyToMove()) .plantId(ddOrder.getPlantId()) .productPlanningId(ddOrder.getProductPlanningId()) .shipperId(ddOrder.getShipperId()) .build(); } private void handleMainDataUpdates(@NonNull final DDOrderCreatedEvent ddOrderCreatedEvent, @NonNull final DDOrderLine ddOrderLine) { if (ddOrderCreatedEvent.getDdOrder().isSimulated()) { return; } final OrgId orgId = ddOrderCreatedEvent.getOrgId(); final ZoneId timeZone = orgDAO.getTimeZone(orgId); final DDOrderMainDataHandler mainDataUpdater = DDOrderMainDataHandler.builder() .ddOrderDetailRequestHandler(ddOrderDetailRequestHandler) .mainDataRequestHandler(mainDataRequestHandler) .abstractDDOrderEvent(ddOrderCreatedEvent) .ddOrderLine(ddOrderLine) .orgZone(timeZone) .build(); mainDataUpdater.handleUpdate(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ddorder\DDOrderAdvisedOrCreatedHandler.java
2
请完成以下Java代码
public abstract class Sha512DigestUtils { /** * Returns an SHA digest. * @return An SHA digest instance. * @throws RuntimeException when a {@link java.security.NoSuchAlgorithmException} is * caught. */ private static MessageDigest getSha512Digest() { try { return MessageDigest.getInstance("SHA-512"); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex.getMessage()); } } /** * Calculates the SHA digest and returns the value as a <code>byte[]</code>. * @param data Data to digest * @return SHA digest */ public static byte[] sha(byte[] data) { return getSha512Digest().digest(data); } /** * Calculates the SHA digest and returns the value as a <code>byte[]</code>. * @param data Data to digest * @return SHA digest */ public static byte[] sha(String data) { return sha(data.getBytes()); } /** * Calculates the SHA digest and returns the value as a hex string.
* @param data Data to digest * @return SHA digest as a hex string */ public static String shaHex(byte[] data) { return new String(Hex.encode(sha(data))); } /** * Calculates the SHA digest and returns the value as a hex string. * @param data Data to digest * @return SHA digest as a hex string */ public static String shaHex(String data) { return new String(Hex.encode(sha(data))); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\token\Sha512DigestUtils.java
1
请完成以下Java代码
public class ActuatorServerLoadProbeWrapper implements ServerLoadProbe { private AtomicReference<ServerMetrics> currentServerMetrics = new AtomicReference<>(null); private final ServerLoadProbe delegate; /** * Constructs a new instance of {@link ActuatorServerLoadProbeWrapper} initialized with the required * {@link ServerLoadProbe} used as the delegate. * * @param serverLoadProbe required {@link ServerLoadProbe}. * @throws IllegalArgumentException if {@link ServerLoadProbe} is {@literal null}. * @see org.apache.geode.cache.server.ServerLoadProbe */ public ActuatorServerLoadProbeWrapper(ServerLoadProbe serverLoadProbe) { Assert.notNull(serverLoadProbe, "ServerLoaderProbe is required"); this.delegate = serverLoadProbe; } /** * Returns the current, most up-to-date details on the {@link ServerLoad} if possible. * * @return the current {@link ServerLoad}. * @see org.apache.geode.cache.server.ServerLoad * @see #getCurrentServerMetrics() * @see java.util.Optional */ public Optional<ServerLoad> getCurrentServerLoad() { return getCurrentServerMetrics().map(getDelegate()::getLoad); } /** * Returns the current, provided {@link ServerMetrics} if available. * * @return the current, provided {@link ServerMetrics} if available. */ public Optional<ServerMetrics> getCurrentServerMetrics() { return Optional.ofNullable(this.currentServerMetrics.get()); } /** * Returns the underlying, wrapped {@link ServerLoadProbe} backing this instance. * * @return the underlying, wrapped {@link ServerLoadProbe}.
* @see org.apache.geode.cache.server.ServerLoadProbe */ protected ServerLoadProbe getDelegate() { return this.delegate; } @Override public ServerLoad getLoad(ServerMetrics metrics) { this.currentServerMetrics.set(metrics); return getDelegate().getLoad(metrics); } @Override public void open() { getDelegate().open(); } @Override public void close() { getDelegate().close(); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator\src\main\java\org\springframework\geode\boot\actuate\health\support\ActuatorServerLoadProbeWrapper.java
1
请在Spring Boot框架中完成以下Java代码
public static Double getDoubleFromJson(ObjectNode objectNode, String fieldName) { String s = getStringFromJson(objectNode, fieldName); if (StringUtils.isNotEmpty(s)) { return Double.valueOf(s); } return null; } public static Long getLongFromJson(ObjectNode objectNode, String fieldName) { String s = getStringFromJson(objectNode, fieldName); if (StringUtils.isNotEmpty(s)) { return Long.valueOf(s); } return null; }
public static Boolean getBooleanFromJson(ObjectNode objectNode, String fieldName, Boolean defaultValue) { Boolean value = getBooleanFromJson(objectNode, fieldName); return value != null ? value : defaultValue; } public static Boolean getBooleanFromJson(ObjectNode objectNode, String fieldName) { String s = getStringFromJson(objectNode, fieldName); if (StringUtils.isNotEmpty(s)) { return Boolean.valueOf(s); } return null; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\history\async\util\AsyncHistoryJsonUtil.java
2
请在Spring Boot框架中完成以下Java代码
public class RetryExceptionJobDemo { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Bean public Job retryExceptionJob() { return jobBuilderFactory.get("retryExceptionJob") .start(step()) .build(); } private Step step() { return stepBuilderFactory.get("step") .<String, String>chunk(2) .reader(listItemReader()) .processor(myProcessor()) .writer(list -> list.forEach(System.out::println)) .faultTolerant() // 配置错误容忍 .retry(MyJobExecutionException.class) // 配置重试的异常类型 .retryLimit(3) // 重试3次,三次过后还是异常的话,则任务会结束, // 异常的次数为reader,processor和writer中的总数,这里仅在processor里演示异常重试 .build(); } private ListItemReader<String> listItemReader() { ArrayList<String> datas = new ArrayList<>(); IntStream.range(0, 5).forEach(i -> datas.add(String.valueOf(i))); return new ListItemReader<>(datas); }
private ItemProcessor<String, String> myProcessor() { return new ItemProcessor<String, String>() { private int count; @Override public String process(String item) throws Exception { System.out.println("当前处理的数据:" + item); if (count >= 2) { return item; } else { count++; throw new MyJobExecutionException("任务处理出错"); } } }; } }
repos\SpringAll-master\72.spring-batch-exception\src\main\java\cc\mrbird\batch\job\RetryExceptionJobDemo.java
2
请完成以下Java代码
public boolean hasChangesRecursivelly() { if (singleDocument == null) { return false; } return singleDocument.hasChangesRecursivelly(); } @Override public void saveIfHasChanges() { if (singleDocument != null) { final DocumentSaveStatus saveStatus = singleDocument.saveIfHasChanges(); if (saveStatus.isSaved()) { forgetSingleDocument(); } else if (saveStatus.isDeleted()) { singleDocument.markAsDeleted(); forgetSingleDocument(); } } } private final void forgetSingleDocument() {
singleDocument = null; } @Override public void markStaleAll() { staled = true; parentDocument.getChangesCollector().collectStaleDetailId(parentDocumentPath, getDetailId()); } @Override public void markStale(final DocumentIdsSelection rowIds) { markStaleAll(); } @Override public boolean isStale() { return staled; } @Override public int getNextLineNo() { return 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\SingleRowDetailIncludedDocumentsCollection.java
1
请完成以下Java代码
public void setTargetUrlParameter(String targetUrlParameter) { if (targetUrlParameter != null) { Assert.hasText(targetUrlParameter, "targetUrlParameter cannot be empty"); } this.targetUrlParameter = targetUrlParameter; } protected @Nullable String getTargetUrlParameter() { return this.targetUrlParameter; } /** * Allows overriding of the behaviour when redirecting to a target URL. * @param redirectStrategy {@link RedirectStrategy} to use */ public void setRedirectStrategy(RedirectStrategy redirectStrategy) { Assert.notNull(redirectStrategy, "redirectStrategy cannot be null"); this.redirectStrategy = redirectStrategy;
} protected RedirectStrategy getRedirectStrategy() { return this.redirectStrategy; } /** * If set to {@code true} the {@code Referer} header will be used (if available). * Defaults to {@code false}. */ public void setUseReferer(boolean useReferer) { this.useReferer = useReferer; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\AbstractAuthenticationTargetUrlRequestHandler.java
1
请完成以下Java代码
public void deploy(EngineDeployment deployment, Map<String, Object> deploymentSettings) { LOGGER.debug("Processing rules deployment {}", deployment.getName()); KnowledgeBuilder knowledgeBuilder = null; DeploymentManager deploymentManager = CommandContextUtil.getProcessEngineConfiguration().getDeploymentManager(); Map<String, EngineResource> resources = deployment.getResources(); for (String resourceName : resources.keySet()) { if (resourceName.endsWith(".drl")) { // is only parsing .drls sufficient? what about other rule dsl's? (@see ResourceType) LOGGER.info("Processing rules resource {}", resourceName); if (knowledgeBuilder == null) { knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); } EngineResource resourceEntity = resources.get(resourceName); byte[] resourceBytes = resourceEntity.getBytes();
Resource droolsResource = ResourceFactory.newByteArrayResource(resourceBytes); knowledgeBuilder.add(droolsResource, ResourceType.DRL); } } if (knowledgeBuilder != null) { KieBase kieBase = knowledgeBuilder.newKieBase(); deploymentManager.getKnowledgeBaseCache().add(deployment.getId(), kieBase); } } @Override public void undeploy(EngineDeployment parentDeployment, boolean cascade) { // Nothing to do } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\rules\RulesDeployer.java
1
请完成以下Java代码
public static MHRConceptCategory forValue(Properties ctx, String value) { if (value == null) { return null; } final int AD_Client_ID = Env.getAD_Client_ID(ctx); // Try cache final String key = AD_Client_ID+"#"+value; MHRConceptCategory cc = s_cacheValue.get(key); if (cc != null) { return cc; } // Try database final String whereClause = COLUMNNAME_Value+"=? AND AD_Client_ID IN (?,?)"; cc = new Query(ctx, Table_Name, whereClause, null) .setParameters(new Object[]{value, 0, AD_Client_ID}) .setOnlyActiveRecords(true)
.setOrderBy("AD_Client_ID DESC") .first(); if (cc != null) { s_cacheValue.put(key, cc); s_cache.put(cc.get_ID(), cc); } return cc; } public MHRConceptCategory(Properties ctx, int HR_Concept_Category_ID, String trxName) { super(ctx, HR_Concept_Category_ID, trxName); } public MHRConceptCategory(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\model\MHRConceptCategory.java
1
请完成以下Java代码
public class GetTaskAttachmentContentCmd implements Command<InputStream>, Serializable { private static final long serialVersionUID = 1L; protected String attachmentId; protected String taskId; public GetTaskAttachmentContentCmd(String taskId, String attachmentId) { this.attachmentId = attachmentId; this.taskId = taskId; } public InputStream execute(CommandContext commandContext) { AttachmentEntity attachment = (AttachmentEntity) commandContext .getAttachmentManager() .findAttachmentByTaskIdAndAttachmentId(taskId, attachmentId); if (attachment == null) {
return null; } String contentId = attachment.getContentId(); if (contentId==null) { return null; } ByteArrayEntity byteArray = commandContext .getDbEntityManager() .selectById(ByteArrayEntity.class, contentId); byte[] bytes = byteArray.getBytes(); return new ByteArrayInputStream(bytes); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetTaskAttachmentContentCmd.java
1
请在Spring Boot框架中完成以下Java代码
private void generateHTMLReport(IReportRunnable report, HttpServletResponse response, HttpServletRequest request) { IRunAndRenderTask runAndRenderTask = birtEngine.createRunAndRenderTask(report); response.setContentType(birtEngine.getMIMEType("html")); IRenderOption options = new RenderOption(); HTMLRenderOption htmlOptions = new HTMLRenderOption(options); htmlOptions.setOutputFormat("html"); htmlOptions.setBaseImageURL("/" + reportsPath + imagesPath); htmlOptions.setImageDirectory(imageFolder); htmlOptions.setImageHandler(htmlImageHandler); runAndRenderTask.setRenderOption(htmlOptions); runAndRenderTask.getAppContext().put(EngineConstants.APPCONTEXT_BIRT_VIEWER_HTTPSERVET_REQUEST, request); try { htmlOptions.setOutputStream(response.getOutputStream()); runAndRenderTask.run(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { runAndRenderTask.close(); } } /** * Generate a report as PDF */ @SuppressWarnings("unchecked") private void generatePDFReport(IReportRunnable report, HttpServletResponse response, HttpServletRequest request) { IRunAndRenderTask runAndRenderTask = birtEngine.createRunAndRenderTask(report); response.setContentType(birtEngine.getMIMEType("pdf")); IRenderOption options = new RenderOption(); PDFRenderOption pdfRenderOption = new PDFRenderOption(options); pdfRenderOption.setOutputFormat("pdf"); runAndRenderTask.setRenderOption(pdfRenderOption); runAndRenderTask.getAppContext().put(EngineConstants.APPCONTEXT_PDF_RENDER_CONTEXT, request);
try { pdfRenderOption.setOutputStream(response.getOutputStream()); runAndRenderTask.run(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { runAndRenderTask.close(); } } @Override public void destroy() { birtEngine.destroy(); Platform.shutdown(); } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-birt\src\main\java\com\baeldung\birt\engine\service\BirtReportService.java
2
请完成以下Java代码
public class InstantRangeQueryFilter<T> implements IQueryFilter<T>, ISqlQueryFilter { private final String columnName; private final Range<Instant> range; private boolean sqlBuilt = false; private String sqlWhereClause = null; private List<Object> sqlParams = null; private InstantRangeQueryFilter(@NonNull final String columnName, @NonNull Range<Instant> range) { this.columnName = columnName; this.range = range; } public static <T> InstantRangeQueryFilter<T> of(@NonNull final String columnName, @NonNull Range<Instant> range) { return new InstantRangeQueryFilter<>(columnName, range); } @Override public boolean accept(final T model) { final Instant value = InterfaceWrapperHelper.getValue(model, columnName) .map(TimeUtil::asInstant) .orElse(null); return value != null && range.contains(value); } @Override public final String getSql() { buildSql(); return sqlWhereClause; } @Override public final List<Object> getSqlParams(final Properties ctx) { return getSqlParams(); } public final List<Object> getSqlParams() { buildSql(); return sqlParams; } private void buildSql() { if (sqlBuilt) { return; } final ArrayList<Object> sqlParams = new ArrayList<>(); final StringBuilder sql = new StringBuilder();
sql.append(columnName).append(" IS NOT NULL"); if (range.hasLowerBound()) { final String operator; final BoundType boundType = range.lowerBoundType(); switch (boundType) { case OPEN: operator = ">"; break; case CLOSED: operator = ">="; break; default: throw new AdempiereException("Unknown bound: " + boundType); } sql.append(" AND ").append(columnName).append(operator).append("?"); sqlParams.add(range.lowerEndpoint()); } if (range.hasUpperBound()) { final String operator; final BoundType boundType = range.upperBoundType(); switch (boundType) { case OPEN: operator = "<"; break; case CLOSED: operator = "<="; break; default: throw new AdempiereException("Unknown bound: " + boundType); } sql.append(" AND ").append(columnName).append(operator).append("?"); sqlParams.add(range.upperEndpoint()); } // this.sqlWhereClause = sql.toString(); this.sqlParams = !sqlParams.isEmpty() ? Collections.unmodifiableList(sqlParams) : ImmutableList.of(); this.sqlBuilt = true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\InstantRangeQueryFilter.java
1
请完成以下Java代码
public PageData<RuleChain> findByTenantId(UUID tenantId, PageLink pageLink) { return findRuleChainsByTenantId(tenantId, pageLink); } @Override public RuleChainId getExternalIdByInternal(RuleChainId internalId) { return Optional.ofNullable(ruleChainRepository.getExternalIdById(internalId.getId())) .map(RuleChainId::new).orElse(null); } @Override public RuleChain findDefaultEntityByTenantId(UUID tenantId) { return findRootRuleChainByTenantIdAndType(tenantId, RuleChainType.CORE); } @Override public PageData<RuleChain> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findRuleChainsByTenantId(tenantId.getId(), pageLink); } @Override public List<EntityInfo> findByTenantIdAndResource(TenantId tenantId, String reference, int limit) { return ruleChainRepository.findRuleChainsByTenantIdAndResource(tenantId.getId(), reference, PageRequest.of(0, limit)); }
@Override public List<EntityInfo> findByResource(String reference, int limit) { return ruleChainRepository.findRuleChainsByResource(reference, PageRequest.of(0, limit)); } @Override public List<RuleChainFields> findNextBatch(UUID id, int batchSize) { return ruleChainRepository.findNextBatch(id, Limit.of(batchSize)); } @Override public EntityType getEntityType() { return EntityType.RULE_CHAIN; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\rule\JpaRuleChainDao.java
1
请完成以下Java代码
protected ImportRecordResult importRecord( final @NonNull IMutable<Object> state_NOTUSED, final @NonNull I_I_Request importRecord, final boolean isInsertOnly_NOTUSED) { // // Create a new request final I_R_Request request = InterfaceWrapperHelper.newInstance(I_R_Request.class, importRecord); request.setAD_Org_ID(importRecord.getAD_Org_ID()); // // BPartner { int bpartnerId = importRecord.getC_BPartner_ID(); if (bpartnerId <= 0) { throw new AdempiereException("BPartner not found"); } request.setC_BPartner_ID(bpartnerId); } // // request type { int requesTypeId = importRecord.getR_RequestType_ID(); if (requesTypeId <= 0) { throw new AdempiereException("Request Type not found"); } request.setR_RequestType_ID(requesTypeId); } // // status { int statusId = importRecord.getR_Status_ID(); if (statusId <= 0) { throw new AdempiereException("Status not found"); } request.setR_Status_ID(statusId); } // // set data from the other fields request.setDateTrx(importRecord.getDateTrx()); request.setDateNextAction(importRecord.getDateNextAction());
request.setSummary(importRecord.getSummary()); request.setDocumentNo(importRecord.getDocumentNo()); int userid = Env.getAD_User_ID(getCtx()); request.setSalesRep_ID(userid); // InterfaceWrapperHelper.save(request); // // Link back the request to current import record importRecord.setR_Request(request); // return ImportRecordResult.Inserted; } @Override protected void markImported(final I_I_Request importRecord) { importRecord.setI_IsImported(X_I_Request.I_ISIMPORTED_Imported); importRecord.setProcessed(true); InterfaceWrapperHelper.save(importRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\request\impexp\RequestImportProcess.java
1
请在Spring Boot框架中完成以下Java代码
public class SeataRestTemplateAutoConfiguration { @Autowired( required = false ) private Collection<RestTemplate> restTemplates; @Autowired private SeataRestTemplateInterceptor seataRestTemplateInterceptor; public SeataRestTemplateAutoConfiguration() { } @Bean public SeataRestTemplateInterceptor seataRestTemplateInterceptor() { return new SeataRestTemplateInterceptor(); }
@PostConstruct public void init() { if (this.restTemplates != null) { Iterator var1 = this.restTemplates.iterator(); while (var1.hasNext()) { RestTemplate restTemplate = (RestTemplate) var1.next(); List<ClientHttpRequestInterceptor> interceptors = new ArrayList(restTemplate.getInterceptors()); interceptors.add(this.seataRestTemplateInterceptor); restTemplate.setInterceptors(interceptors); } } } }
repos\SpringBootLearning-master (1)\springboot-seata\sbm-account-service\src\main\java\com\gf\config\SeataRestTemplateAutoConfiguration.java
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO(Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return (java.lang.String)get_Value(COLUMNNAME_Description); } @Override public void setInvoiceProcessingServiceCompany_ID (int InvoiceProcessingServiceCompany_ID) { if (InvoiceProcessingServiceCompany_ID < 1) set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_ID, null); else set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_ID, Integer.valueOf(InvoiceProcessingServiceCompany_ID)); } @Override public int getInvoiceProcessingServiceCompany_ID() { return get_ValueAsInt(COLUMNNAME_InvoiceProcessingServiceCompany_ID); } @Override public void setServiceCompany_BPartner_ID (int ServiceCompany_BPartner_ID) { if (ServiceCompany_BPartner_ID < 1) set_Value (COLUMNNAME_ServiceCompany_BPartner_ID, null); else set_Value (COLUMNNAME_ServiceCompany_BPartner_ID, Integer.valueOf(ServiceCompany_BPartner_ID)); } @Override public int getServiceCompany_BPartner_ID() {
return get_ValueAsInt(COLUMNNAME_ServiceCompany_BPartner_ID); } @Override public void setServiceFee_Product_ID (int ServiceFee_Product_ID) { if (ServiceFee_Product_ID < 1) set_Value (COLUMNNAME_ServiceFee_Product_ID, null); else set_Value (COLUMNNAME_ServiceFee_Product_ID, Integer.valueOf(ServiceFee_Product_ID)); } @Override public int getServiceFee_Product_ID() { return get_ValueAsInt(COLUMNNAME_ServiceFee_Product_ID); } @Override public void setServiceInvoice_DocType_ID (int ServiceInvoice_DocType_ID) { if (ServiceInvoice_DocType_ID < 1) set_Value (COLUMNNAME_ServiceInvoice_DocType_ID, null); else set_Value (COLUMNNAME_ServiceInvoice_DocType_ID, Integer.valueOf(ServiceInvoice_DocType_ID)); } @Override public int getServiceInvoice_DocType_ID() { return get_ValueAsInt(COLUMNNAME_ServiceInvoice_DocType_ID); } @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_InvoiceProcessingServiceCompany.java
1
请完成以下Java代码
public void registerFactoryForTableName( @NonNull final String tableName, @NonNull final IAttributeSetInstanceAwareFactory factory) { tableName2Factory.put(tableName, factory); } @Override public IAttributeSetInstanceAware createOrNull(final Object referencedObj) { if (referencedObj == null) { return null; } // If already an ASI aware, return it if (referencedObj instanceof IAttributeSetInstanceAware) { return (IAttributeSetInstanceAware)referencedObj; } final IAttributeSetInstanceAwareFactory factory; final String tableName = InterfaceWrapperHelper.getModelTableNameOrNull(referencedObj); if (tableName != null) { factory = getFactoryForTableNameOrDefault(tableName);
} else { return null; } return factory.createOrNull(referencedObj); } private IAttributeSetInstanceAwareFactory getFactoryForTableNameOrDefault(@NonNull final String tableName) { final IAttributeSetInstanceAwareFactory factory = tableName2Factory.get(tableName); if (factory != null) { return factory; } return defaultFactory; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\asi_aware\factory\impl\AttributeSetInstanceAwareFactoryService.java
1
请在Spring Boot框架中完成以下Java代码
public class FlowableVariableEventImpl extends FlowableEngineEventImpl implements FlowableVariableEvent { protected String variableName; protected Object variableValue; protected VariableType variableType; protected String taskId; protected String variableInstanceId; public FlowableVariableEventImpl(FlowableEngineEventType type) { super(type); } @Override public String getVariableName() { return variableName; } public void setVariableName(String variableName) { this.variableName = variableName; } @Override public Object getVariableValue() { return variableValue; } public void setVariableValue(Object variableValue) { this.variableValue = variableValue; } @Override public VariableType getVariableType() { return variableType; } public void setVariableType(VariableType variableType) {
this.variableType = variableType; } @Override public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getVariableInstanceId() { return variableInstanceId; } public void setVariableInstanceId(String variableInstanceId) { this.variableInstanceId = variableInstanceId; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\event\impl\FlowableVariableEventImpl.java
2
请完成以下Java代码
public final class ResourceAsPermission extends AbstractPermission implements Resource { public static final Permission ofName(final String name) { return new ResourceAsPermission(name); } private final String name; private int hashcode = 0; @ToStringBuilder(skip = true) private final Object _resourceId; private ResourceAsPermission(final String name) { super(); Check.assumeNotEmpty(name, "name not empty"); this.name = name; this._resourceId = getClass().getName() + "." + name; } @Override public String toString() { // NOTE: we are making it translateable friendly because it's displayed in Prefereces->Info->Rollen return "@" + name + "@"; } @Override public int hashCode() { if (hashcode == 0) { hashcode = new HashcodeBuilder() .append(name) .toHashcode(); } return hashcode; } @Override public boolean equals(final Object obj) {
if (this == obj) { return true; } final ResourceAsPermission other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(this.name, other.name) .isEqual(); } @Override public Resource getResource() { return this; } @Override public boolean hasAccess(final Access access) { // TODO: return accesses.contains(access); throw new UnsupportedOperationException("Not implemented"); } @Override public Permission mergeWith(Permission accessFrom) { checkCompatibleAndCast(accessFrom); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\ResourceAsPermission.java
1
请完成以下Java代码
public String getProcessDefinitionName() { return processDefinitionName; } public void setProcessDefinitionName(String processDefinitionName) { this.processDefinitionName = processDefinitionName; } public int getProcessDefinitionVersion() { return processDefinitionVersion; } public void setProcessDefinitionVersion(int processDefinitionVersion) { this.processDefinitionVersion = processDefinitionVersion; } public Integer getHistoryTimeToLive() { return historyTimeToLive; } public void setHistoryTimeToLive(Integer historyTimeToLive) { this.historyTimeToLive = historyTimeToLive; } public long getFinishedProcessInstanceCount() { return finishedProcessInstanceCount; } public void setFinishedProcessInstanceCount(Long finishedProcessInstanceCount) { this.finishedProcessInstanceCount = finishedProcessInstanceCount; } public long getCleanableProcessInstanceCount() { return cleanableProcessInstanceCount; } public void setCleanableProcessInstanceCount(Long cleanableProcessInstanceCount) { this.cleanableProcessInstanceCount = cleanableProcessInstanceCount; } public String getTenantId() {
return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String toString() { return this.getClass().getSimpleName() + "[processDefinitionId = " + processDefinitionId + ", processDefinitionKey = " + processDefinitionKey + ", processDefinitionName = " + processDefinitionName + ", processDefinitionVersion = " + processDefinitionVersion + ", historyTimeToLive = " + historyTimeToLive + ", finishedProcessInstanceCount = " + finishedProcessInstanceCount + ", cleanableProcessInstanceCount = " + cleanableProcessInstanceCount + ", tenantId = " + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CleanableHistoricProcessInstanceReportResultEntity.java
1
请完成以下Java代码
private static final ViewActionMethodReturnTypeConverter createReturnTypeConverter(final Method method) { final Class<?> viewActionReturnType = method.getReturnType(); if (Void.class.equals(viewActionReturnType) || void.class.equals(viewActionReturnType)) { return returnValue -> null; } else if (ProcessInstanceResult.ResultAction.class.isAssignableFrom(viewActionReturnType)) { return returnType -> (ProcessInstanceResult.ResultAction)returnType; } else { throw new IllegalArgumentException("Action method's return type is not supported: " + method); } } private static final ViewActionMethodArgumentExtractor createViewActionMethodArgumentExtractor(final String parameterName, final Class<?> parameterType, final ViewActionParam annotation) { if (annotation != null) { return (view, processParameters, selectedDocumentIds) -> processParameters.getFieldView(parameterName).getValueAs(parameterType); } // // selectedDocumentIds internal parameter else if (DocumentIdsSelection.class.isAssignableFrom(parameterType)) { return (view, processParameters, selectedDocumentIds) -> selectedDocumentIds; } // // View parameter else if (IView.class.isAssignableFrom(parameterType)) { return (view, processParameters, selectedDocumentIds) -> view; } // // Primitive type => not supported else if (parameterType.isPrimitive()) { throw new IllegalArgumentException("Action method's primitive parameter " + parameterType + " is not supported for parameterName: " + parameterName); } // // Try getting the bean from spring context else { return (view, processParameters, selectedDocumentIds) -> Adempiere.getBean(parameterType); } } /** Helper class used to generate unique actionIds based on annotated method name */ private static final class ActionIdGenerator
{ private final Map<String, MutableInt> methodName2counter = new HashMap<>(); public String getActionId(final Method actionMethod) { final String methodName = actionMethod.getName(); final MutableInt counter = methodName2counter.computeIfAbsent(methodName, k -> new MutableInt(0)); final int methodNameSuffix = counter.incrementAndGet(); if (methodNameSuffix == 1) { return methodName; } else if (methodNameSuffix > 1) { return methodName + methodNameSuffix; } else { // shall NEVER happen throw new IllegalStateException("internal error: methodNameSuffix <= 0"); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\view\ViewActionDescriptorsFactory.java
1
请在Spring Boot框架中完成以下Java代码
private List<ConfigDataResolutionResult> resolve(ConfigDataLocation location, boolean profileSpecific, Supplier<List<? extends ConfigDataResource>> resolveAction) { List<ConfigDataResource> resources = nonNullList(resolveAction.get()); List<ConfigDataResolutionResult> resolved = new ArrayList<>(resources.size()); for (ConfigDataResource resource : resources) { resolved.add(new ConfigDataResolutionResult(location, resource, profileSpecific)); } return resolved; } @SuppressWarnings("unchecked") private <T> List<T> nonNullList(@Nullable List<? extends T> list) { return (list != null) ? (List<T>) list : Collections.emptyList(); } private <T> List<T> merge(List<T> list1, List<T> list2) {
List<T> merged = new ArrayList<>(list1.size() + list2.size()); merged.addAll(list1); merged.addAll(list2); return merged; } /** * Return the resolvers managed by this object. * @return the resolvers */ List<ConfigDataLocationResolver<?>> getResolvers() { return this.resolvers; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataLocationResolvers.java
2
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSourceActivityId() { return sourceActivityId; } public void setSourceActivityId(String sourceActivityId) { this.sourceActivityId = sourceActivityId; } public String getSourceActivityName() { return sourceActivityName; } public void setSourceActivityName(String sourceActivityName) { this.sourceActivityName = sourceActivityName; } public String getSourceActivityType() { return sourceActivityType; } public void setSourceActivityType(String sourceActivityType) { this.sourceActivityType = sourceActivityType; } public String getTargetActivityId() { return targetActivityId; } public void setTargetActivityId(String targetActivityId) { this.targetActivityId = targetActivityId; } public String getTargetActivityName() { return targetActivityName; } public void setTargetActivityName(String targetActivityName) {
this.targetActivityName = targetActivityName; } public String getTargetActivityType() { return targetActivityType; } public void setTargetActivityType(String targetActivityType) { this.targetActivityType = targetActivityType; } public String getSourceActivityBehaviorClass() { return sourceActivityBehaviorClass; } public void setSourceActivityBehaviorClass(String sourceActivityBehaviorClass) { this.sourceActivityBehaviorClass = sourceActivityBehaviorClass; } public String getTargetActivityBehaviorClass() { return targetActivityBehaviorClass; } public void setTargetActivityBehaviorClass(String targetActivityBehaviorClass) { this.targetActivityBehaviorClass = targetActivityBehaviorClass; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiSequenceFlowTakenEventImpl.java
1
请完成以下Java代码
public String getCamundaCalledElementTenantId() { return camundaCalledElementTenantIdAttribute.getValue(this); } public void setCamundaCalledElementTenantId(String tenantId) { camundaCalledElementTenantIdAttribute.setValue(this, tenantId); } public String getCamundaCaseTenantId() { return camundaCaseTenantIdAttribute.getValue(this); } public void setCamundaCaseTenantId(String tenantId) { camundaCaseTenantIdAttribute.setValue(this, tenantId); } @Override public String getCamundaVariableMappingClass() { return camundaVariableMappingClassAttribute.getValue(this); }
@Override public void setCamundaVariableMappingClass(String camundaClass) { camundaVariableMappingClassAttribute.setValue(this, camundaClass); } @Override public String getCamundaVariableMappingDelegateExpression() { return camundaVariableMappingDelegateExpressionAttribute.getValue(this); } @Override public void setCamundaVariableMappingDelegateExpression(String camundaExpression) { camundaVariableMappingDelegateExpressionAttribute.setValue(this, camundaExpression); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CallActivityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void logReceivedFromMetasfresh(final String queueName, final RequestToProcurementWeb message) { log(queueName, "IN", message, message.getEventId(), message.getRelatedEventId()); } private void log( final String queueName, final String direction, final Object message, final String eventId, final String relatedEventId) { try { final RabbitMQAuditEntry entry = new RabbitMQAuditEntry(); entry.setQueue(queueName); entry.setDirection(direction); entry.setContent(Ascii.truncate(convertToString(message), RabbitMQAuditEntry.CONTENT_LENGTH, "...")); entry.setEventId(eventId); entry.setRelatedEventId(relatedEventId); repository.save(entry); } catch (Exception ex) { logger.warn("Failed saving audit entry for queueName={}, direction={}, message=`{}`.", queueName, direction, message, ex);
} } private String convertToString(@NonNull final Object message) { try { return Constants.PROCUREMENT_WEBUI_OBJECT_MAPPER.writeValueAsString(message); } catch (final Exception ex) { logger.warn("Failed converting message to JSON: {}. Returning toString().", message, ex); return message.toString(); } } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\RabbitMQAuditService.java
2
请完成以下Java代码
public class ALayoutConstraint implements Comparable { /** * Layout Constraint to indicate grid position * @param row row 0..x * @param col column 0..x */ public ALayoutConstraint(int row, int col) { m_row = row; m_col = col; } // ALayoutConstraint /** * Create Next in Row * @return ALayoutConstraint for additional column in same row */ public ALayoutConstraint createNext() { return new ALayoutConstraint(m_row, m_col+1); } // createNext private int m_row; private int m_col; /** * Get Row * @return roe no */ public int getRow() { return m_row; } // getRow /** * Get Column * @return col no */ public int getCol() { return m_col; } // getCol /** * Compares this object with the specified object for order. Returns a * negative integer, zero, or a positive integer as this object is less * than, equal to, or greater than the specified object.<p> * * @param o the Object to be compared. * @return a negative integer if this object is less than the specified object, * zero if equal, * or a positive integer if this object is greater than the specified object. */ public int compareTo(Object o)
{ ALayoutConstraint comp = null; if (o instanceof ALayoutConstraint) comp = (ALayoutConstraint)o; if (comp == null) return +111; // Row compare int rowComp = m_row - comp.getRow(); if (rowComp != 0) return rowComp; // Column compare return m_col - comp.getCol(); } // compareTo /** * Is Object Equal * @param o * @return true if equal */ public boolean equals(Object o) { if (o instanceof ALayoutConstraint) return compareTo(o) == 0; return false; } // equal /** * To String * @return info */ public String toString() { return "ALayoutConstraint [Row=" + m_row + ", Col=" + m_col + "]"; } // toString } // ALayoutConstraint
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ALayoutConstraint.java
1
请完成以下Java代码
public Set<CandidateId> deleteAllSimulatedCandidates() { cleanUpSimulatedRelatedRecords(); final DeleteCandidatesQuery deleteCandidatesQuery = DeleteCandidatesQuery.builder() .status(X_MD_Candidate.MD_CANDIDATE_STATUS_Simulated) .isActive(false) .build(); return candidateService.deleteCandidatesAndDetailsByQuery(deleteCandidatesQuery); } public void deactivateAllSimulatedCandidates() { candidateService.deactivateSimulatedCandidates(); }
private void cleanUpSimulatedRelatedRecords() { for (final SimulatedCleanUpService cleanUpService : simulatedCleanUpServiceList) { try { cleanUpService.cleanUpSimulated(); } catch (final Exception e) { Loggables.get().addLog("{0} failed to cleanup, see error: {1}", cleanUpService.getClass().getName(), e); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\SimulatedCandidateService.java
1
请完成以下Java代码
public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } public String getCaseExecutionId() { return caseExecutionId; } public void setCaseExecutionId(String caseExecutionId) { this.caseExecutionId = caseExecutionId; } public String getErrorMessage() { return typedValueField.getErrorMessage(); } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getState() { return state; } public void setState(String state) { this.state = state; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; }
public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", processDefinitionKey=" + processDefinitionKey + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + ", processInstanceId=" + processInstanceId + ", taskId=" + taskId + ", executionId=" + executionId + ", tenantId=" + tenantId + ", activityInstanceId=" + activityInstanceId + ", caseDefinitionKey=" + caseDefinitionKey + ", caseDefinitionId=" + caseDefinitionId + ", caseInstanceId=" + caseInstanceId + ", caseExecutionId=" + caseExecutionId + ", name=" + name + ", createTime=" + createTime + ", revision=" + revision + ", serializerName=" + getSerializerName() + ", longValue=" + longValue + ", doubleValue=" + doubleValue + ", textValue=" + textValue + ", textValue2=" + textValue2 + ", state=" + state + ", byteArrayId=" + getByteArrayId() + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricVariableInstanceEntity.java
1
请完成以下Java代码
public static String prepareSearchString(final Object value) { return prepareSearchString(value, false); } public static String prepareSearchString(final Object value, final boolean isIdentifier) { if (value == null || value.toString().length() == 0) { return null; } String valueStr; if (isIdentifier) { // metas-2009_0021_AP1_CR064: begin valueStr = ((String)value).trim(); if (!valueStr.startsWith("%")) valueStr = "%" + value; // metas-2009_0021_AP1_CR064: end if (!valueStr.endsWith("%")) valueStr += "%"; } else { valueStr = (String)value; if (valueStr.startsWith("%")) {
; // nothing } else if (valueStr.endsWith("%")) { ; // nothing } else if (valueStr.indexOf("%") < 0) { valueStr = "%" + valueStr + "%"; } else { ; // nothing } } return valueStr; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\FindHelper.java
1
请完成以下Java代码
public void setImplementation(String implementation) { this.implementation = implementation; } @Override public String getDeploymentId() { return deploymentId; } @Override public String getCategory() { return category; } @Override public void setCategory(String category) { this.category = category; } @Override public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @Override public Date getCreateTime() { return createTime; } @Override public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String getResourceName() { return resourceName;
} @Override public void setResourceName(String resourceName) { this.resourceName = resourceName; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String toString() { return "ChannelDefinitionEntity[" + id + "]"; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\ChannelDefinitionEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public int update(Long id, UmsResource umsResource) { umsResource.setId(id); int count = resourceMapper.updateByPrimaryKeySelective(umsResource); adminCacheService.delResourceListByResource(id); return count; } @Override public UmsResource getItem(Long id) { return resourceMapper.selectByPrimaryKey(id); } @Override public int delete(Long id) { int count = resourceMapper.deleteByPrimaryKey(id); adminCacheService.delResourceListByResource(id); return count; } @Override public List<UmsResource> list(Long categoryId, String nameKeyword, String urlKeyword, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum,pageSize); UmsResourceExample example = new UmsResourceExample(); UmsResourceExample.Criteria criteria = example.createCriteria(); if(categoryId!=null){ criteria.andCategoryIdEqualTo(categoryId);
} if(StrUtil.isNotEmpty(nameKeyword)){ criteria.andNameLike('%'+nameKeyword+'%'); } if(StrUtil.isNotEmpty(urlKeyword)){ criteria.andUrlLike('%'+urlKeyword+'%'); } return resourceMapper.selectByExample(example); } @Override public List<UmsResource> listAll() { return resourceMapper.selectByExample(new UmsResourceExample()); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\UmsResourceServiceImpl.java
2
请完成以下Java代码
public boolean isNumericKey() { return true; } @Override public LookupDataSourceFetcher getLookupDataSourceFetcher() { return this; } @Override public Builder newContextForFetchingById(final Object id) { return LookupDataSourceContext.builder(CONTEXT_LookupTableName) .requiresAD_Language() .putFilterById(IdsToFilter.ofSingleValue(id)); } @Override public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx) { final Object id = evalCtx.getSingleIdToFilterAsObject(); if (id == null) { throw new IllegalStateException("No ID provided in " + evalCtx); } return getLookupValueById(id); } public LookupValue getLookupValueById(final Object idObj) { final LookupValue country = getAllCountriesById().getById(idObj); return CoalesceUtil.coalesce(country, LOOKUPVALUE_NULL); } @Override public Builder newContextForFetchingList() { return LookupDataSourceContext.builder(CONTEXT_LookupTableName) .requiresFilterAndLimit() .requiresAD_Language(); } @Override public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx) { // // Determine what we will filter final LookupValueFilterPredicate filter = evalCtx.getFilterPredicate(); final int offset = evalCtx.getOffset(0); final int limit = evalCtx.getLimit(filter.isMatchAll() ? Integer.MAX_VALUE : 100); // // Get, filter, return return getAllCountriesById() .getValues() .stream() .filter(filter) .collect(LookupValuesList.collect()) .pageByOffsetAndLimit(offset, limit); }
private LookupValuesList getAllCountriesById() { final Object cacheKey = "ALL"; return allCountriesCache.getOrLoad(cacheKey, this::retriveAllCountriesById); } private LookupValuesList retriveAllCountriesById() { return Services.get(ICountryDAO.class) .getCountries(Env.getCtx()) .stream() .map(this::createLookupValue) .collect(LookupValuesList.collect()); } private IntegerLookupValue createLookupValue(final I_C_Country countryRecord) { final int countryId = countryRecord.getC_Country_ID(); final IModelTranslationMap modelTranslationMap = InterfaceWrapperHelper.getModelTranslationMap(countryRecord); final ITranslatableString countryName = modelTranslationMap.getColumnTrl(I_C_Country.COLUMNNAME_Name, countryRecord.getName()); final ITranslatableString countryDescription = modelTranslationMap.getColumnTrl(I_C_Country.COLUMNNAME_Description, countryRecord.getName()); return IntegerLookupValue.of(countryId, countryName, countryDescription); } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressCountryLookupDescriptor.java
1
请完成以下Java代码
public NonCaseString trim() { return NonCaseString.of(this.value.trim()); } public NonCaseString replace(char oldChar, char newChar) { return NonCaseString.of(this.value.replace(oldChar, newChar)); } public NonCaseString replaceAll(String regex, String replacement) { return NonCaseString.of(this.value.replaceAll(regex, replacement)); } public NonCaseString substring(int beginIndex) { return NonCaseString.of(this.value.substring(beginIndex)); } public NonCaseString substring(int beginIndex, int endIndex) { return NonCaseString.of(this.value.substring(beginIndex, endIndex)); } public boolean isNotEmpty() { return !this.value.isEmpty(); } @Override public int length() { return this.value.length(); } @Override public char charAt(int index) { return this.value.charAt(index); }
@Override public CharSequence subSequence(int start, int end) { return this.value.subSequence(start, end); } public String[] split(String regex) { return this.value.split(regex); } /** * @return 原始字符串 */ public String get() { return this.value; } @Override public String toString() { return this.value; } }
repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\entity\NonCaseString.java
1
请完成以下Java代码
public Claims getClaims(String token) { return jwtParser .parseClaimsJws(token) .getBody(); } /** * @param token 需要检查的token */ public void checkRenewal(String token) { // 判断是否续期token,计算token的过期时间 String loginKey = loginKey(token); long time = redisUtils.getExpire(loginKey) * 1000; Date expireDate = DateUtil.offset(new Date(), DateField.MILLISECOND, (int) time); // 判断当前时间与过期时间的时间差 long differ = expireDate.getTime() - System.currentTimeMillis(); // 如果在续期检查的范围内,则续期 if (differ <= properties.getDetect()) { long renew = time + properties.getRenew(); redisUtils.expire(loginKey, renew, TimeUnit.MILLISECONDS); } } public String getToken(HttpServletRequest request) { final String requestHeader = request.getHeader(properties.getHeader()); if (requestHeader != null && requestHeader.startsWith(properties.getTokenStartWith())) { return requestHeader.substring(7);
} return null; } /** * 获取登录用户RedisKey * @param token / * @return key */ public String loginKey(String token) { Claims claims = getClaims(token); return properties.getOnlineKey() + claims.getSubject() + ":" + getId(token); } /** * 获取登录用户TokenKey * @param token / * @return / */ public String getId(String token) { Claims claims = getClaims(token); return claims.get(AUTHORITIES_UUID_KEY).toString(); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\security\security\TokenProvider.java
1
请完成以下Java代码
private DistributionFacetsCollection getFacets(@NonNull final DDOrderReferenceQuery query) { final DistributionFacetsCollector collector = DistributionFacetsCollector.builder() .ddOrderService(ddOrderService) .productService(productService) .warehouseService(warehouseService) .sourceDocService(sourceDocService) .build(); collect(query, collector); return collector.toFacetsCollection(); } private <T> void collect( @NonNull final DDOrderReferenceQuery query, @NonNull final DistributionOrderCollector<T> collector) { // // Already started jobs if (!query.isExcludeAlreadyStarted()) { ddOrderService.streamDDOrders(DistributionJobQueries.ddOrdersAssignedToUser(query)) .forEach(collector::collect); } // // New possible jobs @NonNull final QueryLimit suggestedLimit = query.getSuggestedLimit(); if (suggestedLimit.isNoLimit() || !suggestedLimit.isLimitHitOrExceeded(collector.getCollectedItems())) { ddOrderService.streamDDOrders(DistributionJobQueries.toActiveNotAssignedDDOrderQuery(query)) .limit(suggestedLimit.minusSizeOf(collector.getCollectedItems()).toIntOr(Integer.MAX_VALUE)) .forEach(collector::collect); } } @NonNull private ImmutableSet<String> computeActions( @NonNull final List<DDOrderReference> jobReferences, @NonNull final UserId userId) {
final ImmutableSet.Builder<String> actions = ImmutableSet.builder(); if (hasInTransitSchedules(jobReferences, userId)) { actions.add(ACTION_DROP_ALL); if (warehouseService.getTrolleyByUserId(userId).isPresent()) { actions.add(ACTION_PRINT_IN_TRANSIT_REPORT); } } return actions.build(); } private boolean hasInTransitSchedules( @NonNull final List<DDOrderReference> jobReferences, @NonNull final UserId userId) { final LocatorId inTransitLocatorId = warehouseService.getTrolleyByUserId(userId) .map(LocatorQRCode::getLocatorId) .orElse(null); if (inTransitLocatorId != null) { return loadingSupportServices.hasInTransitSchedules(inTransitLocatorId); } else { return jobReferences.stream().anyMatch(DDOrderReference::isInTransit); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\DistributionWorkflowLaunchersProvider.java
1
请完成以下Java代码
private void assertHUIsPicked(@NonNull final I_M_HU hu) { final String huStatus = hu.getHUStatus(); if (X_M_HU.HUSTATUS_Picked.equals(huStatus) || X_M_HU.HUSTATUS_Active.equals(huStatus)) { // NOTE: we are also tolerating Active status // because the HU is changed to Picked only when the picking candidate is Closed. // Until then it's status is Active. return; } final ADReferenceService adReferenceService = ADReferenceService.get(); final Properties ctx = Env.getCtx(); final String currentStatusTrl = adReferenceService.retrieveListNameTrl(ctx, X_M_HU.HUSTATUS_AD_Reference_ID, huStatus); final String pickedStatusTrl = adReferenceService.retrieveListNameTrl(ctx, X_M_HU.HUSTATUS_AD_Reference_ID, X_M_HU.HUSTATUS_Picked) + ", " + adReferenceService.retrieveListNameTrl(ctx, X_M_HU.HUSTATUS_AD_Reference_ID, X_M_HU.HUSTATUS_Active); throw new AdempiereException(MSG_WEBUI_PICKING_WRONG_HU_STATUS_3P, hu.getValue(), currentStatusTrl, pickedStatusTrl); } private void updateHUStatusToActive(@NonNull final I_M_HU hu) { final IHUContextFactory huContextFactory = Services.get(IHUContextFactory.class); final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); final IHUStatusBL huStatusBL = Services.get(IHUStatusBL.class); final IMutableHUContext huContext = huContextFactory.createMutableHUContext(Env.getCtx(), ITrx.TRXNAME_ThreadInherited); huStatusBL.setHUStatus(huContext, hu, X_M_HU.HUSTATUS_Active); handlingUnitsDAO.saveHU(hu); } private void restoreHUsFromSourceHUs(final HuId huId) {
final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); final SourceHUsService sourceHUsService = SourceHUsService.get(); final Collection<I_M_HU> sourceHUs = sourceHUsRepository.retrieveActualSourceHUs(ImmutableSet.of(huId)); for (final I_M_HU sourceHU : sourceHUs) { if (!handlingUnitsBL.isDestroyed(sourceHU)) { continue; } sourceHUsService.restoreHuFromSourceHuMarkerIfPossible(sourceHU); } } private void changeStatusToDraftAndSave(final PickingCandidate pickingCandidate) { pickingCandidate.changeStatusToDraft(); pickingCandidateRepository.save(pickingCandidate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\UnProcessPickingCandidatesAndRestoreSourceHUsCommand.java
1
请完成以下Java代码
public void setUomCode(final String uomCode) { this.uomCode = uomCode; this.uomCodeSet = true; } @NonNull public String getOrgCode() { return orgCode; } @NonNull public String getProductIdentifier() {
return productIdentifier; } @NonNull public TaxCategory getTaxCategory() { return taxCategory; } @NonNull public BigDecimal getPriceStd() { return priceStd; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-pricing\src\main\java\de\metas\common\pricing\v2\productprice\JsonRequestProductPrice.java
1
请完成以下Java代码
private void addMenuItem(JPopupMenu menu, String title, WorkflowNodeTransitionModel line) { WFPopupItem item = new WFPopupItem(title, line); menu.add(item); item.addActionListener(this); } // addMenuItem /** * Action Listener * * @param e event */ @Override public void actionPerformed(ActionEvent e) { log.info(e.toString()); // Add new Node if (e.getSource() == m_NewMenuNode) { log.info("Create New Node"); String nameLabel = Util.cleanAmp(msgBL.getMsg(Env.getCtx(), "Name")); String name = JOptionPane.showInputDialog(this, nameLabel, // message msgBL.getMsg(Env.getCtx(), "CreateNewNode"), // title JOptionPane.QUESTION_MESSAGE); if (name != null && name.length() > 0) { workflowDAO.createWFNode(WFNodeCreateRequest.builder() .workflowId(m_wf.getId()) .value(name) .name(name) .build()); m_parent.load(m_wf.getId(), true); } } // Add/Delete Line else if (e.getSource() instanceof WFPopupItem) { WFPopupItem item = (WFPopupItem)e.getSource(); item.execute(); } } // actionPerformed class WFPopupItem extends JMenuItem { private static final long serialVersionUID = 4634863991042969718L; public WFPopupItem(String title, WorkflowNodeModel node, WFNodeId nodeToId) { super(title); m_node = node; m_line = null; this.nodeToId = nodeToId; } // WFPopupItem /** * Delete Line Item * * @param title title * @param line line to be deleted */ public WFPopupItem(String title, WorkflowNodeTransitionModel line) { super(title); m_node = null; m_line = line; nodeToId = null; } // WFPopupItem /** * The Node */ private final WorkflowNodeModel m_node; /** * The Line */ private final WorkflowNodeTransitionModel m_line; /** * The Next Node ID
*/ private final WFNodeId nodeToId; /** * Execute */ public void execute() { // Add Line if (m_node != null && nodeToId != null) { final I_AD_WF_NodeNext newLine = InterfaceWrapperHelper.newInstance(I_AD_WF_NodeNext.class); newLine.setAD_Org_ID(OrgId.ANY.getRepoId()); newLine.setAD_WF_Node_ID(m_node.getId().getRepoId()); newLine.setAD_WF_Next_ID(nodeToId.getRepoId()); InterfaceWrapperHelper.save(newLine); log.info("Add Line to " + m_node + " -> " + newLine); m_parent.load(m_wf.getId(), true); } // Delete Node else if (m_node != null && nodeToId == null) { log.info("Delete Node: " + m_node); Services.get(IADWorkflowDAO.class).deleteNodeById(m_node.getId()); m_parent.load(m_wf.getId(), true); } // Delete Line else if (m_line != null) { log.info("Delete Line: " + m_line); Services.get(IADWorkflowDAO.class).deleteNodeTransitionById(m_line.getId()); m_parent.load(m_wf.getId(), true); } else log.error("No Action??"); } // execute } // WFPopupItem } // WFContentPanel
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WFContentPanel.java
1
请完成以下Java代码
public class SpringProcessDefinitionCache implements DeploymentCache<ProcessDefinitionCacheEntry> { private final Cache delegate; public SpringProcessDefinitionCache(Cache delegate) { this.delegate = delegate; } @Override public ProcessDefinitionCacheEntry get(String id) { return delegate.get(id, ProcessDefinitionCacheEntry.class); } @Override public void add(String id, ProcessDefinitionCacheEntry object) { delegate.putIfAbsent(id, object); } @Override public void remove(String id) { delegate.evictIfPresent(id);
} @Override public void clear() { delegate.clear(); } @Override public boolean contains(String id) { return delegate.get(id) != null; } public Cache getDelegate() { return delegate; } }
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\cache\SpringProcessDefinitionCache.java
1
请在Spring Boot框架中完成以下Java代码
public class BasicUser { @Id @GeneratedValue private Long id; private String username; @ElementCollection private Set<String> permissions; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() {
return username; } public void setUsername(String username) { this.username = username; } public Set<String> getPermissions() { return permissions; } public void setPermissions(Set<String> permissions) { this.permissions = permissions; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\osiv\model\BasicUser.java
2
请完成以下Java代码
public Map<String, AbstractHitPolicy> getHitPolicyBehaviors() { return hitPolicyBehaviors; } public void setCustomHitPolicyBehaviors(Map<String, AbstractHitPolicy> customHitPolicyBehaviors) { this.customHitPolicyBehaviors = customHitPolicyBehaviors; } public Map<String, AbstractHitPolicy> getCustomHitPolicyBehaviors() { return customHitPolicyBehaviors; } public DecisionRequirementsDiagramGenerator getDecisionRequirementsDiagramGenerator() { return decisionRequirementsDiagramGenerator; } public DmnEngineConfiguration setDecisionRequirementsDiagramGenerator(DecisionRequirementsDiagramGenerator decisionRequirementsDiagramGenerator) { this.decisionRequirementsDiagramGenerator = decisionRequirementsDiagramGenerator; return this; } public boolean isCreateDiagramOnDeploy() { return isCreateDiagramOnDeploy; } public DmnEngineConfiguration setCreateDiagramOnDeploy(boolean isCreateDiagramOnDeploy) { this.isCreateDiagramOnDeploy = isCreateDiagramOnDeploy; return this; }
public String getDecisionFontName() { return decisionFontName; } public DmnEngineConfiguration setDecisionFontName(String decisionFontName) { this.decisionFontName = decisionFontName; return this; } public String getLabelFontName() { return labelFontName; } public DmnEngineConfiguration setLabelFontName(String labelFontName) { this.labelFontName = labelFontName; return this; } public String getAnnotationFontName() { return annotationFontName; } public DmnEngineConfiguration setAnnotationFontName(String annotationFontName) { this.annotationFontName = annotationFontName; return this; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\DmnEngineConfiguration.java
1
请完成以下Java代码
public java.lang.String getName2() { return get_ValueAsString(COLUMNNAME_Name2); } /** * PaymentRule AD_Reference_ID=195 * Reference name: _Payment Rule */ public static final int PAYMENTRULE_AD_Reference_ID=195; /** Cash = B */ public static final String PAYMENTRULE_Cash = "B"; /** CreditCard = K */ public static final String PAYMENTRULE_CreditCard = "K"; /** DirectDeposit = T */ public static final String PAYMENTRULE_DirectDeposit = "T"; /** Check = S */ public static final String PAYMENTRULE_Check = "S"; /** OnCredit = P */ public static final String PAYMENTRULE_OnCredit = "P"; /** DirectDebit = D */ public static final String PAYMENTRULE_DirectDebit = "D"; /** Mixed = M */ public static final String PAYMENTRULE_Mixed = "M"; /** PayPal = L */ public static final String PAYMENTRULE_PayPal = "L"; /** Rückerstattung = E */ public static final String PAYMENTRULE_Reimbursement = "E"; /** Verrechnung = F */ public static final String PAYMENTRULE_Settlement = "F"; @Override public void setPaymentRule (final @Nullable java.lang.String PaymentRule) { set_Value (COLUMNNAME_PaymentRule, PaymentRule); } @Override public java.lang.String getPaymentRule() { return get_ValueAsString(COLUMNNAME_PaymentRule); } @Override public void setPhone (final @Nullable java.lang.String Phone) { set_Value (COLUMNNAME_Phone, Phone); } @Override public java.lang.String getPhone() { return get_ValueAsString(COLUMNNAME_Phone); } @Override public void setPO_PaymentTerm_ID (final int PO_PaymentTerm_ID) { if (PO_PaymentTerm_ID < 1) set_Value (COLUMNNAME_PO_PaymentTerm_ID, null); else set_Value (COLUMNNAME_PO_PaymentTerm_ID, PO_PaymentTerm_ID); } @Override public int getPO_PaymentTerm_ID()
{ return get_ValueAsInt(COLUMNNAME_PO_PaymentTerm_ID); } @Override public void setPO_PricingSystem_ID (final int PO_PricingSystem_ID) { if (PO_PricingSystem_ID < 1) set_Value (COLUMNNAME_PO_PricingSystem_ID, null); else set_Value (COLUMNNAME_PO_PricingSystem_ID, PO_PricingSystem_ID); } @Override public int getPO_PricingSystem_ID() { return get_ValueAsInt(COLUMNNAME_PO_PricingSystem_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setReferrer (final @Nullable java.lang.String Referrer) { set_Value (COLUMNNAME_Referrer, Referrer); } @Override public java.lang.String getReferrer() { return get_ValueAsString(COLUMNNAME_Referrer); } @Override public void setVATaxID (final @Nullable java.lang.String VATaxID) { set_Value (COLUMNNAME_VATaxID, VATaxID); } @Override public java.lang.String getVATaxID() { return get_ValueAsString(COLUMNNAME_VATaxID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_QuickInput.java
1
请在Spring Boot框架中完成以下Java代码
public void setAdditionalInformation(AdditionalInformationType value) { this.additionalInformation = value; } /** * The sales value of the given list line item. * * @return * possible object is * {@link UnitPriceType } * */ public UnitPriceType getSalesValue() { return salesValue; } /** * Sets the value of the salesValue property. * * @param value * allowed object is * {@link UnitPriceType } * */ public void setSalesValue(UnitPriceType value) { this.salesValue = value; } /** * Extra charge for the given list line item. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getExtraCharge() { return extraCharge; } /** * Sets the value of the extraCharge property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setExtraCharge(BigDecimal value) { this.extraCharge = value; } /** * The tax amount for this line item (gross - net = tax amount) * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getTaxAmount() { return taxAmount; } /**
* Sets the value of the taxAmount property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setTaxAmount(BigDecimal value) { this.taxAmount = value; } /** * The overall amount for this line item (net value). * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getLineItemAmount() { return lineItemAmount; } /** * Sets the value of the lineItemAmount property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setLineItemAmount(BigDecimal value) { this.lineItemAmount = value; } /** * Gets the value of the listLineItemExtension property. * * @return * possible object is * {@link ListLineItemExtensionType } * */ public ListLineItemExtensionType getListLineItemExtension() { return listLineItemExtension; } /** * Sets the value of the listLineItemExtension property. * * @param value * allowed object is * {@link ListLineItemExtensionType } * */ public void setListLineItemExtension(ListLineItemExtensionType value) { this.listLineItemExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ListLineItemType.java
2
请完成以下Java代码
public String toCanonicalString() { JsonObject json = JsonUtil.createObject(); JsonUtil.addField(json, JOB_CONFIG_COUNT_EMPTY_RUNS, countEmptyRuns); JsonUtil.addField(json, JOB_CONFIG_EXECUTE_AT_ONCE, immediatelyDue); JsonUtil.addField(json, JOB_CONFIG_MINUTE_FROM, minuteFrom); JsonUtil.addField(json, JOB_CONFIG_MINUTE_TO, minuteTo); return json.toString(); } public static HistoryCleanupJobHandlerConfiguration fromJson(JsonObject jsonObject) { HistoryCleanupJobHandlerConfiguration config = new HistoryCleanupJobHandlerConfiguration(); if (jsonObject.has(JOB_CONFIG_COUNT_EMPTY_RUNS)) { config.setCountEmptyRuns(JsonUtil.getInt(jsonObject, JOB_CONFIG_COUNT_EMPTY_RUNS)); } if (jsonObject.has(JOB_CONFIG_EXECUTE_AT_ONCE)) { config.setImmediatelyDue(JsonUtil.getBoolean(jsonObject, JOB_CONFIG_EXECUTE_AT_ONCE)); } config.setMinuteFrom(JsonUtil.getInt(jsonObject, JOB_CONFIG_MINUTE_FROM)); config.setMinuteTo(JsonUtil.getInt(jsonObject, JOB_CONFIG_MINUTE_TO)); return config; } /** * The delay between two "empty" runs increases twice each time until it reaches {@link HistoryCleanupJobHandlerConfiguration#MAX_DELAY} value. * @param date date to count delay from * @return date with delay */ public Date getNextRunWithDelay(Date date) { Date result = addSeconds(date, Math.min((int)(Math.pow(2., (double)countEmptyRuns) * START_DELAY), MAX_DELAY)); return result; } private Date addSeconds(Date date, int amount) { Calendar c = Calendar.getInstance(); c.setTime(date); c.add(Calendar.SECOND, amount); return c.getTime(); } public int getCountEmptyRuns() {
return countEmptyRuns; } public void setCountEmptyRuns(int countEmptyRuns) { this.countEmptyRuns = countEmptyRuns; } public boolean isImmediatelyDue() { return immediatelyDue; } public void setImmediatelyDue(boolean immediatelyDue) { this.immediatelyDue = immediatelyDue; } public int getMinuteFrom() { return minuteFrom; } public void setMinuteFrom(int minuteFrom) { this.minuteFrom = minuteFrom; } public int getMinuteTo() { return minuteTo; } public void setMinuteTo(int minuteTo) { this.minuteTo = minuteTo; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupJobHandlerConfiguration.java
1
请完成以下Java代码
public HistoricIncidentQuery orderByCauseIncidentId() { orderBy(HistoricIncidentQueryProperty.CAUSE_INCIDENT_ID); return this; } public HistoricIncidentQuery orderByRootCauseIncidentId() { orderBy(HistoricIncidentQueryProperty.ROOT_CAUSE_INCIDENT_ID); return this; } public HistoricIncidentQuery orderByConfiguration() { orderBy(HistoricIncidentQueryProperty.CONFIGURATION); return this; } public HistoricIncidentQuery orderByHistoryConfiguration() { orderBy(HistoricIncidentQueryProperty.HISTORY_CONFIGURATION); return this; } public HistoricIncidentQuery orderByIncidentState() { orderBy(HistoricIncidentQueryProperty.INCIDENT_STATE); return this; } public HistoricIncidentQuery orderByTenantId() { return orderBy(HistoricIncidentQueryProperty.TENANT_ID); } // results //////////////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricIncidentManager() .findHistoricIncidentCountByQueryCriteria(this); } public List<HistoricIncident> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricIncidentManager() .findHistoricIncidentByQueryCriteria(this, page); } // getters ///////////////////////////////////////////////////// public String getId() { return id; } public String getIncidentType() { return incidentType; }
public String getIncidentMessage() { return incidentMessage; } public String getExecutionId() { return executionId; } public String getActivityId() { return activityId; } public String getFailedActivityId() { return failedActivityId; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public String[] getProcessDefinitionKeys() { return processDefinitionKeys; } public String getCauseIncidentId() { return causeIncidentId; } public String getRootCauseIncidentId() { return rootCauseIncidentId; } public String getConfiguration() { return configuration; } public String getHistoryConfiguration() { return historyConfiguration; } public IncidentState getIncidentState() { return incidentState; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricIncidentQueryImpl.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OrderDetail other = (OrderDetail) obj; if (orderId == null) { if (other.orderId != null)
return false; } else if (!orderId.equals(other.orderId)) return false; return true; } public Long getOrderId() { return orderId; } public void setOrderId(Long orderId) { this.orderId = orderId; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\hibernate\fetching\model\OrderDetail.java
1
请完成以下Java代码
public Long getId() { return id; } public Book id(Long id) { this.id = id; return this; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public Book title(String title) { this.title = title; return this; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public Book isbn(String isbn) { this.isbn = isbn; return this; } public void setIsbn(String isbn) { this.isbn = isbn; } public Author getAuthor() { return author;
} public Book author(Author author) { this.author = author; return this; } public void setAuthor(Author author) { this.author = author; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Book)) { return false; } return id != null && id.equals(((Book) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootFluentApiAdditionalMethods\src\main\java\com\bookstore\entity\Book.java
1
请在Spring Boot框架中完成以下Java代码
public static class ControlTotal { @XmlElement(name = "ControlTotalQualifier") protected String controlTotalQualifier; @XmlElement(name = "ControlTotalValue") protected String controlTotalValue; /** * Gets the value of the controlTotalQualifier property. * * @return * possible object is * {@link String } * */ public String getControlTotalQualifier() { return controlTotalQualifier; } /** * Sets the value of the controlTotalQualifier property. * * @param value * allowed object is * {@link String } * */ public void setControlTotalQualifier(String value) { this.controlTotalQualifier = value; } /** * Gets the value of the controlTotalValue property.
* * @return * possible object is * {@link String } * */ public String getControlTotalValue() { return controlTotalValue; } /** * Sets the value of the controlTotalValue property. * * @param value * allowed object is * {@link String } * */ public void setControlTotalValue(String value) { this.controlTotalValue = value; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\DocumentExtensionType.java
2
请完成以下Java代码
public class AsyncHelper<R> implements ApiCallback<R> { private static final Logger log = LoggerFactory.getLogger(AsyncHelper.class); private CoreV1Api api; private CompletableFuture<R> callResult; private AsyncHelper(CoreV1Api api) { this.api = api; } public static <T> CompletableFuture<T> doAsync(CoreV1Api api, ApiInvoker<T> invoker) { AsyncHelper<T> p = new AsyncHelper<>(api); return p.execute(invoker); } private CompletableFuture<R> execute( ApiInvoker<R> invoker) { try { callResult = new CompletableFuture<>(); log.info("[I38] Calling API..."); final Call call = invoker.apply(api,this); log.info("[I41] API Succesfully invoked: method={}, url={}", call.request().method(), call.request().url()); return callResult; } catch(ApiException aex) { callResult.completeExceptionally(aex); return callResult; }
} @Override public void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders) { log.error("[E53] onFailure",e); callResult.completeExceptionally(e); } @Override public void onSuccess(R result, int statusCode, Map<String, List<String>> responseHeaders) { log.error("[E61] onSuccess: statusCode={}",statusCode); callResult.complete(result); } @Override public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { log.info("[E61] onUploadProgress: bytesWritten={}, contentLength={}, done={}",bytesWritten,contentLength,done); } @Override public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { log.info("[E75] onDownloadProgress: bytesRead={}, contentLength={}, done={}",bytesRead,contentLength,done); } }
repos\tutorials-master\kubernetes-modules\k8s-intro\src\main\java\com\baeldung\kubernetes\intro\AsyncHelper.java
1
请在Spring Boot框架中完成以下Java代码
public void setErpelBusinessDocumentHeader(ErpelBusinessDocumentHeaderType value) { this.erpelBusinessDocumentHeader = value; } /** * Gets the value of the document property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the document property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDocument().add(newItem); * </pre> *
* * <p> * Objects of the following type(s) are allowed in the list * {@link DocumentType } * * */ public List<DocumentType> getDocument() { if (document == null) { document = new ArrayList<DocumentType>(); } return this.document; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\message\ErpelMessageType.java
2
请在Spring Boot框架中完成以下Java代码
public TopicBuilder configs(Map<String, String> configProps) { this.configs.putAll(configProps); return this; } /** * Set a configuration option. * @param configName the name. * @param configValue the value. * @return the builder * @see TopicConfig */ public TopicBuilder config(String configName, String configValue) { this.configs.put(configName, configValue); return this; } /** * Set the {@link TopicConfig#CLEANUP_POLICY_CONFIG} to * {@link TopicConfig#CLEANUP_POLICY_COMPACT}. * @return the builder. */ public TopicBuilder compact() { this.configs.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT); return this; }
public NewTopic build() { NewTopic topic = this.replicasAssignments == null ? new NewTopic(this.name, this.partitions, this.replicas) : new NewTopic(this.name, this.replicasAssignments); if (!this.configs.isEmpty()) { topic.configs(this.configs); } return topic; } /** * Create a TopicBuilder with the supplied name. * @param name the name. * @return the builder. */ public static TopicBuilder name(String name) { return new TopicBuilder(name); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\config\TopicBuilder.java
2
请完成以下Java代码
public void setGO_DeliveryOrder_ID (int GO_DeliveryOrder_ID) { if (GO_DeliveryOrder_ID < 1) set_Value (COLUMNNAME_GO_DeliveryOrder_ID, null); else set_Value (COLUMNNAME_GO_DeliveryOrder_ID, Integer.valueOf(GO_DeliveryOrder_ID)); } /** Get GO Delivery Order. @return GO Delivery Order */ @Override public int getGO_DeliveryOrder_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GO_DeliveryOrder_ID); if (ii == null) return 0; return ii.intValue(); } /** Set GO Delivery Order Log. @param GO_DeliveryOrder_Log_ID GO Delivery Order Log */ @Override public void setGO_DeliveryOrder_Log_ID (int GO_DeliveryOrder_Log_ID) { if (GO_DeliveryOrder_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_GO_DeliveryOrder_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_GO_DeliveryOrder_Log_ID, Integer.valueOf(GO_DeliveryOrder_Log_ID)); } /** Get GO Delivery Order Log. @return GO Delivery Order Log */ @Override public int getGO_DeliveryOrder_Log_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GO_DeliveryOrder_Log_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Fehler. @param IsError Ein Fehler ist bei der Durchführung aufgetreten */ @Override public void setIsError (boolean IsError) { set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError)); } /** Get Fehler. @return Ein Fehler ist bei der Durchführung aufgetreten */ @Override public boolean isError () { Object oo = get_Value(COLUMNNAME_IsError); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo); } return false; } /** Set Request Message. @param RequestMessage Request Message */ @Override public void setRequestMessage (java.lang.String RequestMessage) { set_Value (COLUMNNAME_RequestMessage, RequestMessage); } /** Get Request Message. @return Request Message */ @Override public java.lang.String getRequestMessage () { return (java.lang.String)get_Value(COLUMNNAME_RequestMessage); } /** Set Response Message. @param ResponseMessage Response Message */ @Override public void setResponseMessage (java.lang.String ResponseMessage) { set_Value (COLUMNNAME_ResponseMessage, ResponseMessage); } /** Get Response Message. @return Response Message */ @Override public java.lang.String getResponseMessage () { return (java.lang.String)get_Value(COLUMNNAME_ResponseMessage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-gen\de\metas\shipper\gateway\go\model\X_GO_DeliveryOrder_Log.java
1
请完成以下Java代码
public ModificationBuilder skipCustomListeners() { this.skipCustomListeners = true; return this; } @Override public ModificationBuilder skipIoMappings() { this.skipIoMappings = true; return this; } @Override public ModificationBuilder setAnnotation(String annotation) { this.annotation = annotation; return this; } public void execute(boolean writeUserOperationLog) { commandExecutor.execute(new ProcessInstanceModificationCmd(this, writeUserOperationLog)); } @Override public void execute() { execute(true); } @Override public Batch executeAsync() { return commandExecutor.execute(new ProcessInstanceModificationBatchCmd(this)); } public CommandExecutor getCommandExecutor() { return commandExecutor; } public ProcessInstanceQuery getProcessInstanceQuery() { return processInstanceQuery; } public HistoricProcessInstanceQuery getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } public List<String> getProcessInstanceIds() { return processInstanceIds; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; }
public List<AbstractProcessInstanceModificationCommand> getInstructions() { return instructions; } public void setInstructions(List<AbstractProcessInstanceModificationCommand> instructions) { this.instructions = instructions; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public boolean isSkipIoMappings() { return skipIoMappings; } public String getAnnotation() { return annotation; } public void setAnnotationInternal(String annotation) { this.annotation = annotation; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ModificationBuilderImpl.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Issue Status. @param R_IssueStatus_ID Status of an Issue
*/ public void setR_IssueStatus_ID (int R_IssueStatus_ID) { if (R_IssueStatus_ID < 1) set_ValueNoCheck (COLUMNNAME_R_IssueStatus_ID, null); else set_ValueNoCheck (COLUMNNAME_R_IssueStatus_ID, Integer.valueOf(R_IssueStatus_ID)); } /** Get Issue Status. @return Status of an Issue */ public int getR_IssueStatus_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueStatus_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_R_IssueStatus.java
1
请完成以下Java代码
public boolean isSOPriceList () { Object oo = get_Value(COLUMNNAME_IsSOPriceList); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Preis inklusive Steuern. @param IsTaxIncluded Tax is included in the price */ @Override public void setIsTaxIncluded (boolean IsTaxIncluded) { set_Value (COLUMNNAME_IsTaxIncluded, Boolean.valueOf(IsTaxIncluded)); } /** Get Preis inklusive Steuern. @return Tax is included in the price */ @Override public boolean isTaxIncluded () { Object oo = get_Value(COLUMNNAME_IsTaxIncluded); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Preisliste. @param M_PriceList_ID Unique identifier of a Price List */ @Override public void setM_PriceList_ID (int M_PriceList_ID) { if (M_PriceList_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, Integer.valueOf(M_PriceList_ID)); } /** Get Preisliste. @return Unique identifier of a Price List */ @Override public int getM_PriceList_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PriceList_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Preissystem. @param M_PricingSystem_ID Ein Preissystem enthält beliebig viele, Länder-abhängige Preislisten. */ @Override public void setM_PricingSystem_ID (int M_PricingSystem_ID) { if (M_PricingSystem_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PricingSystem_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PricingSystem_ID, Integer.valueOf(M_PricingSystem_ID)); } /** Get Preissystem. @return Ein Preissystem enthält beliebig viele, Länder-abhängige Preislisten. */ @Override public int getM_PricingSystem_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PricingSystem_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Preis Präzision. @param PricePrecision Precision (number of decimals) for the Price */ @Override public void setPricePrecision (int PricePrecision) { set_Value (COLUMNNAME_PricePrecision, Integer.valueOf(PricePrecision)); } /** Get Preis Präzision. @return Precision (number of decimals) for the Price */ @Override public int getPricePrecision () { Integer ii = (Integer)get_Value(COLUMNNAME_PricePrecision); 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_M_PriceList.java
1
请完成以下Java代码
public void updateAddressString(final I_C_BPartner_Location bpLocation) { final int locationId = bpLocation.getC_Location_ID(); if (locationId <= 0) { return; } final int bPartnerId = bpLocation.getC_BPartner_ID(); if (bPartnerId <= 0) { return; } final IBPartnerBL bpartnerBL = Services.get(IBPartnerBL.class); bpartnerBL.setAddress(bpLocation); }
@CalloutMethod(columnNames = { I_C_BPartner_Location.COLUMNNAME_ValidFrom}) public void updatePreviousId(final I_C_BPartner_Location bpLocation) { final int bPartnerId = bpLocation.getC_BPartner_ID(); if (bPartnerId <= 0) { return; } if (bpLocation.getValidFrom() == null) { return; } final IBPartnerBL bpartnerBL = Services.get(IBPartnerBL.class); bpartnerBL.setPreviousIdIfPossible(bpLocation); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\bpartner\callout\C_BPartner_Location.java
1
请在Spring Boot框架中完成以下Java代码
public RpAccount unFreezeSettAmount(String userNo, BigDecimal amount) { RpAccount account = this.getByUserNo_IsPessimist(userNo, true); if (account == null) { throw AccountBizException.ACCOUNT_NOT_EXIT; } Date lastModifyDate = account.getEditTime(); // 不是同一天直接清0 if (!DateUtils.isSameDayWithToday(lastModifyDate)) { account.setTodayExpend(BigDecimal.ZERO); account.setTodayIncome(BigDecimal.ZERO); } // 判断解冻金额是否充足 if (account.getUnbalance().subtract(amount).compareTo(BigDecimal.ZERO) == -1) { // 解冻金额超限 throw AccountBizException.ACCOUNT_UN_FROZEN_AMOUNT_OUTLIMIT; } account.setEditTime(new Date()); account.setUnbalance(account.getUnbalance().subtract(amount));// 解冻 this.rpAccountDao.update(account); return account; } /** * 更新账户历史中的结算状态,并且累加可结算金额 * * @param userNo * 用户编号 * @param collectDate * 汇总日期
* @param riskDay * 风险预存期 * @param totalAmount * 可结算金额累计 * */ @Transactional(rollbackFor = Exception.class) public void settCollectSuccess(String userNo, String collectDate, int riskDay, BigDecimal totalAmount) { LOG.info("==>settCollectSuccess"); LOG.info(String.format("==>userNo:%s, collectDate:%s, riskDay:%s", userNo, collectDate, riskDay)); RpAccount account = this.getByUserNo_IsPessimist(userNo, true); if (account == null) { throw AccountBizException.ACCOUNT_NOT_EXIT.newInstance("账户不存在,用户编号{%s}", userNo).print(); } // 更新账户历史状态 Map<String, Object> params = new HashMap<String, Object>(); params.put("accountNo", account.getAccountNo()); params.put("statDate", collectDate); params.put("riskDay", riskDay); rpAccountHistoryDao.updateCompleteSettTo100(params); // 账户可结算金额的累加 account.setSettAmount(account.getSettAmount().add(totalAmount)); rpAccountDao.update(account); LOG.info("==>settCollectSuccess<=="); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\service\impl\RpAccountTransactionServiceImpl.java
2
请完成以下Java代码
public TopicSubscription setProcessDefinitionKeyIn(List<String> processDefinitionKeys) { this.processDefinitionKeyIn = processDefinitionKeys; return this; } public String getProcessDefinitionVersionTag() { return processDefinitionVersionTag; } public void setProcessDefinitionVersionTag(String processDefinitionVersionTag) { this.processDefinitionVersionTag = processDefinitionVersionTag; } public HashMap<String, Object> getProcessVariables() { return (HashMap<String, Object>) processVariables; } public void setProcessVariables(Map<String, Object> processVariables) { if (this.processVariables == null) { this.processVariables = new HashMap<>(); } for (Map.Entry<String, Object> processVariable : processVariables.entrySet()) { this.processVariables.put(processVariable.getKey(), processVariable.getValue()); } } public boolean isWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public List<String> getTenantIdIn() { return tenantIdIn; } public TopicSubscription setTenantIdIn(List<String> tenantIds) { this.tenantIdIn = tenantIds; return this; } public boolean isIncludeExtensionProperties() { return includeExtensionProperties; } public void setIncludeExtensionProperties(boolean includeExtensionProperties) { this.includeExtensionProperties = includeExtensionProperties; } public int hashCode() {
final int prime = 31; int result = 1; result = prime * result + ((topicName == null) ? 0 : topicName.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TopicSubscriptionImpl other = (TopicSubscriptionImpl) obj; if (topicName == null) { if (other.topicName != null) return false; } else if (!topicName.equals(other.topicName)) { return false; } return true; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\TopicSubscriptionImpl.java
1
请在Spring Boot框架中完成以下Java代码
public DataSize getMaxHeadersSize() { return this.maxHeadersSize; } public void setMaxHeadersSize(DataSize maxHeadersSize) { this.maxHeadersSize = maxHeadersSize; } public DataSize getMaxDiskUsagePerPart() { return this.maxDiskUsagePerPart; } public void setMaxDiskUsagePerPart(DataSize maxDiskUsagePerPart) { this.maxDiskUsagePerPart = maxDiskUsagePerPart; } public Integer getMaxParts() { return this.maxParts; }
public void setMaxParts(Integer maxParts) { this.maxParts = maxParts; } public @Nullable String getFileStorageDirectory() { return this.fileStorageDirectory; } public void setFileStorageDirectory(@Nullable String fileStorageDirectory) { this.fileStorageDirectory = fileStorageDirectory; } public Charset getHeadersCharset() { return this.headersCharset; } public void setHeadersCharset(Charset headersCharset) { this.headersCharset = headersCharset; } }
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\autoconfigure\ReactiveMultipartProperties.java
2
请完成以下Java代码
public int getC_RfQ_TopicSubscriber_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_RfQ_TopicSubscriber_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datum der Abmeldung. @param OptOutDate Date the contact opted out */ @Override public void setOptOutDate (java.sql.Timestamp OptOutDate) { set_Value (COLUMNNAME_OptOutDate, OptOutDate); } /** Get Datum der Abmeldung. @return Date the contact opted out */ @Override public java.sql.Timestamp getOptOutDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_OptOutDate);
} /** Set Anmeldung. @param SubscribeDate Date the contact actively subscribed */ @Override public void setSubscribeDate (java.sql.Timestamp SubscribeDate) { set_Value (COLUMNNAME_SubscribeDate, SubscribeDate); } /** Get Anmeldung. @return Date the contact actively subscribed */ @Override public java.sql.Timestamp getSubscribeDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_SubscribeDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ_TopicSubscriber.java
1
请完成以下Java代码
public class JDomParser { private File file; public JDomParser(File file) { this.file = file; } public List<Element> getAllTitles() { try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(this.getFile()); Element tutorials = doc.getRootElement(); List<Element> titles = tutorials.getChildren("tutorial"); return titles; } catch (JDOMException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public Element getNodeById(String id) { try { SAXBuilder builder = new SAXBuilder(); Document document = (Document) builder.build(file);
String filter = "//*[@tutId='" + id + "']"; XPathFactory xFactory = XPathFactory.instance(); XPathExpression<Element> expr = xFactory.compile(filter, Filters.element()); List<Element> node = expr.evaluate(document); return node.get(0); } catch (JDOMException | IOException e) { e.printStackTrace(); return null; } } public File getFile() { return file; } public void setFile(File file) { this.file = file; } }
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\JDomParser.java
1
请完成以下Java代码
public class WEBUI_PP_Order_IssueServiceProduct extends WEBUI_PP_Order_Template implements IProcessPrecondition { private final IHUPPOrderBL ppOrderBL = Services.get(IHUPPOrderBL.class); private final IProductBL productBL = Services.get(IProductBL.class); @Param(parameterName = "IsOverrideExistingValues") private boolean overrideExistingValues; @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!getSelectedRowIds().isSingleDocumentId()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final PPOrderLineRow ppOrderLineRow = getSingleSelectedRow(); if (!ppOrderLineRow.isIssue()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not an issue line"); } final ProductId productId = ppOrderLineRow.getProductId(); if (productId == null || productBL.isStocked(productId)) { return ProcessPreconditionsResolution.rejectWithInternalReason("not a service product"); } // // OK return ProcessPreconditionsResolution.accept(); } @Override
protected String doIt() { final PPOrderLinesView ppOrder = getView(); final PPOrderLineRow issueRow = getSingleSelectedRow(); ppOrderBL.issueServiceProduct(PPOrderIssueServiceProductRequest.builder() .ppOrderId(ppOrder.getPpOrderId()) .ppOrderBOMLineId(issueRow.getOrderBOMLineId()) .overrideExistingValues(overrideExistingValues) .build()); return MSG_OK; } @Override protected void postProcess(final boolean success) { invalidateView(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_IssueServiceProduct.java
1
请完成以下Java代码
public BigDecimal getRelativePeriod() { if (getColumnType().equals(COLUMNTYPE_RelativePeriod) || getColumnType().equals(COLUMNTYPE_SegmentValue)) return super.getRelativePeriod(); return null; } // getRelativePeriod /** * Get Element Type */ @Override public String getElementType() { if (getColumnType().equals(COLUMNTYPE_SegmentValue)) { return super.getElementType(); } else { return null; } } // getElementType /** * Get Calculation Type */ @Override public String getCalculationType() { if (getColumnType().equals(COLUMNTYPE_Calculation)) return super.getCalculationType(); return null; } // getCalculationType /** * Before Save * @param newRecord new * @return true */ @Override protected boolean beforeSave(boolean newRecord) { // Validate Type String ct = getColumnType(); if (ct.equals(COLUMNTYPE_RelativePeriod)) { setElementType(null); setCalculationType(null); } else if (ct.equals(COLUMNTYPE_Calculation)) {
setElementType(null); setRelativePeriod(null); } else if (ct.equals(COLUMNTYPE_SegmentValue)) { setCalculationType(null); } return true; } // beforeSave /************************************************************************** /** * Copy * @param ctx context * @param AD_Client_ID parent * @param AD_Org_ID parent * @param PA_ReportColumnSet_ID parent * @param source copy source * @param trxName transaction * @return Report Column */ public static MReportColumn copy (Properties ctx, int AD_Client_ID, int AD_Org_ID, int PA_ReportColumnSet_ID, MReportColumn source, String trxName) { MReportColumn retValue = new MReportColumn (ctx, 0, trxName); MReportColumn.copyValues(source, retValue, AD_Client_ID, AD_Org_ID); // retValue.setPA_ReportColumnSet_ID(PA_ReportColumnSet_ID); // parent retValue.setOper_1_ID(0); retValue.setOper_2_ID(0); return retValue; } // copy } // MReportColumn
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\report\MReportColumn.java
1
请完成以下Java代码
public boolean isEffectiveLeafNode() { return children.isEmpty(); } @Nullable public AdWindowId getAdWindowIdOrNull() { if (type == MenuNodeType.Window) { return elementId.toId(AdWindowId::ofRepoId); } else { return null; } } // // // ------------------------------------------------------------------------- // // public static final class Builder { private Integer adMenuId; private String caption; private String captionBreadcrumb; private MenuNodeType type; @Nullable private DocumentId elementId; private String mainTableName; private final List<MenuNode> childrenFirst = new ArrayList<>(); private final List<MenuNode> childrenRest = new ArrayList<>(); private Builder() { } public MenuNode build() { return new MenuNode(this); } public Builder setAD_Menu_ID(final int adMenuId) { this.adMenuId = adMenuId; return this; } public Builder setAD_Menu_ID_None() { // NOTE: don't set it to ZERO because ZERO is usually root node's ID. this.adMenuId = -100; return this; } private int getAD_Menu_ID() { Check.assumeNotNull(adMenuId, "adMenuId shall be set"); return adMenuId; } private String getId() { final int adMenuId = getAD_Menu_ID(); if (type == MenuNodeType.NewRecord) { return adMenuId + "-new"; } else { return String.valueOf(adMenuId); } }
public Builder setCaption(final String caption) { this.caption = caption; return this; } public Builder setCaptionBreadcrumb(final String captionBreadcrumb) { this.captionBreadcrumb = captionBreadcrumb; return this; } public Builder setType(final MenuNodeType type, @Nullable final DocumentId elementId) { this.type = type; this.elementId = elementId; return this; } public Builder setTypeNewRecord(@NonNull final AdWindowId adWindowId) { return setType(MenuNodeType.NewRecord, DocumentId.of(adWindowId)); } public void setTypeGroup() { setType(MenuNodeType.Group, null); } public void addChildToFirstsList(@NonNull final MenuNode child) { childrenFirst.add(child); } public void addChild(@NonNull final MenuNode child) { childrenRest.add(child); } public Builder setMainTableName(final String mainTableName) { this.mainTableName = mainTableName; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\MenuNode.java
1
请完成以下Java代码
private String getClient(@NonNull final XmlBody body) { return body.getPatient().getPerson().getFamilyName() + " " + body.getPatient().getPerson().getGivenName(); } @NonNull private String getBillerEan(@NonNull final XmlBody body) { return body.getBiller().getEanParty(); } @Nullable private String getEmail(@NonNull final XmlBody body) { if (body.getContact().getEmployee() != null) if (body.getContact().getEmployee().getOnline() != null) { return Joiner .on("; ") .join(body.getContact().getEmployee().getOnline().getEmail()); } return null; } @Nullable private String getPhone(@NonNull final XmlBody body) { final XMLEmployee employee = body.getContact().getEmployee(); if (employee != null) { final XMLTelecom employeeTelecom = employee.getTelecom(); if (employeeTelecom != null) { return Joiner .on("; ") .join(employeeTelecom.getPhone()); } } return null; } @Nullable private String getResponsiblePerson(@NonNull final XmlBody body) { String response = ""; final XMLEmployee employee = body.getContact().getEmployee(); if (employee != null)
{ response += employee.getFamilyName(); if (employee.getGivenName() != null) { response += " " + employee.getGivenName(); } } if (response.isEmpty()) { return null; } return response; } @Nullable private String getExplanation(final XmlBody body) { if (body.getRejected() != null) { return body.getRejected().getExplanation(); } return null; } @NonNull private String getRecipient(@NonNull final XmlBody body) { return body.getContact().getCompany().getCompanyName(); } @SuppressWarnings("UnstableApiUsage") private ImmutableList<RejectedError> getErrors(@NonNull final XmlBody body) { if (body.getRejected() != null) { return body.getRejected().getErrors() .stream() .map(it -> new RejectedError(it.getCode(), it.getText())) .collect(ImmutableList.toImmutableList()); } return ImmutableList.of(); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\export\invoice\InvoiceImportClientImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class Application implements CommandLineRunner { //https://docs.spring.io/spring/docs/5.1.6.RELEASE/spring-framework-reference/integration.html#mail @Autowired private JavaMailSender javaMailSender; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void run(String... args) { System.out.println("Sending Email..."); try { //sendEmail(); sendEmailWithAttachment(); } catch (MessagingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Done"); } void sendEmail() { SimpleMailMessage msg = new SimpleMailMessage(); msg.setTo("1@gmail.com", "2@yahoo.com"); msg.setSubject("Testing from Spring Boot"); msg.setText("Hello World \n Spring Boot Email"); javaMailSender.send(msg); } void sendEmailWithAttachment() throws MessagingException, IOException { MimeMessage msg = javaMailSender.createMimeMessage(); // true = multipart message MimeMessageHelper helper = new MimeMessageHelper(msg, true); helper.setTo("1@gmail.com");
helper.setSubject("Testing from Spring Boot"); // default = text/plain //helper.setText("Check attachment for image!"); // true = text/html helper.setText("<h1>Check attachment for image!</h1>", true); //FileSystemResource file = new FileSystemResource(new File("classpath:android.png")); //Resource resource = new ClassPathResource("android.png"); //InputStream input = resource.getInputStream(); //ResourceUtils.getFile("classpath:android.png"); helper.addAttachment("my_photo.png", new ClassPathResource("android.png")); javaMailSender.send(msg); } }
repos\spring-boot-master\email\src\main\java\com\mkyong\Application.java
2
请完成以下Java代码
public final ProcessPreconditionsResolution checkPreconditionsApplicable() { return ProcessPreconditionsResolution.accept() .deriveWithCaptionOverride(buildProcessCaption()); } private String buildProcessCaption() { final List<String> flags = new ArrayList<>(); if (getParentViewRowIdsSelection() != null) { flags.add("parentView"); } if (getChildViewRowIdsSelection() != null) { flags.add("childView"); }
final StringBuilder caption = new StringBuilder(getClass().getSimpleName()); if (!flags.isEmpty()) { caption.append(" (").append(Joiner.on(", ").join(flags)).append(")"); } return caption.toString(); } @Override protected String doIt() throws Exception { return "Parent: " + getParentViewRowIdsSelection() + "\n Child: " + getChildViewRowIdsSelection(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\WEBUI_TestParentChildViewParams.java
1
请在Spring Boot框架中完成以下Java代码
public class CodeGenerator { public static void main(String[] args) throws InterruptedException { AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setFileOverride(true); gc.setActiveRecord(true); gc.setEnableCache(false);// XML 二级缓存 gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(true);// XML columList gc.setOpen(false); gc.setAuthor("gf"); // 自定义文件命名,注意 %s 会自动填充表实体属性! gc.setMapperName("%sMapper"); gc.setXmlName("%sMapper"); gc.setServiceName("%sService"); gc.setServiceImplName("%sServiceImpl"); gc.setControllerName("%sController"); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType( DbType.MYSQL); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUrl("jdbc:mysql://127.0.0.1:3306/test?useSSL=false"); dsc.setUsername("root"); dsc.setPassword("xxxxxx"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.gf"); pc.setController( "controller"); pc.setEntity( "entity" ); //pc.setModuleName("test"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; List<FileOutConfig> focList = new ArrayList<>(); focList.add(new FileOutConfig("/templates/mapper.xml.vm") { @Override public String outputFile(TableInfo tableInfo) { // 自定义输入文件名称 return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
} }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); mpg.setTemplate(new TemplateConfig().setXml(null)); // 策略配置 StrategyConfig strategy = new StrategyConfig(); //此处可以修改为您的表前缀 strategy.setTablePrefix(new String[] { "tb_"}); // 表名生成策略 strategy.setNaming(NamingStrategy.underline_to_camel); // 需要生成的表 strategy.setInclude(new String[] { "tb_employee" }); // 排除生成的表 //strategy.setExclude(new String[]{"test"}); strategy.setEntityLombokModel( true ); mpg.setStrategy(strategy); // 执行生成 mpg.execute(); } }
repos\SpringBootLearning-master (1)\springboot-cache\src\main\java\com\gf\config\CodeGenerator.java
2
请完成以下Java代码
public byte[] getCorrelationId() { return this.correlationId; // NOSONAR } @Override public int hashCode() { if (this.hashCode != null) { return this.hashCode; } final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(this.correlationId); this.hashCode = result; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } CorrelationKey other = (CorrelationKey) obj; if (!Arrays.equals(this.correlationId, other.correlationId)) { return false; } return true; } private static String bytesToHex(byte[] bytes) { boolean uuid = bytes.length == 16; char[] hexChars = new char[bytes.length * 2 + (uuid ? 4 : 0)]; int i = 0; for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF; hexChars[i++] = HEX_ARRAY[v >>> 4]; hexChars[i++] = HEX_ARRAY[v & 0x0F]; if (uuid && (j == 3 || j == 5 || j == 7 || j == 9)) { hexChars[i++] = '-'; } } return new String(hexChars); } @Override public String toString() { if (this.asString == null) { this.asString = bytesToHex(this.correlationId); } return this.asString; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\requestreply\CorrelationKey.java
1
请在Spring Boot框架中完成以下Java代码
public void setEDICctop120VID(BigInteger value) { this.ediCctop120VID = value; } /** * Gets the value of the isoCode property. * * @return * possible object is * {@link String } * */ public String getISOCode() { return isoCode; } /** * Sets the value of the isoCode property. * * @param value * allowed object is * {@link String } * */ public void setISOCode(String value) { this.isoCode = value; } /** * Gets the value of the netdate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getNetdate() { return netdate; } /** * Sets the value of the netdate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setNetdate(XMLGregorianCalendar value) { this.netdate = value; } /** * Gets the value of the netDays property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getNetDays() { return netDays; } /** * Sets the value of the netDays property. * * @param value
* allowed object is * {@link BigInteger } * */ public void setNetDays(BigInteger value) { this.netDays = value; } /** * Gets the value of the singlevat property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getSinglevat() { return singlevat; } /** * Sets the value of the singlevat property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setSinglevat(BigDecimal value) { this.singlevat = value; } /** * Gets the value of the taxfree property. * * @return * possible object is * {@link String } * */ public String getTaxfree() { return taxfree; } /** * Sets the value of the taxfree property. * * @param value * allowed object is * {@link String } * */ public void setTaxfree(String value) { this.taxfree = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop120VType.java
2
请在Spring Boot框架中完成以下Java代码
public class SysLog implements Serializable { @Id @Column(name = "log_id") @ApiModelProperty(value = "ID") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ApiModelProperty(value = "操作用户") private String username; @ApiModelProperty(value = "描述") private String description; @ApiModelProperty(value = "方法名") private String method; @ApiModelProperty(value = "参数") private String params; @ApiModelProperty(value = "日志类型") private String logType; @ApiModelProperty(value = "请求ip") private String requestIp; @ApiModelProperty(value = "地址") private String address; @ApiModelProperty(value = "浏览器")
private String browser; @ApiModelProperty(value = "请求耗时") private Long time; @ApiModelProperty(value = "异常详细") private byte[] exceptionDetail; /** 创建日期 */ @CreationTimestamp @ApiModelProperty(value = "创建日期:yyyy-MM-dd HH:mm:ss") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") private Timestamp createTime; public SysLog(String logType, Long time) { this.logType = logType; this.time = time; } }
repos\eladmin-master\eladmin-logging\src\main\java\me\zhengjie\domain\SysLog.java
2