instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public String toString() { return "Column [" + "name=" + name + ", dbTableNameOrAlias=" + dbTableNameOrAlias + ", dbColumnName=" + dbColumnName + ", dbColumnSQL=" + dbColumnSQL + ", exported=" + exported + "]"; } public String getName() { return name; } public String getDbTableNameOrAlias() { return dbTableNameOrAlias; } public String getDbColumnName() { return dbColumnName; }
public String getDbColumnSQL() { return dbColumnSQL; } public boolean isExported() { return exported; } public void setExported(boolean exported) { this.exported = exported; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\JdbcExporterBuilder.java
1
请完成以下Java代码
private static boolean is8Bit(String str) { if (str == null || str.length() == 0) { return true; } final char[] cc = str.toCharArray(); for (final char element : cc) { if (element > 255) { // System.out.println("Not 8 Bit - " + str); return false; } } return true; } // is8Bit /** * Add Additional Lines to row/col * * @param row * row * @param col * col * @param data * data */ private void addPrintLines(int row, int col, Object data) { while (m_printRows.size() <= row) { m_printRows.add(null); } ArrayList<ArrayList<Object>> columns = m_printRows.get(row); if (columns == null) { columns = new ArrayList<>(m_columnHeader.length); } while (columns.size() <= col) { columns.add(null); } // ArrayList<Object> coordinate = columns.get(col); if (coordinate == null) { coordinate = new ArrayList<>(); } coordinate.add(data); // columns.set(col, coordinate); m_printRows.set(row, columns);
log.trace("row=" + row + ", col=" + col + " - Rows=" + m_printRows.size() + ", Cols=" + columns.size() + " - " + data); } // addAdditionalLines /** Print Data */ private ArrayList<ArrayList<ArrayList<Object>>> m_printRows = new ArrayList<>(); /** * Insert empty Row after current Row * * @param currentRow */ private void insertRow(int currentRow) { } // inserRow /** * Get Print Data including additional Lines * * @param row * row * @param col * col * @return non null array of print objects (may be empty) */ private Object[] getPrintItems(int row, int col) { ArrayList<ArrayList<Object>> columns = null; if (m_printRows.size() > row) { columns = m_printRows.get(row); } if (columns == null) { return new Object[] {}; } ArrayList<Object> coordinate = null; if (columns.size() > col) { coordinate = columns.get(col); } if (coordinate == null) { return new Object[] {}; } // return coordinate.toArray(); } // getPrintItems }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\TableElement.java
1
请在Spring Boot框架中完成以下Java代码
public class Customer { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CUST_SEQ") private long id; private String firstName; private String lastName; private String socialSecurityCode; public Customer() { } public Customer(String firstName, String lastName, String socialSecurityCode) { this.firstName = firstName; this.lastName = lastName; this.socialSecurityCode = socialSecurityCode; } public long getId() { return id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName;
} public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getSocialSecurityCode() { return socialSecurityCode; } public void setSocialSecurityCode(String socialSecurityCode) { this.socialSecurityCode = socialSecurityCode; } @Override public String toString() { return "Customer{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", socialSecurityCode='" + socialSecurityCode + '\'' + '}'; } }
repos\springboot-demo-master\rmi\rmi-server\src\main\java\com\et\rmi\server\model\Customer.java
2
请完成以下Java代码
public BigDecimal getPriceList () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceList); if (bd == null) return Env.ZERO; return bd; } /** Set Price Precision. @param PricePrecision Precision (number of decimals) for the Price */ public void setPricePrecision (int PricePrecision) { set_Value (COLUMNNAME_PricePrecision, Integer.valueOf(PricePrecision)); } /** Get Price Precision. @return Precision (number of decimals) for the Price */ public int getPricePrecision () { Integer ii = (Integer)get_Value(COLUMNNAME_PricePrecision); if (ii == null) return 0; return ii.intValue(); } /** Set Standard Price. @param PriceStd Standard Price */ public void setPriceStd (BigDecimal PriceStd) { set_Value (COLUMNNAME_PriceStd, PriceStd); } /** Get Standard Price. @return Standard Price */ public BigDecimal getPriceStd () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd); if (bd == null) return Env.ZERO; return bd; } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () {
Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Product Key. @param ProductValue Key of the Product */ public void setProductValue (String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } /** Get Product Key. @return Key of the Product */ public String getProductValue () { return (String)get_Value(COLUMNNAME_ProductValue); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set UOM Code. @param X12DE355 UOM EDI X12 Code */ public void setX12DE355 (String X12DE355) { set_Value (COLUMNNAME_X12DE355, X12DE355); } /** Get UOM Code. @return UOM EDI X12 Code */ public String getX12DE355 () { return (String)get_Value(COLUMNNAME_X12DE355); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_PriceList.java
1
请完成以下Spring Boot application配置
spring: application: name: r2dbc-test r2dbc: username: local password: local url: r2dbc:postgresql://localhost:8082/flyway-test-db flyway: url: jdbc:postgresql://localhost:8082/flyway-test-db locations: classpath:db/postgres/
migration main: allow-bean-definition-overriding: true # R2DBC URL r2dbc: url: r2dbc:h2:mem://./testdb
repos\tutorials-master\persistence-modules\r2dbc\src\main\resources\application.yml
2
请完成以下Java代码
public final class MaterialCockpitUtil { public static final String WINDOWID_MaterialCockpitView_String = "540376"; public static final WindowId WINDOWID_MaterialCockpitView = WindowId.fromJson(WINDOWID_MaterialCockpitView_String); public static final String WINDOWID_MaterialCockpit_Detail_String = "540395"; public static final WindowId WINDOWID_MaterialCockpit_DetailView = WindowId.fromJson(WINDOWID_MaterialCockpitView_String); public static final String WINDOW_MaterialCockpit_StockDetail_String = "540457"; public static final WindowId WINDOW_MaterialCockpit_StockDetailView = WindowId.of(Integer.parseInt(WINDOW_MaterialCockpit_StockDetail_String)); public static final String SYSCONFIG_DIM_SPEC_INTERNAL_NAME = "de.metas.ui.web.material.cockpit.DIM_Dimension_Spec.InternalName"; public static final String DEFAULT_DIM_SPEC_INTERNAL_NAME = "Material_Cockpit_Default_Spec"; public static final String SYSCONFIG_INCLUDE_PER_PLANT_DETAIL_ROWS = "de.metas.ui.web.material.cockpit.DisplayPerPlantDetailRows"; private static final String SYSCFG_I_QtyDemand_QtySupply_V_ACTIVE = "de.metas.ui.web.material.cockpit.I_QtyDemand_QtySupply_V.IsActive"; public static final String DONT_FILTER = "DONT_FILTER"; public static final String NON_EMPTY = "NON_EMPTY"; private MaterialCockpitUtil() { }
public static DimensionSpec retrieveDimensionSpec() { final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); final IDimensionspecDAO dimensionspecDAO = Services.get(IDimensionspecDAO.class); final String dimSpecName = sysConfigBL.getValue( SYSCONFIG_DIM_SPEC_INTERNAL_NAME, DEFAULT_DIM_SPEC_INTERNAL_NAME, Env.getAD_Client_ID(), Env.getAD_Org_ID(Env.getCtx())); final DimensionSpec dimensionSpec = dimensionspecDAO.retrieveForInternalNameOrNull(CoalesceUtil.firstNotEmptyTrimmed( dimSpecName, DEFAULT_DIM_SPEC_INTERNAL_NAME)); return Check.assumeNotNull(dimensionSpec, "Unable to load DIM_Dimension_Spec record with InternalName={}", dimSpecName); } public static boolean isI_QtyDemand_QtySupply_VActive() { return Services.get(ISysConfigBL.class).getBooleanValue(SYSCFG_I_QtyDemand_QtySupply_V_ACTIVE, true); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitUtil.java
1
请在Spring Boot框架中完成以下Java代码
public RpAccountCheckMistakeScratchPool getDataById(String id) { return rpAccountCheckMistakeScratchPoolDao.getById(id); } /** * 获取分页数据 * * @param pageParam * @return */ public PageBean listPage(PageParam pageParam, RpAccountCheckMistakeScratchPool rpAccountCheckMistakeScratchPool) { Map<String, Object> paramMap = new HashMap<String, Object>(); return rpAccountCheckMistakeScratchPoolDao.listPage(pageParam, paramMap); } /** * 从缓冲池中删除数据 * * @param scratchPoolList
*/ public void deleteFromPool(List<RpAccountCheckMistakeScratchPool> scratchPoolList) { for (RpAccountCheckMistakeScratchPool record : scratchPoolList) { rpAccountCheckMistakeScratchPoolDao.delete(record.getId()); } } /** * 查询出缓存池中所有的数据 * * @return */ public List<RpAccountCheckMistakeScratchPool> listScratchPoolRecord(Map<String, Object> paramMap) { if (paramMap == null) { paramMap = new HashMap<String, Object>(); } return rpAccountCheckMistakeScratchPoolDao.listByColumn(paramMap); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\service\impl\RpAccountCheckMistakeScratchPoolServiceImpl.java
2
请完成以下Java代码
public String getSourceRef() { return sourceRef; } public void setSourceRef(String sourceRef) { this.sourceRef = sourceRef; } public String getTargetRef() { return targetRef; } public void setTargetRef(String targetRef) { this.targetRef = targetRef; }
@Override public Association clone() { Association clone = new Association(); clone.setValues(this); return clone; } public void setValues(Association otherElement) { super.setValues(otherElement); setSourceRef(otherElement.getSourceRef()); setTargetRef(otherElement.getTargetRef()); if (otherElement.getAssociationDirection() != null) { setAssociationDirection(otherElement.getAssociationDirection()); } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\Association.java
1
请完成以下Java代码
public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public Date getTime() {
return time; } public void setTime(Date time) { this.time = time; } public String getDetailType() { return detailType; } public void setDetailType(String detailType) { this.detailType = detailType; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricDetailEntityImpl.java
1
请完成以下Java代码
public BigDecimal getRRAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RRAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Revenue Recognition Start. @param RRStartDate Revenue Recognition Start Date */ public void setRRStartDate (Timestamp RRStartDate) { set_Value (COLUMNNAME_RRStartDate, RRStartDate); } /** Get Revenue Recognition Start. @return Revenue Recognition Start Date */ public Timestamp getRRStartDate () { return (Timestamp)get_Value(COLUMNNAME_RRStartDate); } public org.compiere.model.I_C_OrderLine getRef_OrderLine() throws RuntimeException { return (org.compiere.model.I_C_OrderLine)MTable.get(getCtx(), org.compiere.model.I_C_OrderLine.Table_Name) .getPO(getRef_OrderLine_ID(), get_TrxName()); } /** Set Referenced Order Line. @param Ref_OrderLine_ID Reference to corresponding Sales/Purchase Order */ public void setRef_OrderLine_ID (int Ref_OrderLine_ID) { if (Ref_OrderLine_ID < 1) set_Value (COLUMNNAME_Ref_OrderLine_ID, null);
else set_Value (COLUMNNAME_Ref_OrderLine_ID, Integer.valueOf(Ref_OrderLine_ID)); } /** Get Referenced Order Line. @return Reference to corresponding Sales/Purchase Order */ public int getRef_OrderLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Ref_OrderLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Ressourcenzuordnung. @param S_ResourceAssignment_ID Ressourcenzuordnung */ public void setS_ResourceAssignment_ID (int S_ResourceAssignment_ID) { if (S_ResourceAssignment_ID < 1) set_Value (COLUMNNAME_S_ResourceAssignment_ID, null); else set_Value (COLUMNNAME_S_ResourceAssignment_ID, Integer.valueOf(S_ResourceAssignment_ID)); } /** Get Ressourcenzuordnung. @return Ressourcenzuordnung */ public int getS_ResourceAssignment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceAssignment_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_C_OrderLine_Overview.java
1
请完成以下Java代码
public Response getHeadersBack() { return echoHeaders(); } @RolesAllowed("ADMIN") @GET @Path("/digest") public Response getHeadersBackFromDigestAuthentication() { // As the Digest authentication require some complex steps to work we'll simulate the process // https://en.wikipedia.org/wiki/Digest_access_authentication#Example_with_explanation if (headers.getHeaderString("authorization") == null) { String authenticationRequired = "Digest " + REALM_KEY + "=\"" + REALM_VALUE + "\", " + QOP_KEY + "=\"" + QOP_VALUE + "\", " + NONCE_KEY + "=\"" + NONCE_VALUE + "\", " + OPAQUE_KEY + "=\"" + OPAQUE_VALUE + "\""; return Response.status(Response.Status.UNAUTHORIZED) .header("WWW-Authenticate", authenticationRequired) .build(); } else { return echoHeaders(); } } @GET @Path("/events") @Produces(MediaType.SERVER_SENT_EVENTS) public void getServerSentEvents(@Context SseEventSink eventSink, @Context Sse sse) { OutboundSseEvent event = sse.newEventBuilder()
.name("echo-headers") .data(String.class, headers.getHeaderString(AddHeaderOnRequestFilter.FILTER_HEADER_KEY)) .build(); eventSink.send(event); } private Response echoHeaders() { Response.ResponseBuilder responseBuilder = Response.noContent(); headers.getRequestHeaders() .forEach((k, v) -> { v.forEach(value -> responseBuilder.header(k, value)); }); return responseBuilder.build(); } }
repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\server\EchoHeaders.java
1
请完成以下Java代码
public abstract class FlowElement extends BaseElement implements HasExecutionListeners, AcceptUpdates { protected String name; protected String documentation; protected List<ActivitiListener> executionListeners = new ArrayList<ActivitiListener>(); protected FlowElementsContainer parentContainer; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public List<ActivitiListener> getExecutionListeners() { return executionListeners; } public void setExecutionListeners(List<ActivitiListener> executionListeners) { this.executionListeners = executionListeners; } @JsonIgnore public FlowElementsContainer getParentContainer() { return parentContainer; } @JsonIgnore public SubProcess getSubProcess() { SubProcess subProcess = null; if (parentContainer instanceof SubProcess) { subProcess = (SubProcess) parentContainer; } return subProcess; }
public void setParentContainer(FlowElementsContainer parentContainer) { this.parentContainer = parentContainer; } public abstract FlowElement clone(); public void setValues(FlowElement otherElement) { super.setValues(otherElement); setName(otherElement.getName()); setDocumentation(otherElement.getDocumentation()); executionListeners = new ArrayList<ActivitiListener>(); if (otherElement.getExecutionListeners() != null && !otherElement.getExecutionListeners().isEmpty()) { for (ActivitiListener listener : otherElement.getExecutionListeners()) { executionListeners.add(listener.clone()); } } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\FlowElement.java
1
请完成以下Java代码
public String greetSomeone(String name) { HelloSomeone helloSomeOne = new HelloSomeone() { @Override public String greet(String name) { return "Hello " + name; } }; return helloSomeOne.greet(name); } // Nested interface within a class interface HelloOuter { public String hello(String name); } // Enum within a class enum Color { RED, GREEN, BLUE; } } interface HelloWorld { public String greet(String name); // Nested class within an interface class InnerClass implements HelloWorld { @Override public String greet(String name) { return "Inner class within an interface"; } } // Nested interface within an interfaces interface HelloSomeone { public String greet(String name);
} // Enum within an interface enum Directon { NORTH, SOUTH, EAST, WEST; } } enum Level { LOW, MEDIUM, HIGH; } enum Foods { DRINKS, EATS; // Enum within Enum enum DRINKS { APPLE_JUICE, COLA; } enum EATS { POTATO, RICE; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-types-3\src\main\java\com\baeldung\classfile\Outer.java
1
请完成以下Java代码
public class XmlElementsToMapPayloadExtractor implements InboundEventPayloadExtractor<Document> { private static final Logger LOGGER = LoggerFactory.getLogger(XmlElementsToMapPayloadExtractor.class); @Override public Collection<EventPayloadInstance> extractPayload(EventModel eventModel, Document payload) { return eventModel.getPayload().stream() .filter(parameterDefinition -> parameterDefinition.isFullPayload() || getChildNode(payload, parameterDefinition.getName()) != null) .map(payloadDefinition -> new EventPayloadInstanceImpl(payloadDefinition, getPayloadValue(payload, payloadDefinition.getName(), payloadDefinition.getType(), payloadDefinition.isFullPayload()))) .collect(Collectors.toList()); } protected Object getPayloadValue(Document document, String definitionName, String definitionType, boolean isFullPayload) { if (isFullPayload) { return document; } Node childNode = getChildNode(document, definitionName); if (childNode != null) { String textContent = childNode.getTextContent(); if (EventPayloadTypes.STRING.equals(definitionType)) { return textContent; } else if (EventPayloadTypes.BOOLEAN.equals(definitionType)) { return Boolean.valueOf(textContent); } else if (EventPayloadTypes.INTEGER.equals(definitionType)) { return Integer.valueOf(textContent); } else if (EventPayloadTypes.DOUBLE.equals(definitionType)) { return Double.valueOf(textContent); } else if (EventPayloadTypes.LONG.equals(definitionType)) { return Long.valueOf(textContent); } else { LOGGER.warn("Unsupported payload type: {} ", definitionType); return textContent;
} } return null; } protected Node getChildNode(Document document, String elementName) { NodeList childNodes = null; if (document.getChildNodes().getLength() == 1) { childNodes = document.getFirstChild().getChildNodes(); } else { childNodes = document.getChildNodes(); } for (int i = 0; i < childNodes.getLength(); i++) { Node node = childNodes.item(i); if (elementName.equals(node.getNodeName())) { return node; } } return null; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\payload\XmlElementsToMapPayloadExtractor.java
1
请完成以下Java代码
private void addImportClass(Class<?> cl) { if (cl.isArray()) { cl = cl.getComponentType(); } if (cl.isPrimitive()) { return; } addImportClass(cl.getCanonicalName()); } /** * Generate java imports */
private void createImports(final StringBuilder sb) { for (final String name : s_importClasses) { sb.append("import ").append(name).append(";").append(NL); } sb.append(NL); } private static boolean isSkipColumn(@NonNull final ColumnInfo columnInfo) { return columnInfo.isRestAPICustomColumn() || COLUMNNAMES_STANDARD.contains(columnInfo.getColumnName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\ad\persistence\modelgen\ModelClassGenerator.java
1
请完成以下Java代码
public String[] recognize(String[] wordArray, String[] posArray) { LexicalAnalyzer analyzer = getAnalyzer(); if (analyzer == null) throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe"); return analyzer.recognize(wordArray, posArray); } @Override public String[] tag(String... words) { LexicalAnalyzer analyzer = getAnalyzer(); if (analyzer == null) throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe"); return analyzer.tag(words); } @Override public String[] tag(List<String> wordList) { LexicalAnalyzer analyzer = getAnalyzer(); if (analyzer == null) throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe");
return analyzer.tag(wordList); } @Override public NERTagSet getNERTagSet() { LexicalAnalyzer analyzer = getAnalyzer(); if (analyzer == null) throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe"); return analyzer.getNERTagSet(); } @Override public Sentence analyze(String sentence) { return new Sentence(flow(sentence)); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\pipe\LexicalAnalyzerPipeline.java
1
请在Spring Boot框架中完成以下Java代码
public class PayProductController{ @Autowired private RpPayProductService rpPayProductService; /** * 函数功能说明 : 查询分页 * * @参数: @return * @return String * @throws */ @RequestMapping(value = "/list", method ={RequestMethod.POST, RequestMethod.GET}) public String list(RpPayProduct rpPayProduct, PageParam pageParam, Model model) { PageBean pageBean = rpPayProductService.listPage(pageParam, rpPayProduct); model.addAttribute("pageBean", pageBean); model.addAttribute("pageParam", pageParam); model.addAttribute("rpPayProduct", rpPayProduct); return "pay/product/list"; } /** * 函数功能说明 :跳转添加 * * @参数: @return * @return String * @throws */ @RequiresPermissions("pay:product:add") @RequestMapping(value = "/addUI", method = RequestMethod.GET) public String addUI() { return "pay/product/add"; } /** * 函数功能说明 : 保存 * * @参数: @return * @return String * @throws */ @RequiresPermissions("pay:product:add") @RequestMapping(value = "/add", method = RequestMethod.POST) public String add(Model model, RpPayProduct rpPayProduct, DwzAjax dwz) { rpPayProductService.createPayProduct(rpPayProduct.getProductCode(), rpPayProduct.getProductName()); dwz.setStatusCode(DWZ.SUCCESS); dwz.setMessage(DWZ.SUCCESS_MSG); model.addAttribute("dwz", dwz); return DWZ.AJAX_DONE; } /** * 函数功能说明 : 删除 * * @参数: @return * @return String * @throws */ @RequiresPermissions("pay:product:delete") @RequestMapping(value = "/delete", method ={RequestMethod.POST, RequestMethod.GET}) public String delete(Model model, DwzAjax dwz, @RequestParam("productCode") String productCode) { rpPayProductService.deletePayProduct(productCode); dwz.setStatusCode(DWZ.SUCCESS); dwz.setMessage(DWZ.SUCCESS_MSG); model.addAttribute("dwz", dwz); return DWZ.AJAX_DONE; }
/** * 函数功能说明 : 查找带回 * * @参数: @return * @return String * @throws */ @RequestMapping(value = "/lookupList", method ={RequestMethod.POST, RequestMethod.GET}) public String lookupList(RpPayProduct rpPayProduct, PageParam pageParam, Model model) { //查询已生效数据 rpPayProduct.setAuditStatus(PublicEnum.YES.name()); PageBean pageBean = rpPayProductService.listPage(pageParam, rpPayProduct); model.addAttribute("pageBean", pageBean); model.addAttribute("pageParam", pageParam); model.addAttribute("rpPayProduct", rpPayProduct); return "pay/product/lookupList"; } /** * 函数功能说明 : 审核 * * @参数: @return * @return String * @throws */ @RequiresPermissions("pay:product:add") @RequestMapping(value = "/audit", method ={RequestMethod.POST, RequestMethod.GET}) public String audit(Model model, DwzAjax dwz, @RequestParam("productCode") String productCode , @RequestParam("auditStatus") String auditStatus) { rpPayProductService.audit(productCode, auditStatus); dwz.setStatusCode(DWZ.SUCCESS); dwz.setMessage(DWZ.SUCCESS_MSG); model.addAttribute("dwz", dwz); return DWZ.AJAX_DONE; } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\pay\PayProductController.java
2
请在Spring Boot框架中完成以下Java代码
public Object getVariableValue(EngineRestVariable restVariable) { Object value; if (restVariable.getType() != null) { // Try locating a converter if the type has been specified RestVariableConverter converter = null; for (RestVariableConverter conv : variableConverters) { if (conv.getRestTypeName().equals(restVariable.getType())) { converter = conv; break; } } if (converter == null) { throw new FlowableIllegalArgumentException("Variable '" + restVariable.getName() + "' has unsupported type: '" + restVariable.getType() + "'."); } value = converter.getVariableValue(restVariable); } else { // Revert to type determined by REST-to-Java mapping when no // explicit type has been provided value = restVariable.getValue(); } return value; }
protected RestUrlBuilder createUrlBuilder() { return RestUrlBuilder.fromCurrentRequest(); } protected void initializeVariableConverters() { variableConverters.add(new StringRestVariableConverter()); variableConverters.add(new IntegerRestVariableConverter()); variableConverters.add(new LongRestVariableConverter()); variableConverters.add(new ShortRestVariableConverter()); variableConverters.add(new DoubleRestVariableConverter()); variableConverters.add(new BigDecimalRestVariableConverter()); variableConverters.add(new BigIntegerRestVariableConverter()); variableConverters.add(new BooleanRestVariableConverter()); variableConverters.add(new DateRestVariableConverter()); variableConverters.add(new InstantRestVariableConverter()); variableConverters.add(new LocalDateRestVariableConverter()); variableConverters.add(new LocalDateTimeRestVariableConverter()); variableConverters.add(new JsonObjectRestVariableConverter(objectMapper)); } }
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\ExternalJobRestResponseFactory.java
2
请完成以下Spring Boot application配置
#Logging logging.level.org.springframework.web=ERROR logging.level.com.mkyong=DEBUG # Test @Value email=test@mkyong.com thread-pool=5 #Below properties mapped to AppProperties.java app.menus[0].title=Home app.menus[0].name=Home app.menus[0].path=/ app.menus[1].title=Login app
.menus[1].name=Login app.menus[1].path=/login app.compiler.timeout=5 app.compiler.output-folder=/temp/ app.error=/error/
repos\spring-boot-master\spring-boot-externalize-config\src\main\resources\application.properties
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; }
public Branch getMainBranch() { return mainBranch; } public void setMainBranch(Branch mainBranch) { this.mainBranch = mainBranch; } public Branch getSubBranch() { return subBranch; } public void setSubBranch(Branch subBranch) { this.subBranch = subBranch; } public Branch getAdditionalBranch() { return additionalBranch; } public void setAdditionalBranch(Branch additionalBranch) { this.additionalBranch = additionalBranch; } }
repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\lazycollection\model\Employee.java
1
请在Spring Boot框架中完成以下Java代码
public void release( @NonNull final PickingSlotId pickingSlotId, @NonNull final PickingJobId pickingJobId) { if (!pickingJobRepository.hasDraftJobsUsingPickingSlot(pickingSlotId, pickingJobId)) { pickingSlotService.releasePickingSlotIfPossible(pickingSlotId); } } @Override public boolean hasAllocationsForSlot(@NonNull final PickingSlotId slotId) { return pickingJobRepository.hasDraftJobsUsingPickingSlot(slotId, null); } public void addToPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId, @NonNull final Set<HuId> huIds) { pickingSlotService.addToPickingSlotQueue(pickingSlotId, huIds); } public PickingSlotSuggestions getPickingSlotsSuggestions(@NonNull final Set<DocumentLocation> deliveryLocations) { if (deliveryLocations.isEmpty()) { return PickingSlotSuggestions.EMPTY; } final ImmutableMap<BPartnerLocationId, DocumentLocation> deliveryLocationsById = Maps.uniqueIndex(deliveryLocations, DocumentLocation::getBpartnerLocationId); final List<I_M_PickingSlot> pickingSlots = pickingSlotService.list(PickingSlotQuery.builder().assignedToBPartnerLocationIds(deliveryLocationsById.keySet()).build()); if (pickingSlots.isEmpty()) { return PickingSlotSuggestions.EMPTY; } final PickingSlotQueuesSummary queues = pickingSlotService.getNotEmptyQueuesSummary(PickingSlotQueueQuery.onlyPickingSlotIds(extractPickingSlotIds(pickingSlots)));
return pickingSlots.stream() .map(pickingSlotIdAndCaption -> toPickingSlotSuggestion(pickingSlotIdAndCaption, deliveryLocationsById, queues)) .collect(PickingSlotSuggestions.collect()); } private static PickingSlotSuggestion toPickingSlotSuggestion( @NonNull final I_M_PickingSlot pickingSlot, @NonNull final ImmutableMap<BPartnerLocationId, DocumentLocation> deliveryLocationsById, @NonNull final PickingSlotQueuesSummary queues) { final PickingSlotIdAndCaption pickingSlotIdAndCaption = toPickingSlotIdAndCaption(pickingSlot); final BPartnerLocationId deliveryLocationId = BPartnerLocationId.ofRepoIdOrNull(pickingSlot.getC_BPartner_ID(), pickingSlot.getC_BPartner_Location_ID()); final DocumentLocation deliveryLocation = deliveryLocationsById.get(deliveryLocationId); return PickingSlotSuggestion.builder() .pickingSlotIdAndCaption(pickingSlotIdAndCaption) .deliveryLocation(deliveryLocation) .countHUs(queues.getCountHUs(pickingSlotIdAndCaption.getPickingSlotId()).orElse(0)) .build(); } private static ImmutableSet<PickingSlotId> extractPickingSlotIds(final List<I_M_PickingSlot> pickingSlots) { return pickingSlots.stream() .map(pickingSlot -> PickingSlotId.ofRepoId(pickingSlot.getM_PickingSlot_ID())) .collect(ImmutableSet.toImmutableSet()); } private static PickingSlotIdAndCaption toPickingSlotIdAndCaption(@NonNull final I_M_PickingSlot record) { return PickingSlotIdAndCaption.of(PickingSlotId.ofRepoId(record.getM_PickingSlot_ID()), record.getPickingSlot()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\PickingJobSlotService.java
2
请在Spring Boot框架中完成以下Java代码
public class MainController { // ------------------------ // PRIVATE FIELDS // ------------------------ // Inject the UserSearch object @Autowired private UserSearch userSearch; // ------------------------ // PUBLIC METHODS // ------------------------ /** * Index main page. */ @RequestMapping("/") @ResponseBody public String index() { return "Try to go here: " + "<a href='/search?q=hola'>/search?q=hola</a>"; } /** * Show search results for the given query. * * @param q The search query. */
@RequestMapping("/search") public String search(String q, Model model) { List<User> searchResults = null; try { searchResults = userSearch.search(q); } catch (Exception ex) { // here you should handle unexpected errors // ... // throw ex; } model.addAttribute("searchResults", searchResults); return "search"; } } // class MainController
repos\spring-boot-samples-master\spring-boot-hibernate-search\src\main\java\netgloo\controllers\MainController.java
2
请完成以下Java代码
public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public Priority getPriority() {
return priority; } public void setPriority(Priority priority) { this.priority = priority; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } }
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\enums\Article.java
1
请完成以下Java代码
public class ErrorEventDefinitionImpl extends EventDefinitionImpl implements ErrorEventDefinition { protected static AttributeReference<Error> errorRefAttribute; protected static Attribute<String> camundaErrorCodeVariableAttribute; protected static Attribute<String> camundaErrorMessageVariableAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ErrorEventDefinition.class, BPMN_ELEMENT_ERROR_EVENT_DEFINITION) .namespaceUri(BPMN20_NS) .extendsType(EventDefinition.class) .instanceProvider(new ModelTypeInstanceProvider<ErrorEventDefinition>() { public ErrorEventDefinition newInstance(ModelTypeInstanceContext instanceContext) { return new ErrorEventDefinitionImpl(instanceContext); } }); errorRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ERROR_REF) .qNameAttributeReference(Error.class) .build(); camundaErrorCodeVariableAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_ERROR_CODE_VARIABLE) .namespace(CAMUNDA_NS) .build(); camundaErrorMessageVariableAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_ERROR_MESSAGE_VARIABLE) .namespace(CAMUNDA_NS) .build(); typeBuilder.build(); } public ErrorEventDefinitionImpl(ModelTypeInstanceContext context) { super(context); } public Error getError() { return errorRefAttribute.getReferenceTargetElement(this); }
public void setError(Error error) { errorRefAttribute.setReferenceTargetElement(this, error); } @Override public void setCamundaErrorCodeVariable(String camundaErrorCodeVariable) { camundaErrorCodeVariableAttribute.setValue(this, camundaErrorCodeVariable); } @Override public String getCamundaErrorCodeVariable() { return camundaErrorCodeVariableAttribute.getValue(this); } @Override public void setCamundaErrorMessageVariable(String camundaErrorMessageVariable) { camundaErrorMessageVariableAttribute.setValue(this, camundaErrorMessageVariable); } @Override public String getCamundaErrorMessageVariable() { return camundaErrorMessageVariableAttribute.getValue(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ErrorEventDefinitionImpl.java
1
请完成以下Java代码
public class C_Order extends MaterialTrackableDocumentByASIInterceptor<I_C_Order, I_C_OrderLine> { private static final String MSG_M_Material_Tracking_Set_In_Orderline = "M_Material_Tracking_Set_In_Orderline"; @Override protected final boolean isEligibleForMaterialTracking(final I_C_Order order) { // Sales orders are not eligible if (order.isSOTrx()) { return false; } return true; } @Override protected List<I_C_OrderLine> retrieveDocumentLines(final I_C_Order document) { // note: we don't have C_Order reversals to check for final IOrderDAO orderDAO = Services.get(IOrderDAO.class); final List<I_C_OrderLine> documentLines = orderDAO.retrieveOrderLines(document, I_C_OrderLine.class); return documentLines; } @Override protected AttributeSetInstanceId getM_AttributeSetInstance(final I_C_OrderLine documentLine) { return AttributeSetInstanceId.ofRepoIdOrNone(documentLine.getM_AttributeSetInstance_ID()); } /** * @param document * In case the purchase order has a partner and product of one line belonging to a complete material tracking and that material tracking is not set into ASI, show an error message. */ @DocValidate(timings = { ModelValidator.TIMING_BEFORE_COMPLETE }) public void verifyMaterialTracking(final I_C_Order document) { final IMaterialTrackingDAO materialTrackingDao = Services.get(IMaterialTrackingDAO.class); final Properties ctx = InterfaceWrapperHelper.getCtx(document); if (document.isSOTrx()) { // nothing to do return; } final List<I_C_OrderLine> documentLines = retrieveDocumentLines(document); for (final I_C_OrderLine line : documentLines)
{ String msg; if (getMaterialTrackingFromDocumentLineASI(line) != null) { continue; // a tracking is set, nothing to do } final IMaterialTrackingQuery queryVO = materialTrackingDao.createMaterialTrackingQuery(); queryVO.setCompleteFlatrateTerm(true); queryVO.setProcessed(false); queryVO.setC_BPartner_ID(document.getC_BPartner_ID()); queryVO.setM_Product_ID(line.getM_Product_ID()); // there can be many trackings for the given product and partner (different parcels), which is not a problem for this verification queryVO.setOnMoreThanOneFound(OnMoreThanOneFound.ReturnFirst); final I_M_Material_Tracking materialTracking = materialTrackingDao.retrieveMaterialTracking(ctx, queryVO); if (materialTracking == null) { continue; // there is no tracking that could be selected, nothing to do } msg = Services.get(IMsgBL.class).getMsg(ctx, MSG_M_Material_Tracking_Set_In_Orderline, new Object[] { document.getDocumentNo(), line.getLine() }); throw new AdempiereException(msg); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\validator\C_Order.java
1
请完成以下Java代码
public static Dependency withId(String id, String groupId, String artifactId) { return withId(id, groupId, artifactId, null); } public static Dependency withId(String id, String scope) { Dependency dependency = withId(id, null, null); dependency.setScope(scope); return dependency; } public static Dependency withId(String id) { return withId(id, SCOPE_COMPILE); } /** * Map several attribute of the dependency for a given compatibility range. */ public static class Mapping { /** * The compatibility range of this mapping. */ private String compatibilityRange; /** * The version to use for this mapping or {@code null} to use the default. */ private String groupId; /** * The groupId to use for this mapping or {@code null} to use the default. */ private String artifactId; /** * The artifactId to use for this mapping or {@code null} to use the default. */ private String version; /** * The starter setting to use for the mapping or {@code null} to use the default. */ private Boolean starter; /** * The extra Bill of Materials to use for this mapping or {@code null} to use the * default. */ private String bom; /** * The extra repository to use for this mapping or {@code null} to use the * default. */ private String repository; @JsonIgnore private VersionRange range; public String getGroupId() { return this.groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getArtifactId() { return this.artifactId; } public void setArtifactId(String artifactId) { this.artifactId = artifactId; } public String getVersion() { return this.version; } public void setVersion(String version) { this.version = version; } public Boolean getStarter() { return this.starter; } public void setStarter(Boolean starter) { this.starter = starter; }
public String getBom() { return this.bom; } public void setBom(String bom) { this.bom = bom; } public String getRepository() { return this.repository; } public void setRepository(String repository) { this.repository = repository; } public VersionRange getRange() { return this.range; } public String getCompatibilityRange() { return this.compatibilityRange; } public void setCompatibilityRange(String compatibilityRange) { this.compatibilityRange = compatibilityRange; } public static Mapping create(String range, String groupId, String artifactId, String version, Boolean starter, String bom, String repository) { Mapping mapping = new Mapping(); mapping.compatibilityRange = range; mapping.groupId = groupId; mapping.artifactId = artifactId; mapping.version = version; mapping.starter = starter; mapping.bom = bom; mapping.repository = repository; return mapping; } } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\Dependency.java
1
请完成以下Java代码
public class C_Invoice_Candidate_GenerateInvoice extends JavaProcess { private boolean p_Selection = true; private boolean p_IgnoreInvoiceSchedule = false; public static final String CHECKBOX_IGNORE_INVOICE_SCHEDULE = "IgnoreInvoiceSchedule"; @Override protected void prepare() { for (final ProcessInfoParameter para : getParametersAsArray()) { final String name = para.getParameterName(); if (para.getParameter() == null) { ; } else if (name.equals("Selection")) { p_Selection = "Y".equals(para.getParameter()); } else if (name.equals(CHECKBOX_IGNORE_INVOICE_SCHEDULE)) { p_IgnoreInvoiceSchedule = "Y".equals(para.getParameter()); } } } @Override protected String doIt() throws Exception { if (!p_Selection) { throw new IllegalStateException("Invoices can only be generated from selection"); } final IInvoiceCandBL service = Services.get(IInvoiceCandBL.class); final IInvoiceGenerateResult result = service.generateInvoicesFromSelection(getCtx(), getPinstanceId(), p_IgnoreInvoiceSchedule, get_TrxName()); final ADHyperlinkBuilder linkHelper = new ADHyperlinkBuilder(); final StringBuffer summary = new StringBuffer("@Generated@"); summary.append(" @C_Invoice_ID@ #").append(result.getInvoiceCount()); if (result.getNotificationCount() > 0)
{ final String notificationsLink = linkHelper.createShowWindowHTML( "@AD_Note_ID@ #" + result.getNotificationCount(), I_AD_Note.Table_Name, -1, // suggested windowID -> use the default one result.getNotificationsWhereClause() ); summary.append(", ").append(notificationsLink); } // Output the actual invoices that were created. // Note that the list will be empty if storing the actual invoices has been switched off to avoid mass-data-memory problems. final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class); for (final I_C_Invoice invoice : result.getC_Invoices()) { addLog(invoice.getC_Invoice_ID(), null, null, invoiceBL.getSummary(invoice)); } return summary.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\process\C_Invoice_Candidate_GenerateInvoice.java
1
请在Spring Boot框架中完成以下Java代码
private List<Object> constructCacheKey(DeviceId deviceId) { return List.of(deviceId); } private void persistInCache(String secretKey, long durationMs, Cache cache, List<Object> key) { ClaimData claimData = new ClaimData(secretKey, System.currentTimeMillis() + validateDurationMs(durationMs)); cache.putIfAbsent(key, claimData); } private long validateDurationMs(long durationMs) { if (durationMs > 0L) { return durationMs; } return systemDurationMs; } private ListenableFuture<Void> removeClaimingSavedData(Cache cache, ClaimDataInfo data, Device device) { if (data.isFromCache()) { cache.evict(data.getKey()); } SettableFuture<Void> result = SettableFuture.create(); telemetryService.deleteAttributes(AttributesDeleteRequest.builder()
.tenantId(device.getTenantId()) .entityId(device.getId()) .scope(AttributeScope.SERVER_SCOPE) .keys(Arrays.asList(CLAIM_ATTRIBUTE_NAME, CLAIM_DATA_ATTRIBUTE_NAME)) .future(result) .build()); return result; } private void cacheEviction(DeviceId deviceId) { Cache cache = cacheManager.getCache(CLAIM_DEVICES_CACHE); cache.evict(constructCacheKey(deviceId)); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\device\ClaimDevicesServiceImpl.java
2
请完成以下Java代码
public ExecutionResult apply(final String trxName) { final boolean rollback = false; return execute(trxName, rollback); } public ExecutionResult rollback(final String trxName) { final boolean rollback = false; return execute(trxName, rollback); } private ExecutionResult execute(final String trxName, final boolean rollback) { final I_AD_MigrationStep step = getAD_MigrationStep(); // // Check if script is suitable for our database final String stepDBType = step.getDBType(); if (!stepDBType.equals(X_AD_MigrationStep.DBTYPE_AllDatabaseTypes) && !(DB.isPostgreSQL() && X_AD_MigrationStep.DBTYPE_Postgres.equals(stepDBType))) { final String dbType = CConnection.get().getType(); step.setStatusCode(null); log("Not suitable for current database type (Step:" + stepDBType + ", Database:" + dbType + ")", "SKIP", false); return ExecutionResult.Skipped; } // // Fetch SQL Statement String sql = rollback ? step.getRollbackStatement() : step.getSQLStatement(); if (Check.isEmpty(sql, true) || sql.trim().equals(";")) { log("No " + (rollback ? "Rollback" : "SQL") + " found", "SKIP", true); if (rollback) { return ExecutionResult.Executed; } else { return ExecutionResult.Skipped;
} } // // Fix/Prepare SQL sql = sql.trim(); if (sql.endsWith(";")) { sql = sql.substring(0, sql.length() - 1); } // // Execute SQL Statement Statement stmt = null; try { if (X_AD_MigrationStep.DBTYPE_AllDatabaseTypes.equals(step.getDBType())) { // Execute script using our conversion layer DB.executeUpdateAndThrowExceptionOnFail(sql, trxName); } else { // Execute script without using the conversion layer because we expect to have it in native SQL stmt = Trx.get(trxName, false).getConnection().createStatement(); stmt.execute(sql); } } catch (SQLException e) { throw new AdempiereException(e); } finally { DB.close(stmt); stmt = null; } log(null, rollback ? "Rollback" : "Applied", false); return ExecutionResult.Executed; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\SQLStatementMigrationStepExecutor.java
1
请完成以下Java代码
protected void doWork() { // InterfaceWrapperHelper.refresh(mImportProcessor); // daysToKeepLog might have changed final int no = Services.get(IIMPProcessorDAO.class).deleteLogs(mImportProcessor); if (no > 0) { m_summary.append("Logs Records deleted=").append(no).append("; "); } if (isProcessRunning()) { // process is already started successfully! return; } // process is not started! m_summary = new StringBuffer(); final Properties ctx = InterfaceWrapperHelper.getCtx(mImportProcessor); final String trxName = InterfaceWrapperHelper.getTrxName(mImportProcessor); log.debug("trxName = " + trxName); log.debug("ImportProcessor = " + mImportProcessor); final String reference = "#" + getRunCount() + " - " + TimeUtil.formatElapsed(getStartWork()); final IIMPProcessorBL impProcessorBL = Services.get(IIMPProcessorBL.class); try (final IAutoCloseable closable = impProcessorBL.setupTemporaryLoggable(mImportProcessor, reference)) { importProcessor = impProcessorBL.getIImportProcessor(mImportProcessor); importProcessor.start(ctx, this, trxName); Check.assume(isProcessRunning(), importProcessor + " has called setProcessRunning(true)"); Loggables.withLogger(log, Level.INFO).addLog(m_summary.toString()); } catch (Exception e) { setProcessRunning(false); log(null, e); try { importProcessor.stop(); } catch (Exception e1) { log(null, e1); } } } private void log(String summary, Throwable t) {
if (summary == null && t != null) { summary = t.getMessage(); } if (t != null) { log.error(summary, t); } final String reference = "#" + getRunCount() + " - " + TimeUtil.formatElapsed(getStartWork()); String text = null; Services.get(IIMPProcessorBL.class).createLog(mImportProcessor, summary, text, reference, t); } @Override public String getServerInfo() { return "#" + getRunCount() + " - Last=" + m_summary.toString(); } /** * @return the isProcessRunning */ @Override public boolean isProcessRunning() { return importProcessorRunning; } /** * @param isProcessRunning the isProcessRunning to set */ @Override public void setProcessRunning(boolean isProcessRunning) { this.importProcessorRunning = isProcessRunning; } /** * @return the mImportProcessor */ @Override public I_IMP_Processor getMImportProcessor() { return mImportProcessor; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\compiere\server\ReplicationProcessor.java
1
请完成以下Java代码
public static String toUnderline(String str, boolean upperCase) { if (str == null || str.trim().isEmpty()) { return str; } StringBuilder result = new StringBuilder(); boolean preIsUnderscore = false; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch == '_') { preIsUnderscore = true; } else if (ch == '-') { ch = '_'; preIsUnderscore = true; // -A -> _a } else if (ch >= 'A' && ch <= 'Z') { // A -> _a if (!preIsUnderscore && i > 0) { // _A -> _a result.append("_"); } preIsUnderscore = false; } else { preIsUnderscore = false; } result.append(upperCase ? Character.toUpperCase(ch) : Character.toLowerCase(ch)); } return result.toString(); } /** * any str ==> lowerCamel */ public static String toLowerCamel(String str) { if (str == null || str.trim().isEmpty()) { return str; }
StringBuilder result = new StringBuilder(); char pre = '\0'; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch == '-' || ch == '—' || ch == '_') { ch = '_'; pre = ch; continue; } char ch2 = ch; if (pre == '_') { ch2 = Character.toUpperCase(ch); pre = ch2; } else if (pre >= 'A' && pre <= 'Z') { pre = ch; ch2 = Character.toLowerCase(ch); } else { pre = ch; } result.append(ch2); } return lowerCaseFirst(result.toString()); } public static boolean isNotNull(String str) { return org.apache.commons.lang3.StringUtils.isNotEmpty(str); } }
repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\util\StringUtilsPlus.java
1
请在Spring Boot框架中完成以下Java代码
public class CityHandler { private static final Logger LOGGER = LoggerFactory.getLogger(CityHandler.class); @Autowired private RedisTemplate redisTemplate; private final CityRepository cityRepository; @Autowired public CityHandler(CityRepository cityRepository) { this.cityRepository = cityRepository; } public Mono<City> save(City city) { return cityRepository.save(city); } public Mono<City> findCityById(Long id) { // 从缓存中获取城市信息 String key = "city_" + id; ValueOperations<String, City> operations = redisTemplate.opsForValue(); // 缓存存在 boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { City city = operations.get(key); LOGGER.info("CityHandler.findCityById() : 从缓存中获取了城市 >> " + city.toString()); return Mono.create(cityMonoSink -> cityMonoSink.success(city)); } // 从 MongoDB 中获取城市信息 Mono<City> cityMono = cityRepository.findById(id); if (cityMono == null) return cityMono; // 插入缓存 cityMono.subscribe(cityObj -> { operations.set(key, cityObj); LOGGER.info("CityHandler.findCityById() : 城市插入缓存 >> " + cityObj.toString()); }); return cityMono;
} public Flux<City> findAllCity() { return cityRepository.findAll().cache(); } public Mono<City> modifyCity(City city) { // 缓存存在,删除缓存 String key = "city_" + city.getId(); boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { redisTemplate.delete(key); LOGGER.info("CityHandler.modifyCity() : 从缓存中删除城市 ID >> " + city.getId()); } return cityRepository.save(city).cache(); } public Mono<Long> deleteCity(Long id) { // 缓存存在,删除缓存 String key = "city_" + id; boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { redisTemplate.delete(key); LOGGER.info("CityHandler.deleteCity() : 从缓存中删除城市 ID >> " + id); } cityRepository.deleteById(id); return Mono.create(cityMonoSink -> cityMonoSink.success(id)); } }
repos\springboot-learning-example-master\springboot-webflux-7-redis-cache\src\main\java\org\spring\springboot\handler\CityHandler.java
2
请完成以下Java代码
public class UpdateDecisionDefinitionHistoryTimeToLiveCmd implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; protected String decisionDefinitionId; protected Integer historyTimeToLive; public UpdateDecisionDefinitionHistoryTimeToLiveCmd(String decisionDefinitionId, Integer historyTimeToLive) { this.decisionDefinitionId = decisionDefinitionId; this.historyTimeToLive = historyTimeToLive; } public Void execute(CommandContext context) { checkAuthorization(context); ensureNotNull(BadUserRequestException.class, "decisionDefinitionId", decisionDefinitionId); if (historyTimeToLive != null) { ensureGreaterThanOrEqual(BadUserRequestException.class, "", "historyTimeToLive", historyTimeToLive, 0); } validate(historyTimeToLive, context); DecisionDefinitionEntity decisionDefinitionEntity = context.getDecisionDefinitionManager().findDecisionDefinitionById(decisionDefinitionId); logUserOperation(context, decisionDefinitionEntity); decisionDefinitionEntity.setHistoryTimeToLive(historyTimeToLive); return null; } protected void checkAuthorization(CommandContext commandContext) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkUpdateDecisionDefinitionById(decisionDefinitionId); } } protected void logUserOperation(CommandContext commandContext, DecisionDefinitionEntity decisionDefinitionEntity) { List<PropertyChange> propertyChanges = new ArrayList<>(); propertyChanges.add(new PropertyChange("historyTimeToLive", decisionDefinitionEntity.getHistoryTimeToLive(), historyTimeToLive)); propertyChanges.add(new PropertyChange("decisionDefinitionId", null, decisionDefinitionId)); propertyChanges.add(new PropertyChange("decisionDefinitionKey", null, decisionDefinitionEntity.getKey())); commandContext.getOperationLogManager() .logDecisionDefinitionOperation(UserOperationLogEntry.OPERATION_TYPE_UPDATE_HISTORY_TIME_TO_LIVE, decisionDefinitionEntity.getTenantId(), propertyChanges); } protected void validate(Integer historyTimeToLive, CommandContext context) { HistoryTimeToLiveParser parser = HistoryTimeToLiveParser.create(context); parser.validate(historyTimeToLive); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\UpdateDecisionDefinitionHistoryTimeToLiveCmd.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_C_Charge_Acct[") .append(get_ID()).append("]"); return sb.toString(); } public I_C_AcctSchema getC_AcctSchema() throws RuntimeException { return (I_C_AcctSchema)MTable.get(getCtx(), I_C_AcctSchema.Table_Name) .getPO(getC_AcctSchema_ID(), get_TrxName()); } /** Set Accounting Schema. @param C_AcctSchema_ID Rules for accounting */ public void setC_AcctSchema_ID (int C_AcctSchema_ID) { if (C_AcctSchema_ID < 1) set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null); else set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID)); } /** Get Accounting Schema. @return Rules for accounting */ public int getC_AcctSchema_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_Charge getC_Charge() throws RuntimeException { return (I_C_Charge)MTable.get(getCtx(), I_C_Charge.Table_Name) .getPO(getC_Charge_ID(), get_TrxName()); } /** Set Charge. @param C_Charge_ID Additional document charges */ public void setC_Charge_ID (int C_Charge_ID) { if (C_Charge_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Charge_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Charge_ID, Integer.valueOf(C_Charge_ID)); } /** Get Charge. @return Additional document charges */ public int getC_Charge_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Charge_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getCh_Expense_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getCh_Expense_Acct(), get_TrxName()); } /** Set Charge Expense. @param Ch_Expense_Acct Charge Expense Account */ public void setCh_Expense_Acct (int Ch_Expense_Acct) { set_Value (COLUMNNAME_Ch_Expense_Acct, Integer.valueOf(Ch_Expense_Acct)); } /** Get Charge Expense. @return Charge Expense Account */ public int getCh_Expense_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_Ch_Expense_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getCh_Revenue_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getCh_Revenue_Acct(), get_TrxName()); } /** Set Charge Revenue. @param Ch_Revenue_Acct Charge Revenue Account */ public void setCh_Revenue_Acct (int Ch_Revenue_Acct) { set_Value (COLUMNNAME_Ch_Revenue_Acct, Integer.valueOf(Ch_Revenue_Acct)); } /** Get Charge Revenue. @return Charge Revenue Account */ public int getCh_Revenue_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_Ch_Revenue_Acct); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Charge_Acct.java
1
请在Spring Boot框架中完成以下Java代码
public ManufacturingJob recomputeQtyToIssueForSteps(@NonNull final PPOrderId ppOrderId) { final ManufacturingJob job = getJobById(ppOrderId); final ManufacturingJob changedJob = job.withChangedRawMaterialIssue( rawMaterialsIssue -> rawMaterialsIssue.withChangedLines(this::recomputeQtyToIssueForSteps)); if (!changedJob.equals(job)) { saveActivityStatuses(changedJob); } return changedJob; } @NonNull private RawMaterialsIssueLine recomputeQtyToIssueForSteps(@NonNull final RawMaterialsIssueLine line) { Quantity qtyLeftToBeIssued = line.getQtyLeftToIssue().toZeroIfNegative(); final ImmutableList.Builder<RawMaterialsIssueStep> updatedStepsListBuilder = ImmutableList.builder(); for (final RawMaterialsIssueStep step : line.getSteps()) { if (step.isIssued()) { updatedStepsListBuilder.add(step); } else if (qtyLeftToBeIssued.isGreaterThan(step.getQtyToIssue())) { updatedStepsListBuilder.add(step); qtyLeftToBeIssued = qtyLeftToBeIssued.subtract(step.getQtyToIssue()); } else { ppOrderIssueScheduleService.updateQtyToIssue(step.getId(), qtyLeftToBeIssued); updatedStepsListBuilder.add(step.withQtyToIssue(qtyLeftToBeIssued)); qtyLeftToBeIssued = qtyLeftToBeIssued.toZero(); } } return line.withSteps(updatedStepsListBuilder.build()); } @NonNull private Optional<Quantity> extractTargetCatchWeight(@NonNull final JsonManufacturingOrderEvent.ReceiveFrom receiveFrom)
{ if (receiveFrom.getCatchWeight() == null || Check.isBlank(receiveFrom.getCatchWeightUomSymbol())) { return Optional.empty(); } return uomDAO.getBySymbol(receiveFrom.getCatchWeightUomSymbol()) .map(uom -> Quantity.of(receiveFrom.getCatchWeight(), uom)); } public QueryLimit getLaunchersLimit() { final int limitInt = sysConfigBL.getIntValue(Constants.SYSCONFIG_LaunchersLimit, -100); return limitInt == -100 ? Constants.DEFAULT_LaunchersLimit : QueryLimit.ofInt(limitInt); } public ManufacturingJob autoIssueWhatWasReceived( @NonNull final ManufacturingJob job, @NonNull final RawMaterialsIssueStrategy issueStrategy) { return newIssueWhatWasReceivedCommand() .job(job) .issueStrategy(issueStrategy) .build().execute(); } public IssueWhatWasReceivedCommandBuilder newIssueWhatWasReceivedCommand() { return IssueWhatWasReceivedCommand.builder() .issueScheduleService(ppOrderIssueScheduleService) .jobService(this) .ppOrderSourceHUService(ppOrderSourceHUService) .sourceHUsService(sourceHUsService); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\ManufacturingJobService.java
2
请完成以下Java代码
public boolean isTakeDocTypeFromPool() { return isTakeDocTypeFromPool; } public void setIsTakeDocTypeFromPool(final boolean isTakeDocTypeFromPool) { this.isTakeDocTypeFromPool = isTakeDocTypeFromPool; } @Override public void setDocTypeInvoicingPoolId(@Nullable final DocTypeInvoicingPoolId docTypeInvoicingPoolId) { this.docTypeInvoicingPoolId = docTypeInvoicingPoolId; } @Override public void setDocTypeInvoiceId(@Nullable final DocTypeId docTypeId) { this.docTypeInvoiceId = docTypeId; } @Override public boolean isTaxIncluded() { return taxIncluded; } public void setTaxIncluded(boolean taxIncluded) { this.taxIncluded = taxIncluded; } /** * Negate all line amounts */ public void negateAllLineAmounts() { for (final IInvoiceCandAggregate lineAgg : getLines()) { lineAgg.negateLineAmounts(); } } /** * Calculates total net amount by summing up all {@link IInvoiceLineRW#getNetLineAmt()}s. * * @return total net amount */ public Money calculateTotalNetAmtFromLines() { final List<IInvoiceCandAggregate> lines = getLines(); Check.assume(lines != null && !lines.isEmpty(), "Invoice {} was not aggregated yet", this); Money totalNetAmt = Money.zero(currencyId); for (final IInvoiceCandAggregate lineAgg : lines) { for (final IInvoiceLineRW line : lineAgg.getAllLines()) { final Money lineNetAmt = line.getNetLineAmt(); totalNetAmt = totalNetAmt.add(lineNetAmt); } } return totalNetAmt; } public void setPaymentTermId(@Nullable final PaymentTermId paymentTermId) { this.paymentTermId = paymentTermId; } @Override public PaymentTermId getPaymentTermId() { return paymentTermId; } public void setPaymentRule(@Nullable final String paymentRule) { this.paymentRule = paymentRule; }
@Override public String getPaymentRule() { return paymentRule; } @Override public String getExternalId() { return externalId; } @Override public int getC_Async_Batch_ID() { return C_Async_Batch_ID; } public void setC_Async_Batch_ID(final int C_Async_Batch_ID) { this.C_Async_Batch_ID = C_Async_Batch_ID; } public String setExternalId(String externalId) { return this.externalId = externalId; } @Override public int getC_Incoterms_ID() { return C_Incoterms_ID; } public void setC_Incoterms_ID(final int C_Incoterms_ID) { this.C_Incoterms_ID = C_Incoterms_ID; } @Override public String getIncotermLocation() { return incotermLocation; } public void setIncotermLocation(final String incotermLocation) { this.incotermLocation = incotermLocation; } @Override public InputDataSourceId getAD_InputDataSource_ID() { return inputDataSourceId;} public void setAD_InputDataSource_ID(final InputDataSourceId inputDataSourceId){this.inputDataSourceId = inputDataSourceId;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceHeaderImpl.java
1
请完成以下Java代码
public void setRMA(final MRMA rma) { final MInvoice originalInvoice = rma.getOriginalInvoice(); if (originalInvoice == null) { throw new AdempiereException("Not invoiced - RMA: " + rma.getDocumentNo()); } setM_RMA_ID(rma.getM_RMA_ID()); setAD_Org_ID(rma.getAD_Org_ID()); setDescription(rma.getDescription()); InvoiceDocumentLocationAdapterFactory .locationAdapter(this) .setFrom(originalInvoice); setSalesRep_ID(rma.getSalesRep_ID()); setGrandTotal(rma.getAmt()); setOpenAmt(rma.getAmt()); setIsSOTrx(rma.isSOTrx()); setTotalLines(rma.getAmt()); setC_Currency_ID(originalInvoice.getC_Currency_ID()); setIsTaxIncluded(originalInvoice.isTaxIncluded()); setM_PriceList_ID(originalInvoice.getM_PriceList_ID()); setC_Project_ID(originalInvoice.getC_Project_ID()); setC_Activity_ID(originalInvoice.getC_Activity_ID()); setC_Campaign_ID(originalInvoice.getC_Campaign_ID()); setUser1_ID(originalInvoice.getUser1_ID());
setUser2_ID(originalInvoice.getUser2_ID()); } /** * Document Status is Complete or Closed * * @return true if CO, CL or RE * @deprecated Please use {@link IInvoiceBL#isComplete(I_C_Invoice)} */ @Deprecated public boolean isComplete() { return Services.get(IInvoiceBL.class).isComplete(this); } // isComplete } // MInvoice
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MInvoice.java
1
请完成以下Java代码
private void createUpdateASIAndLink(final Object documentLine, final I_M_Material_Tracking materialTracking) { materialTrackingAttributeBL.createOrUpdateMaterialTrackingASI(documentLine, materialTracking); InterfaceWrapperHelper.save(documentLine); materialTrackingBL.linkModelToMaterialTracking( MTLinkRequest.builder() .model(documentLine) .materialTrackingRecord(materialTracking) // pass the process parameters on. They contain HU specific infos which this class and module doesn't know or care about, but which are required to // happen when this process runs. Search for references to this process class name in the HU module to find out specifics. .params(getParameterAsIParams()) // unlink from another material tracking if necessary .ifModelAlreadyLinked(IfModelAlreadyLinked.UNLINK_FROM_PREVIOUS) .build()); } /** * @return <code>true</code> for orders and order lines with <code>SOTrx=N</code> (i.e. purchase order lines), <code>false</code> otherwise. */ @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (I_C_Order.Table_Name.equals(context.getTableName())) { final I_C_Order order = context.getSelectedModel(I_C_Order.class); if (order == null)
{ return ProcessPreconditionsResolution.rejectWithInternalReason("context contains no order"); } if (Services.get(IOrderBL.class).isRequisition(order)) { return ProcessPreconditionsResolution.rejectWithInternalReason("Is purchase requisition"); } return ProcessPreconditionsResolution.acceptIf(!order.isSOTrx()); } else if (I_C_OrderLine.Table_Name.equals(context.getTableName())) { final I_C_OrderLine orderLine = context.getSelectedModel(I_C_OrderLine.class); if (orderLine == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("context contains no orderLine"); } return ProcessPreconditionsResolution.acceptIf(!orderLine.getC_Order().isSOTrx()); } return ProcessPreconditionsResolution.reject(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\process\M_Material_Tracking_CreateOrUpdate_ID.java
1
请完成以下Java代码
public class M_HU_Attribute_SnapshotHandler extends AbstractSnapshotHandler<I_M_HU_Attribute, I_M_HU_Attribute_Snapshot, I_M_HU> { M_HU_Attribute_SnapshotHandler(final AbstractSnapshotHandler<I_M_HU, ?, ?> parentHandler) { super(parentHandler); } @Override protected void createSnapshotsByParentIds(final Set<Integer> huIds) { Check.assumeNotEmpty(huIds, "huIds not empty"); query(I_M_HU_Attribute.class) .addInArrayOrAllFilter(I_M_HU_Attribute.COLUMN_M_HU_ID, huIds) .create() .insertDirectlyInto(I_M_HU_Attribute_Snapshot.class) .mapCommonColumns() .mapColumnToConstant(I_M_HU_Attribute_Snapshot.COLUMNNAME_Snapshot_UUID, getSnapshotId()) .execute(); } @Override protected int getModelId(final I_M_HU_Attribute_Snapshot modelSnapshot) { return modelSnapshot.getM_HU_Attribute_ID(); } @Override protected I_M_HU_Attribute getModel(I_M_HU_Attribute_Snapshot modelSnapshot) { return modelSnapshot.getM_HU_Attribute(); } @Override protected Map<Integer, I_M_HU_Attribute_Snapshot> retrieveModelSnapshotsByParent(final I_M_HU hu) { return query(I_M_HU_Attribute_Snapshot.class) .addEqualsFilter(I_M_HU_Attribute_Snapshot.COLUMN_M_HU_ID, hu.getM_HU_ID())
.addEqualsFilter(I_M_HU_Attribute_Snapshot.COLUMN_Snapshot_UUID, getSnapshotId()) .create() .map(I_M_HU_Attribute_Snapshot.class, snapshot2ModelIdFunction); } @Override protected Map<Integer, I_M_HU_Attribute> retrieveModelsByParent(final I_M_HU hu) { return query(I_M_HU_Attribute.class) .addEqualsFilter(I_M_HU_Attribute.COLUMN_M_HU_ID, hu.getM_HU_ID()) .create() .mapById(I_M_HU_Attribute.class); } @Override protected I_M_HU_Attribute_Snapshot retrieveModelSnapshot(final I_M_HU_Attribute model) { throw new UnsupportedOperationException(); } @Override protected void restoreModelWhenSnapshotIsMissing(final I_M_HU_Attribute model) { // shall not happen because we never delete an attribute throw new HUException("Cannot restore " + model + " because snapshot is missing"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\snapshot\impl\M_HU_Attribute_SnapshotHandler.java
1
请完成以下Java代码
public <ModelType> IAggregationKeyBuilder<ModelType> getDefaultAggregationKeyBuilder(final Properties ctx, final Class<ModelType> modelClass, final Boolean isSOTrx, final String aggregationUsageLevel) { final IAggregationKeyBuilder<ModelType> defaultAggregationKeyBuilder = getDefaultAggregationKeyBuilderOrNull(ctx, modelClass, isSOTrx, aggregationUsageLevel); if (defaultAggregationKeyBuilder == null) { throw new AdempiereException("@NotFound@ @C_Aggregation_ID@ (@IsDefault@, " + modelClass + ")"); } return defaultAggregationKeyBuilder; } @Nullable public <ModelType> IAggregationKeyBuilder<ModelType> getDefaultAggregationKeyBuilderOrNull(final Properties ctx, final Class<ModelType> modelClass, final Boolean isSOTrx, final String aggregationUsageLevel) { final IAggregationDAO aggregationDAO = Services.get(IAggregationDAO.class); // // Load it from database { final Aggregation aggregation = aggregationDAO.retrieveDefaultAggregationOrNull(ctx, modelClass, isSOTrx, aggregationUsageLevel); if (aggregation != null) { return createAggregationKeyBuilder(modelClass, aggregation); } } // // Check programmatically registered default { final ArrayKey key = mkDefaultAggregationKey(modelClass, aggregationUsageLevel); @SuppressWarnings("unchecked") final IAggregationKeyBuilder<ModelType> aggregationKeyBuilder = (IAggregationKeyBuilder<ModelType>)defaultAggregationKeyBuilders.get(key); return aggregationKeyBuilder; } } @Override public <ModelType> void setDefaultAggregationKeyBuilder( final Class<? extends ModelType> modelClass, final String aggregationUsageLevel, final IAggregationKeyBuilder<ModelType> aggregationKeyBuilder) { Check.assumeNotNull(modelClass, "modelClass not null"); Check.assumeNotEmpty(aggregationUsageLevel, "aggregationUsageLevel not empty");
Check.assumeNotNull(aggregationKeyBuilder, "aggregationKeyBuilder not null"); final ArrayKey key = mkDefaultAggregationKey(modelClass, aggregationUsageLevel); defaultAggregationKeyBuilders.put(key, aggregationKeyBuilder); } private final ArrayKey mkDefaultAggregationKey(final Class<?> modelClass, final String aggregationUsageLevel) { final String tableName = InterfaceWrapperHelper.getTableName(modelClass); return Util.mkKey(tableName, aggregationUsageLevel); } private final <ModelType> IAggregationKeyBuilder<ModelType> createAggregationKeyBuilder( final Class<ModelType> modelClass, final Aggregation aggregation) { final GenericAggregationKeyBuilder<ModelType> aggregationKeyBuilder = new GenericAggregationKeyBuilder<>(modelClass, aggregation); return aggregationKeyBuilder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\api\impl\AggregationFactory.java
1
请完成以下Java代码
public <K, ET extends T> ListMultimap<K, ET> listMultimap(final Class<ET> modelClass, final Function<ET, K> keyFunction) { final ListMultimap<K, ET> map = LinkedListMultimap.create(); final List<ET> list = list(modelClass); for (final ET item : list) { final K key = keyFunction.apply(item); map.put(key, item); } return map; } @Override public <K, ET extends T> Collection<List<ET>> listAndSplit(final Class<ET> modelClass, final Function<ET, K> keyFunction) { final ListMultimap<K, ET> map = listMultimap(modelClass, keyFunction); return Multimaps.asMap(map).values(); } @Override public ICompositeQueryUpdaterExecutor<T> updateDirectly() { return new CompositeQueryUpdaterExecutor<>(this); } @Override
public <ToModelType> IQueryInsertExecutor<ToModelType, T> insertDirectlyInto(final Class<ToModelType> toModelClass) { return new QueryInsertExecutor<>(toModelClass, this); } /** * Convenience method that evaluates {@link IQuery#OPTION_ReturnReadOnlyRecords}. */ protected boolean isReadOnlyRecords() { return Boolean.TRUE.equals(getOption(OPTION_ReturnReadOnlyRecords)); } abstract <ToModelType> QueryInsertExecutorResult executeInsert(final QueryInsertExecutor<ToModelType, T> queryInserter); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\AbstractTypedQuery.java
1
请在Spring Boot框架中完成以下Java代码
public class WFActivityHandlersRegistry { private static final Logger logger = LogManager.getLogger(WFActivityHandlersRegistry.class); private final ImmutableMap<WFActivityType, WFActivityHandler> handlers; public WFActivityHandlersRegistry(@NonNull final Optional<List<WFActivityHandler>> optionalHandlers) { this.handlers = optionalHandlers .map(handlers -> Maps.uniqueIndex(handlers, WFActivityHandler::getHandledActivityType)) .orElse(ImmutableMap.of()); logger.info("Handlers: {}", handlers); } public WFActivityHandler getHandler(final WFActivityType wfActivityType) { final WFActivityHandler handler = handlers.get(wfActivityType); if (handler == null) { throw new AdempiereException("No handler registered for activity type: " + wfActivityType);
} return handler; } public <T> T getFeature( @NonNull final WFActivityType wfActivityType, @NonNull final Class<T> featureType) { final WFActivityHandler handler = getHandler(wfActivityType); if (featureType.isInstance(handler)) { return featureType.cast(handler); } else { throw new AdempiereException("" + wfActivityType + " does not support " + featureType.getSimpleName()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\service\WFActivityHandlersRegistry.java
2
请在Spring Boot框架中完成以下Java代码
public String getSalesId() { return salesId; } public void setSalesId(String salesId) { this.salesId = salesId; } public OrderMapping updated(OffsetDateTime updated) { this.updated = updated; return this; } /** * Der Zeitstempel der letzten Änderung * @return updated **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getUpdated() { return updated; } public void setUpdated(OffsetDateTime updated) { this.updated = updated; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderMapping orderMapping = (OrderMapping) o; return Objects.equals(this.orderId, orderMapping.orderId) && Objects.equals(this.salesId, orderMapping.salesId) &&
Objects.equals(this.updated, orderMapping.updated); } @Override public int hashCode() { return Objects.hash(orderId, salesId, updated); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OrderMapping {\n"); sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n"); sb.append(" salesId: ").append(toIndentedString(salesId)).append("\n"); sb.append(" updated: ").append(toIndentedString(updated)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderMapping.java
2
请在Spring Boot框架中完成以下Java代码
static class UsingApacheGeodeSecurityContextCondition { } } // This custom PropertySource is required to prevent Pivotal Spring Cloud Services // (spring-cloud-services-starter-service-registry) from losing the Apache Geode or Cloud Cache Security Context // credentials stored in the Environment. static class SpringDataGemFirePropertiesPropertySource extends PropertySource<Properties> { private static final String SPRING_DATA_GEMFIRE_PROPERTIES_PROPERTY_SOURCE_NAME = "spring.data.gemfire.properties"; SpringDataGemFirePropertiesPropertySource(Properties springDataGemFireProperties) { this(SPRING_DATA_GEMFIRE_PROPERTIES_PROPERTY_SOURCE_NAME, springDataGemFireProperties); }
SpringDataGemFirePropertiesPropertySource(String name, Properties springDataGemFireProperties) { super(name, springDataGemFireProperties); } @Nullable @Override public Object getProperty(String name) { return getSource().getProperty(name); } @Override public boolean containsProperty(String name) { return getSource().containsKey(name); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\ClientSecurityAutoConfiguration.java
2
请完成以下Java代码
public BPartnerId getVendorId() { return getPurchaseCandidate().getVendorId(); } public ZonedDateTime getPurchaseDatePromised() { return getPurchaseCandidate().getPurchaseDatePromised(); } public OrderId getSalesOrderId() { final OrderAndLineId salesOrderAndLineId = getPurchaseCandidate().getSalesOrderAndLineIdOrNull(); return salesOrderAndLineId != null ? salesOrderAndLineId.getOrderId() : null; } @Nullable public ForecastLineId getForecastLineId() { return getPurchaseCandidate().getForecastLineId(); } private Quantity getQtyToPurchase() { return getPurchaseCandidate().getQtyToPurchase(); } public boolean purchaseMatchesRequiredQty() { return getPurchasedQty().compareTo(getQtyToPurchase()) == 0; } private boolean purchaseMatchesOrExceedsRequiredQty() { return getPurchasedQty().compareTo(getQtyToPurchase()) >= 0; } public void setPurchaseOrderLineId(@NonNull final OrderAndLineId purchaseOrderAndLineId) { this.purchaseOrderAndLineId = purchaseOrderAndLineId; } public void markPurchasedIfNeeded() { if (purchaseMatchesOrExceedsRequiredQty()) { purchaseCandidate.markProcessed(); } } public void markReqCreatedIfNeeded() { if (purchaseMatchesOrExceedsRequiredQty()) { purchaseCandidate.setReqCreated(true); } } @Nullable public BigDecimal getPrice() { return purchaseCandidate.getPriceEnteredEff(); }
@Nullable public UomId getPriceUomId() { return purchaseCandidate.getPriceUomId(); } @Nullable public Percent getDiscount() { return purchaseCandidate.getDiscountEff(); } @Nullable public String getExternalPurchaseOrderUrl() { return purchaseCandidate.getExternalPurchaseOrderUrl(); } @Nullable public ExternalId getExternalHeaderId() { return purchaseCandidate.getExternalHeaderId(); } @Nullable public ExternalSystemId getExternalSystemId() { return purchaseCandidate.getExternalSystemId(); } @Nullable public ExternalId getExternalLineId() { return purchaseCandidate.getExternalLineId(); } @Nullable public String getPOReference() { return purchaseCandidate.getPOReference(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\remotepurchaseitem\PurchaseOrderItem.java
1
请完成以下Java代码
public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; }
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\DepartIdModel.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<User> findById(long id) { return repository.findById(id) .map(e -> conversionService.convert(e, User.class)); } @Override public Optional<User> findByEmail(String email) { return repository.findByEmail(email) .map(e -> conversionService.convert(e, User.class)); } @Override public Optional<User> findByUsername(String username) { return repository.findByUsername(username) .map(e -> conversionService.convert(e, User.class)); } @Override public User save(User user) { var entity = conversionService.convert(user, UserJdbcEntity.class); var saved = repository.save(entity); return conversionService.convert(saved, User.class); } @Mapper(config = MappingConfig.class) interface ToDomainUserMapper extends Converter<UserJdbcEntity, User> {
@Override User convert(UserJdbcEntity source); } @Mapper(config = MappingConfig.class) interface FromDomainUserMapper extends Converter<User, UserJdbcEntity> { @Override UserJdbcEntity convert(User source); } }
repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\infrastructure\db\jdbc\UserJdbcRepositoryAdapter.java
2
请完成以下Java代码
default List<Listener<K, V>> getListeners() { return Collections.emptyList(); } /** * Listener for share consumer lifecycle events. * * @param <K> the key type. * @param <V> the value type. */ interface Listener<K, V> { /** * A new consumer was created. * @param id the consumer id (factory bean name and client.id separated by a period).
* @param consumer the consumer. */ default void consumerAdded(String id, ShareConsumer<K, V> consumer) { } /** * An existing consumer was removed. * @param id the consumer id (factory bean name and client.id separated by a period). * @param consumer the consumer. */ default void consumerRemoved(@Nullable String id, ShareConsumer<K, V> consumer) { } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\ShareConsumerFactory.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** EntityType AD_Reference_ID=389 */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entity Type. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** 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 Sql ORDER BY.
@param OrderByClause Fully qualified ORDER BY clause */ public void setOrderByClause (String OrderByClause) { set_Value (COLUMNNAME_OrderByClause, OrderByClause); } /** Get Sql ORDER BY. @return Fully qualified ORDER BY clause */ public String getOrderByClause () { return (String)get_Value(COLUMNNAME_OrderByClause); } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReportView.java
1
请完成以下Java代码
public void setTable(final JTable table) { _table = table; } public final JTable getTable() { Check.assumeNotNull(_table, "table configured for action {}", this); return _table; } /** * Method called by API right before the popup is about to be displayed. * * Feel free to extend and implement your custom business logic here. */ public void updateBeforeDisplaying() { // nothing } protected final AnnotatedTableModel<?> getTableModelOrNull() { final JTable table = getTable(); if (table == null)
{ return null; } final TableModel tableModel = table.getModel(); if (tableModel instanceof AnnotatedTableModel<?>) { return (AnnotatedTableModel<?>)tableModel; } return null; } protected final ListSelectionModel getSelectionModelOrNull() { final JTable table = getTable(); if (table == null) { return null; } final ListSelectionModel selectionModel = table.getSelectionModel(); return selectionModel; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTableAction.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; }
public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } @Override public String toString() { return "Attribute{" + "name='" + name + '\'' + ", description='" + description + '\'' + ", unit='" + unit + '\'' + '}'; } }
repos\tutorials-master\graphql-modules\graphql-java\src\main\java\com\baeldung\graphqlreturnmap\entity\Attribute.java
1
请完成以下Java代码
public TenantDto getTenant(UriInfo context) { Tenant tenant = findTenantObject(); if(tenant == null) { throw new InvalidRequestException(Status.NOT_FOUND, "Tenant with id " + resourceId + " does not exist"); } TenantDto dto = TenantDto.fromTenant(tenant); return dto; } public void updateTenant(TenantDto tenantDto) { ensureNotReadOnly(); Tenant tenant = findTenantObject(); if(tenant == null) { throw new InvalidRequestException(Status.NOT_FOUND, "Tenant with id " + resourceId + " does not exist"); } tenantDto.update(tenant); identityService.saveTenant(tenant); } public void deleteTenant() { ensureNotReadOnly(); identityService.deleteTenant(resourceId); } public ResourceOptionsDto availableOperations(UriInfo context) { ResourceOptionsDto dto = new ResourceOptionsDto(); // add links if operations are authorized URI uri = context.getBaseUriBuilder() .path(rootResourcePath) .path(TenantRestService.PATH) .path(resourceId)
.build(); dto.addReflexiveLink(uri, HttpMethod.GET, "self"); if(!identityService.isReadOnly() && isAuthorized(DELETE)) { dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete"); } if(!identityService.isReadOnly() && isAuthorized(UPDATE)) { dto.addReflexiveLink(uri, HttpMethod.PUT, "update"); } return dto; } public TenantUserMembersResource getTenantUserMembersResource() { return new TenantUserMembersResourceImpl(getProcessEngine().getName(), resourceId, rootResourcePath, getObjectMapper()); } public TenantGroupMembersResource getTenantGroupMembersResource() { return new TenantGroupMembersResourceImpl(getProcessEngine().getName(), resourceId, rootResourcePath, getObjectMapper()); } protected Tenant findTenantObject() { try { return identityService.createTenantQuery() .tenantId(resourceId) .singleResult(); } catch(ProcessEngineException e) { throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, "Exception while performing tenant query: " + e.getMessage()); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\identity\impl\TenantResourceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class BatchBankToCustomerStatementV04Wrapper { @NonNull BankToCustomerStatementV04 bankToCustomerStatementV04; private BatchBankToCustomerStatementV04Wrapper(@NonNull final BankToCustomerStatementV04 bankToCustomerStatementV04) { bankToCustomerStatementV04 .getStmt(); this.bankToCustomerStatementV04 = bankToCustomerStatementV04; } @NonNull public ImmutableList<IAccountStatementWrapper> getAccountStatementWrappers( @NonNull final BankAccountService bankAccountService, @NonNull final CurrencyRepository currencyRepository, @NonNull final IMsgBL msgBL) { return bankToCustomerStatementV04.getStmt() .stream()
.map(stmt -> buildAccountStatementWrapper(stmt, bankAccountService, currencyRepository, msgBL)) .collect(ImmutableList.toImmutableList()); } @NonNull private static IAccountStatementWrapper buildAccountStatementWrapper( @NonNull final AccountStatement4 accountStatement4, @NonNull final BankAccountService bankAccountService, @NonNull final CurrencyRepository currencyRepository, @NonNull final IMsgBL msgBL) { return AccountStatement4Wrapper.builder() .accountStatement4(accountStatement4) .bankAccountService(bankAccountService) .currencyRepository(currencyRepository) .msgBL(msgBL) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\wrapper\v04\BatchBankToCustomerStatementV04Wrapper.java
2
请完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo);
} @Override public void setStandardQty (final BigDecimal StandardQty) { set_Value (COLUMNNAME_StandardQty, StandardQty); } @Override public BigDecimal getStandardQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StandardQty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Phase.java
1
请完成以下Java代码
public abstract class BaseModel { @Id protected long id; @Version protected long version; @WhenCreated protected Instant createdOn; @WhenModified protected Instant modifiedOn; public long getId() { return id; } public void setId(long id) { this.id = id; } public Instant getCreatedOn() { return createdOn; } public void setCreatedOn(Instant createdOn) { this.createdOn = createdOn; }
public Instant getModifiedOn() { return modifiedOn; } public void setModifiedOn(Instant modifiedOn) { this.modifiedOn = modifiedOn; } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } }
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\ebean\model\BaseModel.java
1
请在Spring Boot框架中完成以下Java代码
public final class WebServiceTemplateAutoConfiguration { @Bean @ConditionalOnMissingBean WebServiceMessageSenderFactory webServiceHttpMessageSenderFactory( ObjectProvider<ClientHttpRequestFactoryBuilder<?>> clientHttpRequestFactoryBuilder, ObjectProvider<HttpClientSettings> httpClientSettings) { return WebServiceMessageSenderFactory.http( clientHttpRequestFactoryBuilder.getIfAvailable(ClientHttpRequestFactoryBuilder::detect), httpClientSettings.getIfAvailable()); } @Bean @ConditionalOnMissingBean WebServiceTemplateBuilder webServiceTemplateBuilder(
ObjectProvider<WebServiceMessageSenderFactory> httpWebServiceMessageSenderBuilder, ObjectProvider<WebServiceTemplateCustomizer> webServiceTemplateCustomizers) { WebServiceTemplateBuilder templateBuilder = new WebServiceTemplateBuilder(); WebServiceMessageSenderFactory httpMessageSenderFactory = httpWebServiceMessageSenderBuilder.getIfAvailable(); if (httpMessageSenderFactory != null) { templateBuilder = templateBuilder.httpMessageSenderFactory(httpMessageSenderFactory); } List<WebServiceTemplateCustomizer> customizers = webServiceTemplateCustomizers.orderedStream().toList(); if (!customizers.isEmpty()) { templateBuilder = templateBuilder.customizers(customizers); } return templateBuilder; } }
repos\spring-boot-4.0.1\module\spring-boot-webservices\src\main\java\org\springframework\boot\webservices\autoconfigure\client\WebServiceTemplateAutoConfiguration.java
2
请完成以下Java代码
public void run() { final GridTab gridTab = getGridTab(); if (gridTab == null) { return; } final GridController gc = getGridController(); if (gc == null) { return; } final GridField gridField = getGridField(); if (gridField == null) { return; } final String m_columnName = getColumnName(); final Object m_value = getFieldValue(); final VEditor editor = getEditor(); final String columnDisplayName = gridField.getHeader(); final Object valueDisplay = editor == null ? m_value : editor.getDisplay();
final MQuery queryInitial = new MQuery(gridTab.getTableName()); queryInitial.addRestriction(m_columnName, Operator.EQUAL, m_value); Find find = Find.builder() .setParentFrame(null) .setGridTab(gridTab) .setTitle("" + columnDisplayName + "=" + valueDisplay) .setWhereExtended("") .setQuery(queryInitial) .setMinRecords(1) .buildFindDialog(); // final MQuery query = find.getQuery(); find.dispose(); find = null; // Confirmed query if (query != null) { // m_onlyCurrentRows = false; // search history too gridTab.setQuery(query); gc.query(false, 0, GridTabMaxRows.NO_RESTRICTION); // autoSize } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\grid\ed\FilterContextEditorAction.java
1
请完成以下Java代码
private String getOutboundProcessResponse( @NonNull final ExternalSystemScriptedExportConversionConfig config, @NonNull final Properties context, @NonNull final String outboundDataProcessRecordId) { final String rootTableName = tableDAO.retrieveTableName(config.getAdTableId()); final String rootKeyColumnName = columnBL.getSingleKeyColumn(rootTableName); final ProcessExecutor processExecutor = ProcessInfo.builder() .setCtx(context) .setRecord(TableRecordReference.of(config.getAdTableId(), StringUtils.toIntegerOrZero(outboundDataProcessRecordId))) .setAD_Process_ID(config.getOutboundDataProcessId()) .addParameter(rootKeyColumnName, outboundDataProcessRecordId) .buildAndPrepareExecution() .executeSync(); final Resource resource = Optional.ofNullable(processExecutor.getResult()) .map(ProcessExecutionResult::getReportDataResource) .orElse(null);
if (resource == null || !resource.exists()) { throw new AdempiereException("Process did not return a valid Resource") .appendParametersToMessage() .setParameter("OutboundDataProcessId", config.getOutboundDataProcessId()); } try (final InputStream in = resource.getInputStream()) { return StreamUtils.copyToString(in, StandardCharsets.UTF_8); } catch (final IOException ex) { throw new AdempiereException("Failed to read process output Resource", ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\scriptedexportconversion\ExternalSystemScriptedExportConversionService.java
1
请完成以下Java代码
public class C_DunningDoc_CreateExportData implements IWorkpackageProcessor { private static final Logger logger = LogManager.getLogger(C_DunningDoc_CreateExportData.class); private static final WorkpackagesOnCommitSchedulerTemplate<I_C_DunningDoc> // SCHEDULER = WorkpackagesOnCommitSchedulerTemplate .newModelScheduler(C_DunningDoc_CreateExportData.class, I_C_DunningDoc.class) .setCreateOneWorkpackagePerModel(true); public static void scheduleOnTrxCommit(final I_C_DunningDoc dunningDocRecord) { SCHEDULER.schedule(dunningDocRecord); } private final transient IQueueDAO queueDAO = Services.get(IQueueDAO.class); private final transient DunningExportService dunningExportService = SpringContextHolder.instance.getBean(DunningExportService.class);
@Override public Result processWorkPackage( @NonNull final I_C_Queue_WorkPackage workpackage, @Nullable final String localTrxName) { final List<I_C_DunningDoc> dunningDocRecords = queueDAO.retrieveAllItemsSkipMissing(workpackage, I_C_DunningDoc.class); for (final I_C_DunningDoc dunningDocRecord : dunningDocRecords) { Loggables.withLogger(logger, Level.DEBUG).addLog("Going to export data for dunningDocRecord={}", dunningDocRecord); final DunningDocId dunningDocId = DunningDocId.ofRepoId(dunningDocRecord.getC_DunningDoc_ID()); dunningExportService.exportDunnings(ImmutableList.of(dunningDocId)); } return Result.SUCCESS; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\export\async\C_DunningDoc_CreateExportData.java
1
请在Spring Boot框架中完成以下Java代码
public class AlbertaUserRepository { final IQueryBL queryBL = Services.get(IQueryBL.class); @NonNull public AlbertaUser save(final @NonNull AlbertaUser user) { final I_AD_User_Alberta record = InterfaceWrapperHelper.loadOrNew(user.getUserAlbertaId(), I_AD_User_Alberta.class); record.setAD_User_ID(user.getUserId().getRepoId()); record.setTimestamp(TimeUtil.asTimestamp(user.getTimestamp())); record.setTitle(user.getTitle() != null ? user.getTitle().getCode() : null); record.setGender(user.getGender() != null ? user.getGender().getCode() : null); InterfaceWrapperHelper.save(record); return toAlbertaUser(record); } @NonNull public Optional<AlbertaUser> getByUserId(final @NonNull UserId userId) { return queryBL.createQueryBuilder(I_AD_User_Alberta.class) .addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_User_Alberta.COLUMNNAME_AD_User_ID, userId) .create() .firstOnlyOptional(I_AD_User_Alberta.class) .map(this::toAlbertaUser); } @NonNull public AlbertaUser toAlbertaUser(final @NonNull I_AD_User_Alberta record) { final UserAlbertaId userAlbertaId = UserAlbertaId.ofRepoId(record.getAD_User_Alberta_ID()); final UserId userId = UserId.ofRepoId(record.getAD_User_ID()); return AlbertaUser.builder() .userAlbertaId(userAlbertaId) .userId(userId) .title(TitleType.ofCodeNullable(record.getTitle())) .gender(GenderType.ofCodeNullable(record.getGender())) .timestamp(TimeUtil.asInstant(record.getTimestamp())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\bpartner\user\AlbertaUserRepository.java
2
请完成以下Spring Boot application配置
server: port: 8081 dubbo: application: # 服务名称,保持唯一 name: server-consumer # zookeeper地址,用于从中获取注册的服务 registry: address: zookeeper://127.0.0.1:2181 pro
tocol: # dubbo协议,固定写法 name: dubbo monitor: protocol: registry
repos\SpringAll-master\52.Dubbo-OPS-Mointor\spring-boot-dubbo-applicaiton\server-consumer\src\main\resources\application.yml
2
请完成以下Java代码
private void updateQtyOrderedOfOrderLineAndReserveStock(@NonNull final I_M_ShipmentSchedule shipmentSchedule) { if (shipmentSchedule.getAD_Table_ID() != getTableId(I_C_OrderLine.class)) { return; } final I_C_OrderLine orderLine = shipmentSchedule.getC_OrderLine(); if (orderLine == null) { return; } final BigDecimal qtyOrdered = shipmentSchedule.getQtyOrdered(); if (orderLine.getQtyOrdered().compareTo(qtyOrdered) == 0) { return; // avoid unnecessary changes } final I_C_Order order = orderLine.getC_Order(); final DocStatus orderDocStatus = DocStatus.ofNullableCodeOrUnknown(order.getDocStatus()); if (!orderDocStatus.isCompleted()) { // issue https://github.com/metasfresh/metasfresh/issues/3815 return; // don't update e.g. an order that was closed just now, while the async shipment-schedule creation took place. } // note: don't try to suppress shipment schedule invalidation, because maybe other scheds also need updating when this order's qtyOrdered changes. orderLine.setQtyOrdered(qtyOrdered); final MOrder orderPO = LegacyAdapters.convertToPO(order); final MOrderLine orderLinePO = LegacyAdapters.convertToPO(orderLine); orderPO.reserveStock(MDocType.get(orderPO.getCtx(), order.getC_DocType_ID()), ImmutableList.of(orderLinePO)); InterfaceWrapperHelper.save(orderLine); } /**
* Note: keep {@code ifColumnsChanged} in sync with the changeable properties loaded at de.metas.inoutcandidate.ShipmentScheduleRepository.ofRecord. */ @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_M_ShipmentSchedule.COLUMNNAME_ExportStatus, I_M_ShipmentSchedule.COLUMNNAME_POReference, I_M_ShipmentSchedule.COLUMNNAME_QtyToDeliver, I_M_ShipmentSchedule.COLUMNNAME_M_Shipper_ID, I_M_ShipmentSchedule.COLUMNNAME_C_BPartner_Override_ID, I_M_ShipmentSchedule.COLUMNNAME_C_BP_Location_Override_ID, I_M_ShipmentSchedule.COLUMNNAME_AD_User_Override_ID, I_M_ShipmentSchedule.COLUMNNAME_M_AttributeSetInstance_ID, I_M_ShipmentSchedule.COLUMNNAME_DateOrdered } ) public void updateCanBeExportedAfter(@NonNull final I_M_ShipmentSchedule sched) { shipmentScheduleBL.updateCanBeExportedAfter(sched); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\M_ShipmentSchedule.java
1
请完成以下Java代码
public PropertySource<T> getDelegate() { return delegate; } /** {@inheritDoc} */ @Override @NonNull public Object getProperty(@NonNull String name) { return cachingResolver.resolveProperty(name); } /** {@inheritDoc} */ @Override public void refresh() { log.info("Property Source {} refreshed", delegate.getName()); cachingResolver.refresh();
} /** {@inheritDoc} */ @Override @NonNull public T getSource() { T source = delegate.getSource(); if (this.wrapGetSource && source instanceof java.util.Map) { @SuppressWarnings("unchecked") T wrapped = (T) new EncryptableMapWrapper(cachingResolver); return wrapped; } return source; } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\caching\CachingDelegateEncryptablePropertySource.java
1
请在Spring Boot框架中完成以下Java代码
public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @ApiModelProperty(example = "3") public Integer getRetries() { return retries; } public void setRetries(Integer retries) { this.retries = retries; } @ApiModelProperty(example = "null") public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } @ApiModelProperty(example = "2023-06-03T22:05:05.474+0000") public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } @ApiModelProperty(example = "cmmn") public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } @ApiModelProperty(example = "async-history") public String getJobHandlerType() { return jobHandlerType; } public void setJobHandlerType(String jobHandlerType) { this.jobHandlerType = jobHandlerType; } @ApiModelProperty(example = "myCfg") public String getJobHandlerConfiguration() { return jobHandlerConfiguration; }
public void setJobHandlerConfiguration(String jobHandlerConfiguration) { this.jobHandlerConfiguration = jobHandlerConfiguration; } @ApiModelProperty(example = "myAdvancedCfg") public String getAdvancedJobHandlerConfiguration() { return advancedJobHandlerConfiguration; } public void setAdvancedJobHandlerConfiguration(String advancedJobHandlerConfiguration) { this.advancedJobHandlerConfiguration = advancedJobHandlerConfiguration; } @ApiModelProperty(example = "custom value") public String getCustomValues() { return customValues; } public void setCustomValues(String customValues) { this.customValues = customValues; } @ApiModelProperty(example = "node1") public String getLockOwner() { return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } @ApiModelProperty(example = "2023-06-03T22:05:05.474+0000") public Date getLockExpirationTime() { return lockExpirationTime; } public void setLockExpirationTime(Date lockExpirationTime) { this.lockExpirationTime = lockExpirationTime; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\HistoryJobResponse.java
2
请在Spring Boot框架中完成以下Java代码
public R<PostVO> detail(Post post) { Post detail = postService.getOne(Condition.getQueryWrapper(post)); return R.data(PostWrapper.build().entityVO(detail)); } /** * 分页 岗位表 */ @GetMapping("/list") @ApiOperationSupport(order = 2) @Operation(summary = "分页", description = "传入post") public R<IPage<PostVO>> list(Post post, Query query) { IPage<Post> pages = postService.page(Condition.getPage(query), Condition.getQueryWrapper(post)); return R.data(PostWrapper.build().pageVO(pages)); } /** * 自定义分页 岗位表 */ @GetMapping("/page") @ApiOperationSupport(order = 3) @Operation(summary = "分页", description = "传入post") public R<IPage<PostVO>> page(PostVO post, Query query) { IPage<PostVO> pages = postService.selectPostPage(Condition.getPage(query), post); return R.data(pages); } /** * 新增 岗位表 */ @PostMapping("/save") @ApiOperationSupport(order = 4) @Operation(summary = "新增", description = "传入post") public R save(@Valid @RequestBody Post post) { return R.status(postService.save(post)); } /** * 修改 岗位表 */ @PostMapping("/update") @ApiOperationSupport(order = 5) @Operation(summary = "修改", description = "传入post") public R update(@Valid @RequestBody Post post) { return R.status(postService.updateById(post)); } /** * 新增或修改 岗位表 */
@PostMapping("/submit") @ApiOperationSupport(order = 6) @Operation(summary = "新增或修改", description = "传入post") public R submit(@Valid @RequestBody Post post) { post.setTenantId(SecureUtil.getTenantId()); return R.status(postService.saveOrUpdate(post)); } /** * 删除 岗位表 */ @PostMapping("/remove") @ApiOperationSupport(order = 7) @Operation(summary = "逻辑删除", description = "传入ids") public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) { return R.status(postService.deleteLogic(Func.toLongList(ids))); } /** * 下拉数据源 */ @GetMapping("/select") @ApiOperationSupport(order = 8) @Operation(summary = "下拉数据源", description = "传入post") public R<List<Post>> select(String tenantId, BladeUser bladeUser) { List<Post> list = postService.list(Wrappers.<Post>query().lambda().eq(Post::getTenantId, Func.toStr(tenantId, bladeUser.getTenantId()))); return R.data(list); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\PostController.java
2
请完成以下Java代码
private void loadPreferences() { final LoginContext ctx = getCtx(); final ClientId clientId = ctx.getClientId(); final OrgId orgId = ctx.getOrgId(); final UserId userId = ctx.getUserId(); valuePreferenceBL .getAllWindowPreferences(clientId.getRepoId(), orgId.getRepoId(), userId.getRepoId()) .stream() .flatMap(userValuePreferences -> userValuePreferences.values().stream()) .forEach(ctx::setPreference); } /** * Set System Status Message. * NOTE: we are retrieving from database and we are storing in context because this String is used in low level UI components and in some cases there is no database connection at all * * @implSpec <a href="http://dewiki908/mediawiki/index.php/05730_Use_different_Theme_colour_on_UAT_system">task</a>. */ private void loadUIWindowHeaderNotice() { final LoginContext ctx = getCtx(); final ClientId clientId = ctx.getClientId(); final OrgId orgId = ctx.getOrgId(); final String windowHeaderNoticeText = sysConfigBL.getValue(SYSCONFIG_UI_WindowHeader_Notice_Text, clientId.getRepoId(), orgId.getRepoId()); ctx.setProperty(Env.CTXNAME_UI_WindowHeader_Notice_Text, windowHeaderNoticeText); // FRESH-352: also allow setting the status message's foreground and background color. final String windowHeaderBackgroundColor = sysConfigBL.getValue(SYSCONFIG_UI_WindowHeader_Notice_BG_Color, clientId.getRepoId(), orgId.getRepoId()); ctx.setProperty(Env.CTXNAME_UI_WindowHeader_Notice_BG_COLOR, windowHeaderBackgroundColor); final String windowHeaderForegroundColor = sysConfigBL.getValue(SYSCONFIG_UI_WindowHeader_Notice_FG_Color, clientId.getRepoId(), orgId.getRepoId()); ctx.setProperty(Env.CTXNAME_UI_WindowHeader_Notice_FG_COLOR, windowHeaderForegroundColor); } public void setRemoteAddr(final String remoteAddr) { getCtx().setRemoteAddr(remoteAddr); }
// RemoteAddr public void setRemoteHost(final String remoteHost) { getCtx().setRemoteHost(remoteHost); } // RemoteHost public void setWebSessionId(final String webSessionId) { getCtx().setWebSessionId(webSessionId); } public boolean isAllowLoginDateOverride() { return getCtx().isAllowLoginDateOverride(); } } // Login
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Login.java
1
请在Spring Boot框架中完成以下Java代码
public class ExecuterServiceCustomThreadName { private static final Logger logger = LoggerFactory.getLogger(ExecuterServiceCustomThreadName.class); public static void main(String[] args) { usingDefaultFactory(); usingCommonsLang(); usingCustomFactory(); usingGuvava(); } private static void usingDefaultFactory() { ExecutorService executorService = Executors.newFixedThreadPool(3); for (int i = 0; i < 5; i++) { executorService.execute(() -> logger.info(Thread.currentThread().getName())); } executorService.shutdown(); } private static void usingCustomFactory() { CustomThreadFactory myThreadFactory = new CustomThreadFactory("MyCustomThread-"); ExecutorService executorService = Executors.newFixedThreadPool(3, myThreadFactory); for (int i = 0; i < 5; i++) { executorService.execute(() -> logger.info(Thread.currentThread().getName())); } executorService.shutdown(); } private static void usingCommonsLang() { BasicThreadFactory factory = new BasicThreadFactory.Builder() .namingPattern("MyCustomThread-%d").priority(Thread.MAX_PRIORITY).build();
ExecutorService executorService = Executors.newFixedThreadPool(3, factory); for (int i = 0; i < 5; i++) { executorService.execute(() -> logger.info(Thread.currentThread().getName())); } executorService.shutdown(); } private static void usingGuvava() { ThreadFactory namedThreadFactory = new ThreadFactoryBuilder() .setNameFormat("MyCustomThread-%d").build(); ExecutorService executorService = Executors.newFixedThreadPool(3, namedThreadFactory); for (int i = 0; i < 5; i++) { executorService.execute(() -> logger.info(Thread.currentThread().getName())); } executorService.shutdown(); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-5\src\main\java\com\baeldung\executerservicecustomthreadname\ExecuterServiceCustomThreadName.java
2
请完成以下Java代码
public int getC_Print_PackageInfo_ID() { return get_ValueAsInt(COLUMNNAME_C_Print_PackageInfo_ID); } @Override public void setName (java.lang.String Name) { throw new IllegalArgumentException ("Name is virtual column"); } @Override public java.lang.String getName() { return (java.lang.String)get_Value(COLUMNNAME_Name); } @Override public void setPageFrom (int PageFrom) { set_Value (COLUMNNAME_PageFrom, Integer.valueOf(PageFrom)); } @Override public int getPageFrom() { return get_ValueAsInt(COLUMNNAME_PageFrom); } @Override public void setPageTo (int PageTo) { set_Value (COLUMNNAME_PageTo, Integer.valueOf(PageTo)); } @Override
public int getPageTo() { return get_ValueAsInt(COLUMNNAME_PageTo); } @Override public void setPrintServiceName (java.lang.String PrintServiceName) { throw new IllegalArgumentException ("PrintServiceName is virtual column"); } @Override public java.lang.String getPrintServiceName() { return (java.lang.String)get_Value(COLUMNNAME_PrintServiceName); } @Override public void setTrayNumber (int TrayNumber) { throw new IllegalArgumentException ("TrayNumber is virtual column"); } @Override public int getTrayNumber() { return get_ValueAsInt(COLUMNNAME_TrayNumber); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_PackageInfo.java
1
请完成以下Java代码
public void setC_Payment_Reservation(final org.compiere.model.I_C_Payment_Reservation C_Payment_Reservation) { set_ValueFromPO(COLUMNNAME_C_Payment_Reservation_ID, org.compiere.model.I_C_Payment_Reservation.class, C_Payment_Reservation); } @Override public void setC_Payment_Reservation_ID (final int C_Payment_Reservation_ID) { if (C_Payment_Reservation_ID < 1) set_Value (COLUMNNAME_C_Payment_Reservation_ID, null); else set_Value (COLUMNNAME_C_Payment_Reservation_ID, C_Payment_Reservation_ID); } @Override public int getC_Payment_Reservation_ID() { return get_ValueAsInt(COLUMNNAME_C_Payment_Reservation_ID); } @Override public void setExternalId (final @Nullable java.lang.String ExternalId) { set_Value (COLUMNNAME_ExternalId, ExternalId); } @Override public java.lang.String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } @Override public void setPayPal_AuthorizationId (final @Nullable java.lang.String PayPal_AuthorizationId) { set_Value (COLUMNNAME_PayPal_AuthorizationId, PayPal_AuthorizationId); } @Override public java.lang.String getPayPal_AuthorizationId() { return get_ValueAsString(COLUMNNAME_PayPal_AuthorizationId); } @Override public void setPayPal_Order_ID (final int PayPal_Order_ID) { if (PayPal_Order_ID < 1) set_ValueNoCheck (COLUMNNAME_PayPal_Order_ID, null); else set_ValueNoCheck (COLUMNNAME_PayPal_Order_ID, PayPal_Order_ID); } @Override public int getPayPal_Order_ID() { return get_ValueAsInt(COLUMNNAME_PayPal_Order_ID); }
@Override public void setPayPal_OrderJSON (final @Nullable java.lang.String PayPal_OrderJSON) { set_Value (COLUMNNAME_PayPal_OrderJSON, PayPal_OrderJSON); } @Override public java.lang.String getPayPal_OrderJSON() { return get_ValueAsString(COLUMNNAME_PayPal_OrderJSON); } @Override public void setPayPal_PayerApproveUrl (final @Nullable java.lang.String PayPal_PayerApproveUrl) { set_Value (COLUMNNAME_PayPal_PayerApproveUrl, PayPal_PayerApproveUrl); } @Override public java.lang.String getPayPal_PayerApproveUrl() { return get_ValueAsString(COLUMNNAME_PayPal_PayerApproveUrl); } @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java-gen\de\metas\payment\paypal\model\X_PayPal_Order.java
1
请完成以下Java代码
public class C_Invoice_CreateExportData implements IWorkpackageProcessor { private static final Logger logger = LogManager.getLogger(C_Invoice_CreateExportData.class); private static final WorkpackagesOnCommitSchedulerTemplate<I_C_Invoice> // SCHEDULER = WorkpackagesOnCommitSchedulerTemplate .newModelScheduler(C_Invoice_CreateExportData.class, I_C_Invoice.class) .setCreateOneWorkpackagePerModel(true); public static void scheduleOnTrxCommit(final I_C_Invoice invoiceRecord) { SCHEDULER.schedule(invoiceRecord); } private final transient IQueueDAO queueDAO = Services.get(IQueueDAO.class); private final transient InvoiceExportService invoiceExportService = SpringContextHolder.instance.getBean(InvoiceExportService.class); @Override public Result processWorkPackage(
@NonNull final I_C_Queue_WorkPackage workpackage, @NonNull final String localTrxName) { final List<I_C_Invoice> invoiceRecords = queueDAO.retrieveAllItemsSkipMissing(workpackage, I_C_Invoice.class); for (final I_C_Invoice invoiceRecord : invoiceRecords) { try (final MDCCloseable ignore = TableRecordMDC.putTableRecordReference(invoiceRecord)) { Loggables.withLogger(logger, Level.DEBUG).addLog("Going to export data for invoiceRecord={}", invoiceRecord); final InvoiceId invoiceId = InvoiceId.ofRepoId(invoiceRecord.getC_Invoice_ID()); invoiceExportService.exportInvoices(ImmutableList.of(invoiceId)); } } return Result.SUCCESS; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\export\async\C_Invoice_CreateExportData.java
1
请在Spring Boot框架中完成以下Java代码
public Reason getReason() { return this.reason; } /** * Reasons why the exception can be thrown. */ public enum Reason { /** * Access Denied. */ ACCESS_DENIED(HttpStatus.FORBIDDEN), /** * Invalid Audience. */ INVALID_AUDIENCE(HttpStatus.UNAUTHORIZED), /** * Invalid Issuer. */ INVALID_ISSUER(HttpStatus.UNAUTHORIZED), /** * Invalid Key ID. */ INVALID_KEY_ID(HttpStatus.UNAUTHORIZED), /** * Invalid Signature. */ INVALID_SIGNATURE(HttpStatus.UNAUTHORIZED), /** * Invalid Token. */ INVALID_TOKEN(HttpStatus.UNAUTHORIZED), /** * Missing Authorization. */ MISSING_AUTHORIZATION(HttpStatus.UNAUTHORIZED),
/** * Token Expired. */ TOKEN_EXPIRED(HttpStatus.UNAUTHORIZED), /** * Unsupported Token Signing Algorithm. */ UNSUPPORTED_TOKEN_SIGNING_ALGORITHM(HttpStatus.UNAUTHORIZED), /** * Service Unavailable. */ SERVICE_UNAVAILABLE(HttpStatus.SERVICE_UNAVAILABLE); private final HttpStatus status; Reason(HttpStatus status) { this.status = status; } public HttpStatus getStatus() { return this.status; } } }
repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\CloudFoundryAuthorizationException.java
2
请完成以下Java代码
private ExtendTermsResult extendTermsChunk( final @NonNull Iterator<I_C_Flatrate_Term> termsToExtend, final Boolean forceComplete, final int chunkSize) { final ExtendTermsResult result = new ExtendTermsResult(); while (termsToExtend.hasNext()) { final I_C_Flatrate_Term contractToExtend = termsToExtend.next(); final ContractExtendingRequest context = ContractExtendingRequest.builder() .AD_PInstance_ID(getPinstanceId()) .contract(contractToExtend) .forceExtend(false) .forceComplete(forceComplete) .nextTermStartDate(p_startDate) .build(); if (tryExtendTerm(context)) { result.extendedCounter++; } else { result.errorCounter++; } if (result.getCounterSum() >= chunkSize) { return result; } } return result; } @Data private static class ExtendTermsResult
{ int extendedCounter = 0; int errorCounter = 0; public void addToThis(@NonNull final C_Flatrate_Term_Extend_And_Notify_User.ExtendTermsResult other) { extendedCounter += other.extendedCounter; errorCounter += other.errorCounter; } public int getCounterSum() { return extendedCounter + errorCounter; } } private boolean tryExtendTerm(@NonNull final ContractExtendingRequest context) { try { flatrateBL.extendContractAndNotifyUser(context); return true; } catch (final RuntimeException e) { final I_C_Flatrate_Term contract = context.getContract(); final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(e); addLog("Error extending C_FlatrateTerm_ID={} with C_Flatrate_Data_ID={}; AD_Issue_ID={}; {} with message={}", contract.getC_Flatrate_Term_ID(), contract.getC_Flatrate_Data_ID(), issueId, e.getClass().getName(), e.getMessage()); return false; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Flatrate_Term_Extend_And_Notify_User.java
1
请完成以下Java代码
private void addEmbeddedObject(String name, Object embedded) { if(_embedded == null) { _embedded = new TreeMap<String, Object>(); } _embedded.put(name, embedded); } public void addEmbedded(String name, List<HalResource<?>> embeddedCollection) { for (HalResource<?> resource : embeddedCollection) { linker.mergeLinks(resource); } addEmbeddedObject(name, embeddedCollection); } public Object getEmbedded(String name) { return _embedded.get(name); }
/** * Can be used to embed a relation. Embedded all linked resources in the given relation. * * @param relation the relation to embedded * @param processEngine used to resolve the resources * @return the resource itself. */ @SuppressWarnings("unchecked") public T embed(HalRelation relation, ProcessEngine processEngine) { List<HalResource<?>> resolvedLinks = linker.resolve(relation, processEngine); if(resolvedLinks != null && resolvedLinks.size() > 0) { addEmbedded(relation.relName, resolvedLinks); } return (T) this; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\HalResource.java
1
请完成以下Java代码
protected void prepare() { if (I_C_Payment.Table_Name.equals(getTableName())) { p_C_Payment_ID = getRecord_ID(); } for (ProcessInfoParameter para : getParametersAsArray()) { String name = para.getParameterName(); if (para.getParameter() == null) { ; } else if (I_C_Payment.COLUMNNAME_C_Invoice_ID.equals(name)) { p_C_Invoice_ID = para.getParameterAsInt(); } } }
@Override protected String doIt() throws Exception { if (p_C_Payment_ID <= 0) { throw new FillMandatoryException(I_C_Payment.COLUMNNAME_C_Payment_ID); } if (p_C_Invoice_ID <= 0) { throw new FillMandatoryException(I_C_Payment.COLUMNNAME_C_Invoice_ID); } final I_C_Payment payment = InterfaceWrapperHelper.create(getCtx(), p_C_Payment_ID, I_C_Payment.class, get_TrxName()); final I_C_Invoice invoice = InterfaceWrapperHelper.create(getCtx(), p_C_Invoice_ID, I_C_Invoice.class, get_TrxName()); Services.get(IAllocationBL.class).autoAllocateSpecificPayment(invoice, payment, true); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\process\AllocatePayment.java
1
请在Spring Boot框架中完成以下Java代码
public class EventsQueuesProperties { private String orderProcessingRetryQueue; private String orderProcessingAsyncQueue; private String orderProcessingNoRetriesQueue; public String getOrderProcessingRetryQueue() { return orderProcessingRetryQueue; } public void setOrderProcessingRetryQueue(String orderProcessingRetryQueue) { this.orderProcessingRetryQueue = orderProcessingRetryQueue; }
public String getOrderProcessingAsyncQueue() { return orderProcessingAsyncQueue; } public void setOrderProcessingAsyncQueue(String orderProcessingAsyncQueue) { this.orderProcessingAsyncQueue = orderProcessingAsyncQueue; } public String getOrderProcessingNoRetriesQueue() { return orderProcessingNoRetriesQueue; } public void setOrderProcessingNoRetriesQueue(String orderProcessingNoRetriesQueue) { this.orderProcessingNoRetriesQueue = orderProcessingNoRetriesQueue; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-aws-v3\src\main\java\com\baeldung\spring\cloud\aws\sqs\acknowledgement\configuration\EventsQueuesProperties.java
2
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(city, countryCode, postalCode, stateOrProvince); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class TaxAddress {\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append(" countryCode: ").append(toIndentedString(countryCode)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" stateOrProvince: ").append(toIndentedString(stateOrProvince)).append("\n"); sb.append("}"); return sb.toString();
} /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\TaxAddress.java
2
请完成以下Java代码
public class QueryCondition implements Serializable { private static final long serialVersionUID = 4740166316629191651L; private String field; /** 组件的类型(例如:input、select、radio) */ private String type; /** * 对应的数据库字段的类型 * 支持:int、bigDecimal、short、long、float、double、boolean */ private String dbType; private String rule; private String val; public QueryCondition(String field, String type, String dbType, String rule, String val) { this.field = field; this.type = type; this.dbType = dbType; this.rule = rule; this.val = val; } public String getField() { return field; } public void setField(String field) { this.field = field; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDbType() { return dbType; } public void setDbType(String dbType) { this.dbType = dbType; } public String getRule() { return rule; }
public void setRule(String rule) { this.rule = rule; } public String getVal() { return val; } public void setVal(String val) { this.val = val; } @Override public String toString(){ StringBuffer sb =new StringBuffer(); if(field == null || "".equals(field)){ return ""; } sb.append(this.field).append(" ").append(this.rule).append(" ").append(this.type).append(" ").append(this.dbType).append(" ").append(this.val); return sb.toString(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\query\QueryCondition.java
1
请在Spring Boot框架中完成以下Java代码
public class CityESServiceImpl implements CityService { private static final Logger LOGGER = LoggerFactory.getLogger(CityESServiceImpl.class); @Autowired CityRepository cityRepository; @Override public Long saveCity(City city) { City cityResult = cityRepository.save(city); return cityResult.getId(); } @Override public List<City> searchCity(Integer pageNumber, Integer pageSize, String searchContent) { // 分页参数 Pageable pageable = new PageRequest(pageNumber, pageSize);
// Function Score Query FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery() .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("cityname", searchContent)), ScoreFunctionBuilders.weightFactorFunction(1000)) .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("description", searchContent)), ScoreFunctionBuilders.weightFactorFunction(100)); // 创建搜索 DSL 查询 SearchQuery searchQuery = new NativeSearchQueryBuilder() .withPageable(pageable) .withQuery(functionScoreQueryBuilder).build(); LOGGER.info("\n searchCity(): searchContent [" + searchContent + "] \n DSL = \n " + searchQuery.getQuery().toString()); Page<City> searchPageResults = cityRepository.search(searchQuery); return searchPageResults.getContent(); } }
repos\springboot-learning-example-master\springboot-elasticsearch\src\main\java\org\spring\springboot\service\impl\CityESServiceImpl.java
2
请完成以下Java代码
public class FirstCharDigit { public static boolean checkUsingCharAtMethod(String str) { if (str == null || str.length() == 0) { return false; } char c = str.charAt(0); return c >= '0' && c <= '9'; } public static boolean checkUsingIsDigitMethod(String str) { if (str == null || str.length() == 0) { return false; } return Character.isDigit(str.charAt(0)); } public static boolean checkUsingPatternClass(String str) { if (str == null || str.length() == 0) { return false; } return Pattern.compile("^[0-9].*") .matcher(str) .matches(); } public static boolean checkUsingMatchesMethod(String str) {
if (str == null || str.length() == 0) { return false; } return str.matches("^[0-9].*"); } public static boolean checkUsingCharMatcherInRangeMethod(String str) { if (str == null || str.length() == 0) { return false; } return CharMatcher.inRange('0', '9') .matches(str.charAt(0)); } public static boolean checkUsingCharMatcherForPredicateMethod(String str) { if (str == null || str.length() == 0) { return false; } return CharMatcher.forPredicate(Character::isDigit) .matches(str.charAt(0)); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-5\src\main\java\com\baeldung\firstchardigit\FirstCharDigit.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String getMappingPath() { return this.mappingPath; } public void setMappingPath(@Nullable String mappingPath) { this.mappingPath = mappingPath; } public @Nullable DataSize getFragmentSize() { return this.fragmentSize; } public void setFragmentSize(@Nullable DataSize fragmentSize) { this.fragmentSize = fragmentSize; } public @Nullable Ssl getSsl() { return this.ssl; } public void setSsl(@Nullable Ssl ssl) { this.ssl = ssl; } public Spec getSpec() { return this.spec; } public static class Spec { /** * Sub-protocols to use in websocket handshake signature. */ private @Nullable String protocols; /** * Maximum allowable frame payload length. */ private DataSize maxFramePayloadLength = DataSize.ofBytes(65536); /** * Whether to proxy websocket ping frames or respond to them. */ private boolean handlePing; /** * Whether the websocket compression extension is enabled. */ private boolean compress; public @Nullable String getProtocols() {
return this.protocols; } public void setProtocols(@Nullable String protocols) { this.protocols = protocols; } public DataSize getMaxFramePayloadLength() { return this.maxFramePayloadLength; } public void setMaxFramePayloadLength(DataSize maxFramePayloadLength) { this.maxFramePayloadLength = maxFramePayloadLength; } public boolean isHandlePing() { return this.handlePing; } public void setHandlePing(boolean handlePing) { this.handlePing = handlePing; } public boolean isCompress() { return this.compress; } public void setCompress(boolean compress) { this.compress = compress; } } } }
repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketProperties.java
2
请完成以下Java代码
public static List getSqlInjectSortFields(String... sortFields) { List list = new ArrayList<String>(); for (String sortField : sortFields) { list.add(getSqlInjectSortField(sortField)); } return list; } /** * 获取 orderBy type * 返回:字符串 * <p> * 1.检测是否为 asc 或 desc 其中的一个 * 2.限制sql注入 *
* @param orderType * @return */ public static String getSqlInjectOrderType(String orderType) { if (orderType == null) { return null; } orderType = orderType.trim(); if (CommonConstant.ORDER_TYPE_ASC.equalsIgnoreCase(orderType)) { return CommonConstant.ORDER_TYPE_ASC; } else { return CommonConstant.ORDER_TYPE_DESC; } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\SqlInjectionUtil.java
1
请完成以下Java代码
public HttpResponse call() { try (CloseableHttpClient httpClient = clientBuilder.build()) { try (CloseableHttpResponse response = httpClient.execute(request)) { return toFlowableHttpResponse(response); } } catch (ClientProtocolException ex) { throw new FlowableException("HTTP exception occurred", ex); } catch (IOException ex) { throw new FlowableException("IO exception occurred", ex); } } } /** * A HttpDelete alternative that extends {@link HttpEntityEnclosingRequestBase} to allow DELETE with a request body *
* @author ikaakkola */ protected static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { public HttpDeleteWithBody(URI uri) { super(); setURI(uri); } @Override public String getMethod() { return "DELETE"; } } }
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\impl\apache\ApacheHttpComponentsFlowableHttpClient.java
1
请在Spring Boot框架中完成以下Java代码
public class RegistrationBean implements Serializable { private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationBean.class); @ManagedProperty(value = "#{userManagementDAO}") transient private UserManagementDAO userDao; private String userName; private String operationMessage; public void createNewUser() { try { LOGGER.info("Creating new user"); FacesContext context = FacesContext.getCurrentInstance(); boolean operationStatus = userDao.createUser(userName); context.isValidationFailed(); if (operationStatus) { operationMessage = "User " + userName + " created"; } } catch (Exception ex) { LOGGER.error("Error registering new user "); ex.printStackTrace(); operationMessage = "Error " + userName + " not created"; } } public String getUserName() {
return userName; } public void setUserName(String userName) { this.userName = userName; } public void setUserDao(UserManagementDAO userDao) { this.userDao = userDao; } public UserManagementDAO getUserDao() { return this.userDao; } public String getOperationMessage() { return operationMessage; } public void setOperationMessage(String operationMessage) { this.operationMessage = operationMessage; } }
repos\tutorials-master\web-modules\jsf\src\main\java\com\baeldung\springintegration\controllers\RegistrationBean.java
2
请完成以下Java代码
public BBANStructure create() { for (final BBANStructureEntryBuilder line : entryBuilders) { line.create(_BBANStructure); } // sort entries sortEntries(); return _BBANStructure; } private final ArrayList<BBANStructureEntryBuilder> entryBuilders = new ArrayList<>(); @Override public BBANStructureEntryBuilder addBBANStructureEntry() { final BBANStructureEntryBuilder entryBuilder = new BBANStructureEntryBuilder(this); entryBuilders.add(entryBuilder); return entryBuilder; } private void sortEntries() { List<BBANStructureEntry> listEntries = _BBANStructure.getEntries(); // if there is no entry , than we have BBAN structure if (listEntries.isEmpty()) { _BBANStructure = null; return; } // order list by seqNo Collections.sort(listEntries, (entry1, entry2) -> {
String seqNo1 = entry1.getSeqNo(); if (Check.isEmpty(seqNo1, true)) { seqNo1 = "10"; } String seqNo2 = entry2.getSeqNo(); if (Check.isEmpty(seqNo2, true)) { seqNo2 = "20"; } final int no1 = Integer.valueOf(seqNo1); final int no2 = Integer.valueOf(seqNo2); // order if (no1 > no2) { return 1; } else if (no1 < no2) { return -1; } else { return 0; } }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\BBANStructureBuilder.java
1
请完成以下Java代码
public OptimizeRestService getOptimizeRestService(@PathParam("name") String engineName) { return super.getOptimizeRestService(engineName); } @Path("/{name}" + VersionRestService.PATH) public VersionRestService getVersionRestService(@PathParam("name") String engineName) { return super.getVersionRestService(engineName); } @Path("/{name}" + SchemaLogRestService.PATH) public SchemaLogRestService getSchemaLogRestService(@PathParam("name") String engineName) { return super.getSchemaLogRestService(engineName); } @Override @Path("/{name}" + EventSubscriptionRestService.PATH) public EventSubscriptionRestService getEventSubscriptionRestService(@PathParam("name") String engineName) { return super.getEventSubscriptionRestService(engineName); } @Override @Path("/{name}" + TelemetryRestService.PATH) public TelemetryRestService getTelemetryRestService(@PathParam("name") String engineName) { return super.getTelemetryRestService(engineName); } @GET @Produces(MediaType.APPLICATION_JSON)
public List<ProcessEngineDto> getProcessEngineNames() { ProcessEngineProvider provider = getProcessEngineProvider(); Set<String> engineNames = provider.getProcessEngineNames(); List<ProcessEngineDto> results = new ArrayList<ProcessEngineDto>(); for (String engineName : engineNames) { ProcessEngineDto dto = new ProcessEngineDto(); dto.setName(engineName); results.add(dto); } return results; } @Override protected URI getRelativeEngineUri(String engineName) { return UriBuilder.fromResource(NamedProcessEngineRestServiceImpl.class).path("{name}").build(engineName); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\NamedProcessEngineRestServiceImpl.java
1
请完成以下Java代码
public void afterSave(final I_GL_JournalLine glJournalLine) { updateJournalTotal(glJournalLine); } // afterSave @ModelChange(timings = { ModelValidator.TYPE_AFTER_DELETE }) public void afterDelete(final I_GL_JournalLine glJournalLine) { updateJournalTotal(glJournalLine); } // afterDelete /** * Update amounts of {@link I_GL_Journal} and {@link I_GL_JournalBatch}. */ private void updateJournalTotal(final I_GL_JournalLine glJournalLine) { final int glJournalId = glJournalLine.getGL_Journal_ID(); // // Update Journal Total { final String sql = DB.convertSqlToNative("UPDATE GL_Journal j" + " SET (TotalDr, TotalCr) = (SELECT COALESCE(SUM(AmtAcctDr),0), COALESCE(SUM(AmtAcctCr),0)" // croo Bug# 1789935 + " FROM GL_JournalLine jl WHERE jl.IsActive='Y' AND j.GL_Journal_ID=jl.GL_Journal_ID) " + "WHERE GL_Journal_ID=" + glJournalId); final int no = DB.executeUpdateAndThrowExceptionOnFail(sql, ITrx.TRXNAME_ThreadInherited); if (no != 1) { throw new AdempiereException("afterSave - Update Journal #" + no); } } // // Update Batch Total, if there is any batch
{ final String sql = DB.convertSqlToNative("UPDATE GL_JournalBatch jb" + " SET (TotalDr, TotalCr) = (SELECT COALESCE(SUM(TotalDr),0), COALESCE(SUM(TotalCr),0)" + " FROM GL_Journal j WHERE jb.GL_JournalBatch_ID=j.GL_JournalBatch_ID) " + "WHERE GL_JournalBatch_ID=" + "(SELECT DISTINCT GL_JournalBatch_ID FROM GL_Journal WHERE GL_Journal_ID=" + glJournalId + ")"); final int no = DB.executeUpdateAndThrowExceptionOnFail(sql, ITrx.TRXNAME_ThreadInherited); if (no != 0 && no != 1) { throw new AdempiereException("Update Batch #" + no); } } CacheMgt.get().resetLocalNowAndBroadcastOnTrxCommit( ITrx.TRXNAME_ThreadInherited, CacheInvalidateMultiRequest.rootRecord(I_GL_Journal.Table_Name, glJournalId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\GL_JournalLine.java
1
请在Spring Boot框架中完成以下Java代码
public class CKassaApi { @Value("${ckassa.sslPath}") private String sslPath; @Value("${ckassa.sslPassword}") private String sslPassword; public String call(String method, String methodParams) throws Exception { StringBuilder res = new StringBuilder(); String url = "https://demo-api.ckassa.ru/api-shop/" + method; SSLContext sslContext = SSLContexts.custom() .loadKeyMaterial(readStore(), sslPassword.toCharArray()) .build(); CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build(); HttpPost httpMethod = new HttpPost(url); StringEntity params = new StringEntity(methodParams, StandardCharsets.UTF_8.name()); httpMethod.setEntity(params); httpMethod.addHeader("Content-Type", "application/json"); try (CloseableHttpResponse response = httpClient.execute(httpMethod)) {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8)); String line = ""; while((line = rd.readLine()) != null) res.append(line); } return res.toString(); } KeyStore readStore() throws Exception { try (InputStream keyStoreStream = new FileInputStream(new File(sslPath))) { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(keyStoreStream, sslPassword.toCharArray()); return keyStore; } } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\service\order\payment\CKassaApi.java
2
请在Spring Boot框架中完成以下Java代码
public void download(List<RoleDto> roles, HttpServletResponse response) throws IOException { List<Map<String, Object>> list = new ArrayList<>(); for (RoleDto role : roles) { Map<String, Object> map = new LinkedHashMap<>(); map.put("角色名称", role.getName()); map.put("角色级别", role.getLevel()); map.put("描述", role.getDescription()); map.put("创建日期", role.getCreateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } @Override public void verification(Set<Long> ids) { if (userRepository.countByRoles(ids) > 0) { throw new BadRequestException("所选角色存在用户关联,请解除关联再试!"); } } @Override public List<Role> findInMenuId(List<Long> menuIds) {
return roleRepository.findInMenuId(menuIds); } /** * 清理缓存 * @param id / */ public void delCaches(Long id, List<User> users) { users = CollectionUtil.isEmpty(users) ? userRepository.findByRoleId(id) : users; if (CollectionUtil.isNotEmpty(users)) { users.forEach(item -> userCacheManager.cleanUserCache(item.getUsername())); Set<Long> userIds = users.stream().map(User::getId).collect(Collectors.toSet()); redisUtils.delByKeys(CacheKey.DATA_USER, userIds); redisUtils.delByKeys(CacheKey.MENU_USER, userIds); redisUtils.delByKeys(CacheKey.ROLE_AUTH, userIds); redisUtils.delByKeys(CacheKey.ROLE_USER, userIds); } redisUtils.del(CacheKey.ROLE_ID + id); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\RoleServiceImpl.java
2
请完成以下Java代码
public Integer getLockStock() { return lockStock; } public void setLockStock(Integer lockStock) { this.lockStock = lockStock; } public String getSpData() { return spData; } public void setSpData(String spData) { this.spData = spData; } @Override public String toString() { StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", skuCode=").append(skuCode); sb.append(", price=").append(price); sb.append(", stock=").append(stock); sb.append(", lowStock=").append(lowStock); sb.append(", pic=").append(pic); sb.append(", sale=").append(sale); sb.append(", promotionPrice=").append(promotionPrice); sb.append(", lockStock=").append(lockStock); sb.append(", spData=").append(spData); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsSkuStock.java
1
请在Spring Boot框架中完成以下Java代码
public List<NewsCategory> getAllCategories() { return newsCategoryMapper.findCategoryList(null); } @Override public NewsCategory queryById(Long id) { return newsCategoryMapper.selectByPrimaryKey(id); } @Override public PageResult getCategoryPage(PageQueryUtil pageUtil) { List<NewsCategory> categoryList = newsCategoryMapper.findCategoryList(pageUtil); int total = newsCategoryMapper.getTotalCategories(pageUtil); PageResult pageResult = new PageResult(categoryList, total, pageUtil.getLimit(), pageUtil.getPage()); return pageResult; } @Override public Boolean saveCategory(String categoryName) { /** * 查询是否已存在 */ NewsCategory temp = newsCategoryMapper.selectByCategoryName(categoryName); if (temp == null) { NewsCategory newsCategory = new NewsCategory(); newsCategory.setCategoryName(categoryName); return newsCategoryMapper.insertSelective(newsCategory) > 0;
} return false; } @Override public Boolean updateCategory(Long categoryId, String categoryName) { NewsCategory newsCategory = newsCategoryMapper.selectByPrimaryKey(categoryId); if (newsCategory != null) { newsCategory.setCategoryName(categoryName); return newsCategoryMapper.updateByPrimaryKeySelective(newsCategory) > 0; } return false; } @Override public Boolean deleteBatchByIds(Integer[] ids) { if (ids.length < 1) { return false; } //删除分类数据 return newsCategoryMapper.deleteBatch(ids) > 0; } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\service\impl\CategoryServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public List<HALCH1> getHALCH1() { if (halch1 == null) { halch1 = new ArrayList<HALCH1>(); } return this.halch1; } /** * Gets the value of the detail property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the detail property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDETAIL().add(newItem);
* </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DETAILXrech } * * */ public List<DETAILXrech> getDETAIL() { if (detail == null) { detail = new ArrayList<DETAILXrech>(); } return this.detail; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_invoic\de\metas\edi\esb\jaxb\stepcom\invoic\HEADERXrech.java
2
请完成以下Java代码
public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** 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_AD_Desktop.java
1
请完成以下Java代码
public class CompleteCommand { // services @NonNull private final HUConsolidationJobRepository jobRepository; @NonNull private final HUConsolidationTargetCloser targetCloser; // params @NonNull private HUConsolidationJob job; @Builder private CompleteCommand( @NonNull final HUConsolidationJobRepository jobRepository, @NonNull final HUConsolidationTargetCloser targetCloser, // @NonNull final HUConsolidationJob job) { this.jobRepository = jobRepository; this.targetCloser = targetCloser; this.job = job;
} public HUConsolidationJob execute() { if (job.isProcessed()) { throw new AdempiereException("Job is already processed"); } job = targetCloser.closeTarget(job); job = job.withDocStatus(HUConsolidationJobStatus.Completed); jobRepository.save(job); return job; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\commands\complete\CompleteCommand.java
1
请完成以下Java代码
public class LowCodeModeInterceptor implements HandlerInterceptor { /** * 低代码开发模式 */ public static final String LOW_CODE_MODE_DEV = "dev"; public static final String LOW_CODE_MODE_PROD = "prod"; @Resource private JeecgBaseConfig jeecgBaseConfig; /** * 在请求处理之前进行调用 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { CommonAPI commonAPI = null; log.info("低代码模式,拦截请求路径:" + request.getRequestURI()); //1、验证是否开启低代码开发模式控制 if (jeecgBaseConfig == null) { jeecgBaseConfig = SpringContextUtils.getBean(JeecgBaseConfig.class); } if (commonAPI == null) { commonAPI = SpringContextUtils.getBean(CommonAPI.class); } if (jeecgBaseConfig.getFirewall()!=null && LowCodeModeInterceptor.LOW_CODE_MODE_PROD.equals(jeecgBaseConfig.getFirewall().getLowCodeMode())) { String requestURI = request.getRequestURI().substring(request.getContextPath().length()); log.info("低代码模式,拦截请求路径:" + requestURI); LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); Set<String> hasRoles = null; if (loginUser == null) { loginUser = commonAPI.getUserByName(JwtUtil.getUserNameByToken(SpringContextUtils.getHttpServletRequest())); } if (loginUser != null) { //当前登录人拥有的角色 hasRoles = commonAPI.queryUserRolesById(loginUser.getId()); } log.info("get loginUser info: {}", loginUser); log.info("get loginRoles info: {}", hasRoles != null ? hasRoles.toArray() : "空"); //拥有的角色 和 允许开发角色存在交集 boolean hasIntersection = CommonUtils.hasIntersection(hasRoles, CommonConstant.allowDevRoles); //如果是超级管理员 或者 允许开发的角色,则不做限制
if (loginUser!=null && ("admin".equals(loginUser.getUsername()) || hasIntersection)) { return true; } this.returnErrorMessage(response); return false; } return true; } /** * 返回结果 * * @param response */ private void returnErrorMessage(HttpServletResponse response) { //校验失败返回前端 response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); PrintWriter out = null; try { out = response.getWriter(); Result<?> result = Result.error("低代码开发模式为发布模式,不允许使用在线配置!!"); out.print(JSON.toJSON(result)); } catch (IOException e) { e.printStackTrace(); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\firewall\interceptor\LowCodeModeInterceptor.java
1
请完成以下Java代码
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public EventRegistryEngine getObject() throws Exception { configureExternallyManagedTransactions(); if (eventEngineConfiguration.getBeans() == null) { eventEngineConfiguration.setBeans(new SpringBeanFactoryProxyMap(applicationContext)); } this.eventRegistryEngine = eventEngineConfiguration.buildEventRegistryEngine(); return this.eventRegistryEngine; } protected void configureExternallyManagedTransactions() { if (eventEngineConfiguration instanceof SpringEventRegistryEngineConfiguration) { // remark: any config can be injected, so we cannot have SpringConfiguration as member SpringEventRegistryEngineConfiguration engineConfiguration = (SpringEventRegistryEngineConfiguration) eventEngineConfiguration; if (engineConfiguration.getTransactionManager() != null) { eventEngineConfiguration.setTransactionsExternallyManaged(true);
} } } @Override public Class<EventRegistryEngine> getObjectType() { return EventRegistryEngine.class; } @Override public boolean isSingleton() { return true; } public EventRegistryEngineConfiguration getEventEngineConfiguration() { return eventEngineConfiguration; } public void setEventEngineConfiguration(EventRegistryEngineConfiguration eventEngineConfiguration) { this.eventEngineConfiguration = eventEngineConfiguration; } }
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\EventRegistryFactoryBean.java
1
请在Spring Boot框架中完成以下Java代码
public class Item { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private long id; @ManyToOne @JoinColumn(name = "cart_id", nullable = false) private Cart cart; // Hibernate requires no-args constructor public Item() { } public Item(Cart c) { this.cart = c; } public Cart getCart() {
return cart; } public void setCart(Cart cart) { this.cart = cart; } public long getId() { return id; } public void setId(long id) { this.id = id; } }
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\oneToMany\model\Item.java
2
请完成以下Java代码
private I_M_MovementLine getOrCreateMovementLine(final ProductId productId) { return movementLines.computeIfAbsent(productId, this::newMovementLine); } @NonNull private I_M_MovementLine newMovementLine(final ProductId productId) { final I_M_Movement movement = getOrCreateMovementHeader(); I_M_MovementLine movementLine = InterfaceWrapperHelper.newInstance(I_M_MovementLine.class, movement); movementLine.setAD_Org_ID(movement.getAD_Org_ID()); movementLine.setM_Movement_ID(movement.getM_Movement_ID()); movementLine.setIsPackagingMaterial(false); movementLine.setM_Product_ID(productId.getRepoId()); movementLine.setM_Locator_ID(locatorFromId.getRepoId()); movementLine.setM_LocatorTo_ID(request.getToLocatorId().getRepoId()); // // Reference if (request.getDdOrderLineId() != null) { movementLine.setDD_OrderLine_ID(request.getDdOrderLineId().getDdOrderLineId().getRepoId()); }
// NOTE: we are not saving the movement line return movementLine; } private void assertTopLevelHUs(final Collection<I_M_HU> hus) { for (final I_M_HU hu : hus) { if (!handlingUnitsBL.isTopLevel(hu)) { throw new HUException("@M_HU_ID@ @TopLevel@=@N@: " + hu); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\movement\generate\HUMovementGenerator.java
1
请完成以下Java代码
private ImmutableList<I_M_HU> getSelectedHUsToReturn() { ImmutableList<I_M_HU> selectedHUsToReturn = this._selectedHUsToReturn; if (selectedHUsToReturn == null) { final ImmutableSet<HuId> huIds = streamEligibleSelectedRows() .map(HUEditorRow::getHuId) .distinct() .collect(ImmutableSet.toImmutableSet()); selectedHUsToReturn = this._selectedHUsToReturn = ImmutableList.copyOf(handlingUnitsRepo.getByIds(huIds)); } return selectedHUsToReturn; } @Override protected void postProcess(final boolean success) { if (!success) { return;
} final HashSet<HuId> huIdsToRefresh = new HashSet<>(); getSelectedHUsToReturn().stream() .map(hu -> HuId.ofRepoId(hu.getM_HU_ID())) .forEach(huIdsToRefresh::add); if (result != null) { huIdsToRefresh.addAll(result.getReturnedHUIds()); } addHUIdsAndInvalidateView(huIdsToRefresh); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_ReturnFromCustomer.java
1
请完成以下Java代码
public List<String> getIds() { if (ids == null) { createDeploymentMappings(); } return ids; } /** * @return the list of {@link DeploymentMapping}s */ public DeploymentMappings getMappings() { if (mappings == null) { createDeploymentMappings(); } return mappings;
} public boolean isEmpty() { return collectedMappings.isEmpty(); } protected void createDeploymentMappings() { ids = new ArrayList<>(); mappings = new DeploymentMappings(); for (Entry<String, Set<String>> mapping : collectedMappings.entrySet()) { ids.addAll(mapping.getValue()); mappings.add(new DeploymentMapping(mapping.getKey(), mapping.getValue().size())); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchElementConfiguration.java
1
请完成以下Java代码
public int getMaxStackDepth() { return maxStackDepth; } public SecureJavascriptConfigurator setMaxStackDepth(int maxStackDepth) { this.maxStackDepth = maxStackDepth; return this; } public long getMaxMemoryUsed() { return maxMemoryUsed; } public SecureJavascriptConfigurator setMaxMemoryUsed(long maxMemoryUsed) { this.maxMemoryUsed = maxMemoryUsed; return this; } public int getScriptOptimizationLevel() { return scriptOptimizationLevel; } public SecureJavascriptConfigurator setScriptOptimizationLevel(int scriptOptimizationLevel) { this.scriptOptimizationLevel = scriptOptimizationLevel; return this; }
public SecureScriptContextFactory getSecureScriptContextFactory() { return secureScriptContextFactory; } public static SecureScriptClassShutter getSecureScriptClassShutter() { return secureScriptClassShutter; } public SecureJavascriptConfigurator setEnableAccessToBeans(boolean enableAccessToBeans) { this.enableAccessToBeans = enableAccessToBeans; return this; } public boolean isEnableAccessToBeans() { return enableAccessToBeans; } }
repos\flowable-engine-main\modules\flowable-secure-javascript\src\main\java\org\flowable\scripting\secure\SecureJavascriptConfigurator.java
1