instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public String execute(CommandContext commandContext) { DbSqlSessionFactory dbSqlSessionFactory = (DbSqlSessionFactory) commandContext .getSessionFactories() .get(DbSqlSession.class); DbSqlSession dbSqlSession = new DbSqlSession( dbSqlSessionFactory, commandContext.getEntityCache(), connection, catalog, schema ); commandContext.getSessions().put(DbSqlSession.class, dbSqlSession); return dbSqlSession.dbSchemaUpdate(); } } ); } public <T> T executeCommand(Command<T> command) { if (command == null) { throw new ActivitiIllegalArgumentException("The command is null"); } return commandExecutor.execute(command); } public <T> T executeCommand(CommandConfig config, Command<T> command) { if (config == null) { throw new ActivitiIllegalArgumentException("The config is null"); } if (command == null) { throw new ActivitiIllegalArgumentException("The command is null");
} return commandExecutor.execute(config, command); } @Override public <MapperType, ResultType> ResultType executeCustomSql( CustomSqlExecution<MapperType, ResultType> customSqlExecution ) { Class<MapperType> mapperClass = customSqlExecution.getMapperClass(); return commandExecutor.execute( new ExecuteCustomSqlCmd<MapperType, ResultType>(mapperClass, customSqlExecution) ); } @Override public List<EventLogEntry> getEventLogEntries(Long startLogNr, Long pageSize) { return commandExecutor.execute(new GetEventLogEntriesCmd(startLogNr, pageSize)); } @Override public List<EventLogEntry> getEventLogEntriesByProcessInstanceId(String processInstanceId) { return commandExecutor.execute(new GetEventLogEntriesCmd(processInstanceId)); } @Override public void deleteEventLogEntry(long logNr) { commandExecutor.execute(new DeleteEventLogEntry(logNr)); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ManagementServiceImpl.java
1
请完成以下Java代码
public Component getTableCellEditorComponent(final JTable table, final Object valueModel, final boolean isSelected, int rowIndexView, int columnIndexView) { // Set Value final Object valueEditor = convertToEditorValue(valueModel); m_editor.setValue(valueEditor); // Set UI m_editor.setBorder(null); // m_editor.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder")); m_editor.setFont(table.getFont()); final Component editorComp = (Component)m_editor; return editorComp; } @Override public Object getCellEditorValue() { if (m_editor == null) { return null; } final Object valueEditor = m_editor.getValue(); // // Check and convert the value if needed final Object valueModel; if (valueEditor instanceof Number && modelValueClass == KeyNamePair.class) { final int key = ((Number)valueEditor).intValue(); final String name = m_editor.getDisplay(); valueModel = new KeyNamePair(key, name); } else { valueModel = valueEditor; } return valueModel; } @Override public boolean stopCellEditing() { try
{ return super.stopCellEditing(); } catch (Exception e) { final Component comp = (Component)m_editor; final int windowNo = Env.getWindowNo(comp); Services.get(IClientUI.class).warn(windowNo, e); } return false; } @Override public void cancelCellEditing() { super.cancelCellEditing(); } private Object convertToEditorValue(final Object valueModel) { final Object valueEditor; if (valueModel instanceof KeyNamePair && editorValueClass == Integer.class) { valueEditor = ((KeyNamePair)valueModel).getKey(); } else { valueEditor = valueModel; } return valueEditor; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTableModelCellEditor.java
1
请完成以下Java代码
public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Shipment_Declaration getM_Shipment_Declaration() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Shipment_Declaration_ID, org.compiere.model.I_M_Shipment_Declaration.class); } @Override public void setM_Shipment_Declaration(org.compiere.model.I_M_Shipment_Declaration M_Shipment_Declaration) { set_ValueFromPO(COLUMNNAME_M_Shipment_Declaration_ID, org.compiere.model.I_M_Shipment_Declaration.class, M_Shipment_Declaration); } /** Set Abgabemeldung. @param M_Shipment_Declaration_ID Abgabemeldung */ @Override public void setM_Shipment_Declaration_ID (int M_Shipment_Declaration_ID) { if (M_Shipment_Declaration_ID < 1) set_Value (COLUMNNAME_M_Shipment_Declaration_ID, null); else set_Value (COLUMNNAME_M_Shipment_Declaration_ID, Integer.valueOf(M_Shipment_Declaration_ID)); } /** Get Abgabemeldung. @return Abgabemeldung */ @Override public int getM_Shipment_Declaration_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipment_Declaration_ID); if (ii == null) return 0; return ii.intValue(); } /** Set M_Shipment_Declaration_Line. @param M_Shipment_Declaration_Line_ID M_Shipment_Declaration_Line */ @Override public void setM_Shipment_Declaration_Line_ID (int M_Shipment_Declaration_Line_ID) { if (M_Shipment_Declaration_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_Line_ID, Integer.valueOf(M_Shipment_Declaration_Line_ID)); } /** Get M_Shipment_Declaration_Line. @return M_Shipment_Declaration_Line */ @Override public int getM_Shipment_Declaration_Line_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipment_Declaration_Line_ID); if (ii == null)
return 0; return ii.intValue(); } /** Set Pck. Gr.. @param PackageSize Pck. Gr. */ @Override public void setPackageSize (java.lang.String PackageSize) { set_Value (COLUMNNAME_PackageSize, PackageSize); } /** Get Pck. Gr.. @return Pck. Gr. */ @Override public java.lang.String getPackageSize () { return (java.lang.String)get_Value(COLUMNNAME_PackageSize); } /** Set Menge. @param Qty Menge */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Menge */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipment_Declaration_Line.java
1
请完成以下Java代码
public ThreadPoolTaskScheduler build() { return configure(new ThreadPoolTaskScheduler()); } /** * Configure the provided {@link ThreadPoolTaskScheduler} instance using this builder. * @param <T> the type of task scheduler * @param taskScheduler the {@link ThreadPoolTaskScheduler} to configure * @return the task scheduler instance * @see #build() */ public <T extends ThreadPoolTaskScheduler> T configure(T taskScheduler) { PropertyMapper map = PropertyMapper.get(); map.from(this.poolSize).to(taskScheduler::setPoolSize); map.from(this.awaitTermination).to(taskScheduler::setWaitForTasksToCompleteOnShutdown);
map.from(this.awaitTerminationPeriod).asInt(Duration::getSeconds).to(taskScheduler::setAwaitTerminationSeconds); map.from(this.threadNamePrefix).to(taskScheduler::setThreadNamePrefix); map.from(this.taskDecorator).to(taskScheduler::setTaskDecorator); if (!CollectionUtils.isEmpty(this.customizers)) { this.customizers.forEach((customizer) -> customizer.customize(taskScheduler)); } return taskScheduler; } private <T> Set<T> append(@Nullable Set<T> set, Iterable<? extends T> additions) { Set<T> result = new LinkedHashSet<>((set != null) ? set : Collections.emptySet()); additions.forEach(result::add); return Collections.unmodifiableSet(result); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\task\ThreadPoolTaskSchedulerBuilder.java
1
请完成以下Java代码
public boolean isActive() { return po.isActive(); // isActive } /** * Get Created * @return created */ public Timestamp getCreated() { return po.getCreated(); // getCreated } /** * Get Updated * @return updated */ public Timestamp getUpdated() { return po.getUpdated(); // getUpdated } /** * Get CreatedBy * @return AD_User_ID */ public int getCreatedBy() { return po.getCreatedBy(); // getCreateddBy } /** * Get UpdatedBy * @return AD_User_ID */ public int getUpdatedBy() { return po.getUpdatedBy(); // getUpdatedBy } /************************************************************************** * Update Value or create new record. * To reload call load() - not updated * @return true if saved */ public boolean save() { return po.save(); // save } /** * Update Value or create new record. * To reload call load() - not updated * @param trxName transaction * @return true if saved */ public boolean save(String trxName) { return po.save(trxName); // save } /** * Is there a Change to be saved? * @return true if record changed */ public boolean is_Changed() { return po.is_Changed(); // is_Change } /** * Create Single/Multi Key Where Clause * @param withValues if true uses actual values otherwise ? * @return where clause */ public String get_WhereClause(boolean withValues) { return po.get_WhereClause(withValues); // getWhereClause } /************************************************************************** * Delete Current Record * @param force delete also processed records * @return true if deleted */ public boolean delete(boolean force) { return po.delete(force); // delete } /**
* Delete Current Record * @param force delete also processed records * @param trxName transaction */ public boolean delete(boolean force, String trxName) { return po.delete(force, trxName); // delete } /************************************************************************** * Lock it. * @return true if locked */ public boolean lock() { return po.lock(); // lock } /** * UnLock it * @return true if unlocked (false only if unlock fails) */ public boolean unlock(String trxName) { return po.unlock(trxName); // unlock } /** * Set Trx * @param trxName transaction */ public void set_TrxName(String trxName) { po.set_TrxName(trxName); // setTrx } /** * Get Trx * @return transaction */ public String get_TrxName() { return po.get_TrxName(); // getTrx } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\wrapper\AbstractPOWrapper.java
1
请完成以下Java代码
public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } /** * Get shipDate * @return shipDate **/ @ApiModelProperty(value = "") public DateTime getShipDate() { return shipDate; } public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } public Order status(StatusEnum status) { this.status = status; return this; } /** * Order Status * @return status **/ @ApiModelProperty(value = "Order Status") public StatusEnum getStatus() { return status; } public void setStatus(StatusEnum status) { this.status = status; } public Order complete(Boolean complete) { this.complete = complete; return this; } /** * Get complete * @return complete **/ @ApiModelProperty(value = "") public Boolean getComplete() { return complete; } public void setComplete(Boolean complete) { this.complete = complete; } @Override public boolean equals(java.lang.Object o) { if (this == o) {
return true; } if (o == null || getClass() != o.getClass()) { return false; } Order order = (Order) o; return Objects.equals(this.id, order.id) && Objects.equals(this.petId, order.petId) && Objects.equals(this.quantity, order.quantity) && Objects.equals(this.shipDate, order.shipDate) && Objects.equals(this.status, order.status) && Objects.equals(this.complete, order.complete); } @Override public int hashCode() { return Objects.hash(id, petId, quantity, shipDate, status, complete); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Order {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\Order.java
1
请完成以下Java代码
public GatewayFilter apply(Config config) { return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { String value = ServerWebExchangeUtils.expand(exchange, config.getHost()); ServerHttpRequest request = exchange.getRequest().mutate().headers(httpHeaders -> { httpHeaders.remove("Host"); httpHeaders.add("Host", value); }).build(); // Make sure the header we just set is preserved exchange.getAttributes().put(PRESERVE_HOST_HEADER_ATTRIBUTE, true); return chain.filter(exchange.mutate().request(request).build()); } @Override public String toString() { String host = config.getHost(); return filterToStringCreator(SetRequestHostHeaderGatewayFilterFactory.this) .append(host != null ? host : "") .toString(); } }; }
public static class Config { private @Nullable String host; public @Nullable String getHost() { return host; } public void setHost(String host) { this.host = host; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SetRequestHostHeaderGatewayFilterFactory.java
1
请完成以下Java代码
public void setLinkURL (String LinkURL) { set_Value (COLUMNNAME_LinkURL, LinkURL); } /** Get LinkURL. @return Contains URL to a target */ public String getLinkURL () { return (String)get_Value(COLUMNNAME_LinkURL); } /** Set Publication Date. @param PubDate Date on which this article will / should get published */ public void setPubDate (Timestamp PubDate) { set_Value (COLUMNNAME_PubDate, PubDate); } /** Get Publication Date. @return Date on which this article will / should get published */ public Timestamp getPubDate () { return (Timestamp)get_Value(COLUMNNAME_PubDate);
} /** Set Title. @param Title Name this entity is referred to as */ public void setTitle (String Title) { set_Value (COLUMNNAME_Title, Title); } /** Get Title. @return Name this entity is referred to as */ public String getTitle () { return (String)get_Value(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_NewsItem.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isDestroyed() { return getDelegate().isDestroyed(); } @Override public boolean isLocal() { return getDelegate().isLocal(); } @Override public K getKey() { return getDelegate().getKey(); } @Override public Region<K, V> getRegion() { return getDelegate().getRegion(); } @Override public CacheStatistics getStatistics() { return getDelegate().getStatistics(); }
@Override public Object setUserAttribute(Object userAttribute) { return getDelegate().setUserAttribute(userAttribute); } @Override public Object getUserAttribute() { return getDelegate().getUserAttribute(); } @Override public V setValue(V value) { return getDelegate().setValue(value); } @Override @SuppressWarnings("unchecked") public V getValue() { return (V) PdxInstanceWrapper.from(getDelegate().getValue()); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\support\PdxInstanceWrapperRegionAspect.java
2
请在Spring Boot框架中完成以下Java代码
public PickingJobScheduleCollection list(@NonNull final PickingJobScheduleQuery query) { return stream(query).collect(PickingJobScheduleCollection.collect()); } public Stream<PickingJobSchedule> stream(@NonNull final PickingJobScheduleQuery query) { return toSqlQuery(query) .stream() .map(PickingJobScheduleRepository::fromRecord); } public boolean anyMatch(@NonNull final PickingJobScheduleQuery query) { return toSqlQuery(query).anyMatch(); } private IQuery<I_M_Picking_Job_Schedule> toSqlQuery(@NonNull final PickingJobScheduleQuery query) { if (query.isAny()) { throw new AdempiereException("Any query is not allowed"); } final IQueryBuilder<I_M_Picking_Job_Schedule> queryBuilder = queryBL.createQueryBuilder(I_M_Picking_Job_Schedule.class) .orderBy(I_M_Picking_Job_Schedule.COLUMNNAME_M_ShipmentSchedule_ID) .orderBy(I_M_Picking_Job_Schedule.COLUMNNAME_M_Picking_Job_Schedule_ID)
.addOnlyActiveRecordsFilter(); if (!query.getWorkplaceIds().isEmpty()) { queryBuilder.addInArrayFilter(I_M_Picking_Job_Schedule.COLUMNNAME_C_Workplace_ID, query.getWorkplaceIds()); } if (!query.getExcludeJobScheduleIds().isEmpty()) { queryBuilder.addNotInArrayFilter(I_M_Picking_Job_Schedule.COLUMNNAME_M_Picking_Job_Schedule_ID, query.getExcludeJobScheduleIds()); } if (!query.getOnlyShipmentScheduleIds().isEmpty()) { queryBuilder.addInArrayFilter(I_M_Picking_Job_Schedule.COLUMNNAME_M_ShipmentSchedule_ID, query.getOnlyShipmentScheduleIds()); } if (query.getIsProcessed() != null) { queryBuilder.addEqualsFilter(I_M_Picking_Job_Schedule.COLUMNNAME_Processed, query.getIsProcessed()); } return queryBuilder.create(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\job_schedule\repository\PickingJobScheduleRepository.java
2
请完成以下Java代码
public static synchronized String getSubYouBianCode(String parentCode,String localCode) { if(localCode!=null && localCode!=""){ // return parentCode + getNextYouBianCode(localCode); return getNextYouBianCode(localCode); }else{ parentCode = parentCode + "A"+ getNextStrNum(0); } return parentCode; } /** * 将数字前面位数补零 * * @param num * @return */ private static String getNextStrNum(int num) { return getStrNum(getNextNum(num)); } /** * 将数字前面位数补零 * * @param num * @return */ private static String getStrNum(int num) { String s = String.format("%0" + NUM_LENGTH + "d", num); return s; } /** * 递增获取下个数字 * * @param num * @return */ private static int getNextNum(int num) { num++; return num; } /** * 递增获取下个字母 * * @param num * @return */ private static char getNextZiMu(char zimu) { if (zimu == LETTER) { return 'A'; } zimu++; return zimu;
} /** * 根据数字位数获取最大值 * @param length * @return */ private static int getMaxNumByLength(int length){ if(length==0){ return 0; } StringBuilder maxNum = new StringBuilder(); for (int i=0;i<length;i++){ maxNum.append("9"); } return Integer.parseInt(maxNum.toString()); } public static String[] cutYouBianCode(String code){ if(code==null || StringUtil.isNullOrEmpty(code)){ return null; }else{ //获取标准长度为numLength+1,截取的数量为code.length/numLength+1 int c = code.length()/(NUM_LENGTH +1); String[] cutcode = new String[c]; for(int i =0 ; i <c;i++){ cutcode[i] = code.substring(0,(i+1)*(NUM_LENGTH +1)); } return cutcode; } } // public static void main(String[] args) { // // org.jeecgframework.core.util.LogUtil.info(getNextZiMu('C')); // // org.jeecgframework.core.util.LogUtil.info(getNextNum(8)); // // org.jeecgframework.core.util.LogUtil.info(cutYouBianCode("C99A01B01")[2]); // } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\YouBianCodeUtil.java
1
请完成以下Java代码
private String convert (long number) { /* special case */ if (number == 0) { return "Zero"; } String prefix = ""; if (number < 0) { number = -number; prefix = "Negative "; } String soFar = ""; int place = 0; do { long n = number % 1000; if (n != 0) { String s = convertLessThanOneThousand ((int)n); soFar = s + majorNames[place] + soFar; } place++; number /= 1000; } while (number > 0); return (prefix + soFar).trim (); } // convert /************************************************************************** * Get Amount in Words * @param amount numeric amount (352.80) * @return amount in words (three*five*two 80/100) * @throws Exception */ public String getAmtInWords (String amount) throws Exception { if (amount == null) return amount; // StringBuffer sb = new StringBuffer (); int pos = amount.lastIndexOf ('.'); int pos2 = amount.lastIndexOf (','); if (pos2 > pos) pos = pos2; String oldamt = amount; amount = amount.replaceAll (",", ""); int newpos = amount.lastIndexOf ('.'); long dollars = Long.parseLong(amount.substring (0, newpos)); sb.append (convert (dollars)); for (int i = 0; i < oldamt.length (); i++) { if (pos == i) // we are done { String cents = oldamt.substring (i + 1); sb.append (' ').append (cents).append ("/100"); break; }
} return sb.toString (); } // getAmtInWords /** * Test Print * @param amt amount */ private void print (String amt) { try { System.out.println(amt + " = " + getAmtInWords(amt)); } catch (Exception e) { e.printStackTrace(); } } // print /** * Test * @param args ignored */ public static void main (String[] args) { AmtInWords_EN aiw = new AmtInWords_EN(); // aiw.print (".23"); Error aiw.print ("0.23"); aiw.print ("1.23"); aiw.print ("12.345"); aiw.print ("123.45"); aiw.print ("1234.56"); aiw.print ("12345.78"); aiw.print ("123457.89"); aiw.print ("1,234,578.90"); } // main } // AmtInWords_EN
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\AmtInWords_EN.java
1
请在Spring Boot框架中完成以下Java代码
public int getOrder() { return 0; } @Override public void customize(GsonBuilder builder) { GsonProperties properties = this.properties; PropertyMapper map = PropertyMapper.get(); map.from(properties::getGenerateNonExecutableJson).whenTrue().toCall(builder::generateNonExecutableJson); map.from(properties::getExcludeFieldsWithoutExposeAnnotation) .whenTrue() .toCall(builder::excludeFieldsWithoutExposeAnnotation); map.from(properties::getSerializeNulls).whenTrue().toCall(builder::serializeNulls); map.from(properties::getEnableComplexMapKeySerialization) .whenTrue() .toCall(builder::enableComplexMapKeySerialization); map.from(properties::getDisableInnerClassSerialization) .whenTrue() .toCall(builder::disableInnerClassSerialization); map.from(properties::getLongSerializationPolicy).to(builder::setLongSerializationPolicy); map.from(properties::getFieldNamingPolicy).to(builder::setFieldNamingPolicy); map.from(properties::getPrettyPrinting).whenTrue().toCall(builder::setPrettyPrinting); map.from(properties::getStrictness).to(strictnessOrLeniency(builder)); map.from(properties::getDisableHtmlEscaping).whenTrue().toCall(builder::disableHtmlEscaping); map.from(properties::getDateFormat).to(builder::setDateFormat);
} @SuppressWarnings("deprecation") private Consumer<GsonProperties.Strictness> strictnessOrLeniency(GsonBuilder builder) { if (ClassUtils.isPresent("com.google.gson.Strictness", getClass().getClassLoader())) { return (strictness) -> builder.setStrictness(Strictness.valueOf(strictness.name())); } return (strictness) -> { if (strictness == GsonProperties.Strictness.LENIENT) { builder.setLenient(); } }; } } }
repos\spring-boot-4.0.1\module\spring-boot-gson\src\main\java\org\springframework\boot\gson\autoconfigure\GsonAutoConfiguration.java
2
请完成以下Java代码
protected final Frame getCallingFrame() { final GridField gridField = getContext().getEditor().getField(); if (gridField == null) { return null; } final int windowNo = gridField.getWindowNo(); final Frame frame = Env.getWindow(windowNo); return frame; } protected final int getAD_Form_ID() { return _adFormId; } private final synchronized I_AD_Form getAD_Form() { if (!_adFormLoaded) { _adForm = retrieveAD_Form(); _adFormLoaded = true; } return _adForm; } private final I_AD_Form retrieveAD_Form() { final IContextMenuActionContext context = getContext(); Check.assumeNotNull(context, "context not null");
final Properties ctx = context.getCtx(); // Check if user has access to Payment Allocation form final int adFormId = getAD_Form_ID(); final Boolean formAccess = Env.getUserRolePermissions().checkFormAccess(adFormId); if (formAccess == null || !formAccess) { return null; } // Retrieve the form final I_AD_Form form = InterfaceWrapperHelper.create(ctx, adFormId, I_AD_Form.class, ITrx.TRXNAME_None); // Translate it to user's language final I_AD_Form formTrl = InterfaceWrapperHelper.translate(form, I_AD_Form.class); return formTrl; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\OpenFormContextMenuAction.java
1
请完成以下Java代码
public final BPartnerId getPaymentBPartnerId() { final I_C_Payment payment = getC_Payment(); if (payment != null) { return BPartnerId.ofRepoId(payment.getC_BPartner_ID()); } return getBPartnerId(); } @Nullable public final BPartnerLocationId getPaymentBPartnerLocationId() { final I_C_Payment payment = getC_Payment();
if (payment != null) { return BPartnerLocationId.ofRepoIdOrNull(payment.getC_BPartner_ID(), payment.getC_BPartner_Location_ID()); } return getBPartnerLocationId(); } public boolean isPaymentReceipt() { Check.assumeNotNull(paymentReceipt, "payment document exists"); return paymentReceipt; } } // DocLine_Allocation
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine_Allocation.java
1
请完成以下Java代码
public int getR_Status_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Status_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getSeqNo())); } /** Set Timeout in Days. @param TimeoutDays Timeout in Days to change Status automatically */ public void setTimeoutDays (int TimeoutDays) { set_Value (COLUMNNAME_TimeoutDays, Integer.valueOf(TimeoutDays)); } /** Get Timeout in Days. @return Timeout in Days to change Status automatically */ public int getTimeoutDays () {
Integer ii = (Integer)get_Value(COLUMNNAME_TimeoutDays); if (ii == null) return 0; return ii.intValue(); } public I_R_Status getUpdate_Status() throws RuntimeException { return (I_R_Status)MTable.get(getCtx(), I_R_Status.Table_Name) .getPO(getUpdate_Status_ID(), get_TrxName()); } /** Set Update Status. @param Update_Status_ID Automatically change the status after entry from web */ public void setUpdate_Status_ID (int Update_Status_ID) { if (Update_Status_ID < 1) set_Value (COLUMNNAME_Update_Status_ID, null); else set_Value (COLUMNNAME_Update_Status_ID, Integer.valueOf(Update_Status_ID)); } /** Get Update Status. @return Automatically change the status after entry from web */ public int getUpdate_Status_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Update_Status_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_Status.java
1
请完成以下Java代码
public boolean isWeak() { return delegate == null; } public PropertyChangeListener getDelegate() { if (delegate != null) { return delegate; } final PropertyChangeListener delegate = delegateRef.get(); return delegate; } @Override public void propertyChange(final PropertyChangeEvent evt) { final boolean DEBUG = false; final PropertyChangeListener delegate = getDelegate(); if (delegate == null) { // delegate reference expired if (DEBUG) { // TODO remove before integrating into base line!! System.out.println(StringUtils.formatMessage("delegate of {0} is expired", this)); } return; } final Object source = evt.getSource(); final PropertyChangeEvent evtNew; if (source instanceof Reference)
{ final Reference<?> sourceRef = (Reference<?>)source; final Object sourceObj = sourceRef.get(); if (sourceObj == null) { // reference expired if (DEBUG) { // TODO remove before integrating into base line!! System.out.println(StringUtils.formatMessage("sourceObj of {0} is expired", this)); } return; } evtNew = new PropertyChangeEvent(sourceObj, evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); evtNew.setPropagationId(evt.getPropagationId()); } else { evtNew = evt; } delegate.propertyChange(evtNew); } @Override public String toString() { return "WeakPropertyChangeListener [delegate=" + delegate + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\beans\WeakPropertyChangeListener.java
1
请完成以下Java代码
public PurchaseOrderItem buildAndAddToParent() { final PurchaseOrderItem newItem = innerBuilder.build(); parent.purchaseOrderItems.add(newItem); return newItem; } } public OrderItemBuilder createOrderItem() { return new OrderItemBuilder(this); } /** * Intended to be used by the persistence layer */ public void addLoadedPurchaseOrderItem(@NonNull final PurchaseOrderItem purchaseOrderItem) { final PurchaseCandidateId id = getId(); Check.assumeNotNull(id, "purchase candidate shall be saved: {}", this); Check.assumeEquals(id, purchaseOrderItem.getPurchaseCandidateId(), "The given purchaseOrderItem's purchaseCandidateId needs to be equal to this instance's id; purchaseOrderItem={}; this={}", purchaseOrderItem, this); purchaseOrderItems.add(purchaseOrderItem); }
public Quantity getPurchasedQty() { return purchaseOrderItems.stream() .map(PurchaseOrderItem::getPurchasedQty) .reduce(Quantity::add) .orElseGet(() -> getQtyToPurchase().toZero()); } public List<PurchaseOrderItem> getPurchaseOrderItems() { return ImmutableList.copyOf(purchaseOrderItems); } public List<PurchaseErrorItem> getPurchaseErrorItems() { return ImmutableList.copyOf(purchaseErrorItems); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\PurchaseCandidate.java
1
请完成以下Java代码
public RuleChain findByTenantIdAndExternalId(UUID tenantId, UUID externalId) { return DaoUtil.getData(ruleChainRepository.findByTenantIdAndExternalId(tenantId, externalId)); } @Override 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 ScriptEngine getEngineByName(String language) { ScriptEngine scriptEngine = null; if (cacheScriptingEngines) { scriptEngine = cachedEngines.get(language); if (scriptEngine == null) { scriptEngine = scriptEngineManager.getEngineByName(language); if (scriptEngine != null) { // ACT-1858: Special handling for groovy engine regarding GC if (GROOVY_SCRIPTING_LANGUAGE.equals(language)) { try { scriptEngine .getContext() .setAttribute("#jsr223.groovy.engine.keep.globals", "weak", ScriptContext.ENGINE_SCOPE); } catch (Exception ignore) { // ignore this, in case engine doesn't support the // passed attribute } } // Check if script-engine allows caching, using "THREADING" // parameter as defined in spec Object threadingParameter = scriptEngine.getFactory().getParameter("THREADING"); if (threadingParameter != null) { // Add engine to cache as any non-null result from the // threading-parameter indicates at least MT-access cachedEngines.put(language, scriptEngine); } } } } else { scriptEngine = scriptEngineManager.getEngineByName(language); } if (scriptEngine == null) { throw new ActivitiException("Can't find scripting engine for '" + language + "'");
} return scriptEngine; } /** override to build a spring aware ScriptingEngines */ protected Bindings createBindings(VariableScope variableScope) { return scriptBindingsFactory.createBindings(variableScope); } /** override to build a spring aware ScriptingEngines */ protected Bindings createBindings(VariableScope variableScope, boolean storeScriptVariables) { return scriptBindingsFactory.createBindings(variableScope, storeScriptVariables); } public ScriptBindingsFactory getScriptBindingsFactory() { return scriptBindingsFactory; } public void setScriptBindingsFactory(ScriptBindingsFactory scriptBindingsFactory) { this.scriptBindingsFactory = scriptBindingsFactory; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\ScriptingEngines.java
1
请完成以下Java代码
public void run() { Stage stage = getStage(planItemInstanceEntity); String oldState = planItemInstanceEntity.getState(); String newState = PlanItemInstanceState.ACTIVE; planItemInstanceEntity.setState(newState); CommandContextUtil.getCmmnEngineConfiguration(commandContext).getListenerNotificationHelper() .executeLifecycleListeners(commandContext, planItemInstanceEntity, oldState, newState); planItemInstanceEntity.setStage(true); // create case stage started event FlowableEventDispatcher eventDispatcher = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(FlowableCmmnEventBuilder.createStageStartedEvent(getCaseInstance(), planItemInstanceEntity), EngineConfigurationConstants.KEY_CMMN_ENGINE_CONFIG); } Case caseModel = CaseDefinitionUtil.getCase(planItemInstanceEntity.getCaseDefinitionId());
CaseInstanceEntity caseInstanceEntity = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getCaseInstanceEntityManager() .findById(planItemInstanceEntity.getCaseInstanceId()); createPlanItemInstancesForNewOrReactivatedStage(commandContext, caseModel, stage.getPlanItems(), null, caseInstanceEntity, planItemInstanceEntity, planItemInstanceEntity.getTenantId()); planItemInstanceEntity.setLastStartedTime(getCurrentTime(commandContext)); CommandContextUtil.getCmmnHistoryManager(commandContext).recordPlanItemInstanceStarted(planItemInstanceEntity); } @Override public String toString() { return "[Init Stage] Using plan item " + planItemInstanceEntity.getName() + " (" + planItemInstanceEntity.getId() + ")"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\InitStageInstanceOperation.java
1
请完成以下Java代码
public void setMessage2 (String Message2) { set_Value (COLUMNNAME_Message2, Message2); } /** Get Message 2. @return Optional second part of the EMail Message */ public String getMessage2 () { return (String)get_Value(COLUMNNAME_Message2); } /** Set Message 3. @param Message3 Optional third part of the EMail Message */ public void setMessage3 (String Message3) { set_Value (COLUMNNAME_Message3, Message3); } /** Get Message 3. @return Optional third part of the EMail Message */ public String getMessage3 () { return (String)get_Value(COLUMNNAME_Message3); } /** 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 Subject. @param Subject Email Message Subject */ public void setSubject (String Subject) { set_Value (COLUMNNAME_Subject, Subject); } /** Get Subject. @return Email Message Subject */ public String getSubject () { return (String)get_Value(COLUMNNAME_Subject); } /** Set Mail Message. @param W_MailMsg_ID Web Store Mail Message Template */ public void setW_MailMsg_ID (int W_MailMsg_ID) { if (W_MailMsg_ID < 1) set_ValueNoCheck (COLUMNNAME_W_MailMsg_ID, null); else set_ValueNoCheck (COLUMNNAME_W_MailMsg_ID, Integer.valueOf(W_MailMsg_ID)); } /** Get Mail Message. @return Web Store Mail Message Template
*/ public int getW_MailMsg_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_MailMsg_ID); if (ii == null) return 0; return ii.intValue(); } public I_W_Store getW_Store() throws RuntimeException { return (I_W_Store)MTable.get(getCtx(), I_W_Store.Table_Name) .getPO(getW_Store_ID(), get_TrxName()); } /** Set Web Store. @param W_Store_ID A Web Store of the Client */ public void setW_Store_ID (int W_Store_ID) { if (W_Store_ID < 1) set_Value (COLUMNNAME_W_Store_ID, null); else set_Value (COLUMNNAME_W_Store_ID, Integer.valueOf(W_Store_ID)); } /** Get Web Store. @return A Web Store of the Client */ public int getW_Store_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Store_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_W_MailMsg.java
1
请完成以下Java代码
public abstract class CharacterBasedSegment extends Segment { /** * 查询或猜测一个词语的属性, * 先查词典,然后对字母、数字串的属性进行判断,最后猜测未登录词 * @param term * @return */ public static CoreDictionary.Attribute guessAttribute(Term term) { CoreDictionary.Attribute attribute = CoreDictionary.get(term.word); if (attribute == null) { attribute = CustomDictionary.get(term.word); } if (attribute == null) { if (term.nature != null) { if (Nature.nx == term.nature) attribute = new CoreDictionary.Attribute(Nature.nx); else if (Nature.m == term.nature) attribute = CoreDictionary.get(CoreDictionary.M_WORD_ID); } else if (term.word.trim().length() == 0) attribute = new CoreDictionary.Attribute(Nature.x); else attribute = new CoreDictionary.Attribute(Nature.nz); } else term.nature = attribute.nature[0]; return attribute; } /** * 以下方法用于纯分词模型 * 分词、词性标注联合模型则直接重载segSentence */ @Override protected List<Term> segSentence(char[] sentence) { if (sentence.length == 0) return Collections.emptyList(); List<Term> termList = roughSegSentence(sentence); if (!(config.ner || config.useCustomDictionary || config.speechTagging)) return termList; List<Vertex> vertexList = toVertexList(termList, true); if (config.speechTagging) { Viterbi.compute(vertexList, CoreDictionaryTransformMatrixDictionary.transformMatrixDictionary); int i = 0; for (Term term : termList) { if (term.nature != null) term.nature = vertexList.get(i + 1).guessNature(); ++i; } } if (config.useCustomDictionary) { combineByCustomDictionary(vertexList); termList = convert(vertexList, config.offset); } return termList;
} /** * 单纯的分词模型实现该方法,仅输出词 * @param sentence * @return */ protected abstract List<Term> roughSegSentence(char[] sentence); /** * 将中间结果转换为词网顶点, * 这样就可以利用基于Vertex开发的功能, 如词性标注、NER等 * @param wordList * @param appendStart * @return */ protected List<Vertex> toVertexList(List<Term> wordList, boolean appendStart) { ArrayList<Vertex> vertexList = new ArrayList<Vertex>(wordList.size() + 2); if (appendStart) vertexList.add(Vertex.newB()); for (Term word : wordList) { CoreDictionary.Attribute attribute = guessAttribute(word); Vertex vertex = new Vertex(word.word, attribute); vertexList.add(vertex); } if (appendStart) vertexList.add(Vertex.newE()); return vertexList; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\CharacterBasedSegment.java
1
请完成以下Java代码
public void setType(String type) { this.type = type; } public String getValidUntil() { return validUntil; } public void setValidUntil(String validUntil) { this.validUntil = validUntil; } public Boolean isUnlimited() { return isUnlimited; } public void setUnlimited(Boolean isUnlimited) { this.isUnlimited = isUnlimited; }
public Map<String, String> getFeatures() { return features; } public void setFeatures(Map<String, String> features) { this.features = features; } public String getRaw() { return raw; } public void setRaw(String raw) { this.raw = raw; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\telemetry\dto\LicenseKeyDataImpl.java
1
请完成以下Java代码
public String getTypeName() { return TYPE_NAME; } @Override public boolean isCachable() { return true; } @Override public boolean isAbleToStore(Object value) { return value instanceof BpmnAggregation; } @Override public boolean isReadOnly() { return true; } @Override public void setValue(Object value, ValueFields valueFields) {
if (value instanceof BpmnAggregation) { valueFields.setTextValue(((BpmnAggregation) value).getExecutionId()); } else { valueFields.setTextValue(null); } } @Override public Object getValue(ValueFields valueFields) { CommandContext commandContext = Context.getCommandContext(); if (commandContext != null) { return BpmnAggregation.aggregateOverview(valueFields.getTextValue(), valueFields.getName(), commandContext); } else { return processEngineConfiguration.getCommandExecutor() .execute(context -> BpmnAggregation.aggregateOverview(valueFields.getTextValue(), valueFields.getName(), context)); } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\variable\BpmnAggregatedVariableType.java
1
请完成以下Java代码
public void add(URI uri, HttpCookie cookie) { store.add(uri, cookie); } @Override public List<HttpCookie> get(URI uri) { // TODO Auto-generated method stub return null; } @Override public List<HttpCookie> getCookies() { // TODO Auto-generated method stub return null; } @Override public List<URI> getURIs() { // TODO Auto-generated method stub
return null; } @Override public boolean remove(URI uri, HttpCookie cookie) { // TODO Auto-generated method stub return false; } @Override public boolean removeAll() { // TODO Auto-generated method stub return false; } }
repos\tutorials-master\core-java-modules\core-java-networking-5\src\main\java\com\baeldung\networking\cookies\PersistentCookieStore.java
1
请完成以下Java代码
public void run(@Nullable String contextName, Runnable runnable) { try { bind(contextName); runnable.run(); } finally { unbind(contextName); } } /** * Bind the context. * @param contextName the name of the context for the connection factory. */ private void bind(@Nullable String contextName) { if (StringUtils.hasText(contextName)) {
SimpleResourceHolder.bind(this.connectionFactory, contextName); } } /** * Unbind the context. * @param contextName the name of the context for the connection factory. */ private void unbind(@Nullable String contextName) { if (StringUtils.hasText(contextName)) { SimpleResourceHolder.unbind(this.connectionFactory); } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\ConnectionFactoryContextWrapper.java
1
请完成以下Java代码
public static class Builder { private int amount; public Builder amount(int amount) { this.amount = amount; return this; } private double price; public Builder price(double price) { this.price = price; return this; } private Market market; public Builder market(Market market) { this.market = market; return this; } private Currency currency; public Builder currency(Currency currency) { this.currency = currency; return this; } private String symbol; public Builder symbol(String symbol) { this.symbol = symbol; return this; } public MarketData build() { return new MarketData(amount, price, market, currency, symbol); } } public static Builder builder() { return new Builder(); } public int getAmount() { return amount; } public double getPrice() { return price;
} public Market getMarket() { return market; } public Currency getCurrency() { return currency; } public String getSymbol() { return symbol; } @Override public String toString() { return new StringJoiner(", ", MarketData.class.getSimpleName() + "[", "]").add("amount=" + amount) .add("price=" + price) .add("market=" + market) .add("currency=" + currency) .add("symbol='" + symbol + "'") .toString(); } }
repos\tutorials-master\libraries-3\src\main\java\com\baeldung\sbe\MarketData.java
1
请完成以下Java代码
public class X_M_AttributeSearch extends PO implements I_M_AttributeSearch, I_Persistent { /** * */ private static final long serialVersionUID = 20090915L; /** Standard Constructor */ public X_M_AttributeSearch (Properties ctx, int M_AttributeSearch_ID, String trxName) { super (ctx, M_AttributeSearch_ID, trxName); /** if (M_AttributeSearch_ID == 0) { setM_AttributeSearch_ID (0); setName (null); } */ } /** Load Constructor */ public X_M_AttributeSearch (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 3 - Client - Org */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_M_AttributeSearch[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Attribute Search. @param M_AttributeSearch_ID Common Search Attribute */ public void setM_AttributeSearch_ID (int M_AttributeSearch_ID)
{ if (M_AttributeSearch_ID < 1) set_ValueNoCheck (COLUMNNAME_M_AttributeSearch_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSearch_ID, Integer.valueOf(M_AttributeSearch_ID)); } /** Get Attribute Search. @return Common Search Attribute */ public int getM_AttributeSearch_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSearch_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSearch.java
1
请完成以下Java代码
private IPricingResult computeFlatrateTermPrice(@NonNull final FlatrateTermPriceRequest request) { return FlatrateTermPricing.builder() .term(request.getFlatrateTerm()) .termRelatedProductId(request.getProductId()) .priceDate(request.getPriceDate()) .qty(BigDecimal.ONE) .build() .computeOrThrowEx(); } @Override public I_C_Flatrate_Term getById(@NonNull final FlatrateTermId flatrateTermId) { return flatrateDAO.getById(flatrateTermId); } @Override public ImmutableList<I_C_Flatrate_Term> retrieveNextFlatrateTerms(@NonNull final I_C_Flatrate_Term term) { I_C_Flatrate_Term currentTerm = term; final ImmutableList.Builder<I_C_Flatrate_Term> nextFTsBuilder = ImmutableList.builder(); while (currentTerm.getC_FlatrateTerm_Next_ID() > 0) { nextFTsBuilder.add(currentTerm.getC_FlatrateTerm_Next()); currentTerm = currentTerm.getC_FlatrateTerm_Next();
} return nextFTsBuilder.build(); } @Override public final boolean existsTermForOrderLine(final I_C_OrderLine ol) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_Flatrate_Term.class, ol) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Flatrate_Term.COLUMN_C_OrderLine_Term_ID, ol.getC_OrderLine_ID()) .create() .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\FlatrateBL.java
1
请在Spring Boot框架中完成以下Java代码
public class UserService { private EventStore repository; public UserService(EventStore repository) { this.repository = repository; } public void createUser(String userId, String firstName, String lastName) { repository.addEvent(userId, new UserCreatedEvent(userId, firstName, lastName)); } public void updateUser(String userId, Set<Contact> contacts, Set<Address> addresses) throws Exception { User user = UserUtility.recreateUserState(repository, userId); if (user == null) throw new Exception("User does not exist."); user.getContacts() .stream() .filter(c -> !contacts.contains(c)) .forEach(c -> repository.addEvent(userId, new UserContactRemovedEvent(c.getType(), c.getDetail()))); contacts.stream() .filter(c -> !user.getContacts() .contains(c)) .forEach(c -> repository.addEvent(userId, new UserContactAddedEvent(c.getType(), c.getDetail()))); user.getAddresses() .stream() .filter(a -> !addresses.contains(a)) .forEach(a -> repository.addEvent(userId, new UserAddressRemovedEvent(a.getCity(), a.getState(), a.getPostcode()))); addresses.stream() .filter(a -> !user.getAddresses() .contains(a)) .forEach(a -> repository.addEvent(userId, new UserAddressAddedEvent(a.getCity(), a.getState(), a.getPostcode()))); }
public Set<Contact> getContactByType(String userId, String contactType) throws Exception { User user = UserUtility.recreateUserState(repository, userId); if (user == null) throw new Exception("User does not exist."); return user.getContacts() .stream() .filter(c -> c.getType() .equals(contactType)) .collect(Collectors.toSet()); } public Set<Address> getAddressByRegion(String userId, String state) throws Exception { User user = UserUtility.recreateUserState(repository, userId); if (user == null) throw new Exception("User does not exist."); return user.getAddresses() .stream() .filter(a -> a.getState() .equals(state)) .collect(Collectors.toSet()); } }
repos\tutorials-master\patterns-modules\cqrs-es\src\main\java\com\baeldung\patterns\es\service\UserService.java
2
请完成以下Java代码
public void setUserAgent (String UserAgent) { set_Value (COLUMNNAME_UserAgent, UserAgent); } /** Get User Agent. @return Browser Used */ public String getUserAgent () { return (String)get_Value(COLUMNNAME_UserAgent); } public I_W_ClickCount getW_ClickCount() throws RuntimeException { return (I_W_ClickCount)MTable.get(getCtx(), I_W_ClickCount.Table_Name) .getPO(getW_ClickCount_ID(), get_TrxName()); } /** Set Click Count. @param W_ClickCount_ID Web Click Management */ public void setW_ClickCount_ID (int W_ClickCount_ID) { if (W_ClickCount_ID < 1) set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, null); else set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, Integer.valueOf(W_ClickCount_ID)); } /** Get Click Count. @return Web Click Management */ public int getW_ClickCount_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_ClickCount_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Web Click. @param W_Click_ID Individual Web Click */ public void setW_Click_ID (int W_Click_ID) { if (W_Click_ID < 1) set_ValueNoCheck (COLUMNNAME_W_Click_ID, null); else set_ValueNoCheck (COLUMNNAME_W_Click_ID, Integer.valueOf(W_Click_ID)); } /** Get Web Click. @return Individual Web Click */ public int getW_Click_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Click_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_W_Click.java
1
请在Spring Boot框架中完成以下Java代码
public class SqlDocumentFilterConverterContext { @Nullable ViewId viewId; @Nullable UserRolePermissionsKey userRolePermissionsKey; @NonNull ImmutableMap<String, Object> parameters; boolean queryIfNoFilters; @Builder private SqlDocumentFilterConverterContext( @Nullable final ViewId viewId, @Nullable final UserRolePermissionsKey userRolePermissionsKey, @NonNull @Singular final Map<String, Object> parameters, @Nullable final Boolean queryIfNoFilters) { this.viewId = viewId; this.userRolePermissionsKey = userRolePermissionsKey; this.parameters = toImmutableMap(parameters); this.queryIfNoFilters = queryIfNoFilters != null ? queryIfNoFilters : true; } private static ImmutableMap<String, Object> toImmutableMap(final Map<String, Object> map) { if (map instanceof ImmutableMap) { return (ImmutableMap<String, Object>)map; } else { return map.entrySet() .stream() .filter(entry -> entry.getKey() != null && entry.getValue() != null) .collect(GuavaCollectors.toImmutableMap()); }
} public SqlDocumentFilterConverterContext withViewId(@Nullable final ViewId viewId) { return !ViewId.equals(this.viewId, viewId) ? new SqlDocumentFilterConverterContext(viewId, this.userRolePermissionsKey, this.parameters, this.queryIfNoFilters) : this; } public SqlDocumentFilterConverterContext withUserRolePermissionsKey(final UserRolePermissionsKey userRolePermissionsKey) { return !Objects.equals(this.userRolePermissionsKey, userRolePermissionsKey) ? new SqlDocumentFilterConverterContext(this.viewId, userRolePermissionsKey, this.parameters, this.queryIfNoFilters) : this; } public int getPropertyAsInt(@NonNull final String name, final int defaultValue) { final ImmutableMap<String, Object> params = getParameters(); final Object value = params.get(name); return NumberUtils.asInt(value, defaultValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\SqlDocumentFilterConverterContext.java
2
请完成以下Java代码
private void actionButton() { if (!m_button.isEnabled()) { return; } throw new UnsupportedOperationException(); } @Override public void propertyChange(final PropertyChangeEvent evt) { final String propertyName = evt.getPropertyName(); if (propertyName.equals(org.compiere.model.GridField.PROPERTY)) { setValue(evt.getNewValue()); }
else if (propertyName.equals(org.compiere.model.GridField.REQUEST_FOCUS)) { requestFocus(); } } @Override public boolean isAutoCommit() { return true; } @Override public void addMouseListener(final MouseListener l) { m_text.addMouseListener(l); } } // VPAttribute
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VPAttribute.java
1
请完成以下Java代码
public String getReferrer () { return (String)get_Value(COLUMNNAME_Referrer); } /** Set Remote Addr. @param Remote_Addr Remote Address */ public void setRemote_Addr (String Remote_Addr) { set_Value (COLUMNNAME_Remote_Addr, Remote_Addr); } /** Get Remote Addr. @return Remote Address */ public String getRemote_Addr () { return (String)get_Value(COLUMNNAME_Remote_Addr); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getRemote_Addr()); } /** Set Remote Host. @param Remote_Host Remote host Info */ public void setRemote_Host (String Remote_Host) { set_Value (COLUMNNAME_Remote_Host, Remote_Host); } /** Get Remote Host. @return Remote host Info */ public String getRemote_Host () { return (String)get_Value(COLUMNNAME_Remote_Host); } /** Set User Agent. @param UserAgent Browser Used */ public void setUserAgent (String UserAgent) { set_Value (COLUMNNAME_UserAgent, UserAgent); } /** Get User Agent. @return Browser Used */ public String getUserAgent () { return (String)get_Value(COLUMNNAME_UserAgent); }
public I_W_CounterCount getW_CounterCount() throws RuntimeException { return (I_W_CounterCount)MTable.get(getCtx(), I_W_CounterCount.Table_Name) .getPO(getW_CounterCount_ID(), get_TrxName()); } /** Set Counter Count. @param W_CounterCount_ID Web Counter Count Management */ public void setW_CounterCount_ID (int W_CounterCount_ID) { if (W_CounterCount_ID < 1) set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, null); else set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, Integer.valueOf(W_CounterCount_ID)); } /** Get Counter Count. @return Web Counter Count Management */ public int getW_CounterCount_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_CounterCount_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Web Counter. @param W_Counter_ID Individual Count hit */ public void setW_Counter_ID (int W_Counter_ID) { if (W_Counter_ID < 1) set_ValueNoCheck (COLUMNNAME_W_Counter_ID, null); else set_ValueNoCheck (COLUMNNAME_W_Counter_ID, Integer.valueOf(W_Counter_ID)); } /** Get Web Counter. @return Individual Count hit */ public int getW_Counter_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Counter_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_W_Counter.java
1
请完成以下Spring Boot application配置
spring: thymeleaf: cache: true # set to false, this if you are working on UI prefix: file:main-app/main-webapp/src/main/resources/templates/ #directly serve from src folder instead of target web: resources: static-locations: - file:src/main/resources/static/ #directly serve from src folder instead of target - classpath:/META-INF/resources/ - classpath:/resources/ - classpath:/static/ - classpath:/public/ cache: period: 500000 chain: cache: true logging.level: org.jooq.too
ls.LoggerListener: DEBUG org.springframework.security: INFO org.springframework.security.web: INFO org.springframework.cloud: INFO # org.hibernate.SQL: debug # org.hibernate.type: TRACE 'org.hibernate.engine.internal.StatisticalLoggingSessionEventListener': info
repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\resources\application-local.yml
2
请完成以下Java代码
public String getTaskId() { return taskId; } public String getJobId() { return jobId; } public String getJobDefinitionId() { return jobDefinitionId; } public String getBatchId() { return batchId; } public String getUserId() { return userId; } public Date getTimestamp() { return timestamp; } public String getOperationId() { return operationId; } public String getExternalTaskId() { return externalTaskId; } public String getOperationType() { return operationType; }
public String getEntityType() { return entityType; } public String getProperty() { return property; } public String getOrgValue() { return orgValue; } public String getNewValue() { return newValue; } public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public String getCategory() { return category; } public String getAnnotation() { return annotation; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\UserOperationLogEntryDto.java
1
请完成以下Java代码
public org.compiere.model.I_S_Resource getPP_Plant() { return get_ValueAsPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class); } @Override public void setPP_Plant(final org.compiere.model.I_S_Resource PP_Plant) { set_ValueFromPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class, PP_Plant); } @Override public void setPP_Plant_ID (final int PP_Plant_ID) { if (PP_Plant_ID < 1) set_Value (COLUMNNAME_PP_Plant_ID, null); else set_Value (COLUMNNAME_PP_Plant_ID, PP_Plant_ID); } @Override public int getPP_Plant_ID() { return get_ValueAsInt(COLUMNNAME_PP_Plant_ID); } @Override public org.eevolution.model.I_PP_Product_BOMLine getPP_Product_BOMLine() { return get_ValueAsPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class); } @Override public void setPP_Product_BOMLine(final org.eevolution.model.I_PP_Product_BOMLine PP_Product_BOMLine)
{ set_ValueFromPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class, PP_Product_BOMLine); } @Override public void setPP_Product_BOMLine_ID (final int PP_Product_BOMLine_ID) { if (PP_Product_BOMLine_ID < 1) set_Value (COLUMNNAME_PP_Product_BOMLine_ID, null); else set_Value (COLUMNNAME_PP_Product_BOMLine_ID, PP_Product_BOMLine_ID); } @Override public int getPP_Product_BOMLine_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_BOMLine_ID); } @Override public void setPP_Product_Planning_ID (final int PP_Product_Planning_ID) { if (PP_Product_Planning_ID < 1) set_Value (COLUMNNAME_PP_Product_Planning_ID, null); else set_Value (COLUMNNAME_PP_Product_Planning_ID, PP_Product_Planning_ID); } @Override public int getPP_Product_Planning_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_Planning_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_Prod_Detail.java
1
请完成以下Java代码
public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_ProductMember() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_ProductMember_ID(), get_TrxName()); } /** Set Membership. @param M_ProductMember_ID Product used to deternine the price of the membership for the topic type */ public void setM_ProductMember_ID (int M_ProductMember_ID) { if (M_ProductMember_ID < 1) set_Value (COLUMNNAME_M_ProductMember_ID, null);
else set_Value (COLUMNNAME_M_ProductMember_ID, Integer.valueOf(M_ProductMember_ID)); } /** Get Membership. @return Product used to deternine the price of the membership for the topic type */ public int getM_ProductMember_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductMember_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_TopicType.java
1
请在Spring Boot框架中完成以下Java代码
public void setId(String id) { this.id = id; } public String getId() { return id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getType() {
return type; } public void setType(String type) { this.type = type; } public boolean isSaveProcessInstanceId() { return saveProcessInstanceId; } public void setSaveProcessInstanceId(boolean saveProcessInstanceId) { this.saveProcessInstanceId = saveProcessInstanceId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\engine\CommentRequest.java
2
请完成以下Java代码
public boolean isAttachmentStorable(@NonNull final AttachmentEntry attachmentEntry) { return appliesTo(attachmentEntry); } @Override public URI storeAttachment(@NonNull final AttachmentEntry attachmentEntry) { final boolean attachmentIsStoredForThefirstTime = !attachmentEntry .getTags() .toMap() .keySet() .stream() .anyMatch(key -> key.startsWith(AttachmentTags.TAGNAME_STORED_PREFIX)); byte[] attachmentDataToStore; if (attachmentIsStoredForThefirstTime) { attachmentDataToStore = attachmentEntryService.retrieveData(attachmentEntry.getId()); } else { attachmentDataToStore = computeDataWithCopyFlagSetToTrue(attachmentEntry); } final String directory = retrieveDirectoryOrNull(attachmentEntry); final File file = new File(directory, attachmentEntry.getFilename()); try (final FileOutputStream fileOutputStream = new FileOutputStream(file)) { fileOutputStream.write(attachmentDataToStore); return file.toURI(); } catch (final IOException e) { throw new AdempiereException("Unable to write attachment data to file", e).appendParametersToMessage() .setParameter("file", file) .setParameter("attachmentEntry", attachmentEntry); } } private byte[] computeDataWithCopyFlagSetToTrue(@NonNull final AttachmentEntry attachmentEntry) { byte[] attachmentData = attachmentEntryService.retrieveData(attachmentEntry.getId()); // get the converter to use
final String xsdName = XmlIntrospectionUtil.extractXsdValueOrNull(new ByteArrayInputStream(attachmentData)); final CrossVersionRequestConverter converter = crossVersionServiceRegistry.getRequestConverterForXsdName(xsdName); Check.assumeNotNull(converter, "Missing CrossVersionRequestConverter for XSD={}; attachmentEntry={}", xsdName, attachmentEntry); // convert to crossVersion data final XmlRequest crossVersionRequest = converter.toCrossVersionRequest(new ByteArrayInputStream(attachmentData)); // patch final XmlRequest updatedCrossVersionRequest = updateCrossVersionRequest(crossVersionRequest); // convert back to byte[] final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); converter.fromCrossVersionRequest(updatedCrossVersionRequest, outputStream); return outputStream.toByteArray(); } private XmlRequest updateCrossVersionRequest(@NonNull final XmlRequest crossVersionRequest) { final RequestMod mod = RequestMod .builder() .payloadMod(PayloadMod .builder() .copy(true) .build()) .build(); return crossVersionRequest.withMod(mod); } }
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\store\StoreForumDatenaustauschAttachmentService.java
1
请完成以下Java代码
public JsonInventoryLineHU toJson(final InventoryLineHU lineHU, InventoryLine line) { final ProductInfo product = products.getById(line.getProductId()); final HuId huId = lineHU.getHuId(); final String productName = product.getProductName().translate(adLanguage); final String huDisplayName = huId != null ? handlingUnits.getDisplayName(huId) : null; return JsonInventoryLineHU.builder() .id(lineHU.getIdNotNull()) .caption(CoalesceUtil.firstNotBlank(huDisplayName, productName)) .productId(product.getProductId()) .productNo(product.getProductNo()) .productName(productName) .locatorId(line.getLocatorId().getRepoId()) .locatorName(warehouses.getLocatorName(line.getLocatorId())) .huId(huId) .huDisplayName(huDisplayName)
.uom(lineHU.getUOMSymbol()) .qtyBooked(lineHU.getQtyBook().toBigDecimal()) .qtyCount(lineHU.getQtyCount().toBigDecimal()) .countStatus(computeCountStatus(lineHU)) .attributes(loadAllDetails ? JsonAttribute.of(asis.getById(lineHU.getAsiId()), adLanguage) : null) .build(); } public JsonInventoryLineHU toJson(final InventoryLine line, final InventoryLineHUId lineHUId) { final InventoryLineHU lineHU = line.getInventoryLineHUById(lineHUId); return toJson(lineHU, line); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\rest_api\mappers\JsonInventoryJobMapper.java
1
请完成以下Java代码
public String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException { try { return StringExpressionsHelper.evaluateParam(parameter, ctx, onVariableNotFound); } catch (final Exception e) { throw ExpressionEvaluationException.wrapIfNeeded(e) .addExpression(this); } } @Override public IStringExpression resolvePartial(final Evaluatee ctx) throws ExpressionEvaluationException {
try { final String value = StringExpressionsHelper.evaluateParam(parameter, ctx, OnVariableNotFound.ReturnNoResult); if (value == null || value == EMPTY_RESULT) { return this; } return ConstantStringExpression.of(value); } catch (final Exception e) { throw ExpressionEvaluationException.wrapIfNeeded(e) .addExpression(this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\SingleParameterStringExpression.java
1
请完成以下Java代码
public class JsonConverter { public static JSONObject objectToJSONObject(Object object) { try { String jsonString = new ObjectMapper().writeValueAsString(object); return new JSONObject(jsonString); } catch (JSONException | JsonProcessingException e) { e.printStackTrace(); return null; } } public static JSONArray objectToJSONArray(Object object) { try { String jsonString = new ObjectMapper().writeValueAsString(object); return new JSONArray(jsonString);
} catch (JSONException | JsonProcessingException e) { e.printStackTrace(); return null; } } public static <T> T jsonObjectToObject(Object jsonObject, Class<T> clazz) { try { // List<Car> listCar = objectMapper.readValue(jsonCarArray, new TypeReference<List<Car>>(){}); return new ObjectMapper().readValue(jsonObject.toString(), clazz); } catch (IOException e) { return null; } } }
repos\SpringBootBucket-master\springboot-socketio\src\main\java\com\xncoding\jwt\common\JsonConverter.java
1
请完成以下Java代码
protected void sendCancelEvent(JobEntity jobToDelete) { if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { Context.getProcessEngineConfiguration() .getEventDispatcher() .dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.JOB_CANCELED, jobToDelete)); } } protected JobEntity getJobToDelete(CommandContext commandContext) { if (jobId == null) { throw new ActivitiIllegalArgumentException("jobId is null"); } if (log.isDebugEnabled()) { log.debug("Deleting job {}", jobId); }
JobEntity job = commandContext.getJobEntityManager().findById(jobId); if (job == null) { throw new ActivitiObjectNotFoundException("No job found with id '" + jobId + "'", Job.class); } // We need to check if the job was locked, ie acquired by the job acquisition thread // This happens if the job was already acquired, but not yet executed. // In that case, we can't allow to delete the job. if (job.getLockOwner() != null) { throw new ActivitiException("Cannot delete job when the job is being executed. Try again later."); } return job; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\DeleteJobCmd.java
1
请完成以下Java代码
public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public String getServiceRendered() { return serviceRendered; } public void setServiceRendered(String serviceRendered) { this.serviceRendered = serviceRendered; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
repos\tutorials-master\spring-boot-modules\spring-boot-keycloak-adapters\src\main\java\com\baeldung\keycloak\Customer.java
1
请完成以下Java代码
public class FieldExtensionParser extends BaseChildElementParser { @Override public String getElementName() { return ELEMENT_FIELD; } @Override public boolean accepts(BaseElement element) { return ((element instanceof FlowableListener) || (element instanceof ServiceTask) || (element instanceof SendTask) || (element instanceof AbstractFlowableHttpHandler)); } @Override public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model) throws Exception { if (!accepts(parentElement)) { return; } FieldExtension extension = new FieldExtension(); BpmnXMLUtil.addXMLLocation(extension, xtr); extension.setFieldName(xtr.getAttributeValue(null, ATTRIBUTE_FIELD_NAME)); if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_FIELD_STRING))) { extension.setStringValue(xtr.getAttributeValue(null, ATTRIBUTE_FIELD_STRING)); } else if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_FIELD_EXPRESSION))) { extension.setExpression(xtr.getAttributeValue(null, ATTRIBUTE_FIELD_EXPRESSION)); } else { boolean readyWithFieldExtension = false; try { while (!readyWithFieldExtension && xtr.hasNext()) {
xtr.next(); if (xtr.isStartElement() && ELEMENT_FIELD_STRING.equalsIgnoreCase(xtr.getLocalName())) { extension.setStringValue(xtr.getElementText().trim()); } else if (xtr.isStartElement() && ATTRIBUTE_FIELD_EXPRESSION.equalsIgnoreCase(xtr.getLocalName())) { extension.setExpression(xtr.getElementText().trim()); } else if (xtr.isEndElement() && getElementName().equalsIgnoreCase(xtr.getLocalName())) { readyWithFieldExtension = true; } } } catch (Exception e) { LOGGER.warn("Error parsing field extension child elements", e); } } if (parentElement instanceof FlowableListener) { ((FlowableListener) parentElement).getFieldExtensions().add(extension); } else if (parentElement instanceof ServiceTask) { ((ServiceTask) parentElement).getFieldExtensions().add(extension); } else if (parentElement instanceof SendTask) { ((SendTask) parentElement).getFieldExtensions().add(extension); } else { ((AbstractFlowableHttpHandler) parentElement).getFieldExtensions().add(extension); } } }
repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\child\FieldExtensionParser.java
1
请完成以下Java代码
public Response convertToPublish(TransportProtos.AttributeUpdateNotificationMsg msg) throws AdaptorException { return getObserveNotification(msg.toByteArray()); } @Override public Response convertToPublish(TransportProtos.ToDeviceRpcRequestMsg rpcRequest, DynamicMessage.Builder rpcRequestDynamicMessageBuilder) throws AdaptorException { return getObserveNotification(ProtoConverter.convertToRpcRequest(rpcRequest, rpcRequestDynamicMessageBuilder)); } @Override public Response convertToPublish(TransportProtos.ToServerRpcResponseMsg msg) throws AdaptorException { Response response = new Response(CoAP.ResponseCode.CONTENT); response.setPayload(msg.toByteArray()); return response; } @Override public Response convertToPublish(TransportProtos.GetAttributeResponseMsg msg) throws AdaptorException { if (msg.getSharedStateMsg()) { if (StringUtils.isEmpty(msg.getError())) { Response response = new Response(CoAP.ResponseCode.CONTENT); TransportProtos.AttributeUpdateNotificationMsg notificationMsg = TransportProtos.AttributeUpdateNotificationMsg.newBuilder().addAllSharedUpdated(msg.getSharedAttributeListList()).build(); response.setPayload(notificationMsg.toByteArray()); return response; } else { return new Response(CoAP.ResponseCode.INTERNAL_SERVER_ERROR); } } else { if (msg.getClientAttributeListCount() == 0 && msg.getSharedAttributeListCount() == 0) { return new Response(CoAP.ResponseCode.NOT_FOUND); } else { Response response = new Response(CoAP.ResponseCode.CONTENT); response.setPayload(msg.toByteArray());
return response; } } } private Response getObserveNotification(byte[] notification) { Response response = new Response(CoAP.ResponseCode.CONTENT); response.setPayload(notification); return response; } @Override public int getContentFormat() { return MediaTypeRegistry.APPLICATION_OCTET_STREAM; } }
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\adaptors\ProtoCoapAdaptor.java
1
请完成以下Java代码
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
请在Spring Boot框架中完成以下Java代码
public class SyncWeeklySupply implements IConfirmableDTO { String uuid; boolean deleted; long syncConfirmationId; String bpartner_uuid; String product_uuid; LocalDate weekDay; String trend; int version; @Builder(toBuilder = true) @JsonCreator public SyncWeeklySupply( @JsonProperty("uuid") final String uuid, @JsonProperty("deleted") final boolean deleted, @JsonProperty("syncConfirmationId") final long syncConfirmationId, @JsonProperty("bpartner_uuid") final String bpartner_uuid, @JsonProperty("product_uuid") final String product_uuid, @JsonProperty("weekDay") final LocalDate weekDay, @JsonProperty("trend") final String trend, @JsonProperty("version") final int version) { this.uuid = uuid; this.deleted = deleted; this.syncConfirmationId = syncConfirmationId;
this.bpartner_uuid = bpartner_uuid; this.product_uuid = product_uuid; this.weekDay = weekDay; this.trend = trend; this.version = version; } @Override public String toString() { return "SyncWeeklySupply [" + "bpartner_uuid=" + bpartner_uuid + ", product_uuid=" + product_uuid + ", weekDay=" + weekDay + ", trend=" + trend + ", uuid=" + getUuid() + ", version=" + version + "]"; } @Override public IConfirmableDTO withNotDeleted() { return toBuilder().deleted(false).build(); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-procurement\src\main\java\de\metas\common\procurement\sync\protocol\dto\SyncWeeklySupply.java
2
请在Spring Boot框架中完成以下Java代码
public @Nullable String getUsername() { return this.username; } public void setUsername(@Nullable String username) { this.username = username; } public @Nullable String getPassword() { return this.password; } public void setPassword(@Nullable String password) { this.password = password; } public @Nullable String getApiKey() { return this.apiKey; } public void setApiKey(@Nullable String apiKey) { this.apiKey = apiKey; } public Duration getConnectionTimeout() { return this.connectionTimeout; } public void setConnectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; } public Duration getSocketTimeout() { return this.socketTimeout; } public void setSocketTimeout(Duration socketTimeout) { this.socketTimeout = socketTimeout; } public boolean isSocketKeepAlive() { return this.socketKeepAlive; } public void setSocketKeepAlive(boolean socketKeepAlive) { this.socketKeepAlive = socketKeepAlive; } public @Nullable String getPathPrefix() { return this.pathPrefix; } public void setPathPrefix(@Nullable String pathPrefix) { this.pathPrefix = pathPrefix; } public Restclient getRestclient() { return this.restclient; } public static class Restclient { private final Sniffer sniffer = new Sniffer(); private final Ssl ssl = new Ssl(); public Sniffer getSniffer() { return this.sniffer; } public Ssl getSsl() { return this.ssl; }
public static class Sniffer { /** * Whether the sniffer is enabled. */ private boolean enabled; /** * Interval between consecutive ordinary sniff executions. */ private Duration interval = Duration.ofMinutes(5); /** * Delay of a sniff execution scheduled after a failure. */ private Duration delayAfterFailure = Duration.ofMinutes(1); public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Duration getInterval() { return this.interval; } public void setInterval(Duration interval) { this.interval = interval; } public Duration getDelayAfterFailure() { return this.delayAfterFailure; } public void setDelayAfterFailure(Duration delayAfterFailure) { this.delayAfterFailure = delayAfterFailure; } } public static class Ssl { /** * SSL bundle name. */ private @Nullable String bundle; public @Nullable String getBundle() { return this.bundle; } public void setBundle(@Nullable String bundle) { this.bundle = bundle; } } } }
repos\spring-boot-4.0.1\module\spring-boot-elasticsearch\src\main\java\org\springframework\boot\elasticsearch\autoconfigure\ElasticsearchProperties.java
2
请完成以下Java代码
public ProductId getProductId() { return getCostSegmentAndElement().getProductId(); } public UomId getUomId() { return getPrice().getUomId(); } public CostElementId getCostElementId() { return getCostSegmentAndElement().getCostElementId(); } public boolean isInboundCost() { return !getTrxType().isOutboundCost(); } public boolean isMainProduct() { return getTrxType() == PPOrderCostTrxType.MainProduct; } public boolean isCoProduct() { return getTrxType().isCoProduct(); } public boolean isByProduct() { return getTrxType() == PPOrderCostTrxType.ByProduct; } @NonNull public PPOrderCost addingAccumulatedAmountAndQty( @NonNull final CostAmount amt, @NonNull final Quantity qty, @NonNull final QuantityUOMConverter uomConverter) { if (amt.isZero() && qty.isZero()) { return this; } final boolean amtIsPositiveOrZero = amt.signum() >= 0; final boolean amtIsNotZero = amt.signum() != 0;
final boolean qtyIsPositiveOrZero = qty.signum() >= 0; if (amtIsNotZero && amtIsPositiveOrZero != qtyIsPositiveOrZero ) { throw new AdempiereException("Amount and Quantity shall have the same sign: " + amt + ", " + qty); } final Quantity accumulatedQty = getAccumulatedQty(); final Quantity qtyConv = uomConverter.convertQuantityTo(qty, getProductId(), accumulatedQty.getUomId()); return toBuilder() .accumulatedAmount(getAccumulatedAmount().add(amt)) .accumulatedQty(accumulatedQty.add(qtyConv)) .build(); } public PPOrderCost subtractingAccumulatedAmountAndQty( @NonNull final CostAmount amt, @NonNull final Quantity qty, @NonNull final QuantityUOMConverter uomConverter) { return addingAccumulatedAmountAndQty(amt.negate(), qty.negate(), uomConverter); } public PPOrderCost withPrice(@NonNull final CostPrice newPrice) { if (this.getPrice().equals(newPrice)) { return this; } return toBuilder().price(newPrice).build(); } /* package */void setPostCalculationAmount(@NonNull final CostAmount postCalculationAmount) { this.postCalculationAmount = postCalculationAmount; } /* package */void setPostCalculationAmountAsAccumulatedAmt() { setPostCalculationAmount(getAccumulatedAmount()); } /* package */void setPostCalculationAmountAsZero() { setPostCalculationAmount(getPostCalculationAmount().toZero()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderCost.java
1
请完成以下Java代码
public class FlatrateTermRefund_Handler implements ConditionTypeSpecificInvoiceCandidateHandler { @Override public String getConditionsType() { return X_C_Flatrate_Term.TYPE_CONDITIONS_Refund; } /** * @return an empty iterator; invoice candidates that need to be there are created from {@link CandidateAssignmentService}. */ @Override public Iterator<I_C_Flatrate_Term> retrieveTermsWithMissingCandidates(@Nullable final QueryLimit limit_IGNORED) { return ImmutableList .<I_C_Flatrate_Term> of() .iterator(); } @NonNull @Override public CandidatesAutoCreateMode isMissingInvoiceCandidate(@Nullable final I_C_Flatrate_Term flatrateTerm) { return CandidatesAutoCreateMode.DONT; } /** * Does nothing */ @Override public void setSpecificInvoiceCandidateValues( @NonNull final I_C_Invoice_Candidate ic, @NonNull final I_C_Flatrate_Term term) { // nothing to do } /** * @return always one, in the respective term's UOM */ @Override public Quantity calculateQtyEntered(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord) { final UomId uomId = HandlerTools.retrieveUomId(invoiceCandidateRecord); final I_C_UOM uomRecord = loadOutOfTrx(uomId, I_C_UOM.class);
return Quantity.of(ONE, uomRecord); } /** * @return {@link PriceAndTax#NONE} because the tax remains unchanged and the price is updated in {@link CandidateAssignmentService}. */ @Override public PriceAndTax calculatePriceAndTax(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord) { return PriceAndTax.NONE; // no changes to be made } @Override public Consumer<I_C_Invoice_Candidate> getInvoiceScheduleSetterFunction( @Nullable final Consumer<I_C_Invoice_Candidate> IGNORED_defaultImplementation) { return ic -> { final FlatrateTermId flatrateTermId = FlatrateTermId.ofRepoId(ic.getRecord_ID()); final RefundContractRepository refundContractRepository = SpringContextHolder.instance.getBean(RefundContractRepository.class); final RefundContract refundContract = refundContractRepository.getById(flatrateTermId); final NextInvoiceDate nextInvoiceDate = refundContract.computeNextInvoiceDate(asLocalDate(ic.getDeliveryDate())); ic.setC_InvoiceSchedule_ID(nextInvoiceDate.getInvoiceSchedule().getId().getRepoId()); ic.setDateToInvoice(asTimestamp(nextInvoiceDate.getDateToInvoice())); }; } /** Just return the record's current date */ @Override public Timestamp calculateDateOrdered(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord) { return invoiceCandidateRecord.getDateOrdered(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\invoicecandidatehandler\FlatrateTermRefund_Handler.java
1
请完成以下Java代码
public class PDF2WordExample { private static final String FILENAME = "src/main/resources/pdf.pdf"; public static void main(String[] args) { try { generateDocFromPDF(FILENAME); } catch (IOException e) { e.printStackTrace(); } } private static void generateDocFromPDF(String filename) throws IOException { XWPFDocument doc = new XWPFDocument(); String pdf = filename; PdfReader reader = new PdfReader(pdf);
PdfReaderContentParser parser = new PdfReaderContentParser(reader); for (int i = 1; i <= reader.getNumberOfPages(); i++) { TextExtractionStrategy strategy = parser.processContent(i, new SimpleTextExtractionStrategy()); String text = strategy.getResultantText(); XWPFParagraph p = doc.createParagraph(); XWPFRun run = p.createRun(); run.setText(text); run.addBreak(BreakType.PAGE); } FileOutputStream out = new FileOutputStream("src/output/pdf.docx"); doc.write(out); out.close(); reader.close(); doc.close(); } }
repos\tutorials-master\text-processing-libraries-modules\pdf\src\main\java\com\baeldung\pdf\PDF2WordExample.java
1
请在Spring Boot框架中完成以下Java代码
public void persistAuthors() { List<Author> authors = new ArrayList<>(); for (int i = 0; i < 100; i++) { Author author = new Author(); author.setName("Name_" + i); author.setGenre("Genre_" + i); author.setAge((int) ((Math.random() + 0.1) * 100)); authors.add(author); } authorRepository.saveAll(authors); } // good if you want to delete all records public void deleteAuthorsViaDeleteAllInBatch() { authorRepository.deleteAllInBatch(); } // good if the number of deletes can be converted into // a DELETE of type, delete from author where id=? or id=? or id=? ... // without exceeding the maximum accepted size (as a workaround, // split the number of deletes in multiple chunks to avoid this issue) // doesn't prevent lost updates @Transactional public void deleteAuthorsViaDeleteInBatch() { List<Author> authors = authorRepository.findByAgeLessThan(60);
authorRepository.deleteInBatch(authors); } // good if you want an alternative to deleteInBatch() @Transactional public void deleteAuthorsViaDeleteInBulk() { List<Author> authors = authorRepository.findByAgeLessThan(60); authorRepository.deleteInBulk(authors); } // good if you need to delete in a classical batch approach @Transactional public void deleteAuthorsViaDeleteAll() { List<Author> authors = authorRepository.findByAgeLessThan(60); authorRepository.deleteAll(authors); // for deleting all Authors use deleteAll() with no arguments } // good if you need to delete in a classical batch approach @Transactional public void deleteAuthorsViaDelete() { List<Author> authors = authorRepository.findByAgeLessThan(60); authors.forEach(authorRepository::delete); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchDeleteSingleEntity\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public void setC_BPartner_ID (final int C_BPartner_ID) { if (C_BPartner_ID < 1) set_Value (COLUMNNAME_C_BPartner_ID, null); else set_Value (COLUMNNAME_C_BPartner_ID, C_BPartner_ID); } @Override public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setC_BPartner_Location_ID (final int C_BPartner_Location_ID) { if (C_BPartner_Location_ID < 1) set_Value (COLUMNNAME_C_BPartner_Location_ID, null); else set_Value (COLUMNNAME_C_BPartner_Location_ID, C_BPartner_Location_ID); } @Override public int getC_BPartner_Location_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Location_ID); } @Override public void setIsDynamic (final boolean IsDynamic) { set_Value (COLUMNNAME_IsDynamic, IsDynamic); } @Override public boolean isDynamic() { return get_ValueAsBoolean(COLUMNNAME_IsDynamic); } @Override public void setIsPickingRackSystem (final boolean IsPickingRackSystem) { set_Value (COLUMNNAME_IsPickingRackSystem, IsPickingRackSystem); } @Override public boolean isPickingRackSystem() { return get_ValueAsBoolean(COLUMNNAME_IsPickingRackSystem); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_Value (COLUMNNAME_M_HU_ID, null); else set_Value (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setM_Locator_ID (final int M_Locator_ID) { if (M_Locator_ID < 1) set_Value (COLUMNNAME_M_Locator_ID, null); else set_Value (COLUMNNAME_M_Locator_ID, M_Locator_ID); } @Override public int getM_Locator_ID() { return get_ValueAsInt(COLUMNNAME_M_Locator_ID); } @Override public void setM_Picking_Job_ID (final int M_Picking_Job_ID) { if (M_Picking_Job_ID < 1) set_Value (COLUMNNAME_M_Picking_Job_ID, null); else set_Value (COLUMNNAME_M_Picking_Job_ID, M_Picking_Job_ID); }
@Override public int getM_Picking_Job_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_ID); } @Override public void setM_PickingSlot_ID (final int M_PickingSlot_ID) { if (M_PickingSlot_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PickingSlot_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PickingSlot_ID, M_PickingSlot_ID); } @Override public int getM_PickingSlot_ID() { return get_ValueAsInt(COLUMNNAME_M_PickingSlot_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setPickingSlot (final java.lang.String PickingSlot) { set_Value (COLUMNNAME_PickingSlot, PickingSlot); } @Override public java.lang.String getPickingSlot() { return get_ValueAsString(COLUMNNAME_PickingSlot); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\picking\model\X_M_PickingSlot.java
1
请在Spring Boot框架中完成以下Java代码
private void sendFailureResponse(HttpServletResponse response, SecurityResponse securityResponse) { try { response.sendError(securityResponse.getStatus().value(), securityResponse.getMessage()); } catch (Exception ex) { logger.debug("Failed to send error response", ex); } } } /** * {@link ServletWebOperation} wrapper to add security. */ private static class SecureServletWebOperation implements ServletWebOperation { private final ServletWebOperation delegate; private final SecurityInterceptor securityInterceptor; private final EndpointId endpointId; SecureServletWebOperation(ServletWebOperation delegate, SecurityInterceptor securityInterceptor, EndpointId endpointId) { this.delegate = delegate; this.securityInterceptor = securityInterceptor; this.endpointId = endpointId; }
@Override public @Nullable Object handle(HttpServletRequest request, @Nullable Map<String, String> body) { SecurityResponse securityResponse = this.securityInterceptor.preHandle(request, this.endpointId); if (!securityResponse.getStatus().equals(HttpStatus.OK)) { return new ResponseEntity<Object>(securityResponse.getMessage(), securityResponse.getStatus()); } return this.delegate.handle(request, body); } } static class CloudFoundryWebEndpointServletHandlerMappingRuntimeHints implements RuntimeHintsRegistrar { private final ReflectiveRuntimeHintsRegistrar reflectiveRegistrar = new ReflectiveRuntimeHintsRegistrar(); private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar(); @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { this.reflectiveRegistrar.registerRuntimeHints(hints, CloudFoundryLinksHandler.class); this.bindingRegistrar.registerReflectionHints(hints.reflection(), Link.class); } } }
repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\servlet\CloudFoundryWebEndpointServletHandlerMapping.java
2
请完成以下Java代码
private static Executor createAsyncExecutor() { final CustomizableThreadFactory asyncThreadFactory = new CustomizableThreadFactory(LookupCacheInvalidationDispatcher.class.getSimpleName()); asyncThreadFactory.setDaemon(true); return Executors.newSingleThreadExecutor(asyncThreadFactory); } @PostConstruct private void postConstruct() { CacheMgt.get().addCacheResetListener(this); } @Override public long reset(final CacheInvalidateMultiRequest multiRequest) { final ITrxManager trxManager = Services.get(ITrxManager.class); final ITrx currentTrx = trxManager.getThreadInheritedTrx(OnTrxMissingPolicy.ReturnTrxNone); if (trxManager.isNull(currentTrx)) { async.execute(() -> resetNow(extractTableNames(multiRequest))); } else { final TableNamesToResetCollector collector = currentTrx.getProperty(TRXPROP_TableNamesToInvalidate, trx -> { final TableNamesToResetCollector c = new TableNamesToResetCollector(); trx.getTrxListenerManager() .newEventListener(TrxEventTiming.AFTER_COMMIT) .registerHandlingMethod(innerTrx -> { final Set<String> tableNames = c.toSet(); if (tableNames.isEmpty()) { return; } async.execute(() -> resetNow(tableNames)); }); return c; }); collector.addTableNames(extractTableNames(multiRequest)); } return 1; // not relevant } private Set<String> extractTableNames(final CacheInvalidateMultiRequest multiRequest) { if (multiRequest.isResetAll()) { // not relevant for our lookups return ImmutableSet.of(); } return multiRequest.getRequests()
.stream() .filter(request -> !request.isAll()) // not relevant for our lookups .map(CacheInvalidateRequest::getTableNameEffective) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } private void resetNow(final Set<String> tableNames) { if (tableNames.isEmpty()) { return; } lookupDataSourceFactory.cacheInvalidateOnRecordsChanged(tableNames); } private static final class TableNamesToResetCollector { private final Set<String> tableNames = new HashSet<>(); public Set<String> toSet() { return ImmutableSet.copyOf(tableNames); } public void addTableNames(final Collection<String> tableNamesToAdd) { tableNames.addAll(tableNamesToAdd); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LookupCacheInvalidationDispatcher.java
1
请完成以下Java代码
public int getLink_BankStatementLine_ID() { return get_ValueAsInt(COLUMNNAME_Link_BankStatementLine_ID); } @Override public void setMemo (final @Nullable java.lang.String Memo) { set_Value (COLUMNNAME_Memo, Memo); } @Override public java.lang.String getMemo() { return get_ValueAsString(COLUMNNAME_Memo); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setReconciledBy_SAP_GLJournal_ID (final int ReconciledBy_SAP_GLJournal_ID) { if (ReconciledBy_SAP_GLJournal_ID < 1) set_Value (COLUMNNAME_ReconciledBy_SAP_GLJournal_ID, null); else set_Value (COLUMNNAME_ReconciledBy_SAP_GLJournal_ID, ReconciledBy_SAP_GLJournal_ID); } @Override public int getReconciledBy_SAP_GLJournal_ID() { return get_ValueAsInt(COLUMNNAME_ReconciledBy_SAP_GLJournal_ID); } @Override public void setReconciledBy_SAP_GLJournalLine_ID (final int ReconciledBy_SAP_GLJournalLine_ID) { if (ReconciledBy_SAP_GLJournalLine_ID < 1) set_Value (COLUMNNAME_ReconciledBy_SAP_GLJournalLine_ID, null); else set_Value (COLUMNNAME_ReconciledBy_SAP_GLJournalLine_ID, ReconciledBy_SAP_GLJournalLine_ID); } @Override public int getReconciledBy_SAP_GLJournalLine_ID() { return get_ValueAsInt(COLUMNNAME_ReconciledBy_SAP_GLJournalLine_ID); } @Override public void setReferenceNo (final @Nullable java.lang.String ReferenceNo) { set_Value (COLUMNNAME_ReferenceNo, ReferenceNo); }
@Override public java.lang.String getReferenceNo() { return get_ValueAsString(COLUMNNAME_ReferenceNo); } @Override public void setStatementLineDate (final java.sql.Timestamp StatementLineDate) { set_Value (COLUMNNAME_StatementLineDate, StatementLineDate); } @Override public java.sql.Timestamp getStatementLineDate() { return get_ValueAsTimestamp(COLUMNNAME_StatementLineDate); } @Override public void setStmtAmt (final BigDecimal StmtAmt) { set_Value (COLUMNNAME_StmtAmt, StmtAmt); } @Override public BigDecimal getStmtAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StmtAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTrxAmt (final BigDecimal TrxAmt) { set_Value (COLUMNNAME_TrxAmt, TrxAmt); } @Override public BigDecimal getTrxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TrxAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValutaDate (final java.sql.Timestamp ValutaDate) { set_Value (COLUMNNAME_ValutaDate, ValutaDate); } @Override public java.sql.Timestamp getValutaDate() { return get_ValueAsTimestamp(COLUMNNAME_ValutaDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_BankStatementLine.java
1
请完成以下Java代码
public class QueueProcessorFactory implements IQueueProcessorFactory { private final QueueProcessorDescriptorIndex queueProcessorDescriptorIndex = QueueProcessorDescriptorIndex.getInstance(); private final IWorkPackageQueueFactory workPackageQueueFactory = Services.get(IWorkPackageQueueFactory.class); private IWorkpackageLogsRepository getLogsRepository() { return SpringContextHolder.instance.getBean(IWorkpackageLogsRepository.class); } @Override public IQueueProcessor createAsynchronousQueueProcessor(final I_C_Queue_Processor config, final IWorkPackageQueue queue) { final IWorkpackageLogsRepository logsRepository = getLogsRepository(); return new ThreadPoolQueueProcessor(config, queue, logsRepository); }
private IQueueProcessorEventDispatcher queueProcessorEventDispatcher = new DefaultQueueProcessorEventDispatcher(); @Override public IQueueProcessorEventDispatcher getQueueProcessorEventDispatcher() { return queueProcessorEventDispatcher; } @Override public IQueueProcessor createAsynchronousQueueProcessor(@NonNull final QueuePackageProcessorId packageProcessorId) { final I_C_Queue_Processor queueProcessorConfig = queueProcessorDescriptorIndex.getQueueProcessor(packageProcessorId); final IWorkPackageQueue queue = workPackageQueueFactory.getQueueForPackageProcessing(queueProcessorConfig); return createAsynchronousQueueProcessor(queueProcessorConfig, queue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\QueueProcessorFactory.java
1
请完成以下Java代码
public int getC_DocType_PrintOptions_ID() { return get_ValueAsInt(COLUMNNAME_C_DocType_PrintOptions_ID); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * DocumentFlavor AD_Reference_ID=541225 * Reference name: C_DocType_PrintOptions_DocumentFlavor */ public static final int DOCUMENTFLAVOR_AD_Reference_ID=541225; /** EMail = E */ public static final String DOCUMENTFLAVOR_EMail = "E"; /** Print = P */ public static final String DOCUMENTFLAVOR_Print = "P"; @Override public void setDocumentFlavor (final java.lang.String DocumentFlavor) { set_Value (COLUMNNAME_DocumentFlavor, DocumentFlavor); } @Override public java.lang.String getDocumentFlavor() { return get_ValueAsString(COLUMNNAME_DocumentFlavor); } @Override public void setPRINTER_OPTS_IsPrintLogo (final boolean PRINTER_OPTS_IsPrintLogo)
{ set_Value (COLUMNNAME_PRINTER_OPTS_IsPrintLogo, PRINTER_OPTS_IsPrintLogo); } @Override public boolean isPRINTER_OPTS_IsPrintLogo() { return get_ValueAsBoolean(COLUMNNAME_PRINTER_OPTS_IsPrintLogo); } @Override public void setPRINTER_OPTS_IsPrintTotals (final boolean PRINTER_OPTS_IsPrintTotals) { set_Value (COLUMNNAME_PRINTER_OPTS_IsPrintTotals, PRINTER_OPTS_IsPrintTotals); } @Override public boolean isPRINTER_OPTS_IsPrintTotals() { return get_ValueAsBoolean(COLUMNNAME_PRINTER_OPTS_IsPrintTotals); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType_PrintOptions.java
1
请完成以下Java代码
class InOutCostsViewFilterHelper { public static final String FILTER_ID = "default"; public static String PARAM_C_BPartner_ID = "C_BPartner_ID"; public static String PARAM_C_Order_ID = "C_Order_ID"; public static String PARAM_C_Cost_Type_ID = I_C_Cost_Type.COLUMNNAME_C_Cost_Type_ID; public static DocumentFilterDescriptor createFilterDescriptor(@NonNull final LookupDescriptorProviders lookupDescriptorProviders) { return DocumentFilterDescriptor.builder() .setFilterId(FILTER_ID) .setFrequentUsed(false) //.setInlineRenderMode(DocumentFilterInlineRenderMode.INLINE_PARAMETERS) .setDisplayName("default") .addParameter(newParamDescriptor(PARAM_C_BPartner_ID) .widgetType(DocumentFieldWidgetType.Lookup) .lookupDescriptor(lookupDescriptorProviders.searchInTable(I_C_BPartner.Table_Name).provideForFilter())) .addParameter(newParamDescriptor(PARAM_C_Order_ID) .widgetType(DocumentFieldWidgetType.Lookup) .lookupDescriptor(lookupDescriptorProviders.searchInTable(I_C_Order.Table_Name).provideForFilter())) .addParameter(newParamDescriptor(PARAM_C_Cost_Type_ID) .widgetType(DocumentFieldWidgetType.Lookup) .lookupDescriptor(lookupDescriptorProviders.searchInTable(I_C_Cost_Type.Table_Name).provideForFilter())) .build(); }
private static DocumentFilterParamDescriptor.Builder newParamDescriptor(final String fieldName) { return DocumentFilterParamDescriptor.builder() .fieldName(fieldName) .displayName(TranslatableStrings.adElementOrMessage(fieldName)); } public static InOutCostQuery toInOutCostQuery( @NonNull final SOTrx soTrx, @Nullable final DocumentFilter filter) { return InOutCostQuery.builder() .limit(QueryLimit.ONE_HUNDRED) .bpartnerId(filter != null ? BPartnerId.ofRepoIdOrNull(filter.getParameterValueAsInt(PARAM_C_BPartner_ID, -1)) : null) .soTrx(soTrx) .orderId(filter != null ? OrderId.ofRepoIdOrNull(filter.getParameterValueAsInt(PARAM_C_Order_ID, -1)) : null) .costTypeId(filter != null ? OrderCostTypeId.ofRepoIdOrNull(filter.getParameterValueAsInt(PARAM_C_Cost_Type_ID, -1)) : null) .includeReversed(false) .onlyWithOpenAmountToInvoice(true) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoice\match_inout_costs\InOutCostsViewFilterHelper.java
1
请在Spring Boot框架中完成以下Java代码
public class LastInvoiceCostingMethodHandler extends CostingMethodHandlerTemplate { public LastInvoiceCostingMethodHandler(@NonNull final CostingMethodHandlerUtils utils) { super(utils); } @Override public CostingMethod getCostingMethod() { return CostingMethod.LastInvoice; } @Override protected CostDetailCreateResult createCostForMatchInvoice_MaterialCosts(final CostDetailCreateRequest request) { final CurrentCost currentCosts = utils.getCurrentCost(request); final CostDetailPreviousAmounts previousCosts = CostDetailPreviousAmounts.of(currentCosts); final CostDetailCreateResult result = utils.createCostDetailRecordWithChangedCosts(request, previousCosts); final CostAmount amt = request.getAmt(); final Quantity qty = request.getQty(); final boolean isOutboundTrx = qty.signum() < 0; if (!isOutboundTrx) { if (qty.signum() != 0) { final CostAmount price = amt.divide(qty, currentCosts.getPrecision()); currentCosts.setCostPrice(CostPrice.ownCostPrice(price, qty.getUomId())); } else { currentCosts.addToOwnCostPrice(amt); } } currentCosts.addToCurrentQtyAndCumulate(qty, amt, utils.getQuantityUOMConverter()); utils.saveCurrentCost(currentCosts); return result; } @Override
protected CostDetailCreateResult createOutboundCostDefaultImpl(final CostDetailCreateRequest request) { final CurrentCost currentCosts = utils.getCurrentCost(request); final CostDetailPreviousAmounts previousCosts = CostDetailPreviousAmounts.of(currentCosts); final CostDetailCreateResult result = utils.createCostDetailRecordWithChangedCosts(request, previousCosts); currentCosts.addToCurrentQtyAndCumulate(request.getQty(), request.getAmt(), utils.getQuantityUOMConverter()); utils.saveCurrentCost(currentCosts); return result; } @Override public void voidCosts(final CostDetailVoidRequest request) { throw new UnsupportedOperationException(); } @Override public MoveCostsResult createMovementCosts(@NonNull final MoveCostsRequest request) { // TODO Auto-generated method stub throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\methods\LastInvoiceCostingMethodHandler.java
2
请完成以下Java代码
public void setQuery(String query) { this.query = query; } public @Nullable String getQuery() { return this.query; } public void setOperationName(@Nullable String operationName) { this.operationName = operationName; } @Override public @Nullable String getOperationName() { return this.operationName; } public void setVariables(Map<String, Object> variables) { this.variables = variables; } @Override public Map<String, Object> getVariables() { return this.variables; } public void setExtensions(Map<String, Object> extensions) { this.extensions = extensions; } @Override public Map<String, Object> getExtensions() { return this.extensions;
} @Override public String getDocument() { if (this.query == null) { if (this.extensions.get("persistedQuery") != null) { return PersistedQuerySupport.PERSISTED_QUERY_MARKER; } throw new ServerWebInputException("No 'query'"); } return this.query; } @Override public Map<String, Object> toMap() { throw new UnsupportedOperationException(); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\support\SerializableGraphQlRequest.java
1
请完成以下Java代码
public org.compiere.model.I_C_ElementValue getUser1() { return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser1(final org.compiere.model.I_C_ElementValue User1) { set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1); } @Override public void setUser1_ID (final int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, User1_ID); } @Override public int getUser1_ID() { return get_ValueAsInt(COLUMNNAME_User1_ID); } @Override public org.compiere.model.I_C_ElementValue getUser2() { return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser2(final org.compiere.model.I_C_ElementValue User2) { set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2); } @Override public void setUser2_ID (final int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, User2_ID); } @Override public int getUser2_ID() { return get_ValueAsInt(COLUMNNAME_User2_ID); }
@Override public void setUserFlag (final @Nullable java.lang.String UserFlag) { set_Value (COLUMNNAME_UserFlag, UserFlag); } @Override public java.lang.String getUserFlag() { return get_ValueAsString(COLUMNNAME_UserFlag); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice.java
1
请在Spring Boot框架中完成以下Java代码
public class MyInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource { @Autowired private PermissionMapper permissionMapper; /** * 每一个资源所需要的角色 Collection<ConfigAttribute>决策器会用到 */ private static HashMap<String, Collection<ConfigAttribute>> map =null; /** * 返回请求的资源需要的角色 */ @Override public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException { //object 中包含用户请求的request 信息 HttpServletRequest request = ((FilterInvocation) o).getHttpRequest(); for (Iterator<String> it = map.keySet().iterator() ; it.hasNext();) { String url = it.next(); if (new AntPathRequestMatcher( url ).matches( request )) { return map.get( url ); } } return null; } @Override public Collection<ConfigAttribute> getAllConfigAttributes() { //初始化 所有资源 对应的角色 loadResourceDefine(); return null; } @Override public boolean supports(Class<?> aClass) { return true;
} /** * 初始化 所有资源 对应的角色 */ public void loadResourceDefine() { map = new HashMap<>(16); //权限资源 和 角色对应的表 也就是 角色权限 中间表 List<RolePermisson> rolePermissons = permissionMapper.getRolePermissions(); //某个资源 可以被哪些角色访问 for (RolePermisson rolePermisson : rolePermissons) { String url = rolePermisson.getUrl(); String roleName = rolePermisson.getRoleName(); ConfigAttribute role = new SecurityConfig(roleName); if(map.containsKey(url)){ map.get(url).add(role); }else{ List<ConfigAttribute> list = new ArrayList<>(); list.add( role ); map.put( url , list ); } } } }
repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\config\MyInvocationSecurityMetadataSourceService.java
2
请完成以下Java代码
protected static boolean isBoolean(Object obj) { return obj instanceof Boolean; } protected static boolean isDate(Object obj) { return (obj instanceof Date || obj instanceof DateTime || obj instanceof LocalDate || obj instanceof java.time.LocalDate || obj instanceof LocalDateTime || obj instanceof Instant); } protected static boolean isNumber(Object obj) { return obj instanceof Number; } protected Map<String, Object> createDefensiveCopyInputVariables(Map<String, Object> inputVariables) { Map<String, Object> defensiveCopyMap = new HashMap<>(); if (inputVariables != null) { for (Map.Entry<String, Object> entry : inputVariables.entrySet()) { Object newValue = null;
if (entry.getValue() == null) { // do nothing } else if (entry.getValue() instanceof Long) { newValue = Long.valueOf(((Long) entry.getValue()).longValue()); } else if (entry.getValue() instanceof Double) { newValue = Double.valueOf(((Double) entry.getValue()).doubleValue()); } else if (entry.getValue() instanceof Integer) { newValue = Integer.valueOf(((Integer) entry.getValue()).intValue()); } else if (entry.getValue() instanceof Date) { newValue = new Date(((Date) entry.getValue()).getTime()); } else if (entry.getValue() instanceof Boolean) { newValue = Boolean.valueOf(((Boolean) entry.getValue()).booleanValue()); } else { newValue = new String(entry.getValue().toString()); } defensiveCopyMap.put(entry.getKey(), newValue); } } return defensiveCopyMap; } }
repos\flowable-engine-main\modules\flowable-dmn-api\src\main\java\org\flowable\dmn\api\DecisionExecutionAuditContainer.java
1
请完成以下Java代码
public void setUserAgent (String UserAgent) { set_Value (COLUMNNAME_UserAgent, UserAgent); } /** Get User Agent. @return Browser Used */ public String getUserAgent () { return (String)get_Value(COLUMNNAME_UserAgent); } public I_W_CounterCount getW_CounterCount() throws RuntimeException { return (I_W_CounterCount)MTable.get(getCtx(), I_W_CounterCount.Table_Name) .getPO(getW_CounterCount_ID(), get_TrxName()); } /** Set Counter Count. @param W_CounterCount_ID Web Counter Count Management */ public void setW_CounterCount_ID (int W_CounterCount_ID) { if (W_CounterCount_ID < 1) set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, null); else set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, Integer.valueOf(W_CounterCount_ID)); } /** Get Counter Count. @return Web Counter Count Management */ public int getW_CounterCount_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_W_CounterCount_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Web Counter. @param W_Counter_ID Individual Count hit */ public void setW_Counter_ID (int W_Counter_ID) { if (W_Counter_ID < 1) set_ValueNoCheck (COLUMNNAME_W_Counter_ID, null); else set_ValueNoCheck (COLUMNNAME_W_Counter_ID, Integer.valueOf(W_Counter_ID)); } /** Get Web Counter. @return Individual Count hit */ public int getW_Counter_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Counter_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_W_Counter.java
1
请完成以下Java代码
public class WordFilter extends java.util.Hashtable<String, Object> implements Filter { /** * */ private static final long serialVersionUID = 7530768970669548477L; public WordFilter() { super(4); } /** Returns the name of the filter */ public String getInfo() { return "WordFilter"; } /** this method actually performs the filtering. */ public String process(String to_process) { if ( to_process == null || to_process.length() == 0 ) return ""; String tmp = ""; // the true at the end is the key to making it work StringTokenizer st = new StringTokenizer(to_process, " ", true); StringBuffer newValue = new StringBuffer(to_process.length() + 50); while ( st.hasMoreTokens() ) { tmp = st.nextToken(); if (hasAttribute(tmp)) newValue.append((String)get(tmp)); else newValue.append(tmp); } return newValue.toString(); } /** Put a filter somewhere we can get to it. */ public Filter addAttribute(String attribute,Object entity) { put(attribute,entity); return(this);
} /** Get rid of a current filter. */ public Filter removeAttribute(String attribute) { try { remove(attribute); } catch(NullPointerException exc) { // don't really care if this throws a null pointer exception } return(this); } /** Does the filter filter this? */ public boolean hasAttribute(String attribute) { return(containsKey(attribute)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\filter\WordFilter.java
1
请完成以下Java代码
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ArchiveSetDataRequest other = (ArchiveSetDataRequest)obj; if (adArchiveId != other.adArchiveId) { return false; } if (!Arrays.equals(data, other.data)) { return false; } if (sessionId != other.sessionId) { return false; } return true; }
public int getSessionId() { return sessionId; } public void setSessionId(final int sessionId) { this.sessionId = sessionId; } public int getAdArchiveId() { return adArchiveId; } public void setAdArchiveId(final int adArchiveId) { this.adArchiveId = adArchiveId; } public byte[] getData() { return data; } public void setData(final byte[] data) { this.data = data; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive.api\src\main\java\de\metas\document\archive\esb\api\ArchiveSetDataRequest.java
1
请完成以下Java代码
public String getAmiId() { return amiId; } public String getHostname() { return hostname; } public String getInstanceType() { return instanceType; } public String getServiceDomain() { return serviceDomain; } public String getName() { return name; } @Override public String toString() {
StringBuilder builder = new StringBuilder(); builder.append("EC2Metadata [amiId="); builder.append(amiId); builder.append(", hostname="); builder.append(hostname); builder.append(", instanceType="); builder.append(instanceType); builder.append(", serviceDomain="); builder.append(serviceDomain); builder.append(", name="); builder.append(name); builder.append("]"); return builder.toString(); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-aws\src\main\java\com\baeldung\spring\cloud\aws\ec2\EC2Metadata.java
1
请完成以下Java代码
public class URLTokenizer { /** * 预置分词器 */ public static final Segment SEGMENT = HanLP.newSegment(); private static final Pattern WEB_URL = Pattern.compile("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?((?:(?:[a-zA-Z0-9\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF][a-zA-Z0-9\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF\\-]{0,64}\\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-80akhbyknj4f|xn\\-\\-9t4b11yi5a|xn\\-\\-deba0ad|xn\\-\\-g6w251d|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-zckzah)|y[etu]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?(?:\\b|$)"); /** * 分词 * @param text 文本 * @return 分词结果 */ public static List<Term> segment(String text) {
List<Term> termList = new LinkedList<Term>(); Matcher matcher = WEB_URL.matcher(text); int begin = 0; int end; while (matcher.find()) { end = matcher.start(); termList.addAll(SEGMENT.seg(text.substring(begin, end))); termList.add(new Term(matcher.group(), Nature.xu)); begin = matcher.end(); } if (begin < text.length()) termList.addAll(SEGMENT.seg(text.substring(begin))); return termList; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\URLTokenizer.java
1
请完成以下Java代码
public class ByteArrayValueSerializer extends PrimitiveValueSerializer<BytesValue> { public ByteArrayValueSerializer() { super(ValueType.BYTES); } public BytesValue convertToTypedValue(UntypedValueImpl untypedValue) { Object value = untypedValue.getValue(); if (value instanceof byte[]) { return Variables.byteArrayValue((byte[]) value, untypedValue.isTransient()); } else { byte[] data = IoUtil.readInputStream((InputStream) value, null); return Variables.byteArrayValue(data, untypedValue.isTransient()); } }
public BytesValue readValue(ValueFields valueFields, boolean asTransientValue) { return Variables.byteArrayValue(valueFields.getByteArrayValue(), asTransientValue); } public void writeValue(BytesValue variableValue, ValueFields valueFields) { valueFields.setByteArrayValue(variableValue.getValue()); } @Override protected boolean canWriteValue(TypedValue typedValue) { return super.canWriteValue(typedValue) || typedValue.getValue() instanceof InputStream; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\ByteArrayValueSerializer.java
1
请在Spring Boot框架中完成以下Java代码
public class MqttTransportHealthChecker extends TransportHealthChecker<MqttTransportMonitoringConfig> { private MqttClient mqttClient; private static final String DEVICE_TELEMETRY_TOPIC = "v1/devices/me/telemetry"; protected MqttTransportHealthChecker(MqttTransportMonitoringConfig config, TransportMonitoringTarget target) { super(config, target); } @Override protected void initClient() throws Exception { if (mqttClient == null || !mqttClient.isConnected()) { String clientId = MqttAsyncClient.generateClientId(); String accessToken = target.getDevice().getCredentials().getCredentialsId(); mqttClient = new MqttClient(target.getBaseUrl(), clientId, new MemoryPersistence()); mqttClient.setTimeToWait(config.getRequestTimeoutMs()); MqttConnectOptions options = new MqttConnectOptions(); options.setUserName(accessToken); options.setConnectionTimeout(config.getRequestTimeoutMs() / 1000); IMqttToken result = mqttClient.connectWithResult(options); if (result.getException() != null) { throw result.getException(); } log.debug("Initialized MQTT client for URI {}", mqttClient.getServerURI()); } } @Override protected void sendTestPayload(String payload) throws Exception { MqttMessage message = new MqttMessage(); message.setPayload(payload.getBytes()); message.setQos(config.getQos());
mqttClient.publish(DEVICE_TELEMETRY_TOPIC, message); } @Override protected void destroyClient() throws Exception { if (mqttClient != null) { mqttClient.disconnect(); mqttClient = null; log.info("Disconnected MQTT client"); } } @Override protected TransportType getTransportType() { return TransportType.MQTT; } }
repos\thingsboard-master\monitoring\src\main\java\org\thingsboard\monitoring\service\transport\impl\MqttTransportHealthChecker.java
2
请在Spring Boot框架中完成以下Java代码
public InMemoryUserDetailsManager userDetailsService() { UserDetails user1 = User.withUsername("user1") .password("user1Pass") .roles("USER") .build(); UserDetails user2 = User.withUsername("user2") .password("user2Pass") .roles("USER") .build(); return new InMemoryUserDetailsManager(user1, user2); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf() .disable() .authorizeRequests() .requestMatchers("/anonymous*") .anonymous() .requestMatchers("/login*") .permitAll() .anyRequest() .authenticated() .and() .requiresChannel() .requestMatchers("/login*", "/perform_login") .requiresSecure() .anyRequest() .requiresInsecure() .and() .sessionManagement() .sessionFixation() .none() .and() .formLogin() .loginPage("/login.html")
.loginProcessingUrl("/perform_login") .defaultSuccessUrl("/homepage.html", true) .failureUrl("/login.html?error=true") .and() .logout() .logoutUrl("/perform_logout") .deleteCookies("JSESSIONID") .logoutSuccessHandler(logoutSuccessHandler()); return http.build(); } @Bean public LogoutSuccessHandler logoutSuccessHandler() { return new CustomLogoutSuccessHandler(); } }
repos\tutorials-master\spring-security-modules\spring-security-web-login-2\src\main\java\com\baeldung\spring\ChannelSecSecurityConfig.java
2
请完成以下Java代码
public static StockQtyAndUOMQty toZeroIfPositive(@NonNull final StockQtyAndUOMQty stockQtyAndUOMQty) { return stockQtyAndUOMQty.signum() > 0 ? stockQtyAndUOMQty.toZero() : stockQtyAndUOMQty; } public Quantity getQtyInUOM(@NonNull final UomId uomId, @NonNull final QuantityUOMConverter converter) { if (uomQty != null) { if (UomId.equals(uomQty.getUomId(), uomId)) { return uomQty; } else if (UomId.equals(uomQty.getSourceUomId(), uomId))
{ return uomQty.switchToSource(); } } if (UomId.equals(stockQty.getUomId(), uomId)) { return stockQty; } else if (UomId.equals(stockQty.getSourceUomId(), uomId)) { return stockQty.switchToSource(); } return converter.convertQuantityTo(stockQty, productId, uomId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\StockQtyAndUOMQty.java
1
请完成以下Java代码
public class OAuth2ClientRegistrationAuthenticationToken extends AbstractAuthenticationToken { @Serial private static final long serialVersionUID = 7135429161909989115L; @Nullable private final Authentication principal; private final OAuth2ClientRegistration clientRegistration; /** * Constructs an {@code OAuth2ClientRegistrationAuthenticationToken} using the * provided parameters. * @param principal the authenticated principal * @param clientRegistration the client registration */ public OAuth2ClientRegistrationAuthenticationToken(@Nullable Authentication principal, OAuth2ClientRegistration clientRegistration) { super(Collections.emptyList()); Assert.notNull(clientRegistration, "clientRegistration cannot be null"); this.principal = principal; this.clientRegistration = clientRegistration; if (principal != null) { setAuthenticated(principal.isAuthenticated()); } } @Nullable @Override public Object getPrincipal() {
return this.principal; } @Override public Object getCredentials() { return ""; } /** * Returns the client registration. * @return the client registration */ public OAuth2ClientRegistration getClientRegistration() { return this.clientRegistration; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2ClientRegistrationAuthenticationToken.java
1
请在Spring Boot框架中完成以下Java代码
public String getTypeName() { return TYPE_NAME; } @Override public boolean isCachable() { return true; } @Override public boolean isAbleToStore(Object value) { if (value == null) { return true; } return LocalDate.class.isAssignableFrom(value.getClass()); } @Override public Object getValue(ValueFields valueFields) { Long longValue = valueFields.getLongValue(); if (longValue != null) { return new LocalDate(longValue); } return null; } @Override public void setValue(Object value, ValueFields valueFields) { if (value != null) { if (valueFields.getTaskId() != null) { JodaDeprecationLogger.LOGGER.warn(
"Using Joda-Time LocalDate has been deprecated and will be removed in a future version. Task Variable {} in task {} was a Joda-Time LocalDate. ", valueFields.getName(), valueFields.getTaskId()); } else if (valueFields.getProcessInstanceId() != null) { JodaDeprecationLogger.LOGGER.warn( "Using Joda-Time LocalDate has been deprecated and will be removed in a future version. Process Variable {} in process instance {} and execution {} was a Joda-Time LocalDate. ", valueFields.getName(), valueFields.getProcessInstanceId(), valueFields.getExecutionId()); } else { JodaDeprecationLogger.LOGGER.warn( "Using Joda-Time LocalDate has been deprecated and will be removed in a future version. Variable {} in {} instance {} and sub-scope {} was a Joda-Time LocalDate. ", valueFields.getName(), valueFields.getScopeType(), valueFields.getScopeId(), valueFields.getSubScopeId()); } valueFields.setLongValue(((LocalDate) value).toDateTimeAtStartOfDay().getMillis()); } else { valueFields.setLongValue(null); } } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\JodaDateType.java
2
请完成以下Java代码
public void setM_HU_PI_Version(final de.metas.handlingunits.model.I_M_HU_PI_Version M_HU_PI_Version) { set_ValueFromPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class, M_HU_PI_Version); } @Override public void setM_HU_PI_Version_ID (final int M_HU_PI_Version_ID) { if (M_HU_PI_Version_ID < 1) set_Value (COLUMNNAME_M_HU_PI_Version_ID, null); else set_Value (COLUMNNAME_M_HU_PI_Version_ID, M_HU_PI_Version_ID); } @Override public int getM_HU_PI_Version_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Version_ID); } @Override public void setM_HU_Snapshot_ID (final int M_HU_Snapshot_ID) { if (M_HU_Snapshot_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Snapshot_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Snapshot_ID, M_HU_Snapshot_ID); } @Override public int getM_HU_Snapshot_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Snapshot_ID); } @Override public void setM_Locator_ID (final int M_Locator_ID) { if (M_Locator_ID < 1) set_Value (COLUMNNAME_M_Locator_ID, null); else set_Value (COLUMNNAME_M_Locator_ID, M_Locator_ID);
} @Override public int getM_Locator_ID() { return get_ValueAsInt(COLUMNNAME_M_Locator_ID); } @Override public void setSnapshot_UUID (final java.lang.String Snapshot_UUID) { set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID); } @Override public java.lang.String getSnapshot_UUID() { return get_ValueAsString(COLUMNNAME_Snapshot_UUID); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Snapshot.java
1
请完成以下Java代码
public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } @Override public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } public String toEventMessage(String message) { String eventMessage = message.replaceAll("\\s+", " "); if (eventMessage.length() > 163) { eventMessage = eventMessage.substring(0, 160) + "..."; } return eventMessage; }
@Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", type=" + type + ", userId=" + userId + ", time=" + time + ", taskId=" + taskId + ", processInstanceId=" + processInstanceId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", revision= "+ revision + ", removalTime=" + removalTime + ", action=" + action + ", message=" + message + ", fullMessage=" + fullMessage + ", tenantId=" + tenantId + "]"; } @Override public void setRevision(int revision) { this.revision = revision; } @Override public int getRevision() { return revision; } @Override public int getRevisionNext() { return revision + 1; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CommentEntity.java
1
请完成以下Java代码
public void updateBPartnerAddressOverride(final I_M_ReceiptSchedule sched) { final IReceiptScheduleBL receiptScheduleBL = Services.get(IReceiptScheduleBL.class); receiptScheduleBL.updateBPartnerAddressOverride(sched); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void updateHeaderAggregationKey(final I_M_ReceiptSchedule sched) { if (sched.isProcessed()) { return; } final IAggregationKeyBuilder<I_M_ReceiptSchedule> headerAggregationKeyBuilder = receiptScheduleBL.getHeaderAggregationKeyBuilder(); final String headerAggregationKey = headerAggregationKeyBuilder.buildKey(sched); sched.setHeaderAggregationKey(headerAggregationKey); }
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_M_ReceiptSchedule.COLUMNNAME_IsActive, I_M_ReceiptSchedule.COLUMNNAME_M_Warehouse_Override_ID, I_M_ReceiptSchedule.COLUMNNAME_DeliveryRule_Override, I_M_ReceiptSchedule.COLUMNNAME_PriorityRule_Override, I_M_ReceiptSchedule.COLUMNNAME_QtyToMove_Override, I_M_ReceiptSchedule.COLUMNNAME_AD_User_Override_ID, I_M_ReceiptSchedule.COLUMNNAME_BPartnerAddress_Override, I_M_ReceiptSchedule.COLUMNNAME_DeliveryViaRule_Override, I_M_ReceiptSchedule.COLUMNNAME_IsBPartnerAddress_Override, I_M_ReceiptSchedule.COLUMNNAME_ExportStatus }) public void updateCanBeExportedAfter(@NonNull final I_M_ReceiptSchedule sched) { receiptScheduleBL.updateCanBeExportedFrom(sched); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\M_ReceiptSchedule.java
1
请完成以下Java代码
public TableMetaData getTableMetaData(String tableName) { TableMetaData result = new TableMetaData(); try { result.setTableName(tableName); DatabaseMetaData metaData = getDbSqlSession().getSqlSession().getConnection().getMetaData(); if ("postgres".equals(getDbSqlSession().getDbSqlSessionFactory().getDatabaseType())) { tableName = tableName.toLowerCase(); } String catalog = null; if ( getProcessEngineConfiguration().getDatabaseCatalog() != null && getProcessEngineConfiguration().getDatabaseCatalog().length() > 0 ) { catalog = getProcessEngineConfiguration().getDatabaseCatalog(); } String schema = null; if ( getProcessEngineConfiguration().getDatabaseSchema() != null && getProcessEngineConfiguration().getDatabaseSchema().length() > 0 ) { if ("oracle".equals(getDbSqlSession().getDbSqlSessionFactory().getDatabaseType())) { schema = getProcessEngineConfiguration().getDatabaseSchema().toUpperCase(); } else { schema = getProcessEngineConfiguration().getDatabaseSchema(); } } ResultSet resultSet = metaData.getColumns(catalog, schema, tableName, null); while (resultSet.next()) { boolean wrongSchema = false; if (schema != null && schema.length() > 0) { for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
String columnName = resultSet.getMetaData().getColumnName(i + 1); if ("TABLE_SCHEM".equalsIgnoreCase(columnName) || "TABLE_SCHEMA".equalsIgnoreCase(columnName)) { if ( !schema.equalsIgnoreCase( resultSet.getString(resultSet.getMetaData().getColumnName(i + 1)) ) ) { wrongSchema = true; } break; } } } if (!wrongSchema) { String name = resultSet.getString("COLUMN_NAME").toUpperCase(); String type = resultSet.getString("TYPE_NAME").toUpperCase(); result.addColumnMetaData(name, type); } } } catch (SQLException e) { throw new ActivitiException("Could not retrieve database metadata: " + e.getMessage()); } if (result.getColumnNames().isEmpty()) { // According to API, when a table doesn't exist, null should be returned result = null; } return result; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TableDataManagerImpl.java
1
请完成以下Java代码
public I_AD_ReportView getAD_ReportView() throws RuntimeException { return (I_AD_ReportView)MTable.get(getCtx(), I_AD_ReportView.Table_Name) .getPO(getAD_ReportView_ID(), get_TrxName()); } /** Set Report View. @param AD_ReportView_ID View used to generate this report */ public void setAD_ReportView_ID (int AD_ReportView_ID) { if (AD_ReportView_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_ReportView_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_ReportView_ID, Integer.valueOf(AD_ReportView_ID)); } /** Get Report View. @return View used to generate this report */ public int getAD_ReportView_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_ReportView_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getAD_ReportView_ID())); } /** Set Function Column. @param FunctionColumn Overwrite Column with Function */ public void setFunctionColumn (String FunctionColumn) {
set_Value (COLUMNNAME_FunctionColumn, FunctionColumn); } /** Get Function Column. @return Overwrite Column with Function */ public String getFunctionColumn () { return (String)get_Value(COLUMNNAME_FunctionColumn); } /** Set SQL Group Function. @param IsGroupFunction This function will generate a Group By Clause */ public void setIsGroupFunction (boolean IsGroupFunction) { set_Value (COLUMNNAME_IsGroupFunction, Boolean.valueOf(IsGroupFunction)); } /** Get SQL Group Function. @return This function will generate a Group By Clause */ public boolean isGroupFunction () { Object oo = get_Value(COLUMNNAME_IsGroupFunction); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReportView_Col.java
1
请在Spring Boot框架中完成以下Java代码
public static class LogEntriesQuery { public static LogEntriesQuery of(@NonNull final TableRecordReference tableRecordReference) { return LogEntriesQuery.builder() .tableRecordReference(tableRecordReference) .followLocationIdChanges(false) .build(); } @Singular List<TableRecordReference> tableRecordReferences; /** * If {@code true} and the respective {@link TableRecordReference}'s change logs contain changes to FK columns that reference {@code C_Location}, * then those {@code C_Location} records are loaded (all of them in one DB-access). * * Then, instead of adding {@link RecordChangeLogEntry}s for the different {@code C_Location_ID} values, * the actual {@code C_Location} records are compared with each other and {@link RecordChangeLogEntry} are derived from their differences. * * Then those @{@code C_Location}-derived {@link RecordChangeLogEntry}s are added to the respective {@link TableRecordReference}'s change log. * <p/> * If you don't want this to happen e.g. for {@code C_BPartner_Location}, you can set {@code IsAllowLogging='N'} for the column {@code C_BPartner_Location.C_Location_ID}.<br/> * If you don't want this to happen in general, you can set {@code IsChangeLog='N'} for the entire {@code C_Location} table. * <p/> * Note that {@link RecordChangeLogEntry}s are <b>not</b> derived for these {@code C_Location}-columns:
* <li>{@code Created}, but note that the {@code C_Location} record's {@code Created} value is used in the {@link RecordChangeLogEntry} * <li>{@code CreatedBy} same as {@code Created} * <li>{@code Updated} and {@code UpdatedBy}: since {@code C_Location} is immutable, they don't matter anyways * <li>{@code IsActive}, because it's generally not accessible via UI and we don't want it to be confused with e.g. {@code C_BPartner_Location.IsActive}. * <li>{@code C_Location_ID} * <li>Every {@code C_Location}-column with {@code IsAllowLogging='N'} * <p/> * Also note: if you have e.g. {@code IsAllowLogging='Y'} for {@code C_BPartner_Location.C_Location_ID}, and {@link followLocationIdChanges=false}, * then the change log contains the different location ID, * i.e. {@link KeyNamePair}s with the {@code C_Location_ID} and the locations rendered address string. */ @Default boolean followLocationIdChanges = false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\LogEntriesRepository.java
2
请完成以下Java代码
private final boolean isEmpty() { return facets.isEmpty() && facetCategories.isEmpty(); } public Builder<ModelType> addFacetCategory(final IFacetCategory facetCategory) { Check.assumeNotNull(facetCategory, "facetCategory not null"); facetCategories.add(facetCategory); return this; } public Builder<ModelType> addFacet(final IFacet<ModelType> facet) { Check.assumeNotNull(facet, "facet not null"); facets.add(facet); facetCategories.add(facet.getFacetCategory()); return this; } public Builder<ModelType> addFacets(final Iterable<IFacet<ModelType>> facets) { Check.assumeNotNull(facets, "facet not null"); for (final IFacet<ModelType> facet : facets) { addFacet(facet); } return this; }
/** @return true if there was added at least one facet */ public boolean hasFacets() { return !facets.isEmpty(); } public Builder<ModelType> addFacetCollectorResult(final IFacetCollectorResult<ModelType> facetCollectorResult) { // NOTE: we need to add the categories first, to make sure we preserve the order of categories this.facetCategories.addAll(facetCollectorResult.getFacetCategories()); this.facets.addAll(facetCollectorResult.getFacets()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\FacetCollectorResult.java
1
请完成以下Java代码
public static String printAnIsoscelesTriangleUsingStringUtils(int N) { StringBuilder result = new StringBuilder(); for (int r = 1; r <= N; r++) { result.append(StringUtils.repeat(' ', N - r)); result.append(StringUtils.repeat('*', 2 * r - 1)); result.append(System.lineSeparator()); } return result.toString(); } public static String printAnIsoscelesTriangleUsingSubstring(int N) { StringBuilder result = new StringBuilder(); String helperString = StringUtils.repeat(' ', N - 1) + StringUtils.repeat('*', N * 2 - 1);
for (int r = 0; r < N; r++) { result.append(helperString.substring(r, N + 2 * r)); result.append(System.lineSeparator()); } return result.toString(); } public static void main(String[] args) { System.out.println(printARightTriangle(5)); System.out.println(printAnIsoscelesTriangle(5)); System.out.println(printAnIsoscelesTriangleUsingStringUtils(5)); System.out.println(printAnIsoscelesTriangleUsingSubstring(5)); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-3\src\main\java\com\baeldung\algorithms\printtriangles\PrintTriangleExamples.java
1
请完成以下Spring Boot application配置
spring.jpa.properties.hibernate.globally_quoted_identifiers=true spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.jpa.hibernate.ddl-auto=update # Disable Hibernate validation spring.jpa.pro
perties.jakarta.persistence.validation.mode=none com.baeldung.tenant.channels[0]=retail com.baeldung.tenant.channels[1]=wholesale
repos\tutorials-master\spring-boot-modules\spring-boot-validation\src\main\resources\application.properties
2
请完成以下Java代码
public void setReversal_ID (final int Reversal_ID) { if (Reversal_ID < 1) set_Value (COLUMNNAME_Reversal_ID, null); else set_Value (COLUMNNAME_Reversal_ID, Reversal_ID); } @Override public int getReversal_ID() { return get_ValueAsInt(COLUMNNAME_Reversal_ID); } @Override public void setUpdateQty (final @Nullable java.lang.String UpdateQty) { set_Value (COLUMNNAME_UpdateQty, UpdateQty); } @Override public java.lang.String getUpdateQty() { return get_ValueAsString(COLUMNNAME_UpdateQty); } @Override public org.compiere.model.I_C_ElementValue getUser1() { return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser1(final org.compiere.model.I_C_ElementValue User1) { set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1); } @Override public void setUser1_ID (final int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, User1_ID); } @Override public int getUser1_ID() { return get_ValueAsInt(COLUMNNAME_User1_ID); }
@Override public org.compiere.model.I_C_ElementValue getUser2() { return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser2(final org.compiere.model.I_C_ElementValue User2) { set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2); } @Override public void setUser2_ID (final int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, User2_ID); } @Override public int getUser2_ID() { return get_ValueAsInt(COLUMNNAME_User2_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Inventory.java
1
请完成以下Java代码
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws Exception { Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); if (workbook != null); downLoadExcel(fileName, response, workbook); } public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass) throws Exception { if (StringUtils.isBlank(filePath)){ return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); }catch (NoSuchElementException e){ throw new Exception("template not null"); } catch (Exception e) { e.printStackTrace(); throw new Exception(e.getMessage()); } return list; }
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws Exception { if (file == null){ return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params); }catch (NoSuchElementException e){ throw new Exception("excel file not null"); } catch (Exception e) { throw new Exception(e.getMessage()); } return list; } }
repos\springboot-demo-master\eaypoi\src\main\java\com\et\easypoi\Util\FileUtil.java
1
请完成以下Java代码
private JsonExternalReferenceLookupResponse createResponseFromRepoResult( @NonNull final ImmutableMap<JsonExternalReferenceLookupItem, ExternalReferenceQuery> item2Query, @NonNull final ExternalReferenceQueriesResult externalReferences) { final JsonExternalReferenceLookupResponse.JsonExternalReferenceLookupResponseBuilder result = JsonExternalReferenceLookupResponse.builder(); for (final Map.Entry<JsonExternalReferenceLookupItem, ExternalReferenceQuery> lookupItem2QueryEntry : item2Query.entrySet()) { final JsonExternalReferenceLookupItem lookupItem = lookupItem2QueryEntry.getKey(); final ExternalReference externalReference = externalReferences.get(lookupItem2QueryEntry.getValue()).orElse(null); final JsonExternalReferenceItem responseItem; if (externalReference == null) { responseItem = JsonExternalReferenceItem.of(lookupItem); }
else { responseItem = JsonExternalReferenceItem.builder() .lookupItem(lookupItem) .metasfreshId(JsonMetasfreshId.of(externalReference.getRecordId())) .externalReference(externalReference.getExternalReference()) .version(externalReference.getVersion()) .externalReferenceUrl(externalReference.getExternalReferenceUrl()) .systemName(JsonExternalSystemName.of(externalReference.getExternalSystem().getType().getValue())) .externalReferenceId(JsonMetasfreshId.of(externalReference.getExternalReferenceId().getRepoId())) .build(); } result.item(responseItem); } return result.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\rest\v2\ExternalReferenceRestControllerService.java
1
请完成以下Java代码
private static Method getDumpHeapMethod(Class<?> mxBeanClass) { Method method = ReflectionUtils.findMethod(mxBeanClass, "triggerDumpToFile", String.class, String.class); Assert.state(method != null, "'method' must not be null"); return method; } @Override public File dumpHeap(@Nullable Boolean live) throws IOException, InterruptedException { Assert.state(live == null, "OpenJ9DiagnosticsMXBean does not support live parameter when dumping the heap"); String file = (String) ReflectionUtils.invokeMethod(this.dumpHeapMethod, this.diagnosticMXBean, "heap", null); Assert.state(file != null, "'file' must not be null"); return new File(file); } } /** * Exception to be thrown if the {@link HeapDumper} cannot be created. */ protected static class HeapDumperUnavailableException extends RuntimeException { public HeapDumperUnavailableException(String message, Throwable cause) { super(message, cause); } } private static final class TemporaryFileSystemResource extends FileSystemResource { private final Log logger = LogFactory.getLog(getClass()); private TemporaryFileSystemResource(File file) { super(file); } @Override public ReadableByteChannel readableChannel() throws IOException { ReadableByteChannel readableChannel = super.readableChannel(); return new ReadableByteChannel() { @Override public boolean isOpen() { return readableChannel.isOpen(); } @Override public void close() throws IOException { closeThenDeleteFile(readableChannel); } @Override public int read(ByteBuffer dst) throws IOException { return readableChannel.read(dst); } };
} @Override public InputStream getInputStream() throws IOException { return new FilterInputStream(super.getInputStream()) { @Override public void close() throws IOException { closeThenDeleteFile(this.in); } }; } private void closeThenDeleteFile(Closeable closeable) throws IOException { try { closeable.close(); } finally { deleteFile(); } } private void deleteFile() { try { Files.delete(getFile().toPath()); } catch (IOException ex) { TemporaryFileSystemResource.this.logger .warn("Failed to delete temporary heap dump file '" + getFile() + "'", ex); } } @Override public boolean isFile() { // Prevent zero-copy so we can delete the file on close return false; } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\management\HeapDumpWebEndpoint.java
1
请完成以下Java代码
protected boolean afterSave(boolean newRecord, boolean success) { // Update Fields if (!newRecord) { if (is_ValueChanged(MColumn.COLUMNNAME_Name) || is_ValueChanged(MColumn.COLUMNNAME_Description) || is_ValueChanged(MColumn.COLUMNNAME_Help)) { StringBuilder sql = new StringBuilder("UPDATE AD_Field SET Name=") .append(DB.TO_STRING(getName())) .append(", Description=").append(DB.TO_STRING(getDescription())) .append(", Help=").append(DB.TO_STRING(getHelp())) .append(" WHERE AD_Column_ID=").append(get_ID()); int no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), get_TrxName()); log.debug("afterSave - Fields updated #" + no); } } return success; } // afterSave @Override public String toString() { return MoreObjects.toStringHelper(this) .add("AD_Column_ID", getAD_Column_ID()) .add("ColumnName", getColumnName()) .toString(); } @Deprecated public static int getColumn_ID(String TableName, String columnName) { int m_table_id = MTable.getTable_ID(TableName); if (m_table_id == 0) return 0; int retValue = 0; String SQL = "SELECT AD_Column_ID FROM AD_Column WHERE AD_Table_ID = ? AND columnname = ?"; try { PreparedStatement pstmt = DB.prepareStatement(SQL, null); pstmt.setInt(1, m_table_id); pstmt.setString(2, columnName); ResultSet rs = pstmt.executeQuery(); if (rs.next()) retValue = rs.getInt(1); rs.close(); pstmt.close();
} catch (SQLException e) { s_log.error(SQL, e); retValue = -1; } return retValue; } // end vpj-cd e-evolution /** * Get Table Id for a column * * @param ctx context * @param AD_Column_ID id * @param trxName transaction * @return MColumn */ public static int getTable_ID(Properties ctx, int AD_Column_ID, String trxName) { final String sqlStmt = "SELECT AD_Table_ID FROM AD_Column WHERE AD_Column_ID=?"; return DB.getSQLValue(trxName, sqlStmt, AD_Column_ID); } public static boolean isSuggestSelectionColumn(String columnName, boolean caseSensitive) { if (columnName == null || Check.isBlank(columnName)) return false; // if (columnName.equals("Value") || (!caseSensitive && columnName.equalsIgnoreCase("Value"))) return true; else if (columnName.equals("Name") || (!caseSensitive && columnName.equalsIgnoreCase("Name"))) return true; else if (columnName.equals("DocumentNo") || (!caseSensitive && columnName.equalsIgnoreCase("DocumentNo"))) return true; else if (columnName.equals("Description") || (!caseSensitive && columnName.equalsIgnoreCase("Description"))) return true; else if (columnName.contains("Name") || (!caseSensitive && columnName.toUpperCase().contains("Name".toUpperCase()))) return true; else if(columnName.equals("DocStatus") || (!caseSensitive && columnName.equalsIgnoreCase("DocStatus"))) return true; else return false; } } // MColumn
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MColumn.java
1
请在Spring Boot框架中完成以下Java代码
public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } public static class ResponseParam { private int code; private String msg; private ResponseParam(int code, String msg) { this.code = code; this.msg = msg; } public static ResponseParam buildParam(int code, String msg) { return new ResponseParam(code, msg); }
public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } }
repos\spring-boot-leaning-master\2.x_42_courses\第 2-9 课:Spring Boot 中使用 Swagger2 构建 RESTful APIs\spring-boot-swagger\src\main\java\com\neo\config\BaseResult.java
2
请在Spring Boot框架中完成以下Java代码
public class EjbProcessEngineService implements ProcessEngineService { @EJB protected EjbBpmPlatformBootstrap ejbBpmPlatform; /** the processEngineServiceDelegate */ protected ProcessEngineService processEngineServiceDelegate; @PostConstruct protected void initProcessEngineServiceDelegate() { processEngineServiceDelegate = ejbBpmPlatform.getProcessEngineService(); } public ProcessEngine getDefaultProcessEngine() { return processEngineServiceDelegate.getDefaultProcessEngine();
} public List<ProcessEngine> getProcessEngines() { return processEngineServiceDelegate.getProcessEngines(); } public Set<String> getProcessEngineNames() { return processEngineServiceDelegate.getProcessEngineNames(); } public ProcessEngine getProcessEngine(String name) { return processEngineServiceDelegate.getProcessEngine(name); } }
repos\camunda-bpm-platform-master\javaee\ejb-service\src\main\java\org\camunda\bpm\container\impl\ejb\EjbProcessEngineService.java
2
请完成以下Java代码
public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getSystemHost() { return systemHost; } public void setSystemHost(String systemHost) { this.systemHost = systemHost; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getStartTimestamp() { return startTimestamp; } public void setStartTimestamp(Date startTimestamp) { this.startTimestamp = startTimestamp; } public Date getLastAccessTime() { return lastAccessTime; }
public void setLastAccessTime(Date lastAccessTime) { this.lastAccessTime = lastAccessTime; } public Long getTimeout() { return timeout; } public void setTimeout(Long timeout) { this.timeout = timeout; } }
repos\SpringAll-master\17.Spring-Boot-Shiro-Session\src\main\java\com\springboot\pojo\UserOnline.java
1
请完成以下Java代码
public String getPropagationType() { return X_M_HU_PI_Attribute.PROPAGATIONTYPE_NoPropagation; } /** * @return {@link NullAggregationStrategy#instance}. */ @Override public IAttributeAggregationStrategy retrieveAggregationStrategy() { return NullAggregationStrategy.instance; } /** * @return {@link NullSplitterStrategy#instance}. */ @Override public IAttributeSplitterStrategy retrieveSplitterStrategy() { return NullSplitterStrategy.instance; } /** * @return {@link CopyHUAttributeTransferStrategy#instance}. */ @Override public IHUAttributeTransferStrategy retrieveTransferStrategy() { return CopyHUAttributeTransferStrategy.instance; } /** * @return {@code true}. */ @Override public boolean isReadonlyUI() { return true; } /** * @return {@code true}. */ @Override public boolean isDisplayedUI() { return true; } @Override public boolean isMandatory() { return false; } @Override public boolean isOnlyIfInProductAttributeSet() {
return false; } /** * @return our attribute instance's {@code M_Attribute_ID}. */ @Override public int getDisplaySeqNo() { return attributeInstance.getM_Attribute_ID(); } /** * @return {@code true} */ @Override public boolean isUseInASI() { return true; } /** * @return {@code false}, since no HU-PI attribute is involved. */ @Override public boolean isDefinedByTemplate() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\AIAttributeValue.java
1
请完成以下Java代码
static void validateAndAddDPoPParametersIfAvailable(HttpServletRequest request, Map<String, Object> additionalParameters) { final String dPoPProofHeaderName = OAuth2AccessToken.TokenType.DPOP.getValue(); String dPoPProof = request.getHeader(dPoPProofHeaderName); if (StringUtils.hasText(dPoPProof)) { if (Collections.list(request.getHeaders(dPoPProofHeaderName)).size() != 1) { throwError(OAuth2ErrorCodes.INVALID_REQUEST, dPoPProofHeaderName, ACCESS_TOKEN_REQUEST_ERROR_URI); } else { additionalParameters.put("dpop_proof", dPoPProof); additionalParameters.put("dpop_method", request.getMethod()); additionalParameters.put("dpop_target_uri", request.getRequestURL().toString()); } } } static void throwError(String errorCode, String parameterName, String errorUri) { OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, errorUri);
throw new OAuth2AuthenticationException(error); } static String normalizeUserCode(String userCode) { Assert.hasText(userCode, "userCode cannot be empty"); StringBuilder sb = new StringBuilder(userCode.toUpperCase(Locale.ENGLISH).replaceAll("[^A-Z\\d]+", "")); Assert.isTrue(sb.length() == 8, "userCode must be exactly 8 alpha/numeric characters"); sb.insert(4, '-'); return sb.toString(); } static boolean validateUserCode(String userCode) { return (userCode != null && userCode.toUpperCase(Locale.ENGLISH).replaceAll("[^A-Z\\d]+", "").length() == 8); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\web\authentication\OAuth2EndpointUtils.java
1
请完成以下Java代码
public static OrderLinePriceUpdateRequestBuilder prepare(final org.compiere.model.I_C_OrderLine orderLine) { return builder() .updateLineNetAmt(true) .orderLine(InterfaceWrapperHelper.create(orderLine, I_C_OrderLine.class)) .resultUOM(ResultUOM.PRICE_UOM_IF_ORDERLINE_IS_NEW); } public enum ResultUOM { CONTEXT_UOM, PRICE_UOM, PRICE_UOM_IF_ORDERLINE_IS_NEW } @NonNull I_C_OrderLine orderLine; // // Pricing context overrides PricingSystemId pricingSystemIdOverride; PriceListId priceListIdOverride; Quantity qtyOverride; /** If not {@code null}, then the pricing engine is requested to not revalidate the PricingConditionsBreak, but go with this one*/ PricingConditionsBreak pricingConditionsBreakOverride; // // Result options @NonNull ResultUOM resultUOM;
// // Updating the order line options boolean updatePriceEnteredAndDiscountOnlyIfNotAlreadySet; // task 06727 boolean updateLineNetAmt; @Default boolean applyPriceLimitRestrictions = true; boolean updateProfitPriceActual; // // // public static class OrderLinePriceUpdateRequestBuilder { public OrderLinePriceUpdateRequestBuilder orderLine(final org.compiere.model.I_C_OrderLine orderLine) { this.orderLine = InterfaceWrapperHelper.create(orderLine, I_C_OrderLine.class); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderLinePriceUpdateRequest.java
1
请完成以下Java代码
protected DockerComposeFile getComposeFile() { DockerComposeFile composeFile = (CollectionUtils.isEmpty(this.properties.getFile())) ? DockerComposeFile.find(this.workingDirectory) : DockerComposeFile.of(this.properties.getFile()); Assert.state(composeFile != null, () -> "No Docker Compose file found in directory '%s'".formatted( ((this.workingDirectory != null) ? this.workingDirectory : new File(".")).toPath().toAbsolutePath())); if (composeFile.getFiles().size() == 1) { logger.info(LogMessage.format("Using Docker Compose file %s", composeFile.getFiles().get(0))); } else { logger.info(LogMessage.format("Using Docker Compose files %s", composeFile.toString())); } return composeFile; } protected DockerCompose getDockerCompose(DockerComposeFile composeFile, Set<String> activeProfiles, List<String> arguments) { return DockerCompose.get(composeFile, this.properties.getHost(), activeProfiles, arguments); }
private boolean isIgnored(RunningService service) { return service.labels().containsKey(IGNORE_LABEL); } /** * Publish a {@link DockerComposeServicesReadyEvent} directly to the event listeners * since we cannot call {@link ApplicationContext#publishEvent} this early. * @param event the event to publish */ private void publishEvent(DockerComposeServicesReadyEvent event) { SimpleApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster(); this.eventListeners.forEach(multicaster::addApplicationListener); multicaster.multicastEvent(event); } }
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\lifecycle\DockerComposeLifecycleManager.java
1
请完成以下Java代码
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