instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
class ServletOutputToInputConverter extends HttpServletResponseWrapper { private StringBuilder builder = new StringBuilder(); ServletOutputToInputConverter(HttpServletResponse response) { super(response); } @Override public ServletOutputStream getOutputStream() throws IOException { return new ServletOutputStream() { @Override public void write(int b) throws IOException { builder.append(Character.valueOf((char) b)); } @Override public void setWriteListener(WriteListener listener) { } @Override public boolean isReady() { return true; } }; } public ServletInputStream getInputStream() { ByteArrayInputStream body = new ByteArrayInputStream(builder.toString().getBytes()); return new ServletInputStream() { @Override
public int read() throws IOException { return body.read(); } @Override public void setReadListener(ReadListener listener) { } @Override public boolean isReady() { return true; } @Override public boolean isFinished() { return body.available() <= 0; } }; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webmvc\src\main\java\org\springframework\cloud\gateway\mvc\ProxyExchange.java
1
请完成以下Java代码
public void setContentHTML (String ContentHTML) { set_Value (COLUMNNAME_ContentHTML, ContentHTML); } /** Get Content HTML. @return Contains the content itself */ public String getContentHTML () { return (String)get_Value(COLUMNNAME_ContentHTML); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ 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 Valid. @param IsValid Element is valid */
public void setIsValid (boolean IsValid) { set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid)); } /** Get Valid. @return Element is valid */ public boolean isValid () { Object oo = get_Value(COLUMNNAME_IsValid); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ 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_CM_Container_Element.java
1
请完成以下Java代码
public boolean isEngineTablePresent() { return isTablePresent("ACT_RU_EXECUTION"); } public boolean isHistoryTablePresent() { return isTablePresent("ACT_HI_PROCINST"); } protected String getCleanVersion(String versionString) { Matcher matcher = CLEAN_VERSION_REGEX.matcher(versionString); if (!matcher.find()) { throw new FlowableException("Illegal format for version: " + versionString); } String cleanString = matcher.group(); try { Double.parseDouble(cleanString); // try to parse it, to see if it is // really a number return cleanString; } catch (NumberFormatException nfe) { throw new FlowableException("Illegal format for version: " + versionString, nfe); } }
protected ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return CommandContextUtil.getProcessEngineConfiguration(); } @Override protected String getResourcesRootDirectory() { return "org/flowable/db/"; } @Override public String getContext() { return "bpmn"; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\db\ProcessDbSchemaManager.java
1
请完成以下Java代码
class ConnectionAcquireTimeThresholdExceededEventListener extends EventListener<ConnectionAcquireTimeThresholdExceededEvent> { public static final Logger LOGGER = LoggerFactory.getLogger(ConnectionAcquireTimeThresholdExceededEventListener.class); public ConnectionAcquireTimeThresholdExceededEventListener() { super(ConnectionAcquireTimeThresholdExceededEvent.class); } @Override public void on(ConnectionAcquireTimeThresholdExceededEvent event) { LOGGER.info("ConnectionAcquireTimeThresholdExceededEvent Caught event {}", event); } } class ConnectionLeaseTimeThresholdExceededEventListener extends EventListener<ConnectionLeaseTimeThresholdExceededEvent> { public static final Logger LOGGER = LoggerFactory.getLogger(ConnectionLeaseTimeThresholdExceededEventListener.class); public ConnectionLeaseTimeThresholdExceededEventListener() { super(ConnectionLeaseTimeThresholdExceededEvent.class); } @Override public void on(ConnectionLeaseTimeThresholdExceededEvent event) { LOGGER.info("ConnectionLeaseTimeThresholdExceededEvent Caught event {}", event);
} } class ConnectionAcquireTimeoutEventListener extends EventListener<ConnectionAcquireTimeoutEvent> { public static final Logger LOGGER = LoggerFactory.getLogger(ConnectionAcquireTimeoutEventListener.class); public ConnectionAcquireTimeoutEventListener() { super(ConnectionAcquireTimeoutEvent.class); } @Override public void on(ConnectionAcquireTimeoutEvent event) { LOGGER.info("ConnectionAcquireTimeoutEvent Caught event {}", event); } }
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\flexypool\FlexypoolConfig.java
1
请完成以下Java代码
protected String getTargetTableName() { return I_C_Postal.Table_Name; } @Override protected void updateAndValidateImportRecordsImpl() { } @Override protected String getImportOrderBySql() { return I_I_Postal.COLUMNNAME_Postal; } @Override public I_I_Postal retrieveImportRecord(final Properties ctx, final ResultSet rs) { return new X_I_Postal(ctx, rs, ITrx.TRXNAME_ThreadInherited); } @Override protected ImportRecordResult importRecord( @NonNull final IMutable<Object> state_NOTUSED, @NonNull final I_I_Postal importRecord, final boolean isInsertOnly_NOTUSED) { return importPostalCode(importRecord); } private ImportRecordResult importPostalCode(@NonNull final I_I_Postal importRecord) {
// the current handling for duplicates (postal code + country) is nonexistent. // we blindly try to insert in db, and if there are unique constraints failing the records will automatically be marked as failed. //noinspection UnusedAssignment ImportRecordResult importResult = ImportRecordResult.Nothing; final I_C_Postal cPostal = createNewCPostalCode(importRecord); importResult = ImportRecordResult.Inserted; importRecord.setC_Postal_ID(cPostal.getC_Postal_ID()); InterfaceWrapperHelper.save(importRecord); return importResult; } private I_C_Postal createNewCPostalCode(final I_I_Postal importRecord) { final I_C_Postal cPostal = InterfaceWrapperHelper.create(getCtx(), I_C_Postal.class, ITrx.TRXNAME_ThreadInherited); cPostal.setC_Country(Services.get(ICountryDAO.class).retrieveCountryByCountryCode(importRecord.getCountryCode())); cPostal.setCity(importRecord.getCity()); cPostal.setPostal(importRecord.getPostal()); cPostal.setRegionName(importRecord.getRegionName()); // these 2 are not yet used // importRecord.getValidFrom() // importRecord.getValidTo() InterfaceWrapperHelper.save(cPostal); return cPostal; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\impexp\PostalCodeImportProcess.java
1
请完成以下Java代码
public void setIsPublicWrite (boolean IsPublicWrite) { set_Value (COLUMNNAME_IsPublicWrite, Boolean.valueOf(IsPublicWrite)); } /** Get Public Write. @return Public can write entries */ public boolean isPublicWrite () { Object oo = get_Value(COLUMNNAME_IsPublicWrite); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Knowledge Topic. @param K_Topic_ID Knowledge Topic */ public void setK_Topic_ID (int K_Topic_ID) { if (K_Topic_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Topic_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Topic_ID, Integer.valueOf(K_Topic_ID)); } /** Get Knowledge Topic. @return Knowledge Topic */ public int getK_Topic_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Topic_ID); if (ii == null) return 0; return ii.intValue(); } public I_K_Type getK_Type() throws RuntimeException { return (I_K_Type)MTable.get(getCtx(), I_K_Type.Table_Name) .getPO(getK_Type_ID(), get_TrxName()); } /** Set Knowldge Type. @param K_Type_ID Knowledge Type */ public void setK_Type_ID (int K_Type_ID) { if (K_Type_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Type_ID, null);
else set_ValueNoCheck (COLUMNNAME_K_Type_ID, Integer.valueOf(K_Type_ID)); } /** Get Knowldge Type. @return Knowledge Type */ public int getK_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Topic.java
1
请完成以下Java代码
public IExporter createExporter(final String mimeType, final IExportDataSource dataSource, final Properties config) { Check.assumeNotNull(dataSource, "dataSource not null"); final Class<? extends IExporter> exporterClass = exporterClasses.get(mimeType); if (exporterClass == null) { throw new AdempiereException("Exporter class not found for MimeType '" + mimeType + "'"); } IExporter exporter = null; try { exporter = exporterClass.newInstance(); } catch (Exception e) { throw new AdempiereException(e.getLocalizedMessage(), e); } exporter.setDataSource(dataSource); exporter.setConfig(config);
return exporter; } @Override public void registerExporter(String mimeType, Class<? extends IExporter> exporterClass) { Check.assume(!Check.isEmpty(mimeType, true), "mimeType not empty"); Check.assumeNotNull(exporterClass, "exporterClass not null"); exporterClasses.put(mimeType.trim(), exporterClass); // TODO Auto-generated method stub } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\ExporterFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class C_Order { private final IOrderDAO orderDAO = Services.get(IOrderDAO.class); private final CallOrderService callOrderService; private final DocumentChangeHandler_Order orderDocumentChangeHandler; public C_Order( @NonNull final CallOrderService callOrderService, @NonNull final DocumentChangeHandler_Order orderDocumentChangeHandler) { this.callOrderService = callOrderService; this.orderDocumentChangeHandler = orderDocumentChangeHandler; } @DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE }) public void handleComplete(final I_C_Order order) { if (callOrderService.isCallOrder(OrderId.ofRepoId(order.getC_Order_ID()))) { orderDocumentChangeHandler.onComplete(order); } else { handleOrderComplete(order); } }
@DocValidate(timings = { ModelValidator.TIMING_AFTER_REACTIVATE }) public void handleReactivate(final I_C_Order order) { orderDocumentChangeHandler.onReactivate(order); } private void handleOrderComplete(@NonNull final I_C_Order order) { orderDAO.retrieveOrderLines(order, I_C_OrderLine.class) .stream() .filter(ol -> ol.getC_Flatrate_Conditions_ID() > 0) .forEach(callOrderService::createCallOrderContractIfRequired); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\interceptor\C_Order.java
2
请完成以下Java代码
public final class AuthorizationObservationConvention implements ObservationConvention<AuthorizationObservationContext<?>> { static final String OBSERVATION_NAME = "spring.security.authorizations"; /** * {@inheritDoc} */ @Override public String getName() { return OBSERVATION_NAME; } @Override public String getContextualName(AuthorizationObservationContext<?> context) { return "authorize " + getObjectType(context); } /** * {@inheritDoc} */ @Override public KeyValues getLowCardinalityKeyValues(AuthorizationObservationContext<?> context) { return KeyValues.of("spring.security.authentication.type", getAuthenticationType(context)) .and("spring.security.object", getObjectType(context)) .and("spring.security.authorization.decision", getAuthorizationDecision(context)); } /** * {@inheritDoc} */ @Override public KeyValues getHighCardinalityKeyValues(AuthorizationObservationContext<?> context) { return KeyValues.of("spring.security.authentication.authorities", getAuthorities(context)) .and("spring.security.authorization.decision.details", getDecisionDetails(context)); } @Override public boolean supportsContext(Observation.Context context) { return context instanceof AuthorizationObservationContext<?>; } private String getAuthenticationType(AuthorizationObservationContext<?> context) { if (context.getAuthentication() == null) { return "n/a"; } return context.getAuthentication().getClass().getSimpleName(); } private String getObjectType(AuthorizationObservationContext<?> context) { if (context.getObject() == null) { return "unknown"; } if (context.getObject() instanceof MethodInvocation) { return "method"; }
String className = context.getObject().getClass().getSimpleName(); if (className.contains("Method")) { return "method"; } if (className.contains("Request")) { return "request"; } if (className.contains("Message")) { return "message"; } if (className.contains("Exchange")) { return "exchange"; } return className; } private String getAuthorizationDecision(AuthorizationObservationContext<?> context) { if (context.getAuthorizationResult() == null) { return "unknown"; } return String.valueOf(context.getAuthorizationResult().isGranted()); } private String getAuthorities(AuthorizationObservationContext<?> context) { if (context.getAuthentication() == null) { return "n/a"; } return String.valueOf(context.getAuthentication().getAuthorities()); } private String getDecisionDetails(AuthorizationObservationContext<?> context) { if (context.getAuthorizationResult() == null) { return "unknown"; } AuthorizationResult decision = context.getAuthorizationResult(); return String.valueOf(decision); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\AuthorizationObservationConvention.java
1
请在Spring Boot框架中完成以下Java代码
public class CourseRegistration { @Id @Column(name = "id") private Long id; @ManyToOne @JoinColumn(name = "student_id") private Student student; @ManyToOne @JoinColumn(name = "course_id") private Course course; @Column(name = "registered_at") private LocalDateTime registeredAt; @Column(name = "grade") private int grade; // additional properties public CourseRegistration() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } public LocalDateTime getRegisteredAt() { return registeredAt; } public void setRegisteredAt(LocalDateTime registeredAt) { this.registeredAt = registeredAt; } public int getGrade() { return grade; }
public void setGrade(int grade) { this.grade = grade; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CourseRegistration other = (CourseRegistration) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\manytomany\model\CourseRegistration.java
2
请完成以下Java代码
public class PosTable extends MiniTable { /** * */ private static final long serialVersionUID = 7884238751207398699L; public PosTable() { super(); setRowSelectionAllowed(true); setColumnSelectionAllowed(false); setMultiSelection(false); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setRowHeight(30); setAutoResize(false);
} public void growScrollbars() { // fatter scroll bars Container p = getParent(); if (p instanceof JViewport) { Container gp = p.getParent(); if (gp instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane) gp; scrollPane.getVerticalScrollBar().setPreferredSize(new Dimension(30,0)); scrollPane.getHorizontalScrollBar().setPreferredSize(new Dimension(0,30)); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\pos\PosTable.java
1
请完成以下Java代码
public void resetRefundValue(@NonNull final I_C_Flatrate_RefundConfig configRecord) { final String refundBase = configRecord.getRefundBase(); if (X_C_Flatrate_RefundConfig.REFUNDBASE_Percentage.equals(refundBase)) { configRecord.setRefundAmt(null); } else if (X_C_Flatrate_RefundConfig.REFUNDBASE_Amount.equals(refundBase)) { configRecord.setRefundPercent(null); } else { Check.fail("Unsupported C_Flatrate_RefundConfig.RefundBase value={}; configRecord={}", refundBase, configRecord); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void assertValid(@NonNull final I_C_Flatrate_RefundConfig configRecord) { if (configRecord.getC_Flatrate_Conditions_ID() <= 0) { return; }
final RefundConfigQuery query = RefundConfigQuery .builder() .conditionsId(ConditionsId.ofRepoId(configRecord.getC_Flatrate_Conditions_ID())) .build(); final List<RefundConfig> existingRefundConfigs = refundConfigRepository.getByQuery(query); final RefundConfig newRefundConfig = refundConfigRepository.ofRecord(configRecord); final ArrayList<RefundConfig> allRefundConfigs = new ArrayList<>(existingRefundConfigs); allRefundConfigs.add(newRefundConfig); RefundConfigs.assertValid(allRefundConfigs); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\interceptor\C_Flatrate_RefundConfig.java
1
请完成以下Java代码
public class RestrictedPersonIdentificationSEPA { @XmlElement(name = "Id", required = true) protected String id; @XmlElement(name = "SchmeNm", required = true) protected RestrictedPersonIdentificationSchemeNameSEPA schmeNm; /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) {
this.id = value; } /** * Gets the value of the schmeNm property. * * @return * possible object is * {@link RestrictedPersonIdentificationSchemeNameSEPA } * */ public RestrictedPersonIdentificationSchemeNameSEPA getSchmeNm() { return schmeNm; } /** * Sets the value of the schmeNm property. * * @param value * allowed object is * {@link RestrictedPersonIdentificationSchemeNameSEPA } * */ public void setSchmeNm(RestrictedPersonIdentificationSchemeNameSEPA value) { this.schmeNm = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\RestrictedPersonIdentificationSEPA.java
1
请在Spring Boot框架中完成以下Java代码
public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getQualifierDelimiter() { return this.qualifierDelimiter; } public void setQualifierDelimiter(String qualifierDelimiter) { this.qualifierDelimiter = qualifierDelimiter; } public int getDefaultPageSize() { return this.defaultPageSize; } public void setDefaultPageSize(int defaultPageSize) { this.defaultPageSize = defaultPageSize; } public int getMaxPageSize() { return this.maxPageSize; } public void setMaxPageSize(int maxPageSize) { this.maxPageSize = maxPageSize; } public PageSerializationMode getSerializationMode() { return this.serializationMode;
} public void setSerializationMode(PageSerializationMode serializationMode) { this.serializationMode = serializationMode; } } /** * Sort properties. */ public static class Sort { /** * Sort parameter name. */ private String sortParameter = "sort"; public String getSortParameter() { return this.sortParameter; } public void setSortParameter(String sortParameter) { this.sortParameter = sortParameter; } } }
repos\spring-boot-4.0.1\module\spring-boot-data-commons\src\main\java\org\springframework\boot\data\autoconfigure\web\DataWebProperties.java
2
请在Spring Boot框架中完成以下Java代码
public SecurityContextConfigurer<H> requireExplicitSave(boolean requireExplicitSave) { this.requireExplicitSave = requireExplicitSave; return this; } boolean isRequireExplicitSave() { return this.requireExplicitSave; } SecurityContextRepository getSecurityContextRepository() { SecurityContextRepository securityContextRepository = getBuilder() .getSharedObject(SecurityContextRepository.class); if (securityContextRepository == null) { securityContextRepository = new DelegatingSecurityContextRepository( new RequestAttributeSecurityContextRepository(), new HttpSessionSecurityContextRepository()); } return securityContextRepository; } @Override @SuppressWarnings("unchecked") public void configure(H http) { SecurityContextRepository securityContextRepository = getSecurityContextRepository(); if (this.requireExplicitSave) {
SecurityContextHolderFilter securityContextHolderFilter = postProcess( new SecurityContextHolderFilter(securityContextRepository)); securityContextHolderFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy()); http.addFilter(securityContextHolderFilter); } else { SecurityContextPersistenceFilter securityContextFilter = new SecurityContextPersistenceFilter( securityContextRepository); securityContextFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy()); SessionManagementConfigurer<?> sessionManagement = http.getConfigurer(SessionManagementConfigurer.class); SessionCreationPolicy sessionCreationPolicy = (sessionManagement != null) ? sessionManagement.getSessionCreationPolicy() : null; if (SessionCreationPolicy.ALWAYS == sessionCreationPolicy) { securityContextFilter.setForceEagerSessionCreation(true); http.addFilter(postProcess(new ForceEagerSessionCreationFilter())); } securityContextFilter = postProcess(securityContextFilter); http.addFilter(securityContextFilter); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\SecurityContextConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
public int getC_Project_Repair_Consumption_Summary_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_Repair_Consumption_Summary_ID); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); }
@Override public void setQtyConsumed (final BigDecimal QtyConsumed) { set_Value (COLUMNNAME_QtyConsumed, QtyConsumed); } @Override public BigDecimal getQtyConsumed() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyConsumed); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReserved (final BigDecimal QtyReserved) { set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_Consumption_Summary.java
2
请完成以下Java代码
public AuthenticationResult extractAuthenticatedUser(HttpServletRequest request, ProcessEngine engine) { String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION); if (authorizationHeader != null && authorizationHeader.startsWith(BASIC_AUTH_HEADER_PREFIX)) { String encodedCredentials = authorizationHeader.substring(BASIC_AUTH_HEADER_PREFIX.length()); String decodedCredentials = new String(Base64.decodeBase64(encodedCredentials)); int firstColonIndex = decodedCredentials.indexOf(":"); if (firstColonIndex == -1) { return AuthenticationResult.unsuccessful(); } else { String userName = decodedCredentials.substring(0, firstColonIndex); String password = decodedCredentials.substring(firstColonIndex + 1); if (isAuthenticated(engine, userName, password)) { return AuthenticationResult.successful(userName); } else { return AuthenticationResult.unsuccessful(userName); }
} } else { return AuthenticationResult.unsuccessful(); } } protected boolean isAuthenticated(ProcessEngine engine, String userName, String password) { return engine.getIdentityService().checkPassword(userName, password); } @Override public void augmentResponseByAuthenticationChallenge( HttpServletResponse response, ProcessEngine engine) { response.setHeader(HttpHeaders.WWW_AUTHENTICATE, BASIC_AUTH_HEADER_PREFIX + "realm=\"" + engine.getName() + "\""); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\security\auth\impl\HttpBasicAuthenticationProvider.java
1
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_B_TopicCategory[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Topic Category. @param B_TopicCategory_ID Auction Topic Category */ public void setB_TopicCategory_ID (int B_TopicCategory_ID) { if (B_TopicCategory_ID < 1) set_ValueNoCheck (COLUMNNAME_B_TopicCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_B_TopicCategory_ID, Integer.valueOf(B_TopicCategory_ID)); } /** Get Topic Category. @return Auction Topic Category */ public int getB_TopicCategory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_B_TopicCategory_ID); if (ii == null) return 0; return ii.intValue(); } public I_B_TopicType getB_TopicType() throws RuntimeException { return (I_B_TopicType)MTable.get(getCtx(), I_B_TopicType.Table_Name) .getPO(getB_TopicType_ID(), get_TrxName()); } /** Set Topic Type. @param B_TopicType_ID Auction Topic Type */ public void setB_TopicType_ID (int B_TopicType_ID) { if (B_TopicType_ID < 1) set_ValueNoCheck (COLUMNNAME_B_TopicType_ID, null); else set_ValueNoCheck (COLUMNNAME_B_TopicType_ID, Integer.valueOf(B_TopicType_ID)); } /** Get Topic Type. @return Auction Topic Type */ public int getB_TopicType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_B_TopicType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description)
{ set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_TopicCategory.java
1
请完成以下Java代码
public ActiveOrHistoricCurrencyAndAmount getAmt() { return amt; } /** * Sets the value of the amt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setAmt(ActiveOrHistoricCurrencyAndAmount value) { this.amt = value; } /** * Gets the value of the cdtDbtInd property. * * @return * possible object is * {@link CreditDebitCode } * */ public CreditDebitCode getCdtDbtInd() { return cdtDbtInd; } /** * Sets the value of the cdtDbtInd property. * * @param value * allowed object is * {@link CreditDebitCode } * */ public void setCdtDbtInd(CreditDebitCode value) { this.cdtDbtInd = value; } /** * Gets the value of the rsn property. * * @return * possible object is * {@link String } * */ public String getRsn() { return rsn; } /** * Sets the value of the rsn property. * * @param value * allowed object is * {@link String } * */ public void setRsn(String value) { this.rsn = value;
} /** * Gets the value of the addtlInf property. * * @return * possible object is * {@link String } * */ public String getAddtlInf() { return addtlInf; } /** * Sets the value of the addtlInf property. * * @param value * allowed object is * {@link String } * */ public void setAddtlInf(String value) { this.addtlInf = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\DocumentAdjustment1.java
1
请在Spring Boot框架中完成以下Java代码
private void setMimeMappings(WebServerFactory server) { if (server instanceof ConfigurableServletWebServerFactory) { MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT); // IE issue, see https://github.com/jhipster/generator-jhipster/pull/711 mappings.add("html", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase()); // CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64 mappings.add("json", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase()); ConfigurableServletWebServerFactory servletWebServer = (ConfigurableServletWebServerFactory) server; servletWebServer.setMimeMappings(mappings); } } /** * Initializes Metrics. */ private void initMetrics(ServletContext servletContext, EnumSet<DispatcherType> disps) { log.debug("Initializing Metrics registries"); servletContext.setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, metricRegistry); servletContext.setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry); log.debug("Registering Metrics Filter"); FilterRegistration.Dynamic metricsFilter = servletContext.addFilter("webappMetricsFilter", new InstrumentedFilter()); metricsFilter.addMappingForUrlPatterns(disps, true, "/*"); metricsFilter.setAsyncSupported(true); log.debug("Registering Metrics Servlet"); ServletRegistration.Dynamic metricsAdminServlet = servletContext.addServlet("metricsServlet", new MetricsServlet()); metricsAdminServlet.addMapping("/management/metrics/*"); metricsAdminServlet.setAsyncSupported(true); metricsAdminServlet.setLoadOnStartup(2); } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter");
source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } /** * Initializes H2 console. */ private void initH2Console(ServletContext servletContext) { log.debug("Initialize H2 console"); H2ConfigurationHelper.initH2Console(servletContext); } @Autowired(required = false) public void setMetricRegistry(MetricRegistry metricRegistry) { this.metricRegistry = metricRegistry; } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\config\WebConfigurer.java
2
请完成以下Java代码
public String getFoosWithHeaders() { return "Get some Foos with Header"; } // @RequestMapping(value = "/foos", method = RequestMethod.GET, headers = "Accept=application/json") // @ResponseBody // public String getFoosAsJsonFromBrowser() { // return "Get some Foos with Header Old"; // } @RequestMapping(value = "/foos", produces = { "application/json", "application/xml" }) @ResponseBody public String getFoosAsJsonFromREST() { return "Get some Foos with Header New"; } // advanced - multiple mappings @RequestMapping(value = { "/advanced/bars", "/advanced/foos" }) @ResponseBody public String getFoosOrBarsByPath() { return "Advanced - Get some Foos or Bars"; } @RequestMapping(value = "*") @ResponseBody public String getFallback() { return "Fallback for GET Requests"; } @RequestMapping(value = "*", method = { RequestMethod.GET, RequestMethod.POST }) @ResponseBody public String allFallback() { return "Fallback for All Requests"; } @RequestMapping(value = "/foos/multiple", method = { RequestMethod.PUT, RequestMethod.POST }) @ResponseBody public String putAndPostFoos() { return "Advanced - PUT and POST within single method"; }
// --- Ambiguous Mapping @GetMapping(value = "foos/duplicate" ) public ResponseEntity<String> duplicate() { return new ResponseEntity<>("Duplicate", HttpStatus.OK); } // uncomment for exception of type java.lang.IllegalStateException: Ambiguous mapping // @GetMapping(value = "foos/duplicate" ) // public String duplicateEx() { // return "Duplicate"; // } @GetMapping(value = "foos/duplicate", produces = MediaType.APPLICATION_XML_VALUE) public ResponseEntity<String> duplicateXml() { return new ResponseEntity<>("<message>Duplicate</message>", HttpStatus.OK); } @GetMapping(value = "foos/duplicate", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> duplicateJson() { return new ResponseEntity<>("{\"message\":\"Duplicate\"}", HttpStatus.OK); } }
repos\tutorials-master\spring-web-modules\spring-rest-http\src\main\java\com\baeldung\requestmapping\FooMappingExamplesController.java
1
请完成以下Java代码
public PersonIdentificationSchemeName1Choice getSchmeNm() { return schmeNm; } /** * Sets the value of the schmeNm property. * * @param value * allowed object is * {@link PersonIdentificationSchemeName1Choice } * */ public void setSchmeNm(PersonIdentificationSchemeName1Choice value) { this.schmeNm = value; } /** * Gets the value of the issr property. * * @return * possible object is * {@link String }
* */ public String getIssr() { return issr; } /** * Sets the value of the issr property. * * @param value * allowed object is * {@link String } * */ public void setIssr(String value) { this.issr = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\GenericPersonIdentification1.java
1
请在Spring Boot框架中完成以下Java代码
public String getRedisNamespace() { return this.redisNamespace; } public SaveMode getSaveMode() { return this.saveMode; } public SessionIdGenerator getSessionIdGenerator() { return this.sessionIdGenerator; } public RedisSerializer<Object> getDefaultRedisSerializer() { return this.defaultRedisSerializer; } @Autowired public void setRedisConnectionFactory( @SpringSessionRedisConnectionFactory ObjectProvider<ReactiveRedisConnectionFactory> springSessionRedisConnectionFactory, ObjectProvider<ReactiveRedisConnectionFactory> redisConnectionFactory) { ReactiveRedisConnectionFactory redisConnectionFactoryToUse = springSessionRedisConnectionFactory .getIfAvailable(); if (redisConnectionFactoryToUse == null) { redisConnectionFactoryToUse = redisConnectionFactory.getObject(); } this.redisConnectionFactory = redisConnectionFactoryToUse; } @Autowired(required = false) @Qualifier("springSessionDefaultRedisSerializer") public void setDefaultRedisSerializer(RedisSerializer<Object> defaultRedisSerializer) { this.defaultRedisSerializer = defaultRedisSerializer; }
@Autowired(required = false) public void setSessionRepositoryCustomizer( ObjectProvider<ReactiveSessionRepositoryCustomizer<T>> sessionRepositoryCustomizers) { this.sessionRepositoryCustomizers = sessionRepositoryCustomizers.orderedStream().collect(Collectors.toList()); } protected List<ReactiveSessionRepositoryCustomizer<T>> getSessionRepositoryCustomizers() { return this.sessionRepositoryCustomizers; } protected ReactiveRedisTemplate<String, Object> createReactiveRedisTemplate() { RedisSerializer<String> keySerializer = RedisSerializer.string(); RedisSerializer<Object> defaultSerializer = (this.defaultRedisSerializer != null) ? this.defaultRedisSerializer : new JdkSerializationRedisSerializer(); RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext .<String, Object>newSerializationContext(defaultSerializer) .key(keySerializer) .hashKey(keySerializer) .build(); return new ReactiveRedisTemplate<>(this.redisConnectionFactory, serializationContext); } public ReactiveRedisConnectionFactory getRedisConnectionFactory() { return this.redisConnectionFactory; } @Autowired(required = false) public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) { this.sessionIdGenerator = sessionIdGenerator; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\server\AbstractRedisWebSessionConfiguration.java
2
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { final List<ProductsToPickRow> selectedRows = getSelectedRows(); if (selectedRows.isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal(); } if (!selectedRows.stream().allMatch(ProductsToPickRow::isEligibleForRejectPicking)) { return ProcessPreconditionsResolution.rejectWithInternalReason("select only rows that can be picked"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { getSelectedRows() .stream() .filter(ProductsToPickRow::isEligibleForRejectPicking) .forEach(this::markAsWillNotPick);
invalidateView(); return MSG_OK; } private void markAsWillNotPick(final ProductsToPickRow row) { final RejectPickingResult result = pickingCandidatesService.rejectPicking(RejectPickingRequest.builder() .shipmentScheduleId(row.getShipmentScheduleId()) .qtyToReject(row.getQtyEffective()) .rejectPickingFromHuId(row.getPickFromHUId()) .existingPickingCandidateId(row.getPickingCandidateId()) .build()); updateViewRowFromPickingCandidate(row.getId(), result.getPickingCandidate()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\process\ProductsToPick_MarkWillNotPickSelected.java
1
请完成以下Java代码
public java.lang.String getIsDirectPrint () { return (java.lang.String)get_Value(COLUMNNAME_IsDirectPrint); } /** Set Letzte Seiten. @param LastPages Letzte Seiten */ @Override public void setLastPages (int LastPages) { set_Value (COLUMNNAME_LastPages, Integer.valueOf(LastPages)); } /** Get Letzte Seiten. @return Letzte Seiten */ @Override public int getLastPages () { Integer ii = (Integer)get_Value(COLUMNNAME_LastPages); if (ii == null) return 0; return ii.intValue(); }
/** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_PrinterRouting.java
1
请在Spring Boot框架中完成以下Java代码
public List<PlanningQuantityType> getPlanningQuantity() { if (planningQuantity == null) { planningQuantity = new ArrayList<PlanningQuantityType>(); } return this.planningQuantity; } /** * Gets the value of the forecastListLineItemExtension property. * * @return * possible object is * {@link ForecastListLineItemExtensionType } * */ public ForecastListLineItemExtensionType getForecastListLineItemExtension() {
return forecastListLineItemExtension; } /** * Sets the value of the forecastListLineItemExtension property. * * @param value * allowed object is * {@link ForecastListLineItemExtensionType } * */ public void setForecastListLineItemExtension(ForecastListLineItemExtensionType value) { this.forecastListLineItemExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ForecastListLineItemType.java
2
请在Spring Boot框架中完成以下Java代码
public ReturnT<String> clearLog(int jobGroup, int jobId, int type){ Date clearBeforeTime = null; int clearBeforeNum = 0; if (type == 1) { clearBeforeTime = DateUtil.addMonths(new Date(), -1); // 清理一个月之前日志数据 } else if (type == 2) { clearBeforeTime = DateUtil.addMonths(new Date(), -3); // 清理三个月之前日志数据 } else if (type == 3) { clearBeforeTime = DateUtil.addMonths(new Date(), -6); // 清理六个月之前日志数据 } else if (type == 4) { clearBeforeTime = DateUtil.addYears(new Date(), -1); // 清理一年之前日志数据 } else if (type == 5) { clearBeforeNum = 1000; // 清理一千条以前日志数据 } else if (type == 6) { clearBeforeNum = 10000; // 清理一万条以前日志数据 } else if (type == 7) { clearBeforeNum = 30000; // 清理三万条以前日志数据 } else if (type == 8) { clearBeforeNum = 100000; // 清理十万条以前日志数据
} else if (type == 9) { clearBeforeNum = 0; // 清理所有日志数据 } else { return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("joblog_clean_type_unvalid")); } List<Long> logIds = null; do { logIds = xxlJobLogDao.findClearLogIds(jobGroup, jobId, clearBeforeTime, clearBeforeNum, 1000); if (logIds!=null && logIds.size()>0) { xxlJobLogDao.clearLog(logIds); } } while (logIds!=null && logIds.size()>0); return ReturnT.SUCCESS; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\JobLogController.java
2
请在Spring Boot框架中完成以下Java代码
public class WebConfigurer implements WebMvcConfigurer { @Autowired private RequestMappingHandlerAdapter requestMappingHandlerAdapter; @PostConstruct public void init() { // 获取当前 RequestMappingHandlerAdapter 所有的 ArgumentResolver对象 List<HandlerMethodArgumentResolver> argumentResolvers = requestMappingHandlerAdapter.getArgumentResolvers(); List<HandlerMethodArgumentResolver> newArgumentResolvers = new ArrayList<>(argumentResolvers.size() + 1); // 添加 PropertiesHandlerMethodArgumentResolver 到集合第一个位置 newArgumentResolvers.add(0, new PropertiesHandlerMethodArgumentResolver()); // 将原 ArgumentResolver 添加到集合中 newArgumentResolvers.addAll(argumentResolvers); // 重新设置 ArgumentResolver对象集合 requestMappingHandlerAdapter.setArgumentResolvers(newArgumentResolvers);
// 获取当前 RequestMappingHandlerAdapter 所有的 returnValueHandlers对象 List<HandlerMethodReturnValueHandler> returnValueHandlers = requestMappingHandlerAdapter.getReturnValueHandlers(); List<HandlerMethodReturnValueHandler> newReturnValueHandlers = new ArrayList<>(returnValueHandlers.size() + 1); // 添加 PropertiesHandlerMethodReturnValueHandler 到集合第一个位置 newReturnValueHandlers.add(0, new PropertiesHandlerMethodReturnValueHandler()); // 将原 returnValueHandlers 添加到集合中 newReturnValueHandlers.addAll(returnValueHandlers); // 重新设置 ReturnValueHandlers对象集合 requestMappingHandlerAdapter.setReturnValueHandlers(newReturnValueHandlers); } public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { // converters.add(new PropertiesHttpMessageConverter()); // 指定顺序,这里为第一个 converters.add(0, new PropertiesHttpMessageConverter()); } }
repos\SpringAll-master\47.Spring-Boot-Content-Negotiation\src\main\java\com\example\demo\config\WebConfigurer.java
2
请完成以下Java代码
public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } public I_M_PriceList getM_PriceList() throws RuntimeException { return (I_M_PriceList)MTable.get(getCtx(), I_M_PriceList.Table_Name) .getPO(getM_PriceList_ID(), get_TrxName()); } /** Set Price List. @param M_PriceList_ID Unique identifier of a Price List */ public void setM_PriceList_ID (int M_PriceList_ID) { if (M_PriceList_ID < 1) set_Value (COLUMNNAME_M_PriceList_ID, null); else set_Value (COLUMNNAME_M_PriceList_ID, Integer.valueOf(M_PriceList_ID)); } /** Get Price List. @return Unique identifier of a Price List */ public int getM_PriceList_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PriceList_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_ProductMember() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_ProductMember_ID(), get_TrxName()); } /** Set Membership. @param M_ProductMember_ID Product used to deternine the price of the membership for the topic type */ public void setM_ProductMember_ID (int M_ProductMember_ID)
{ if (M_ProductMember_ID < 1) set_Value (COLUMNNAME_M_ProductMember_ID, null); else set_Value (COLUMNNAME_M_ProductMember_ID, Integer.valueOf(M_ProductMember_ID)); } /** Get Membership. @return Product used to deternine the price of the membership for the topic type */ public int getM_ProductMember_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductMember_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_TopicType.java
1
请在Spring Boot框架中完成以下Java代码
public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search") String search) { MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder(); if (search != null) { Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); Matcher matcher = pattern.matcher(search + ","); while (matcher.find()) { builder.with(matcher.group(1), matcher.group(2), matcher.group(3)); } } BooleanExpression exp = builder.build(); return myUserRepository.findAll(exp); } @RequestMapping(method = RequestMethod.GET, value = "/users/rsql") @ResponseBody public List<User> findAllByRsql(@RequestParam(value = "search") String search) { Node rootNode = new RSQLParser().parse(search); Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>()); return dao.findAll(spec); } @RequestMapping(method = RequestMethod.GET, value = "/api/myusers")
@ResponseBody public Iterable<MyUser> findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) Predicate predicate) { return myUserRepository.findAll(predicate); } // API - WRITE @RequestMapping(method = RequestMethod.POST, value = "/users") @ResponseStatus(HttpStatus.CREATED) public void create(@RequestBody User resource) { Preconditions.checkNotNull(resource); dao.save(resource); } @RequestMapping(method = RequestMethod.POST, value = "/myusers") @ResponseStatus(HttpStatus.CREATED) public void addMyUser(@RequestBody MyUser resource) { Preconditions.checkNotNull(resource); myUserRepository.save(resource); } }
repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\web\controller\UserController.java
2
请完成以下Java代码
public void setIsPublicWrite (boolean IsPublicWrite) { set_Value (COLUMNNAME_IsPublicWrite, Boolean.valueOf(IsPublicWrite)); } /** Get Public Write. @return Public can write entries */ public boolean isPublicWrite () { Object oo = get_Value(COLUMNNAME_IsPublicWrite); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Knowldge Type. @param K_Type_ID Knowledge Type */ public void setK_Type_ID (int K_Type_ID) { if (K_Type_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Type_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Type_ID, Integer.valueOf(K_Type_ID)); } /** Get Knowldge Type. @return Knowledge Type */
public int getK_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Type.java
1
请完成以下Java代码
public void setPluFileDestination (final java.lang.String PluFileDestination) { set_Value (COLUMNNAME_PluFileDestination, PluFileDestination); } @Override public java.lang.String getPluFileDestination() { return get_ValueAsString(COLUMNNAME_PluFileDestination); } @Override public void setPluFileLocalFolder (final @Nullable java.lang.String PluFileLocalFolder) { set_Value (COLUMNNAME_PluFileLocalFolder, PluFileLocalFolder); } @Override public java.lang.String getPluFileLocalFolder() { return get_ValueAsString(COLUMNNAME_PluFileLocalFolder); } @Override public void setProduct_BaseFolderName (final String Product_BaseFolderName) { set_Value (COLUMNNAME_Product_BaseFolderName, Product_BaseFolderName); } @Override public String getProduct_BaseFolderName() { return get_ValueAsString(COLUMNNAME_Product_BaseFolderName); } @Override public void setTCP_Host (final String TCP_Host) {
set_Value (COLUMNNAME_TCP_Host, TCP_Host); } @Override public String getTCP_Host() { return get_ValueAsString(COLUMNNAME_TCP_Host); } @Override public void setTCP_PortNumber (final int TCP_PortNumber) { set_Value (COLUMNNAME_TCP_PortNumber, TCP_PortNumber); } @Override public int getTCP_PortNumber() { return get_ValueAsInt(COLUMNNAME_TCP_PortNumber); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl.java
1
请完成以下Java代码
public class X_InvoiceProcessingServiceCompany extends org.compiere.model.PO implements I_InvoiceProcessingServiceCompany, org.compiere.model.I_Persistent { private static final long serialVersionUID = 394872485L; /** Standard Constructor */ public X_InvoiceProcessingServiceCompany (Properties ctx, int InvoiceProcessingServiceCompany_ID, String trxName) { super (ctx, InvoiceProcessingServiceCompany_ID, trxName); } /** Load Constructor */ public X_InvoiceProcessingServiceCompany (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return (java.lang.String)get_Value(COLUMNNAME_Description); } @Override public void setInvoiceProcessingServiceCompany_ID (int InvoiceProcessingServiceCompany_ID) { if (InvoiceProcessingServiceCompany_ID < 1) set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_ID, null); else set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_ID, Integer.valueOf(InvoiceProcessingServiceCompany_ID)); } @Override public int getInvoiceProcessingServiceCompany_ID() { return get_ValueAsInt(COLUMNNAME_InvoiceProcessingServiceCompany_ID); } @Override public void setServiceCompany_BPartner_ID (int ServiceCompany_BPartner_ID) { if (ServiceCompany_BPartner_ID < 1) set_Value (COLUMNNAME_ServiceCompany_BPartner_ID, null);
else set_Value (COLUMNNAME_ServiceCompany_BPartner_ID, Integer.valueOf(ServiceCompany_BPartner_ID)); } @Override public int getServiceCompany_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_ServiceCompany_BPartner_ID); } @Override public void setServiceFee_Product_ID (int ServiceFee_Product_ID) { if (ServiceFee_Product_ID < 1) set_Value (COLUMNNAME_ServiceFee_Product_ID, null); else set_Value (COLUMNNAME_ServiceFee_Product_ID, Integer.valueOf(ServiceFee_Product_ID)); } @Override public int getServiceFee_Product_ID() { return get_ValueAsInt(COLUMNNAME_ServiceFee_Product_ID); } @Override public void setServiceInvoice_DocType_ID (int ServiceInvoice_DocType_ID) { if (ServiceInvoice_DocType_ID < 1) set_Value (COLUMNNAME_ServiceInvoice_DocType_ID, null); else set_Value (COLUMNNAME_ServiceInvoice_DocType_ID, Integer.valueOf(ServiceInvoice_DocType_ID)); } @Override public int getServiceInvoice_DocType_ID() { return get_ValueAsInt(COLUMNNAME_ServiceInvoice_DocType_ID); } @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_InvoiceProcessingServiceCompany.java
1
请完成以下Java代码
public class DeptVO extends Dept implements INode<DeptVO> { @Serial private static final long serialVersionUID = 1L; /** * 主键ID */ @JsonSerialize(using = ToStringSerializer.class) private Long id; /** * 父节点ID */ @JsonSerialize(using = ToStringSerializer.class) private Long parentId; /** * 子孙节点 */
@JsonInclude(JsonInclude.Include.NON_EMPTY) private List<DeptVO> children; @Override public List<DeptVO> getChildren() { if (this.children == null) { this.children = new ArrayList<>(); } return this.children; } /** * 上级部门 */ private String parentName; }
repos\SpringBlade-master\blade-service-api\blade-system-api\src\main\java\org\springblade\system\vo\DeptVO.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public Point getLocation() { return location; } public void setLocation(Point location) { this.location = location; } @Override public int hashCode() { int hash = 1; if (id != null) { hash = hash * 31 + id.hashCode(); } if (name != null) { hash = hash * 31 + name.hashCode(); } if (location != null) { hash = hash * 31 + location.hashCode(); } return hash; } @Override public boolean equals(Object obj) { if ((obj == null) || (obj.getClass() != this.getClass())) return false; if (obj == this) return true; Campus other = (Campus) obj; return this.hashCode() == other.hashCode(); }
@SuppressWarnings("unused") private Campus() { } public Campus(Builder b) { this.id = b.id; this.name = b.name; this.location = b.location; } public static class Builder { private String id; private String name; private Point location; public static Builder newInstance() { return new Builder(); } public Campus build() { return new Campus(this); } public Builder id(String id) { this.id = id; return this; } public Builder name(String name) { this.name = name; return this; } public Builder location(Point location) { this.location = location; return this; } } }
repos\tutorials-master\persistence-modules\spring-data-couchbase-2\src\main\java\com\baeldung\spring\data\couchbase\model\Campus.java
1
请完成以下Java代码
public PInstanceId getAD_PInstance_ID() { return AD_PInstance_ID; } public static final class Builder { private int AD_Session_ID; private String trxName; private int AD_Table_ID; private int AD_Column_ID; private int record_ID; private int AD_Client_ID; private int AD_Org_ID; private Object oldValue; private Object newValue; private String eventType; private int AD_User_ID; private PInstanceId AD_PInstance_ID; private Builder() { super(); } public ChangeLogRecord build() { return new ChangeLogRecord(this); } public Builder setAD_Session_ID(final int AD_Session_ID) { this.AD_Session_ID = AD_Session_ID; return this; } public Builder setTrxName(final String trxName) { this.trxName = trxName; return this; } public Builder setAD_Table_ID(final int AD_Table_ID) { this.AD_Table_ID = AD_Table_ID; return this; } public Builder setAD_Column_ID(final int AD_Column_ID) { this.AD_Column_ID = AD_Column_ID; return this; } public Builder setRecord_ID(final int record_ID) { this.record_ID = record_ID; return this; } public Builder setAD_Client_ID(final int AD_Client_ID) { this.AD_Client_ID = AD_Client_ID; return this; }
public Builder setAD_Org_ID(final int AD_Org_ID) { this.AD_Org_ID = AD_Org_ID; return this; } public Builder setOldValue(final Object oldValue) { this.oldValue = oldValue; return this; } public Builder setNewValue(final Object newValue) { this.newValue = newValue; return this; } public Builder setEventType(final String eventType) { this.eventType = eventType; return this; } public Builder setAD_User_ID(final int AD_User_ID) { this.AD_User_ID = AD_User_ID; return this; } /** * * @param AD_PInstance_ID * @return * @task https://metasfresh.atlassian.net/browse/FRESH-314 */ public Builder setAD_PInstance_ID(final PInstanceId AD_PInstance_ID) { this.AD_PInstance_ID = AD_PInstance_ID; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\session\ChangeLogRecord.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_BPartner_ID (final int C_BPartner_ID) { if (C_BPartner_ID < 1) set_Value (COLUMNNAME_C_BPartner_ID, null); else set_Value (COLUMNNAME_C_BPartner_ID, C_BPartner_ID); } @Override public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } /** * CU_TU_PLU AD_Reference_ID=541906 * Reference name: CU_TU_PLU */ public static final int CU_TU_PLU_AD_Reference_ID=541906; /** CU = CU */ public static final String CU_TU_PLU_CU = "CU"; /** TU = TU */ public static final String CU_TU_PLU_TU = "TU"; @Override public void setCU_TU_PLU (final String CU_TU_PLU) { set_Value (COLUMNNAME_CU_TU_PLU, CU_TU_PLU); } @Override public String getCU_TU_PLU() { return get_ValueAsString(COLUMNNAME_CU_TU_PLU); } @Override public void setExternalSystem_Config_LeichMehl_ProductMapping_ID (final int ExternalSystem_Config_LeichMehl_ProductMapping_ID) { if (ExternalSystem_Config_LeichMehl_ProductMapping_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_LeichMehl_ProductMapping_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_LeichMehl_ProductMapping_ID, ExternalSystem_Config_LeichMehl_ProductMapping_ID); } @Override public int getExternalSystem_Config_LeichMehl_ProductMapping_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_LeichMehl_ProductMapping_ID); } @Override public I_LeichMehl_PluFile_ConfigGroup getLeichMehl_PluFile_ConfigGroup() { return get_ValueAsPO(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, I_LeichMehl_PluFile_ConfigGroup.class); } @Override public void setLeichMehl_PluFile_ConfigGroup(final I_LeichMehl_PluFile_ConfigGroup LeichMehl_PluFile_ConfigGroup) { set_ValueFromPO(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, I_LeichMehl_PluFile_ConfigGroup.class, LeichMehl_PluFile_ConfigGroup); } @Override
public void setLeichMehl_PluFile_ConfigGroup_ID (final int LeichMehl_PluFile_ConfigGroup_ID) { if (LeichMehl_PluFile_ConfigGroup_ID < 1) set_Value (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, null); else set_Value (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, LeichMehl_PluFile_ConfigGroup_ID); } @Override public int getLeichMehl_PluFile_ConfigGroup_ID() { return get_ValueAsInt(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPLU_File (final String PLU_File) { set_Value (COLUMNNAME_PLU_File, PLU_File); } @Override public String getPLU_File() { return get_ValueAsString(COLUMNNAME_PLU_File); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl_ProductMapping.java
1
请完成以下Java代码
public ProcessApplicationReference getReference() { ensureInitialized(); return getEjbProcessApplicationReference(); } @Override protected String autodetectProcessApplicationName() { return lookupEeApplicationName(); } /** allows subclasses to provide a custom business interface */ protected Class<? extends ProcessApplicationInterface> getBusinessInterface() { return ProcessApplicationInterface.class; } @Override public <T> T execute(Callable<T> callable) throws ProcessApplicationExecutionException { ClassLoader originalClassloader = ClassLoaderUtil.getContextClassloader(); ClassLoader processApplicationClassloader = getProcessApplicationClassloader(); try { if (originalClassloader != processApplicationClassloader) { ClassLoaderUtil.setContextClassloader(processApplicationClassloader); } return callable.call(); } catch(Exception e) { throw LOG.processApplicationExecutionException(e); } finally { ClassLoaderUtil.setContextClassloader(originalClassloader); } } protected void ensureInitialized() { if(selfReference == null) { selfReference = lookupSelfReference(); } ensureEjbProcessApplicationReferenceInitialized(); } protected abstract void ensureEjbProcessApplicationReferenceInitialized();
protected abstract ProcessApplicationReference getEjbProcessApplicationReference(); /** * lookup a proxy object representing the invoked business view of this component. */ protected abstract ProcessApplicationInterface lookupSelfReference(); /** * determine the ee application name based on information obtained from JNDI. */ protected String lookupEeApplicationName() { try { InitialContext initialContext = new InitialContext(); String appName = (String) initialContext.lookup(JAVA_APP_APP_NAME_PATH); String moduleName = (String) initialContext.lookup(MODULE_NAME_PATH); // make sure that if an EAR carries multiple PAs, they are correctly // identified by appName + moduleName if (moduleName != null && !moduleName.equals(appName)) { return appName + "/" + moduleName; } else { return appName; } } catch (NamingException e) { throw LOG.ejbPaCannotAutodetectName(e); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\AbstractEjbProcessApplication.java
1
请完成以下Java代码
public void setRelatedProduct_ID (int RelatedProduct_ID) { if (RelatedProduct_ID < 1) set_ValueNoCheck (COLUMNNAME_RelatedProduct_ID, null); else set_ValueNoCheck (COLUMNNAME_RelatedProduct_ID, Integer.valueOf(RelatedProduct_ID)); } /** Get Related Product. @return Related Product */ public int getRelatedProduct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_RelatedProduct_ID); if (ii == null) return 0; return ii.intValue(); } /** RelatedProductType AD_Reference_ID=313 */ public static final int RELATEDPRODUCTTYPE_AD_Reference_ID=313; /** Web Promotion = P */ public static final String RELATEDPRODUCTTYPE_WebPromotion = "P"; /** Alternative = A */ public static final String RELATEDPRODUCTTYPE_Alternative = "A";
/** Supplemental = S */ public static final String RELATEDPRODUCTTYPE_Supplemental = "S"; /** Set Related Product Type. @param RelatedProductType Related Product Type */ public void setRelatedProductType (String RelatedProductType) { set_ValueNoCheck (COLUMNNAME_RelatedProductType, RelatedProductType); } /** Get Related Product Type. @return Related Product Type */ public String getRelatedProductType () { return (String)get_Value(COLUMNNAME_RelatedProductType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_RelatedProduct.java
1
请完成以下Java代码
protected String doIt() throws Exception { final PartitionConfig config = dlmService.loadPartitionConfig(configDB); final List<TableRecordIdDescriptor> tableRecordReferences = Services.get(ITableRecordIdDAO.class).retrieveAllTableRecordIdReferences(); // get those descriptors whose referencedTableName is the table name of at least one line final List<TableRecordIdDescriptor> descriptors = retainRelevantDescriptors(config, tableRecordReferences); final PartitionConfig augmentedConfig = partitionerService.augmentPartitionerConfig(config, descriptors); dlmService.storePartitionConfig(augmentedConfig); return MSG_OK; } /**
* From the given <code>descriptors</code> list, return those ones that reference of the lines of the given <code>config</code>. * * @param config * @param tableRecordReferences * @return */ @VisibleForTesting /* package */ List<TableRecordIdDescriptor> retainRelevantDescriptors(final PartitionConfig config, final List<TableRecordIdDescriptor> descriptors) { return descriptors.stream() .filter(r -> config.getLine(r.getTargetTableName()).isPresent()) .collect(Collectors.toList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\process\DLM_Partition_Config_Add_TableRecord_Lines.java
1
请完成以下Java代码
public java.math.BigDecimal getDivideRate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DivideRate); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Ziel ist Catch-Maßeinheit. @param IsCatchUOMForProduct Legt fest ob die Ziel-Maßeinheit die Parallel-Maßeinheit des Produktes ist, auf die bei einer Catch-Weight-Abrechnung zurückgegriffen wird */ @Override public void setIsCatchUOMForProduct (boolean IsCatchUOMForProduct) { set_Value (COLUMNNAME_IsCatchUOMForProduct, Boolean.valueOf(IsCatchUOMForProduct)); } /** Get Ziel ist Catch-Maßeinheit. @return Legt fest ob die Ziel-Maßeinheit die Parallel-Maßeinheit des Produktes ist, auf die bei einer Catch-Weight-Abrechnung zurückgegriffen wird */ @Override public boolean isCatchUOMForProduct () { Object oo = get_Value(COLUMNNAME_IsCatchUOMForProduct); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt.
@return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Faktor. @param MultiplyRate Rate to multiple the source by to calculate the target. */ @Override public void setMultiplyRate (java.math.BigDecimal MultiplyRate) { set_Value (COLUMNNAME_MultiplyRate, MultiplyRate); } /** Get Faktor. @return Rate to multiple the source by to calculate the target. */ @Override public java.math.BigDecimal getMultiplyRate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MultiplyRate); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_UOM_Conversion.java
1
请完成以下Java代码
public void validateInactivation(@NonNull final I_C_DocType_Invoicing_Pool docTypeInvoicingPoolRecord) { if (docTypeInvoicingPoolRecord.isActive()) { return; } final ImmutableSet<DocTypeId> referencingDocTypeIds = docTypeBL .getDocTypeIdsByInvoicingPoolId(DocTypeInvoicingPoolId.ofRepoId(docTypeInvoicingPoolRecord.getC_DocType_Invoicing_Pool_ID())); if (!referencingDocTypeIds.isEmpty()) { throw new AdempiereException(MSG_REFERENCED_INVOICING_POOL) .markAsUserValidationError() .appendParametersToMessage() .setParameter("DocTypeIds", referencingDocTypeIds) .setParameter("DocTypeInvoicingPoolId", docTypeInvoicingPoolRecord.getC_DocType_Invoicing_Pool_ID()); } } private void validatePositiveAmountDocType(@NonNull final I_C_DocType_Invoicing_Pool docTypeInvoicingPoolRecord) { final DocTypeId positiveAmountDocTypeId = DocTypeId.ofRepoId(docTypeInvoicingPoolRecord.getPositive_Amt_C_DocType_ID()); validateDocType(positiveAmountDocTypeId, docTypeInvoicingPoolRecord); }
private void validateNegativeAmountDocType(@NonNull final I_C_DocType_Invoicing_Pool docTypeInvoicingPoolRecord) { final DocTypeId negativeAmountDocTypeId = DocTypeId.ofRepoId(docTypeInvoicingPoolRecord.getNegative_Amt_C_DocType_ID()); validateDocType(negativeAmountDocTypeId, docTypeInvoicingPoolRecord); } private void validateDocType( @NonNull final DocTypeId docTypeId, @NonNull final I_C_DocType_Invoicing_Pool docTypeInvoicingPoolRecord) { final I_C_DocType docTypeRecord = docTypeBL.getById(docTypeId); if (docTypeRecord.isSOTrx() != docTypeInvoicingPoolRecord.isSOTrx()) { throw new AdempiereException(MSG_DIFFERENT_SO_TRX_INVOICING_POOL_DOCUMENT_TYPE) .markAsUserValidationError() .appendParametersToMessage() .setParameter("DocType.Name", docTypeRecord.getName()) .setParameter("DocTypeInvoicingPoolId", docTypeInvoicingPoolRecord.getC_DocType_Invoicing_Pool_ID()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\invoicingpool\C_DocType_Invoicing_Pool.java
1
请完成以下Java代码
public void setCdtDbtInd(CreditDebitCode value) { this.cdtDbtInd = value; } /** * Gets the value of the tp property. * * @return * possible object is * {@link InterestType1Choice } * */ public InterestType1Choice getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link InterestType1Choice } * */ public void setTp(InterestType1Choice value) { this.tp = value; } /** * Gets the value of the rate 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 rate property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRate().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Rate3 } * * */ public List<Rate3> getRate() { if (rate == null) { rate = new ArrayList<Rate3>(); } return this.rate; } /** * Gets the value of the frToDt property. * * @return * possible object is * {@link DateTimePeriodDetails } *
*/ public DateTimePeriodDetails getFrToDt() { return frToDt; } /** * Sets the value of the frToDt property. * * @param value * allowed object is * {@link DateTimePeriodDetails } * */ public void setFrToDt(DateTimePeriodDetails value) { this.frToDt = value; } /** * Gets the value of the rsn property. * * @return * possible object is * {@link String } * */ public String getRsn() { return rsn; } /** * Sets the value of the rsn property. * * @param value * allowed object is * {@link String } * */ public void setRsn(String value) { this.rsn = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TransactionInterest2.java
1
请完成以下Java代码
public static MEXPFormat getFormatByAD_Client_IDAD_Table_IDAndVersion(final Properties ctx, final int AD_Client_ID, final int AD_Table_ID, final String version, final String trxName) { final String key = Services.get(IADTableDAO.class).retrieveTableName(AD_Table_ID) + version; MEXPFormat retValue=null; if(trxName == null) { retValue = s_cache.get(key); } if(retValue!=null) { return retValue; } final List<Object> params = new ArrayList<>(); final StringBuilder whereClause = new StringBuilder(" AD_Client_ID = ? ") .append(" AND ").append(X_EXP_Format.COLUMNNAME_AD_Table_ID).append(" = ? "); params.add(AD_Client_ID); params.add(AD_Table_ID); // metas: tsa: changed to filter by version only if is provided if (!Check.isEmpty(version, true)) { whereClause.append(" AND ").append(X_EXP_Format.COLUMNNAME_Version).append(" = ?"); params.add(version); } retValue = new Query(ctx,X_EXP_Format.Table_Name,whereClause.toString(),trxName) .setParameters(params) .setOrderBy(X_EXP_Format.COLUMNNAME_Version+" DESC") .first(); if(retValue!=null) { retValue.getFormatLines(); if(trxName == null) // metas: tsa: cache only if trxName==null { s_cache.put (key, retValue); exp_format_by_id_cache.put(retValue.getEXP_Format_ID(), retValue); }
} return retValue; } @Override public String toString() { return "MEXPFormat[ID=" + get_ID() + "; Value = " + getValue() + "]"; } /** * Before Delete * @return true of it can be deleted */ @Override protected boolean beforeDelete () { for (final I_EXP_FormatLine line : getFormatLinesOrderedBy(true, null)) { InterfaceWrapperHelper.delete(line); } return true; } // beforeDelete }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MEXPFormat.java
1
请完成以下Java代码
public BigDecimal getQtyTU() { return invoiceLine.getQtyEnteredTU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { invoiceLine.setQtyEnteredTU(qtyPacks); } @Override public void setC_BPartner_ID(final int partnerId) { values.setC_BPartner_ID(partnerId); }
@Override public int getC_BPartner_ID() { return values.getC_BPartner_ID(); } @Override public boolean isInDispute() { return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\InvoiceLineHUPackingAware.java
1
请完成以下Java代码
public class User { int id; String name; Role role = new Role(); public User() { } public User(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } }
repos\tutorials-master\libraries-stream\src\main\java\com\baeldung\streamex\User.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Book other = (Book) obj; if (author == null) { if (other.author != null) return false; } else if (!author.equals(other.author)) return false; if (Double.doubleToLongBits(cost) != Double.doubleToLongBits(other.cost)) return false; if (isbn == null) { if (other.isbn != null)
return false; } else if (!isbn.equals(other.isbn)) return false; if (publisher == null) { if (other.publisher != null) return false; } else if (!publisher.equals(other.publisher)) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; return true; } }
repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\bsontojson\Book.java
1
请完成以下Java代码
public boolean contains(PropertyListKey<?> property) { return properties.containsKey(property.getName()); } /** * Returns <code>true</code> if this properties contains a mapping for the specified property key. * * @param property * the property key whose presence is to be tested * @return <code>true</code> if this properties contains a mapping for the specified property key */ public boolean contains(PropertyMapKey<?, ?> property) { return properties.containsKey(property.getName()); }
/** * Returns a map view of this properties. Changes to the map are not reflected * to the properties. * * @return a map view of this properties */ public Map<String, Object> toMap() { return new HashMap<String, Object>(properties); } @Override public String toString() { return "Properties [properties=" + properties + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\Properties.java
1
请完成以下Java代码
public class DBRes_da extends ListResourceBundle { /** Data */ static final Object[][] contents = new String[][] { { "CConnectionDialog", "Forbindelse" }, { "Name", "Navn" }, { "AppsHost", "Programvært" }, { "AppsPort", "Programport" }, { "TestApps", "Test programserver" }, { "DBHost", "Databasevært" }, { "DBPort", "Databaseport" }, { "DBName", "Databasenavn" }, { "DBUidPwd", "Bruger/adgangskode" }, { "ViaFirewall", "via Firewall" }, { "FWHost", "Firewall-vært" }, { "FWPort", "Firewall-port" }, { "TestConnection", "Test database" }, { "Type", "Databasetype" }, { "BequeathConnection", "Nedarv forbindelse" }, { "Overwrite", "Overskriv" },
{ "ConnectionProfile", "Connection" }, { "LAN", "LAN" }, { "TerminalServer", "Terminal Server" }, { "VPN", "VPN" }, { "WAN", "WAN" }, { "ConnectionError", "Fejl i forbindelse" }, { "ServerNotActive", "Server er ikke aktiv" } }; /** * Get Contsnts * @return contents */ public Object[][] getContents() { return contents; } // getContent } // Res
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\connectiondialog\i18n\DBRes_da.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Prefix. @param Prefix Prefix before the sequence number */ public void setPrefix (String Prefix) { set_Value (COLUMNNAME_Prefix, Prefix); } /** Get Prefix. @return Prefix before the sequence number */ public String getPrefix () { return (String)get_Value(COLUMNNAME_Prefix); } /** 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 Remote Client. @param Remote_Client_ID Remote Client to be used to replicate / synchronize data with. */ public void setRemote_Client_ID (int Remote_Client_ID) { if (Remote_Client_ID < 1) set_ValueNoCheck (COLUMNNAME_Remote_Client_ID, null); else set_ValueNoCheck (COLUMNNAME_Remote_Client_ID, Integer.valueOf(Remote_Client_ID)); } /** Get Remote Client. @return Remote Client to be used to replicate / synchronize data with. */ public int getRemote_Client_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Remote_Client_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Remote Organization. @param Remote_Org_ID Remote Organization to be used to replicate / synchronize data with.
*/ public void setRemote_Org_ID (int Remote_Org_ID) { if (Remote_Org_ID < 1) set_ValueNoCheck (COLUMNNAME_Remote_Org_ID, null); else set_ValueNoCheck (COLUMNNAME_Remote_Org_ID, Integer.valueOf(Remote_Org_ID)); } /** Get Remote Organization. @return Remote Organization to be used to replicate / synchronize data with. */ public int getRemote_Org_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Remote_Org_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Suffix. @param Suffix Suffix after the number */ public void setSuffix (String Suffix) { set_Value (COLUMNNAME_Suffix, Suffix); } /** Get Suffix. @return Suffix after the number */ public String getSuffix () { return (String)get_Value(COLUMNNAME_Suffix); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication.java
1
请完成以下Java代码
public final class FallbackStubFactory implements StubFactory { @Override public boolean isApplicable(final Class<? extends AbstractStub<?>> stubType) { return true; } @Override public AbstractStub<?> createStub(final Class<? extends AbstractStub<?>> stubType, final Channel channel) { try { // Search for public static *Grpc#new*Stub(Channel) final Class<?> declaringClass = stubType.getDeclaringClass(); if (declaringClass != null) { for (final Method method : declaringClass.getMethods()) { final String name = method.getName(); final int modifiers = method.getModifiers(); final Parameter[] parameters = method.getParameters(); if (name.startsWith("new") && name.endsWith("Stub")
&& Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers) && method.getReturnType().isAssignableFrom(stubType) && parameters.length == 1 && Channel.class.equals(parameters[0].getType())) { return AbstractStub.class.cast(method.invoke(null, channel)); } } } // Search for a public constructor *Stub(Channel) final Constructor<? extends AbstractStub<?>> constructor = stubType.getConstructor(Channel.class); return constructor.newInstance(channel); } catch (final Exception e) { throw new BeanInstantiationException(stubType, "Failed to create gRPC client via FallbackStubFactory", e); } } }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\stubfactory\FallbackStubFactory.java
1
请完成以下Java代码
public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } @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(", memberNickName=").append(memberNickName); sb.append(", topicId=").append(topicId); sb.append(", memberIcon=").append(memberIcon); sb.append(", content=").append(content); sb.append(", createTime=").append(createTime); sb.append(", showStatus=").append(showStatus); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsTopicComment.java
1
请完成以下Java代码
public String toString() { return filterToStringCreator(RequestHeaderSizeGatewayFilterFactory.this) .append("maxSize", config.getMaxSize()) .toString(); } }; } private static String getErrorMessage(HashMap<String, Long> longHeaders, DataSize maxSize) { StringBuilder msg = new StringBuilder(String.format(ERROR_PREFIX, maxSize)); longHeaders .forEach((header, size) -> msg.append(String.format(ERROR, header, DataSize.of(size, DataUnit.BYTES)))); return msg.toString(); } public static class Config { private DataSize maxSize = DataSize.ofBytes(16000L); private @Nullable String errorHeaderName; public DataSize getMaxSize() { return maxSize; }
public void setMaxSize(DataSize maxSize) { this.maxSize = maxSize; } public @Nullable String getErrorHeaderName() { return errorHeaderName; } public void setErrorHeaderName(String errorHeaderName) { this.errorHeaderName = errorHeaderName; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RequestHeaderSizeGatewayFilterFactory.java
1
请完成以下Java代码
public void initialize() { if (threadPoolTaskScheduler != null) { threadPoolTaskScheduler.initialize(); } Instant initialInstant = Instant.now().plus(initialDelay); taskScheduler.scheduleWithFixedDelay(createChangeDetectionRunnable(), initialInstant, delay); } protected Runnable createChangeDetectionRunnable() { return new EventRegistryChangeDetectionRunnable(eventRegistryChangeDetectionManager); } @Override public void shutdown() { destroy(); } @Override
public void destroy() { if (threadPoolTaskScheduler != null) { threadPoolTaskScheduler.destroy(); } } public EventRegistryChangeDetectionManager getEventRegistryChangeDetectionManager() { return eventRegistryChangeDetectionManager; } @Override public void setEventRegistryChangeDetectionManager(EventRegistryChangeDetectionManager eventRegistryChangeDetectionManager) { this.eventRegistryChangeDetectionManager = eventRegistryChangeDetectionManager; } public TaskScheduler getTaskScheduler() { return taskScheduler; } public void setTaskScheduler(TaskScheduler taskScheduler) { this.taskScheduler = taskScheduler; } }
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\management\DefaultSpringEventRegistryChangeDetectionExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public AnonymousConfigurer<H> authenticationFilter(AnonymousAuthenticationFilter authenticationFilter) { this.authenticationFilter = authenticationFilter; return this; } @Override public void init(H http) { if (this.authenticationProvider == null) { this.authenticationProvider = new AnonymousAuthenticationProvider(getKey()); } this.authenticationProvider = postProcess(this.authenticationProvider); http.authenticationProvider(this.authenticationProvider); } @Override public void configure(H http) { if (this.authenticationFilter == null) { this.authenticationFilter = new AnonymousAuthenticationFilter(getKey(), this.principal, this.authorities); } this.authenticationFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy()); this.authenticationFilter.afterPropertiesSet(); http.addFilter(this.authenticationFilter);
} private String getKey() { if (this.computedKey != null) { return this.computedKey; } if (this.key == null) { this.computedKey = UUID.randomUUID().toString(); } else { this.computedKey = this.key; } return this.computedKey; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\AnonymousConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
public RegionShortcut getShortcut() { return this.shortcut != null ? this.shortcut : DEFAULT_SERVER_REGION_SHORTCUT; } public void setShortcut(RegionShortcut shortcut) { this.shortcut = shortcut; } } public static class SessionProperties { @NestedConfigurationProperty private final SessionAttributesProperties attributes = new SessionAttributesProperties(); @NestedConfigurationProperty private final SessionExpirationProperties expiration = new SessionExpirationProperties(); @NestedConfigurationProperty private final SessionRegionProperties region = new SessionRegionProperties(); @NestedConfigurationProperty private final SessionSerializerProperties serializer = new SessionSerializerProperties(); public SessionAttributesProperties getAttributes() { return this.attributes; } public SessionExpirationProperties getExpiration() { return this.expiration; } public SessionRegionProperties getRegion() { return this.region; } public SessionSerializerProperties getSerializer() { return this.serializer; } } public static class SessionAttributesProperties { private String[] indexable; public String[] getIndexable() { return this.indexable; } public void setIndexable(String[] indexable) { this.indexable = indexable; } } public static class SessionExpirationProperties { private int maxInactiveIntervalSeconds; public int getMaxInactiveIntervalSeconds() { return this.maxInactiveIntervalSeconds; } public void setMaxInactiveIntervalSeconds(int maxInactiveIntervalSeconds) { this.maxInactiveIntervalSeconds = maxInactiveIntervalSeconds; } public void setMaxInactiveInterval(Duration duration) {
int maxInactiveIntervalInSeconds = duration != null ? Long.valueOf(duration.toSeconds()).intValue() : GemFireHttpSessionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS; setMaxInactiveIntervalSeconds(maxInactiveIntervalInSeconds); } } public static class SessionRegionProperties { private String name; public String getName() { return this.name; } public void setName(String name) { this.name = name; } } public static class SessionSerializerProperties { private String beanName; public String getBeanName() { return this.beanName; } public void setBeanName(String beanName) { this.beanName = beanName; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\SpringSessionProperties.java
2
请完成以下Java代码
public class AlarmInfo extends Alarm { @Serial private static final long serialVersionUID = 2807343093519543363L; @Getter @Setter @Schema(description = "Alarm originator name", example = "Thermostat") private String originatorName; @Getter @Setter @Schema(description = "Alarm originator label", example = "Thermostat label") private String originatorLabel; @Setter @Schema(description = "Originator display name", example = "Thermostat") private String originatorDisplayName; @Getter @Setter @Schema(description = "Alarm assignee") private AlarmAssignee assignee; public AlarmInfo() { super(); } public AlarmInfo(Alarm alarm) { super(alarm); }
public String getOriginatorDisplayName() { return originatorDisplayName != null ? originatorDisplayName : (originatorLabel != null ? originatorLabel : originatorName); } public AlarmInfo(AlarmInfo alarmInfo) { super(alarmInfo); this.originatorName = alarmInfo.getOriginatorName(); this.originatorLabel = alarmInfo.getOriginatorLabel(); this.originatorDisplayName = alarmInfo.getOriginatorDisplayName(); this.assignee = alarmInfo.getAssignee(); } public AlarmInfo(Alarm alarm, String originatorName, String originatorLabel, AlarmAssignee assignee) { super(alarm); this.originatorName = originatorName; this.originatorLabel = originatorLabel; this.assignee = assignee; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\alarm\AlarmInfo.java
1
请完成以下Java代码
public String getComponent() { return component; } public void setComponent(String component) { this.component = component; } public String getComponentName() { return componentName; } public void setComponentName(String componentName) { this.componentName = componentName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Double getSortNo() { return sortNo; } public void setSortNo(Double sortNo) { this.sortNo = sortNo; } public Integer getMenuType() { return menuType; } public void setMenuType(Integer menuType) { this.menuType = menuType; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isRoute() { return route; } public void setRoute(boolean route) { this.route = route; } public Integer getDelFlag() { return delFlag; } public void setDelFlag(Integer delFlag) { this.delFlag = delFlag; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) {
this.updateBy = updateBy; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getPerms() { return perms; } public void setPerms(String perms) { this.perms = perms; } public boolean getIsLeaf() { return isLeaf; } public void setIsLeaf(boolean isLeaf) { this.isLeaf = isLeaf; } public String getPermsType() { return permsType; } public void setPermsType(String permsType) { this.permsType = permsType; } public java.lang.String getStatus() { return status; } public void setStatus(java.lang.String status) { this.status = status; } /*update_begin author:wuxianquan date:20190908 for:get set方法 */ public boolean isInternalOrExternal() { return internalOrExternal; } public void setInternalOrExternal(boolean internalOrExternal) { this.internalOrExternal = internalOrExternal; } /*update_end author:wuxianquan date:20190908 for:get set 方法 */ public boolean isHideTab() { return hideTab; } public void setHideTab(boolean hideTab) { this.hideTab = hideTab; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\SysPermissionTree.java
1
请完成以下Java代码
public class TextManipulator { private String text; public TextManipulator(String text) { this.text = text; } public String getText() { return text; } public void appendText(String newText) { text = text.concat(newText); } public String findWordAndReplace(String word, String replacementWord) { if (text.contains(word)) {
text = text.replace(word, replacementWord); } return text; } public String findWordAndDelete(String word) { if (text.contains(word)) { text = text.replace(word, ""); } return text; } /* * Bad practice when implementing SRP principle, not in the scope of this class public void printText() { System.out.println(textManipulator.getText()); }*/ }
repos\tutorials-master\patterns-modules\solid\src\main\java\com\baeldung\s\TextManipulator.java
1
请完成以下Java代码
public void setIsPrintFunctionSymbols (boolean IsPrintFunctionSymbols) { set_Value (COLUMNNAME_IsPrintFunctionSymbols, Boolean.valueOf(IsPrintFunctionSymbols)); } /** Get Print Function Symbols. @return Print Symbols for Functions (Sum, Average, Count) */ public boolean isPrintFunctionSymbols () { Object oo = get_Value(COLUMNNAME_IsPrintFunctionSymbols); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } public I_AD_PrintColor getLine_PrintColor() throws RuntimeException { return (I_AD_PrintColor)MTable.get(getCtx(), I_AD_PrintColor.Table_Name) .getPO(getLine_PrintColor_ID(), get_TrxName()); } /** Set Line Color. @param Line_PrintColor_ID Table line color */ public void setLine_PrintColor_ID (int Line_PrintColor_ID) { if (Line_PrintColor_ID < 1) set_Value (COLUMNNAME_Line_PrintColor_ID, null); else set_Value (COLUMNNAME_Line_PrintColor_ID, Integer.valueOf(Line_PrintColor_ID)); } /** Get Line Color. @return Table line color */ public int getLine_PrintColor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Line_PrintColor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Line Stroke. @param LineStroke Width of the Line Stroke */ public void setLineStroke (BigDecimal LineStroke) { set_Value (COLUMNNAME_LineStroke, LineStroke); } /** Get Line Stroke. @return Width of the Line Stroke */ public BigDecimal getLineStroke () {
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_LineStroke); if (bd == null) return Env.ZERO; return bd; } /** LineStrokeType AD_Reference_ID=312 */ public static final int LINESTROKETYPE_AD_Reference_ID=312; /** Solid Line = S */ public static final String LINESTROKETYPE_SolidLine = "S"; /** Dashed Line = D */ public static final String LINESTROKETYPE_DashedLine = "D"; /** Dotted Line = d */ public static final String LINESTROKETYPE_DottedLine = "d"; /** Dash-Dotted Line = 2 */ public static final String LINESTROKETYPE_Dash_DottedLine = "2"; /** Set Line Stroke Type. @param LineStrokeType Type of the Line Stroke */ public void setLineStrokeType (String LineStrokeType) { set_Value (COLUMNNAME_LineStrokeType, LineStrokeType); } /** Get Line Stroke Type. @return Type of the Line Stroke */ public String getLineStrokeType () { return (String)get_Value(COLUMNNAME_LineStrokeType); } /** 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_PrintTableFormat.java
1
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres spring.datasource.username=postgres spring.datasource.password=postgres spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true spring.jp
a.properties.hibernate.jdbc.batch_size = 30 spring.jpa.properties.hibernate.generate_statistics=true logging.level.org.hibernate.type.descriptor.sql=TRACE
repos\Hibernate-SpringBoot-master\HibernateSpringBootHiLo\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public class ExecutorConfig { /** * Set the ThreadPoolExecutor's core pool size. */ private int corePoolSize = 10; /** * Set the ThreadPoolExecutor's maximum pool size. */ private int maxPoolSize = 200; /** * Set the capacity for the ThreadPoolExecutor's BlockingQueue. */ private int queueCapacity = 10; // @Bean // public Executor mySimpleAsync() { // ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // executor.setCorePoolSize(corePoolSize); // executor.setMaxPoolSize(maxPoolSize); // executor.setQueueCapacity(queueCapacity); // executor.setThreadNamePrefix("MySimpleExecutor-"); // executor.initialize(); // return executor; // }
@Bean public Executor myAsync() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix("MyExecutor-"); // rejection-policy:当pool已经达到max size的时候,如何处理新任务 // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } }
repos\SpringBootBucket-master\springboot-rabbitmq-rpc\springboot-rabbitmq-rpc-server\src\main\java\com\xncoding\pos\config\ExecutorConfig.java
2
请完成以下Java代码
public static Map<String, TimerDeclarationImpl> getDeclarationsForScope(PvmScope scope) { if (scope == null) { return Collections.emptyMap(); } Map<String, TimerDeclarationImpl> result = scope.getProperties().get(BpmnProperties.TIMER_DECLARATIONS); if (result != null) { return result; } else { return Collections.emptyMap(); } } /** * @return all timeout listeners declared in the given scope */
public static Map<String, Map<String, TimerDeclarationImpl>> getTimeoutListenerDeclarationsForScope(PvmScope scope) { if (scope == null) { return Collections.emptyMap(); } Map<String, Map<String, TimerDeclarationImpl>> result = scope.getProperties().get(BpmnProperties.TIMEOUT_LISTENER_DECLARATIONS); if (result != null) { return result; } else { return Collections.emptyMap(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\TimerDeclarationImpl.java
1
请完成以下Java代码
private <T extends Serializable> Class<T> classIdTypeFrom(String className) { if (className == null) { return null; } try { return (Class) Class.forName(className); } catch (ClassNotFoundException ex) { log.debug("Unable to find class id type on classpath", ex); return null; } } private <T> boolean canConvertFromStringTo(Class<T> targetType) { return this.conversionService.canConvert(String.class, targetType); } private <T extends Serializable> T convertFromStringTo(String identifier, Class<T> targetType) { return this.conversionService.convert(identifier, targetType); } /** * Converts to a {@link Long}, attempting to use the {@link ConversionService} if * available. * @param identifier The identifier * @return Long version of the identifier * @throws NumberFormatException if the string cannot be parsed to a long. * @throws org.springframework.core.convert.ConversionException if a conversion * exception occurred * @throws IllegalArgumentException if targetType is null */ private Long convertToLong(Serializable identifier) { if (this.conversionService.canConvert(identifier.getClass(), Long.class)) { return this.conversionService.convert(identifier, Long.class); } return Long.valueOf(identifier.toString()); } private boolean isString(Serializable object) { return object.getClass().isAssignableFrom(String.class); } void setConversionService(ConversionService conversionService) { Assert.notNull(conversionService, "conversionService must not be null"); this.conversionService = conversionService; }
private static class StringToLongConverter implements Converter<String, Long> { @Override public Long convert(String identifierAsString) { if (identifierAsString == null) { throw new ConversionFailedException(TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Long.class), null, null); } return Long.parseLong(identifierAsString); } } private static class StringToUUIDConverter implements Converter<String, UUID> { @Override public UUID convert(String identifierAsString) { if (identifierAsString == null) { throw new ConversionFailedException(TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(UUID.class), null, null); } return UUID.fromString(identifierAsString); } } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\jdbc\AclClassIdUtils.java
1
请完成以下Java代码
private String getSQLDataType() { final String columnName = getColumnName(); final ReferenceId displayType = getReferenceId(); final int fieldLength = getFieldLength(); return DB.getSQLDataType(displayType.getRepoId(), columnName, fieldLength); } private String getSQLDefaultValue() { final int displayType = referenceId.getRepoId(); if (defaultValue != null && !defaultValue.isEmpty() && defaultValue.indexOf('@') == -1 // no variables && (!(DisplayType.isID(displayType) && defaultValue.equals("-1")))) // not for ID's with default -1 { if (DisplayType.isText(displayType) || displayType == DisplayType.List || displayType == DisplayType.YesNo // Two special columns: Defined as Table but DB Type is String || columnName.equals("EntityType") || columnName.equals("AD_Language") || (displayType == DisplayType.Button && !(columnName.endsWith("_ID")))) { if (!defaultValue.startsWith(DB.QUOTE_STRING) && !defaultValue.endsWith(DB.QUOTE_STRING)) { return DB.TO_STRING(defaultValue); } else
{ return defaultValue; } } else { return defaultValue; } } else { return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\ddl\ColumnDDL.java
1
请完成以下Java代码
public static final BigDecimal calculatePercentage(final BigDecimal qty, final BigDecimal qtyReference) { if (qty == null || qty.signum() == 0) { return BigDecimal.ZERO; } if (qtyReference == null) { // shall not happen return null; } if (qtyReference.signum() == 0) { return BigDecimal.ZERO; } return qty.divide(qtyReference, 12, RoundingMode.HALF_UP) .multiply(Env.ONEHUNDRED) .setScale(2, RoundingMode.HALF_UP); } /** * * @param qtyBase * @param percentage between 0...100 * @param uom UOM (for precision) * @return qtyBase x percentage / 100 (rounded by UOM's StdPrecision) */ public static final BigDecimal calculateQtyAsPercentageOf(final BigDecimal qtyBase, final BigDecimal percentage, final I_C_UOM uom) { if (qtyBase == null || qtyBase.signum() == 0)
{ return BigDecimal.ZERO; } if (percentage == null || percentage.signum() == 0) { return BigDecimal.ZERO; } final int precision = uom.getStdPrecision(); final BigDecimal qty = qtyBase .multiply(percentage) .divide(Env.ONEHUNDRED, precision, RoundingMode.HALF_UP); return qty; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\util\QualityBasedInspectionUtils.java
1
请完成以下Java代码
public VariableMapper getVariableMapper() { return null; } @Override public FunctionMapper getFunctionMapper() { return null; } @Override public jakarta.el.ELResolver getELResolver() { return getWrappedResolver(); } }; } protected BeanManager getBeanManager() { return BeanManagerLookup.getBeanManager(); } protected jakarta.el.ELResolver getWrappedResolver() { BeanManager beanManager = getBeanManager(); jakarta.el.ELResolver resolver = beanManager.getELResolver(); return resolver; } @Override public Class<?> getCommonPropertyType(ELContext context, Object base) { return getWrappedResolver().getCommonPropertyType(this.context, base); } @Override public Class<?> getType(ELContext context, Object base, Object property) { return getWrappedResolver().getType(this.context, base, property); } @Override public Object getValue(ELContext context, Object base, Object property) {
try { Object result = getWrappedResolver().getValue(this.context, base, property); context.setPropertyResolved(result != null); return result; } catch (IllegalStateException e) { // dependent scoped / EJBs Object result = ProgrammaticBeanLookup.lookup(property.toString(), getBeanManager()); context.setPropertyResolved(result != null); return result; } } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { return getWrappedResolver().isReadOnly(this.context, base, property); } @Override public void setValue(ELContext context, Object base, Object property, Object value) { getWrappedResolver().setValue(this.context, base, property, value); } @Override public Object invoke(ELContext context, Object base, Object method, java.lang.Class<?>[] paramTypes, Object[] params) { Object result = getWrappedResolver().invoke(this.context, base, method, paramTypes, params); context.setPropertyResolved(result != null); return result; } }
repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\el\CdiResolver.java
1
请在Spring Boot框架中完成以下Java代码
public class BatchBuilderImpl implements BatchBuilder { protected BatchServiceConfiguration batchServiceConfiguration; protected CommandExecutor commandExecutor; protected String batchType; protected String searchKey; protected String searchKey2; protected String status; protected String batchDocumentJson; protected String tenantId; public BatchBuilderImpl() {} public BatchBuilderImpl(CommandExecutor commandExecutor, BatchServiceConfiguration batchServiceConfiguration) { this.commandExecutor = commandExecutor; this.batchServiceConfiguration = batchServiceConfiguration; } public BatchBuilderImpl(BatchServiceConfiguration batchServiceConfiguration) { this.batchServiceConfiguration = batchServiceConfiguration; } @Override public BatchBuilder batchType(String batchType) { this.batchType = batchType; return this; } @Override public BatchBuilder searchKey(String searchKey) { this.searchKey = searchKey; return this; } @Override public BatchBuilder searchKey2(String searchKey2) { this.searchKey2 = searchKey2; return this; } @Override public BatchBuilder status(String status) { this.status = status; return this; } @Override public BatchBuilder batchDocumentJson(String batchDocumentJson) { this.batchDocumentJson = batchDocumentJson; return this; } @Override public BatchBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } @Override public Batch create() { if (commandExecutor != null) { BatchBuilder selfBatchBuilder = this; return commandExecutor.execute(new Command<>() { @Override public Batch execute(CommandContext commandContext) { return batchServiceConfiguration.getBatchEntityManager().createBatch(selfBatchBuilder);
} }); } else { return ((BatchServiceImpl) batchServiceConfiguration.getBatchService()).createBatch(this); } } @Override public String getBatchType() { return batchType; } @Override public String getSearchKey() { return searchKey; } @Override public String getSearchKey2() { return searchKey2; } @Override public String getStatus() { return status; } @Override public String getBatchDocumentJson() { return batchDocumentJson; } @Override public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchBuilderImpl.java
2
请在Spring Boot框架中完成以下Java代码
static BigDecimal extractBigDecimal(final Object value) { if (value == null) { return null; } if (value instanceof BigDecimal) { return (BigDecimal)value; } final String valueStr = value.toString().trim(); if (valueStr.isEmpty()) { return null; } return extractBigDecimalFromStringWithUnknownLocale(valueStr); } /** * @deprecated this code is required for old excel files (>2018) where some number are encoded as strings. It can soon be removed. */ @Deprecated private static BigDecimal extractBigDecimalFromStringWithUnknownLocale(@NonNull final String valueStr) { BigDecimal actualNumber = null; try { for (final NumberFormat numberFormat : numberFormats) { final Number parsed = numberFormat.parse(valueStr); final BigDecimal numberCandidate = new BigDecimal(parsed.toString()); if (actualNumber == null) { actualNumber = numberCandidate; continue; } final boolean isIntegerActual = isInteger(actualNumber); final boolean isIntegerCandidate = isInteger(numberCandidate); if (actualNumber.equals(numberCandidate)) { continue; } else if (isIntegerActual) { // Maybe the decimal separator was ignored. Use the smaller number. if (numberCandidate.compareTo(actualNumber) < 0) { actualNumber = numberCandidate; } } else if (!isIntegerCandidate) { // both the actual number and the number candidate have decimal separators. // This means that one of them could have used the both separators, for thousands and decimals. // Take the greater number in this case if (numberCandidate.compareTo(actualNumber) > 0) { actualNumber = numberCandidate; } } } return actualNumber; } catch (final Exception e) { // ignore it } return null;
} private static boolean isInteger(final BigDecimal numberCandidate) { return numberCandidate.stripTrailingZeros().scale() <= 0; } @Nullable private Date extractDate(@NonNull final Map<String, Object> map, @NonNull final String key) { final Object value = getValue(map, key); if (value == null) { return null; } if (value instanceof Date) { return (Date)value; } // // Fallback: try parsing the dates from strings using some common predefined formats // NOTE: this shall not happen very often because we take care of dates when we are parsing the Excel file. final String valueStr = value.toString().trim(); if (valueStr.isEmpty()) { return null; } for (final DateFormat dateFormat : dateFormats) { try { return dateFormat.parse(valueStr); } catch (final ParseException e) { // ignore it } } return null; } private static <T> T coalesce(final T value, final T defaultValue) { return value == null ? defaultValue : value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\excelimport\Excel_OLCand_Row_Builder.java
2
请完成以下Java代码
public boolean isNull(final Object model, final String columnName) { return POWrapper.isNull(model, columnName); } @Nullable @Override public <T> T getDynAttribute(final @NonNull Object model, final String attributeName) { return POWrapper.getDynAttribute(model, attributeName); } @Override public Object setDynAttribute(final Object model, final String attributeName, final Object value) { return POWrapper.setDynAttribute(model, attributeName, value); } public <T> T computeDynAttributeIfAbsent(@NonNull final Object model, @NonNull final String attributeName, @NonNull final Supplier<T> supplier) { return POWrapper.computeDynAttributeIfAbsent(model, attributeName, supplier); } @Override public <T extends PO> T getPO(final Object model, final boolean strict) { // always strict, else other wrapper helpers will handle it!
return POWrapper.getStrictPO(model); } @Override public Evaluatee getEvaluatee(final Object model) { return POWrapper.getStrictPO(model); } @Override public boolean isCopy(final Object model) {return POWrapper.getStrictPO(model).isCopiedFromOtherRecord();} @Override public boolean isCopying(final Object model) {return POWrapper.getStrictPO(model).isCopying();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POInterfaceWrapperHelper.java
1
请完成以下Java代码
public String getExtraValue() { return extraValue; } public String getInvolvedUser() { return involvedUser; } public Collection<String> getInvolvedGroups() { return involvedGroups; } public String getTenantId() { return tenantId; } public boolean isWithoutTenantId() { return withoutTenantId; } public boolean isIncludeLocalVariables() { return includeLocalVariables; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } @Override protected void ensureVariablesInitialized() {
super.ensureVariablesInitialized(); for (PlanItemInstanceQueryImpl orQueryObject : orQueryObjects) { orQueryObject.ensureVariablesInitialized(); } } public List<PlanItemInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<List<String>> getSafeCaseInstanceIds() { return safeCaseInstanceIds; } public void setSafeCaseInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeCaseInstanceIds = safeProcessInstanceIds; } public Collection<String> getCaseInstanceIds() { return caseInstanceIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\PlanItemInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
protected void configureDecisionDefinitionQuery(DecisionDefinitionQueryImpl query) { getAuthorizationManager().configureDecisionDefinitionQuery(query); getTenantManager().configureQuery(query); } protected ListQueryParameterObject configureParameterizedQuery(Object parameter) { return getTenantManager().configureQuery(parameter); } @Override public DecisionDefinitionEntity findLatestDefinitionById(String id) { return findDecisionDefinitionById(id); } @Override public DecisionDefinitionEntity findLatestDefinitionByKey(String key) { return findLatestDecisionDefinitionByKey(key); } @Override public DecisionDefinitionEntity getCachedResourceDefinitionEntity(String definitionId) { return getDbEntityManager().getCachedEntity(DecisionDefinitionEntity.class, definitionId); }
@Override public DecisionDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) { return findLatestDecisionDefinitionByKeyAndTenantId(definitionKey, tenantId); } @Override public DecisionDefinitionEntity findDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) { return findDecisionDefinitionByKeyVersionAndTenantId(definitionKey, definitionVersion, tenantId); } @Override public DecisionDefinitionEntity findDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId) { return findDecisionDefinitionByKeyVersionTagAndTenantId(definitionKey, definitionVersionTag, tenantId); } @Override public DecisionDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) { return findDecisionDefinitionByDeploymentAndKey(deploymentId, definitionKey); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionDefinitionManager.java
2
请完成以下Java代码
public String getVariableScopeKey() { return "connector"; } protected VariableStore<CoreVariableInstance> getVariableStore() { return (VariableStore) variableStore; } @Override protected VariableInstanceFactory<CoreVariableInstance> getVariableInstanceFactory() { return (VariableInstanceFactory) SimpleVariableInstanceFactory.INSTANCE; } @Override protected List<VariableInstanceLifecycleListener<CoreVariableInstance>> getVariableInstanceLifecycleListeners() { return Collections.emptyList(); }
public AbstractVariableScope getParentVariableScope() { return parent; } public void writeToRequest(ConnectorRequest<?> request) { for (CoreVariableInstance variable : variableStore.getVariables()) { request.setRequestParameter(variable.getName(), variable.getTypedValue(true).getValue()); } } public void readFromResponse(ConnectorResponse response) { Map<String, Object> responseParameters = response.getResponseParameters(); for (Entry<String, Object> entry : responseParameters.entrySet()) { setVariableLocal(entry.getKey(), entry.getValue()); } } }
repos\camunda-bpm-platform-master\engine-plugins\connect-plugin\src\main\java\org\camunda\connect\plugin\impl\ConnectorVariableScope.java
1
请在Spring Boot框架中完成以下Java代码
public MSV3ClientConfig toMSV3ClientConfig(@NonNull final I_MSV3_Vendor_Config configDataRecord) { final URL baseUrl = toURL(configDataRecord); return newMSV3ClientConfig() .baseUrl(baseUrl) .authUsername(configDataRecord.getUserID()) .authPassword(configDataRecord.getPassword()) .bpartnerId(de.metas.vertical.pharma.msv3.protocol.types.BPartnerId.of(configDataRecord.getC_BPartner_ID())) .version(getVersionById(configDataRecord.getVersion())) .configId(MSV3ClientConfigId.ofRepoId(configDataRecord.getMSV3_Vendor_Config_ID())) .build(); } private static Version getVersionById(final String versionId) { if (X_MSV3_Vendor_Config.VERSION_1.equals(versionId)) { return MSV3ClientConfig.VERSION_1; } else if (X_MSV3_Vendor_Config.VERSION_2.equals(versionId)) { return MSV3ClientConfig.VERSION_2; } else { throw new AdempiereException("Unknow MSV3 protocol version: " + versionId); } } public MSV3ClientConfigBuilder newMSV3ClientConfig() { return MSV3ClientConfig.builder() .clientSoftwareId(CLIENT_SOFTWARE_IDENTIFIER.get()); } private static URL toURL(@NonNull final I_MSV3_Vendor_Config configDataRecord) { try { return new URL(configDataRecord.getMSV3_BaseUrl()); } catch (MalformedURLException e) { throw new AdempiereException("The MSV3_BaseUrl value of the given MSV3_Vendor_Config can't be parsed as URL", e) .appendParametersToMessage() .setParameter("MSV3_BaseUrl", configDataRecord.getMSV3_BaseUrl()) .setParameter("MSV3_Vendor_Config", configDataRecord); } }
public MSV3ClientConfig save(@NonNull final MSV3ClientConfig config) { final I_MSV3_Vendor_Config configRecord = createOrUpdateRecord(config); saveRecord(configRecord); return config.toBuilder() .configId(MSV3ClientConfigId.ofRepoId(configRecord.getMSV3_Vendor_Config_ID())) .build(); } private I_MSV3_Vendor_Config createOrUpdateRecord(@NonNull final MSV3ClientConfig config) { final I_MSV3_Vendor_Config configRecord; if (config.getConfigId() != null) { final int repoId = config.getConfigId().getRepoId(); configRecord = load(repoId, I_MSV3_Vendor_Config.class); } else { configRecord = newInstance(I_MSV3_Vendor_Config.class); } configRecord.setC_BPartner_ID(config.getBpartnerId().getBpartnerId()); configRecord.setMSV3_BaseUrl(config.getBaseUrl().toExternalForm()); configRecord.setPassword(config.getAuthPassword()); configRecord.setUserID(config.getAuthUsername()); return configRecord; } private ClientSoftwareId retrieveSoftwareIndentifier() { try { final ADSystemInfo adSystem = Services.get(ISystemBL.class).get(); return ClientSoftwareId.of("metasfresh-" + adSystem.getDbVersion()); } catch (final RuntimeException e) { return ClientSoftwareId.of("metasfresh-<unable to retrieve version!>"); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\config\MSV3ClientConfigRepository.java
2
请在Spring Boot框架中完成以下Java代码
public void upload(MultipartFile[] files) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (MultipartFile file : files) { String fileName = file.getOriginalFilename(); boolean match = FILE_STORAGE.stream().anyMatch(fileInfo -> fileInfo.getFileName().equals(fileName)); if (match) { throw new RuntimeException("File [ " + fileName + " ] already exist"); } String currentTime = simpleDateFormat.format(new Date()); try (InputStream in = file.getInputStream(); OutputStream out = Files.newOutputStream(Paths.get(filePath + fileName))) { FileCopyUtils.copy(in, out); } catch (IOException e) { log.error("File [{}] upload failed", fileName, e); throw new RuntimeException(e); } FileInfo fileInfo = new FileInfo().setFileName(fileName).setUploadTime(currentTime); FILE_STORAGE.add(fileInfo);
} } @Override public List<FileInfo> list() { return FILE_STORAGE; } @Override public Resource getFile(String fileName) { FILE_STORAGE.stream() .filter(info -> info.getFileName().equals(fileName)) .findFirst() .orElseThrow(() -> new RuntimeException("File [ " + fileName + " ] not exist")); File file = new File(filePath + fileName); return new FileSystemResource(file); } }
repos\springboot-demo-master\file\src\main\java\com\et\service\impl\FileUploadServiceImpl.java
2
请完成以下Java代码
public String getToActivityId() { return toActivityId; } @Override public ManyToOneMapping inParentProcessOfCallActivityId(String fromCallActivityId) { this.fromCallActivityId = fromCallActivityId; this.toCallActivityId = null; this.callActivityProcessDefinitionVersion = null; return this; } @Override public ManyToOneMapping inSubProcessOfCallActivityId(String toCallActivityId) { this.toCallActivityId = toCallActivityId; this.callActivityProcessDefinitionVersion = null; this.fromCallActivityId = null; return this; } @Override public ManyToOneMapping inSubProcessOfCallActivityId(String toCallActivityId, int subProcessDefVersion) { this.toCallActivityId = toCallActivityId; this.callActivityProcessDefinitionVersion = subProcessDefVersion; this.fromCallActivityId = null; return this; } @Override public ManyToOneMapping withNewAssignee(String newAssigneeId) { this.withNewAssignee = newAssigneeId; return this; } @Override public String getWithNewAssignee() { return withNewAssignee; } @Override public ManyToOneMapping withNewOwner(String newOwner) { this.withNewOwner = newOwner;
return this; } @Override public String getWithNewOwner() { return withNewOwner; } @Override public ManyToOneMapping withLocalVariable(String variableName, Object variableValue) { withLocalVariables.put(variableName, variableValue); return this; } @Override public ManyToOneMapping withLocalVariables(Map<String, Object> variables) { withLocalVariables.putAll(variables); return this; } @Override public Map<String, Object> getActivityLocalVariables() { return withLocalVariables; } @Override public String toString() { return "ManyToOneMapping{" + "fromActivityIds=" + fromActivityIds + ", toActivityId='" + toActivityId + '\'' + '}'; } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\migration\ActivityMigrationMapping.java
1
请在Spring Boot框架中完成以下Java代码
public class COL { public static COL of(final String data) { return new COL(new DATA(data)); } @JsonProperty("DATA") DATA data; @JsonCreator public COL(@JsonProperty("DATA") final DATA data) { this.data = data; } public String getValueAsString() { return data != null ? data.getValue() : null; } public <T> T getValue(@NonNull final Function<String, T> mapper) { final String valueStr = getValueAsString(); if (valueStr == null) { return null; } return mapper.apply(valueStr); } public BigDecimal getValueAsBigDecimal() { return getValue(COL::toBigDecimal); } private static BigDecimal toBigDecimal(final String valueStr) { if (valueStr == null || valueStr.trim().isEmpty()) { return null; }
try { return new BigDecimal(valueStr); } catch (final Exception e) { return null; } } public Integer getValueAsInteger() { return getValue(COL::toInteger); } private static Integer toInteger(final String valueStr) { if (valueStr == null || valueStr.trim().isEmpty()) { return null; } try { return Integer.parseInt(valueStr); } catch (final Exception e) { return null; } } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-filemaker\src\main\java\de\metas\common\filemaker\COL.java
2
请完成以下Java代码
public class CustomMultipartFile implements MultipartFile { private byte[] input; public CustomMultipartFile(byte[] input) { this.input = input; } @Override public String getName() { return null; } @Override public String getOriginalFilename() { return null; } @Override public String getContentType() { return null; } @Override public boolean isEmpty() { return input == null || input.length == 0;
} @Override public long getSize() { return input.length; } @Override public byte[] getBytes() { return input; } @Override public InputStream getInputStream() { return new ByteArrayInputStream(input); } @Override public void transferTo(File destination) throws IOException, IllegalStateException { try(FileOutputStream fos = new FileOutputStream(destination)) { fos.write(input); } } }
repos\tutorials-master\spring-web-modules\spring-mvc-file\src\main\java\com\baeldung\file\CustomMultipartFile.java
1
请在Spring Boot框架中完成以下Java代码
public class ZuulRouteRefreshListener implements ApplicationListener<EnvironmentChangeEvent> { private static final Logger logger = LoggerFactory.getLogger(ZuulRouteRefreshListener.class); @Autowired private ApplicationEventPublisher publisher; @Autowired private RouteLocator routeLocator; @Override public void onApplicationEvent(EnvironmentChangeEvent event) { // 判断是否有 `zuul.` 配置变化 boolean zuulConfigUpdated = false; for (String key : event.getKeys()) {
if (key.startsWith("zuul.")) { zuulConfigUpdated = true; break; } } if (!zuulConfigUpdated) { return; } // 发布 RoutesRefreshedEvent 事件 this.publisher.publishEvent(new RoutesRefreshedEvent(routeLocator)); logger.info("发布 RoutesRefreshedEvent 事件完成,刷新 Zuul 路由"); } }
repos\SpringBoot-Labs-master\labx-21\labx-21-sc-zuul-demo03-config-nacos\src\main\java\cn\iocoder\springcloud\labx21\zuuldemo\ZuulRouteRefreshListener.java
2
请在Spring Boot框架中完成以下Java代码
private void prepareExternalStatusCreateRequest(@NonNull final Exchange exchange, @NonNull final JsonExternalStatus externalStatus) { final ScriptedImportConversionRestAPIContext context = ProcessorHelper.getPropertyOrThrowError(exchange, PROPERTY_SCRIPTED_SCRIPTED_IMPORTED_CONVERSION_CONTEXT, ScriptedImportConversionRestAPIContext.class); final JsonExternalSystemRequest request = context.getRequest(); final JsonStatusRequest jsonStatusRequest = JsonStatusRequest.builder() .status(externalStatus) .pInstanceId(request.getAdPInstanceId()) .build(); final ExternalStatusCreateCamelRequest camelRequest = ExternalStatusCreateCamelRequest.builder() .jsonStatusRequest(jsonStatusRequest) .externalSystemConfigType(getExternalSystemTypeCode()) .externalSystemChildConfigValue(request.getExternalSystemChildConfigValue()) .serviceValue(getServiceValue()) .build(); exchange.getIn().setBody(camelRequest, JsonExternalSystemRequest.class); } @Override public String getServiceValue() { return "defaultRestAPIScriptedImportConversion";
} @Override public String getExternalSystemTypeCode() { return SCRIPTED_IMPORT_CONVERSION_SYSTEM_NAME; } @Override public String getEnableCommand() { return ENABLE_RESOURCE_ROUTE; } @Override public String getDisableCommand() { return DISABLE_RESOURCE_ROUTE; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-scriptedadapter\src\main\java\de\metas\camel\externalsystems\scriptedadapter\convertmsg\to_mf\ScriptedImportConversionRestAPIRouteBuilder.java
2
请完成以下Java代码
public Callable<String> getWithResilience4jTimeLimiter(@RequestParam String title) { return TimeLimiter.decorateFutureSupplier(ourTimeLimiter, () -> CompletableFuture.supplyAsync(() -> getAuthor(title))); } @GetMapping("/author/mvc-request-timeout") public Callable<String> getWithMvcRequestTimeout(@RequestParam String title) { return () -> getAuthor(title); } @GetMapping("/author/webclient") public String getWithWebClient(@RequestParam String title) { return webClient.get() .uri(uriBuilder -> uriBuilder.path("/author/transactional") .queryParam("title", title) .build()) .retrieve() .bodyToMono(String.class) .block(); }
@GetMapping("/author/restclient") public String getWithRestClient(@RequestParam String title) { return restClient.get() .uri(uriBuilder -> uriBuilder.path("/author/transactional") .queryParam("title", title) .build()) .retrieve() .body(String.class); } private String getAuthor(String title) { bookRepository.wasteTime(); return bookRepository.findById(title) .map(Book::getAuthor) .orElse("No book found for this title."); } }
repos\tutorials-master\spring-web-modules\spring-rest-http\src\main\java\com\baeldung\requesttimeout\RequestTimeoutRestController.java
1
请完成以下Java代码
public Predicate<ServerWebExchange> apply(Config config) { Pattern pattern = (StringUtils.hasText(config.regexp)) ? Pattern.compile(config.regexp) : null; return new GatewayPredicate() { @Override public boolean test(ServerWebExchange exchange) { if (!StringUtils.hasText(config.header)) { return false; } List<String> values = exchange.getRequest().getHeaders().getValuesAsList(config.header); if (values.isEmpty()) { return false; } // values is now guaranteed to not be empty if (pattern != null) { // check if a header value matches for (int i = 0; i < values.size(); i++) { String value = values.get(i); if (pattern.asMatchPredicate().test(value)) { return true; } } return false; } // there is a value and since regexp is empty, we only check existence. return true; } @Override public Object getConfig() { return config; } @Override public String toString() { return String.format("Header: %s regexp=%s", config.header, config.regexp); } }; } public static class Config {
@NotEmpty private @Nullable String header; private @Nullable String regexp; public @Nullable String getHeader() { return header; } public Config setHeader(String header) { this.header = header; return this; } public @Nullable String getRegexp() { return regexp; } public Config setRegexp(@Nullable String regexp) { this.regexp = regexp; return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\HeaderRoutePredicateFactory.java
1
请在Spring Boot框架中完成以下Java代码
public PersistenceUnitTransactionType getTransactionType() { return transactionType; } @Override public DataSource getJtaDataSource() { return jtaDataSource; } public PersistenceUnitInfoImpl setJtaDataSource(DataSource jtaDataSource) { this.jtaDataSource = jtaDataSource; this.nonJtaDataSource = null; transactionType = PersistenceUnitTransactionType.JTA; return this; } @Override public DataSource getNonJtaDataSource() { return nonJtaDataSource; } public PersistenceUnitInfoImpl setNonJtaDataSource(DataSource nonJtaDataSource) { this.nonJtaDataSource = nonJtaDataSource; this.jtaDataSource = null; transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; return this; } @Override public List<String> getMappingFileNames() { return mappingFileNames; } @Override public List<URL> getJarFileUrls() { return Collections.emptyList(); } @Override public URL getPersistenceUnitRootUrl() { return null; } @Override public List<String> getManagedClassNames() { return managedClassNames; } @Override public boolean excludeUnlistedClasses() { return false;
} @Override public SharedCacheMode getSharedCacheMode() { return SharedCacheMode.UNSPECIFIED; } @Override public ValidationMode getValidationMode() { return ValidationMode.AUTO; } public Properties getProperties() { return properties; } @Override public String getPersistenceXMLSchemaVersion() { return JPA_VERSION; } @Override public ClassLoader getClassLoader() { return Thread.currentThread().getContextClassLoader(); } @Override public void addTransformer(ClassTransformer transformer) { throw new UnsupportedOperationException("Not supported yet."); } @Override public ClassLoader getNewTempClassLoader() { return null; } }
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\daopattern\config\PersistenceUnitInfoImpl.java
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } @Override public org.compiere.model.I_C_OrderLine getC_OrderLine() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_OrderLine_ID, org.compiere.model.I_C_OrderLine.class); } @Override public void setC_OrderLine(org.compiere.model.I_C_OrderLine C_OrderLine) { set_ValueFromPO(COLUMNNAME_C_OrderLine_ID, org.compiere.model.I_C_OrderLine.class, C_OrderLine); } /** Set Auftragsposition. @param C_OrderLine_ID Auftragsposition */ @Override public void setC_OrderLine_ID (int C_OrderLine_ID) { if (C_OrderLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, Integer.valueOf(C_OrderLine_ID)); } /** Get Auftragsposition. @return Auftragsposition */ @Override public int getC_OrderLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_OrderLine_ID); if (ii == null) return 0; return ii.intValue(); } @Override
public de.metas.esb.edi.model.I_EDI_Desadv getEDI_Desadv() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_EDI_Desadv_ID, de.metas.esb.edi.model.I_EDI_Desadv.class); } @Override public void setEDI_Desadv(de.metas.esb.edi.model.I_EDI_Desadv EDI_Desadv) { set_ValueFromPO(COLUMNNAME_EDI_Desadv_ID, de.metas.esb.edi.model.I_EDI_Desadv.class, EDI_Desadv); } /** Set DESADV. @param EDI_Desadv_ID DESADV */ @Override public void setEDI_Desadv_ID (int EDI_Desadv_ID) { if (EDI_Desadv_ID < 1) set_ValueNoCheck (COLUMNNAME_EDI_Desadv_ID, null); else set_ValueNoCheck (COLUMNNAME_EDI_Desadv_ID, Integer.valueOf(EDI_Desadv_ID)); } /** Get DESADV. @return DESADV */ @Override public int getEDI_Desadv_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_EDI_Desadv_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_NullDelivery_C_OrderLine_v.java
1
请在Spring Boot框架中完成以下Java代码
public JSONObject listAllPermission() { List<JSONObject> permissions = userDao.listAllPermission(); return CommonUtil.successPage(permissions); } /** * 添加角色 */ @Transactional(rollbackFor = Exception.class) @SuppressWarnings("unchecked") public JSONObject addRole(JSONObject jsonObject) { userDao.insertRole(jsonObject); userDao.insertRolePermission(jsonObject.getString("roleId"), (List<Integer>) jsonObject.get("permissions")); return CommonUtil.successJson(); } /** * 修改角色 */ @Transactional(rollbackFor = Exception.class) @SuppressWarnings("unchecked") public JSONObject updateRole(JSONObject jsonObject) { String roleId = jsonObject.getString("roleId"); List<Integer> newPerms = (List<Integer>) jsonObject.get("permissions"); JSONObject roleInfo = userDao.getRoleAllInfo(jsonObject); Set<Integer> oldPerms = (Set<Integer>) roleInfo.get("permissionIds"); //修改角色名称 updateRoleName(jsonObject, roleInfo); //添加新权限 saveNewPermission(roleId, newPerms, oldPerms); //移除旧的不再拥有的权限 removeOldPermission(roleId, newPerms, oldPerms); return CommonUtil.successJson(); } /** * 修改角色名称 */ private void updateRoleName(JSONObject paramJson, JSONObject roleInfo) { String roleName = paramJson.getString("roleName"); if (!roleName.equals(roleInfo.getString("roleName"))) { userDao.updateRoleName(paramJson); } } /** * 为角色添加新权限
*/ private void saveNewPermission(String roleId, Collection<Integer> newPerms, Collection<Integer> oldPerms) { List<Integer> waitInsert = new ArrayList<>(); for (Integer newPerm : newPerms) { if (!oldPerms.contains(newPerm)) { waitInsert.add(newPerm); } } if (waitInsert.size() > 0) { userDao.insertRolePermission(roleId, waitInsert); } } /** * 删除角色 旧的 不再拥有的权限 */ private void removeOldPermission(String roleId, Collection<Integer> newPerms, Collection<Integer> oldPerms) { List<Integer> waitRemove = new ArrayList<>(); for (Integer oldPerm : oldPerms) { if (!newPerms.contains(oldPerm)) { waitRemove.add(oldPerm); } } if (waitRemove.size() > 0) { userDao.removeOldPermission(roleId, waitRemove); } } /** * 删除角色 */ @Transactional(rollbackFor = Exception.class) public JSONObject deleteRole(JSONObject jsonObject) { String roleId = jsonObject.getString("roleId"); int userCount = userDao.countRoleUser(roleId); if (userCount > 0) { return CommonUtil.errorJson(ErrorEnum.E_10008); } userDao.removeRole(roleId); userDao.removeRoleAllPermission(roleId); return CommonUtil.successJson(); } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\service\UserService.java
2
请在Spring Boot框架中完成以下Java代码
public class KotlinProjectGenerationConfiguration { private final ProjectDescription description; public KotlinProjectGenerationConfiguration(ProjectDescription description) { this.description = description; } @Bean KotlinSourceCodeWriter kotlinSourceCodeWriter(IndentingWriterFactory indentingWriterFactory) { return new KotlinSourceCodeWriter(this.description.getLanguage(), indentingWriterFactory); } @Bean MainSourceCodeProjectContributor<KotlinTypeDeclaration, KotlinCompilationUnit, KotlinSourceCode> mainKotlinSourceCodeProjectContributor( ObjectProvider<MainApplicationTypeCustomizer<?>> mainApplicationTypeCustomizers, ObjectProvider<MainCompilationUnitCustomizer<?, ?>> mainCompilationUnitCustomizers, ObjectProvider<MainSourceCodeCustomizer<?, ?, ?>> mainSourceCodeCustomizers, KotlinSourceCodeWriter kotlinSourceCodeWriter) { return new MainSourceCodeProjectContributor<>(this.description, KotlinSourceCode::new, kotlinSourceCodeWriter, mainApplicationTypeCustomizers, mainCompilationUnitCustomizers, mainSourceCodeCustomizers); } @Bean TestSourceCodeProjectContributor<KotlinTypeDeclaration, KotlinCompilationUnit, KotlinSourceCode> testKotlinSourceCodeProjectContributor( ObjectProvider<TestApplicationTypeCustomizer<?>> testApplicationTypeCustomizers, ObjectProvider<TestSourceCodeCustomizer<?, ?, ?>> testSourceCodeCustomizers, KotlinSourceCodeWriter kotlinSourceCodeWriter) { return new TestSourceCodeProjectContributor<>(this.description, KotlinSourceCode::new, kotlinSourceCodeWriter, testApplicationTypeCustomizers, testSourceCodeCustomizers);
} @Bean @ConditionalOnBuildSystem(GradleBuildSystem.ID) public GitIgnoreCustomizer kotlinGradlePluginGitIgnoreCustomizer() { return (gitIgnore) -> { GitIgnore.GitIgnoreSection section = gitIgnore.addSectionIfAbsent("Kotlin"); section.add(".kotlin"); }; } @Bean public KotlinProjectSettings kotlinProjectSettings(ObjectProvider<KotlinVersionResolver> kotlinVersionResolver, InitializrMetadata metadata) { String kotlinVersion = kotlinVersionResolver .getIfAvailable(() -> new InitializrMetadataKotlinVersionResolver(metadata)) .resolveKotlinVersion(this.description); return new SimpleKotlinProjectSettings(kotlinVersion, this.description.getLanguage().jvmVersion()); } @Bean public KotlinJacksonBuildCustomizer kotlinJacksonBuildCustomizer(InitializrMetadata metadata) { return new KotlinJacksonBuildCustomizer(metadata, this.description); } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\kotlin\KotlinProjectGenerationConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public float getEvictionOffHeapPercentage() { return this.evictionOffHeapPercentage; } public void setEvictionOffHeapPercentage(float evictionOffHeapPercentage) { this.evictionOffHeapPercentage = evictionOffHeapPercentage; } public String getLogLevel() { return this.logLevel; } public void setLogLevel(String logLevel) { this.logLevel = logLevel; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public OffHeapProperties getOffHeap() { return this.offHeap; } public PeerCacheProperties getPeer() { return this.peer; } public CacheServerProperties getServer() { return this.server; } public static class CompressionProperties { private String compressorBeanName; private String[] regionNames = {}; public String getCompressorBeanName() { return this.compressorBeanName;
} public void setCompressorBeanName(String compressorBeanName) { this.compressorBeanName = compressorBeanName; } public String[] getRegionNames() { return this.regionNames; } public void setRegionNames(String[] regionNames) { this.regionNames = regionNames; } } public static class OffHeapProperties { private String memorySize; private String[] regionNames = {}; public String getMemorySize() { return this.memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String[] getRegionNames() { return this.regionNames; } public void setRegionNames(String[] regionNames) { this.regionNames = regionNames; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\CacheProperties.java
2
请完成以下Java代码
private DeliveryOrderItem createDeliveryOrderItems(final PackageItem packageItem) { Check.assumeNotNull(packageItem.getQuantity(), "quantity must not be null, for packageItem " + packageItem); final ProductId productId = packageItem.getProductId(); final I_M_Product product = productDAO.getById(productId); final BigDecimal weightInKg = computeNominalGrossWeightInKg(packageItem).orElse(BigDecimal.ZERO); final I_C_OrderLine orderLine = orderDAO.getOrderLineById(packageItem.getOrderLineId()); final UomId targetUOMID = CoalesceUtil.coalesceNotNull(UomId.ofRepoIdOrNull(orderLine.getPrice_UOM_ID()), packageItem.getQuantity().getUomId()); final Quantity quantity = uomConversionBL.convertQuantityTo(packageItem.getQuantity(), productId, targetUOMID); final Money unitPrice = Money.of(orderLine.getPriceEntered(), CurrencyId.ofRepoId(orderLine.getC_Currency_ID())); final Money totalPackageValue = unitPrice.multiply(quantity.toBigDecimal()); return DeliveryOrderItem.builder() .productName(product.getName()) .productValue(product.getValue())
.totalWeightInKg(weightInKg) .shippedQuantity(packageItem.getQuantity()) .unitPrice(unitPrice) .totalValue(totalPackageValue) .build(); } private Optional<BigDecimal> computeNominalGrossWeightInKg(final PackageItem packageItem) { final ProductId productId = packageItem.getProductId(); final Quantity quantity = packageItem.getQuantity(); return productBL.computeGrossWeight(productId, quantity) .map(weight -> uomConversionBL.convertToKilogram(weight, productId)) .map(Quantity::getAsBigDecimal); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.nshift\src\main\java\de\metas\shipper\gateway\nshift\NShiftDraftDeliveryOrderCreator.java
1
请完成以下Java代码
public static List<List<Term>> seg2sentence(String text, boolean shortest) { return SEGMENT.seg2sentence(text, shortest); } /** * 切分为句子形式 * * @param text * @param filterArrayChain 自定义过滤器链 * @return */ public static List<List<Term>> seg2sentence(String text, Filter... filterArrayChain) { List<List<Term>> sentenceList = SEGMENT.seg2sentence(text); for (List<Term> sentence : sentenceList) { ListIterator<Term> listIterator = sentence.listIterator(); while (listIterator.hasNext()) { if (filterArrayChain != null) {
Term term = listIterator.next(); for (Filter filter : filterArrayChain) { if (!filter.shouldInclude(term)) { listIterator.remove(); break; } } } } } return sentenceList; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\NotionalTokenizer.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonCacheStats { // // Cache Info long cacheId; @NonNull String name; @NonNull Set<String> labels; @NonNull CacheMapType type; int initialCapacity; int maximumSize; int expireMinutes; @JsonInclude(JsonInclude.Include.NON_EMPTY) @Nullable String debugAcquireStacktrace; // // Actual Stats long size; long hitCount; @NonNull BigDecimal hitRate; long missCount; @NonNull BigDecimal missRate; public static JsonCacheStats of(@NonNull final CCacheStats stats) { return JsonCacheStats.builder()
.cacheId(stats.getCacheId()) .name(stats.getName()) .labels(stats.getLabels().stream() .map(CacheLabel::getName) .collect(ImmutableSet.toImmutableSet())) .type(stats.getConfig().getCacheMapType()) .initialCapacity(stats.getConfig().getInitialCapacity()) .maximumSize(stats.getConfig().getMaximumSize()) .expireMinutes(stats.getConfig().getExpireMinutes()) .debugAcquireStacktrace(stats.getDebugAcquireStacktrace()) // .size(stats.getSize()) .hitCount(stats.getHitCount()) .hitRate(stats.getHitRate().toBigDecimal()) .missCount(stats.getMissCount()) .missRate(stats.getMissRate().toBigDecimal()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\rest\JsonCacheStats.java
2
请完成以下Java代码
public int getC_Workplace_ExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_C_Workplace_ExternalSystem_ID); } @Override public void setC_Workplace_ID (final int C_Workplace_ID) { if (C_Workplace_ID < 1) set_Value (COLUMNNAME_C_Workplace_ID, null); else set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID); } @Override public int getC_Workplace_ID() { return get_ValueAsInt(COLUMNNAME_C_Workplace_ID); }
@Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Workplace_ExternalSystem.java
1
请完成以下Java代码
public void setTextValue2(String textValue2) { this.textValue2 = textValue2; } public byte[] getByteValue() { return byteValue; } public void setByteValue(byte[] byteValue) { this.byteValue = byteValue; } public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public void setByteArrayId(String id) { byteArrayId = id; } public String getByteArrayId() { return byteArrayId; } public String getVariableInstanceId() { return variableInstanceId; } public void setVariableInstanceId(String variableInstanceId) { this.variableInstanceId = variableInstanceId; } public String getScopeActivityInstanceId() { return scopeActivityInstanceId; } public void setScopeActivityInstanceId(String scopeActivityInstanceId) { this.scopeActivityInstanceId = scopeActivityInstanceId; } public void setInitial(Boolean isInitial) { this.isInitial = isInitial; } public Boolean isInitial() { return isInitial; } @Override
public String toString() { return this.getClass().getSimpleName() + "[variableName=" + variableName + ", variableInstanceId=" + variableInstanceId + ", revision=" + revision + ", serializerName=" + serializerName + ", longValue=" + longValue + ", doubleValue=" + doubleValue + ", textValue=" + textValue + ", textValue2=" + textValue2 + ", byteArrayId=" + byteArrayId + ", activityInstanceId=" + activityInstanceId + ", scopeActivityInstanceId=" + scopeActivityInstanceId + ", eventType=" + eventType + ", executionId=" + executionId + ", id=" + id + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", taskId=" + taskId + ", timestamp=" + timestamp + ", tenantId=" + tenantId + ", isInitial=" + isInitial + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricVariableUpdateEventEntity.java
1
请完成以下Java代码
public void setTxCtgy(String value) { this.txCtgy = value; } /** * Gets the value of the saleRcncltnId property. * * @return * possible object is * {@link String } * */ public String getSaleRcncltnId() { return saleRcncltnId; } /** * Sets the value of the saleRcncltnId property. * * @param value * allowed object is * {@link String } * */ public void setSaleRcncltnId(String value) { this.saleRcncltnId = value; } /** * Gets the value of the seqNbRg property. * * @return * possible object is * {@link CardSequenceNumberRange1 } * */ public CardSequenceNumberRange1 getSeqNbRg() { return seqNbRg; }
/** * Sets the value of the seqNbRg property. * * @param value * allowed object is * {@link CardSequenceNumberRange1 } * */ public void setSeqNbRg(CardSequenceNumberRange1 value) { this.seqNbRg = value; } /** * Gets the value of the txDtRg property. * * @return * possible object is * {@link DateOrDateTimePeriodChoice } * */ public DateOrDateTimePeriodChoice getTxDtRg() { return txDtRg; } /** * Sets the value of the txDtRg property. * * @param value * allowed object is * {@link DateOrDateTimePeriodChoice } * */ public void setTxDtRg(DateOrDateTimePeriodChoice value) { this.txDtRg = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CardAggregated1.java
1
请完成以下Java代码
private void checkNotValidCharactersInVariableName(String name, String errorMsg) { if (!variableNameValidator.validate(name)) { throw new IllegalStateException(errorMsg + (name != null ? name : "null")); } } public CreateTaskVariablePayload handleCreateTaskVariablePayload( CreateTaskVariablePayload createTaskVariablePayload ) { checkNotValidCharactersInVariableName(createTaskVariablePayload.getName(), "Variable has not a valid name: "); Object value = createTaskVariablePayload.getValue(); if (value instanceof String) { handleAsDate((String) value).ifPresent(createTaskVariablePayload::setValue); } return createTaskVariablePayload; } public UpdateTaskVariablePayload handleUpdateTaskVariablePayload( UpdateTaskVariablePayload updateTaskVariablePayload ) { checkNotValidCharactersInVariableName( updateTaskVariablePayload.getName(), "You cannot update a variable with not a valid name: " ); Object value = updateTaskVariablePayload.getValue(); if (value instanceof String) { handleAsDate((String) value).ifPresent(updateTaskVariablePayload::setValue); }
return updateTaskVariablePayload; } public Map<String, Object> handlePayloadVariables(Map<String, Object> variables) { if (variables != null) { Set<String> mismatchedVars = variableNameValidator.validateVariables(variables); if (!mismatchedVars.isEmpty()) { throw new IllegalStateException("Variables have not valid names: " + String.join(", ", mismatchedVars)); } handleStringVariablesAsDates(variables); } return variables; } private void handleStringVariablesAsDates(Map<String, Object> variables) { if (variables != null) { variables .entrySet() .stream() .filter(stringObjectEntry -> stringObjectEntry.getValue() instanceof String) .forEach(stringObjectEntry -> handleAsDate((String) stringObjectEntry.getValue()).ifPresent(stringObjectEntry::setValue) ); } } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\impl\TaskVariablesPayloadValidator.java
1
请完成以下Java代码
private Iterator<I_M_ReceiptSchedule> retrieveReceiptSchedules(final ProcessInfo pi) { return Services.get(IQueryBL.class).createQueryBuilder(I_M_ReceiptSchedule.class, pi.getCtx(), ITrx.TRXNAME_None) // Filter by process info selection .filter(new ProcessInfoSelectionQueryFilter<I_M_ReceiptSchedule>(pi)) // FIXME: we need to fetch also those who where processed because on some of them we fully allocated to HUs and we cannot distinguish right now // // Just those that are not processed // .filter(new EqualsQueryFilter<I_M_ReceiptSchedule>(I_M_ReceiptSchedule.COLUMNNAME_Processed, false)) .create() // Only active records .setOnlyActiveRecords(true) // Only those on which logged in user has RW access .setRequiredAccess(Access.WRITE)
// .iterate(I_M_ReceiptSchedule.class); } @Override public List<IHUDocument> createHUDocumentsFromModel(final Object model) { final I_M_ReceiptSchedule schedule = InterfaceWrapperHelper.create(model, I_M_ReceiptSchedule.class); final List<IHUDocument> subsequentDocuments = null; // we don't care for subsequent documents final IHUDocumentLine line = createHUDocumentLine(schedule, subsequentDocuments); final IHUDocument doc = createHUDocumentFromLines(Collections.singletonList(line)); return Collections.singletonList(doc); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\ReceiptScheduleHUDocumentFactory.java
1
请完成以下Java代码
public InputMethodRequests getInputMethodRequests() { return m_textPane.getInputMethodRequests(); } /** * Set Input Verifier * @param l verifyer */ @Override public void setInputVerifier (InputVerifier l) { m_textPane.setInputVerifier(l); } // metas: begin public String getContentType() { if (m_textPane != null) return m_textPane.getContentType(); return null; } private void setHyperlinkListener() { if (hyperlinkListenerClass == null) { return; } try { final HyperlinkListener listener = (HyperlinkListener)hyperlinkListenerClass.newInstance(); m_textPane.addHyperlinkListener(listener); } catch (Exception e)
{ log.warn("Cannot instantiate hyperlink listener - " + hyperlinkListenerClass, e); } } private static Class<?> hyperlinkListenerClass; static { final String hyperlinkListenerClassname = "de.metas.adempiere.gui.ADHyperlinkHandler"; try { hyperlinkListenerClass = Thread.currentThread().getContextClassLoader().loadClass(hyperlinkListenerClassname); } catch (Exception e) { log.warn("Cannot instantiate hyperlink listener - " + hyperlinkListenerClassname, e); } } @Override public final ICopyPasteSupportEditor getCopyPasteSupport() { return copyPasteSupport; } // metas: end } // CTextPane
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextPane.java
1
请完成以下Java代码
public int hashCode() { return Objects.hashCode(loginName); } /** * 重载equals,只计算loginName; */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; }
if (getClass() != obj.getClass()) { return false; } ShiroUser other = (ShiroUser) obj; if (loginName == null) { if (other.loginName != null) { return false; } } else if (!loginName.equals(other.loginName)) { return false; } return true; } }
repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\ShiroUser.java
1
请完成以下Java代码
public static TypedValue untypedValue(Object value, boolean isTransient) { if(value == null) { return untypedNullValue(isTransient); } else if (value instanceof TypedValueBuilder<?>) { return ((TypedValueBuilder<?>) value).setTransient(isTransient).create(); } else if (value instanceof TypedValue) { TypedValue transientValue = (TypedValue) value; if (value instanceof NullValueImpl) { transientValue = untypedNullValue(isTransient); } else if (value instanceof FileValue) { ((FileValueImpl) transientValue).setTransient(isTransient); } else if (value instanceof AbstractTypedValue<?>) { ((AbstractTypedValue<?>) transientValue).setTransient(isTransient); } return transientValue; } else { // unknown value return new UntypedValueImpl(value, isTransient); } } /** * Returns a builder to create a new {@link FileValue} with the given * {@code filename}. */ public static FileValueBuilder fileValue(String filename) { return fileValue(filename, false); } /** * Returns a builder to create a new {@link FileValue} with the given * {@code filename}. */ public static FileValueBuilder fileValue(String filename, boolean isTransient) { return new FileValueBuilderImpl(filename).setTransient(isTransient); } /** * Shortcut for calling {@code Variables.fileValue(name).file(file).mimeType(type).create()}.
* The name is set to the file name and the mime type is detected via {@link MimetypesFileTypeMap}. */ public static FileValue fileValue(File file){ String contentType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(file); return new FileValueBuilderImpl(file.getName()).file(file).mimeType(contentType).create(); } /** * Shortcut for calling {@code Variables.fileValue(name).file(file).mimeType(type).setTransient(isTransient).create()}. * The name is set to the file name and the mime type is detected via {@link MimetypesFileTypeMap}. */ public static FileValue fileValue(File file, boolean isTransient){ String contentType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(file); return new FileValueBuilderImpl(file.getName()).file(file).mimeType(contentType).setTransient(isTransient).create(); } /** * @return an empty {@link VariableContext} (from which no variables can be resolved). */ public static VariableContext emptyVariableContext() { return EmptyVariableContext.INSTANCE; } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\Variables.java
1
请完成以下Java代码
private Map<AggregationItemId, AggregationItem> createAggregationItem_TypeAttribute(final I_C_AggregationItem aggregationItemDef) { final I_C_Aggregation_Attribute attributeDef = aggregationItemDef.getC_Aggregation_Attribute(); if (attributeDef == null || attributeDef.getC_Aggregation_Attribute_ID() <= 0) { throw new AdempiereException("@NotFound@ @C_Aggregation_Attribute_ID@" + "\n @C_Aggregation_ID@: " + aggregationItemDef.getC_Aggregation().getName() + "\n @C_AggregationItem_ID@: " + aggregationItemDef); } if (!attributeDef.isActive()) { return null; } final String attributeType = attributeDef.getType(); final AggregationAttribute aggregationAttribute; if (X_C_Aggregation_Attribute.TYPE_Attribute.equals(attributeType)) { final String attributeName = attributeDef.getCode(); aggregationAttribute = new AggregationAttribute(attributeName); } else { throw new AdempiereException("@Unknown@ @Type@: " + attributeType + "\n @C_Aggregation_ID@: " + aggregationItemDef.getC_Aggregation().getName() + "\n @C_AggregationItem_ID@: " + aggregationItemDef + "\n @C_Aggregation_Attribute_ID@: " + attributeDef); } // // Create aggregation item final ILogicExpression includeLogic = getLogicExpression(aggregationItemDef); final AggregationItem aggregationItem = AggregationItem.builder() .id(AggregationItemId.ofRepoId(aggregationItemDef.getC_AggregationItem_ID())) .type(Type.Attribute) .columnName(null) .displayType(-1) .attribute(aggregationAttribute) .includeLogic(includeLogic) .build();
return ImmutableMap.of(aggregationItem.getId(), aggregationItem); } /** * * @return true if aggregation is eligible and shall be considered * @throws AdempiereException if aggregation is not eligible and this is not acceptable */ private boolean checkEligible(final I_C_Aggregation aggregationDef) { if (aggregationDef == null) { return false; // not eligible } final int aggregationId = aggregationDef.getC_Aggregation_ID(); if (aggregationId <= 0) { return false; // not eligible } // Avoid cycles (i.e. self including an aggregation, direct or indirect) if (!seenAggregationIds.add(aggregationId)) { throw new AdempiereException("Aggregation cycle detected: " + aggregationDef); // return false; // not eligible } final String tableName = aggregationDef.getAD_Table().getTableName(); final String tableNameExpected = getTableName(); if (!Objects.equals(tableNameExpected, tableName)) { throw new AdempiereException("Aggregation's table name does not match" + "\n @C_Aggregation_ID@: " + aggregationDef + "\n @TableName@: " + tableName + "\n @TableName@ (expected): " + tableNameExpected); } return true; // eligible } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\api\impl\C_Aggregation2AggregationBuilder.java
1
请完成以下Java代码
public List<VariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new VariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<VariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } public Date getClaimTime() { return claimTime; } public void setClaimTime(Date claimTime) { this.claimTime = claimTime; } public Integer getAppVersion() {
return this.appVersion; } public void setAppVersion(Integer appVersion) { this.appVersion = appVersion; } public String toString() { return "Task[id=" + id + ", name=" + name + "]"; } private String truncate(String string, int maxLength) { if (string != null) { return string.length() > maxLength ? string.substring(0, maxLength) : string; } return null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TaskEntityImpl.java
1