instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public static void precedence_example() { boolean x = true; boolean y = false; System.out.println(!x && y); // prints false System.out.println(!(x && y)); // prints true } public static void pitfalls_ComplexConditionsExample() { int count = 9; int total = 100; if (!(count >= 10 || total >= 1000)) { System.out.println("Some more work to do"); } } public static void pitfalls_simplifyComplexConditionsByReversingLogicExample() { int count = 9; int total = 100;
if (count < 10 && total < 1000) { System.out.println("Some more work to do"); } } public static void exitEarlyExample() { boolean isValid = false; if(!isValid) { throw new IllegalArgumentException("Invalid input"); } // Code to execute when isValid == true goes here } }
repos\tutorials-master\core-java-modules\core-java-lang-syntax-2\src\main\java\com\baeldung\core\operators\notoperator\NotOperator.java
1
请在Spring Boot框架中完成以下Java代码
public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getVariableName() { return variableName; } public void setVariableName(String variableName) { this.variableName = variableName; } public String getVariableNameLike() { return variableNameLike; } public void setVariableNameLike(String variableNameLike) {
this.variableNameLike = variableNameLike; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = QueryVariable.class) public List<QueryVariable> getVariables() { return variables; } public void setVariables(List<QueryVariable> variables) { this.variables = variables; } public void setExcludeLocalVariables(Boolean excludeLocalVariables) { this.excludeLocalVariables = excludeLocalVariables; } public Boolean getExcludeLocalVariables() { return excludeLocalVariables; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricVariableInstanceQueryRequest.java
2
请完成以下Java代码
public void addShipmentSchedule(final I_M_ShipmentSchedule schedule) { final IProductStorage storage = new ShipmentScheduleQtyPickedProductStorage(schedule); final GenericAllocationSourceDestination sourceOrDestination = new GenericAllocationSourceDestination(storage, (I_M_HU_Item)null, // we don't have any HU Item schedule // we use our shipment schedule as a reference model ); addAllocationSourceOrDestination(sourceOrDestination); } public void addShipmentSchedules(final List<I_M_ShipmentSchedule> schedules) { if (schedules == null || schedules.isEmpty()) { // nothing to add return;
} for (final I_M_ShipmentSchedule schedule : schedules) { addShipmentSchedule(schedule); } } @Override public IAllocationResult unload(final IAllocationRequest request) { // Make sure that request has no referenced object because we will use the shipment schedules are referenced objects. Check.assumeNull(request.getReference(), "Request shall have no referenced object: {}", request); return super.unload(request); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\ShipmentScheduleListAllocationSource.java
1
请完成以下Java代码
public ResponseEntity<JsonError> handleDBUniqueConstraintException(@NonNull final DBUniqueConstraintException e) { return logAndCreateError( e, "At least one record already existed in the system:" + e.getMessage(), HttpStatus.UNPROCESSABLE_ENTITY); } @ExceptionHandler(Exception.class) public ResponseEntity<JsonError> handleException(@NonNull final Exception e) { final ResponseStatus responseStatus = e.getClass().getAnnotation(ResponseStatus.class); if (responseStatus != null) { return logAndCreateError(e, responseStatus.reason(), responseStatus.code()); } return logAndCreateError(e, HttpStatus.UNPROCESSABLE_ENTITY); } private ResponseEntity<JsonError> logAndCreateError( @NonNull final Exception e, @NonNull final HttpStatus status) {
return logAndCreateError(e, null, status); } private ResponseEntity<JsonError> logAndCreateError( @NonNull final Exception e, @Nullable final String detail, @NonNull final HttpStatus status) { final String logMessage = coalesceSuppliers( () -> detail, e::getMessage, () -> e.getClass().getSimpleName()); Loggables.withFallbackToLogger(logger, Level.ERROR).addLog(logMessage, e); final String adLanguage = Env.getADLanguageOrBaseLanguage(); final JsonError error = JsonError.builder() .error(JsonErrors.ofThrowable(e, adLanguage, TranslatableStrings.constant(detail))) .build(); return new ResponseEntity<>(error, status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\exception\RestResponseEntityExceptionHandler.java
1
请在Spring Boot框架中完成以下Java代码
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security.passwordEncoder(passwordEncoder); } /** * We set our authorization storage feature specifying that we would use the * JDBC store for token and authorization code storage.<br> * <br> * * We also attach the {@link AuthenticationManager} so that password grants * can be processed. */ @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authorizationCodeServices(authorizationCodeServices()) .authenticationManager(auth).tokenStore(tokenStore()) .approvalStoreDisabled(); } /** * Setup the client application which attempts to get access to user's * account after user permission. */ @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource) .passwordEncoder(passwordEncoder) .withClient("client") .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token","password", "implicit") .authorities("ROLE_CLIENT") .resourceIds("apis") .scopes("read") .secret("secret") .accessTokenValiditySeconds(300);
} /** * Configure the {@link AuthenticationManagerBuilder} with initial * configuration to setup users. * * @author anilallewar * */ @Configuration @Order(Ordered.LOWEST_PRECEDENCE - 20) protected static class AuthenticationManagerConfiguration extends GlobalAuthenticationConfigurerAdapter { @Autowired private DataSource dataSource; /** * Setup 2 users with different roles */ @Override public void init(AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth.jdbcAuthentication().dataSource(dataSource).withUser("dave") .password("secret").roles("USER"); auth.jdbcAuthentication().dataSource(dataSource).withUser("anil") .password("password").roles("ADMIN"); // @formatter:on } } }
repos\spring-boot-microservices-master\auth-server\src\main\java\com\rohitghatol\microservice\auth\config\OAuthConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authorizationCodeServices(authorizationCodeServices()) .authenticationManager(auth).tokenStore(tokenStore()) .approvalStoreDisabled(); } /** * Setup the client application which attempts to get access to user's * account after user permission. */ @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource) .passwordEncoder(passwordEncoder) .withClient("client") .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token","password", "implicit") .authorities("ROLE_CLIENT") .resourceIds("apis") .scopes("read") .secret("secret") .accessTokenValiditySeconds(300); } /** * Configure the {@link AuthenticationManagerBuilder} with initial * configuration to setup users. * * @author anilallewar *
*/ @Configuration @Order(Ordered.LOWEST_PRECEDENCE - 20) protected static class AuthenticationManagerConfiguration extends GlobalAuthenticationConfigurerAdapter { @Autowired private DataSource dataSource; /** * Setup 2 users with different roles */ @Override public void init(AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth.jdbcAuthentication().dataSource(dataSource).withUser("dave") .password("secret").roles("USER"); auth.jdbcAuthentication().dataSource(dataSource).withUser("anil") .password("password").roles("ADMIN"); // @formatter:on } } }
repos\spring-boot-microservices-master\auth-server\src\main\java\com\rohitghatol\microservice\auth\config\OAuthConfiguration.java
2
请完成以下Java代码
public String getLieferscheinnummer() { return lieferscheinnummer; } /** * Sets the value of the lieferscheinnummer property. * * @param value * allowed object is * {@link String } * */ public void setLieferscheinnummer(String value) { this.lieferscheinnummer = value; } /** * Gets the value of the pzn property. * */ public long getPZN() { return pzn; } /** * Sets the value of the pzn property. * */ public void setPZN(long value) { this.pzn = value; } /** * Gets the value of the retourenMenge property. * */ public int getRetourenMenge() { return retourenMenge; } /** * Sets the value of the retourenMenge property. * */ public void setRetourenMenge(int value) { this.retourenMenge = value; } /** * Gets the value of the retouregrund property. * * @return * possible object is * {@link RetoureGrund } * */ public RetoureGrund getRetouregrund() { return retouregrund; } /** * Sets the value of the retouregrund property. * * @param value
* allowed object is * {@link RetoureGrund } * */ public void setRetouregrund(RetoureGrund value) { this.retouregrund = value; } /** * Gets the value of the charge property. * * @return * possible object is * {@link String } * */ public String getCharge() { return charge; } /** * Sets the value of the charge property. * * @param value * allowed object is * {@link String } * */ public void setCharge(String value) { this.charge = value; } /** * Gets the value of the verfalldatum property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getVerfalldatum() { return verfalldatum; } /** * Sets the value of the verfalldatum property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setVerfalldatum(XMLGregorianCalendar value) { this.verfalldatum = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourePositionType.java
1
请完成以下Java代码
public int getKeepResponseDays() { return get_ValueAsInt(COLUMNNAME_KeepResponseDays); } /** * Method AD_Reference_ID=541306 * Reference name: Http_Method */ public static final int METHOD_AD_Reference_ID=541306; /** GET = GET */ public static final String METHOD_GET = "GET"; /** POST = POST */ public static final String METHOD_POST = "POST"; /** PUT = PUT */ public static final String METHOD_PUT = "PUT"; /** DELETE = DELETE */ public static final String METHOD_DELETE = "DELETE"; /** OPTIONS = OPTIONS */ public static final String METHOD_OPTIONS = "OPTIONS"; /** PATCH = PATCH */ public static final String METHOD_PATCH = "PATCH"; /** HEAD = HEAD */ public static final String METHOD_HEAD = "HEAD"; /** TRACE = TRACE */ public static final String METHOD_TRACE = "TRACE"; /** CONNECT = CONNECT */ public static final String METHOD_CONNECT = "CONNECT"; @Override public void setMethod (final @Nullable java.lang.String Method) { set_Value (COLUMNNAME_Method, Method); } @Override public java.lang.String getMethod() { return get_ValueAsString(COLUMNNAME_Method); } /** * NotifyUserInCharge AD_Reference_ID=541315 * Reference name: NotifyItems */ public static final int NOTIFYUSERINCHARGE_AD_Reference_ID=541315; /** Niemals = NEVER */ public static final String NOTIFYUSERINCHARGE_Niemals = "NEVER "; /** Aufrufen mit Fehler = ONLY_ON_ERROR */ public static final String NOTIFYUSERINCHARGE_AufrufenMitFehler = "ONLY_ON_ERROR "; /** Allen Aufrufen = ALWAYS */ public static final String NOTIFYUSERINCHARGE_AllenAufrufen = "ALWAYS "; @Override public void setNotifyUserInCharge (final @Nullable java.lang.String NotifyUserInCharge) { set_Value (COLUMNNAME_NotifyUserInCharge, NotifyUserInCharge); } @Override
public java.lang.String getNotifyUserInCharge() { return get_ValueAsString(COLUMNNAME_NotifyUserInCharge); } @Override public void setPathPrefix (final @Nullable java.lang.String PathPrefix) { set_Value (COLUMNNAME_PathPrefix, PathPrefix); } @Override public java.lang.String getPathPrefix() { return get_ValueAsString(COLUMNNAME_PathPrefix); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Audit_Config.java
1
请完成以下Java代码
public void setPayment_WriteOff_A(final org.compiere.model.I_C_ValidCombination Payment_WriteOff_A) { set_ValueFromPO(COLUMNNAME_Payment_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class, Payment_WriteOff_A); } @Override public void setPayment_WriteOff_Acct (final int Payment_WriteOff_Acct) { set_Value (COLUMNNAME_Payment_WriteOff_Acct, Payment_WriteOff_Acct); } @Override public int getPayment_WriteOff_Acct() { return get_ValueAsInt(COLUMNNAME_Payment_WriteOff_Acct); } @Override public org.compiere.model.I_C_ValidCombination getRealizedGain_A() { return get_ValueAsPO(COLUMNNAME_RealizedGain_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setRealizedGain_A(final org.compiere.model.I_C_ValidCombination RealizedGain_A) { set_ValueFromPO(COLUMNNAME_RealizedGain_Acct, org.compiere.model.I_C_ValidCombination.class, RealizedGain_A); } @Override public void setRealizedGain_Acct (final int RealizedGain_Acct) { set_Value (COLUMNNAME_RealizedGain_Acct, RealizedGain_Acct); } @Override public int getRealizedGain_Acct()
{ return get_ValueAsInt(COLUMNNAME_RealizedGain_Acct); } @Override public org.compiere.model.I_C_ValidCombination getRealizedLoss_A() { return get_ValueAsPO(COLUMNNAME_RealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setRealizedLoss_A(final org.compiere.model.I_C_ValidCombination RealizedLoss_A) { set_ValueFromPO(COLUMNNAME_RealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class, RealizedLoss_A); } @Override public void setRealizedLoss_Acct (final int RealizedLoss_Acct) { set_Value (COLUMNNAME_RealizedLoss_Acct, RealizedLoss_Acct); } @Override public int getRealizedLoss_Acct() { return get_ValueAsInt(COLUMNNAME_RealizedLoss_Acct); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_BankAccount_Acct.java
1
请完成以下Java代码
public MAlertRecipient[] getRecipients (boolean reload) { if (m_recipients != null && !reload) return m_recipients; //FR: [ 2214883 ] Remove SQL code and Replace for Query - red1 String whereClause = "AD_Alert_ID=?"; List <MAlertRecipient> list = new Query(getCtx(), MAlertRecipient.Table_Name, whereClause, null) .setParameters(new Object[]{getAD_Alert_ID()}) .list(MAlertRecipient.class); // m_recipients = new MAlertRecipient[ list.size() ]; m_recipients = list.toArray (m_recipients); return m_recipients; } // getRecipients /** * Get First Role if exist * @return AD_Role_ID or -1 */ public RoleId getFirstRoleId() { getRecipients(false); for (int i = 0; i < m_recipients.length; i++) { if (m_recipients[i].getAD_Role_ID() >= 0) { return RoleId.ofRepoId(m_recipients[i].getAD_Role_ID()); } } return null; } // getForstAD_Role_ID /** * Get First User Role if exist * @return AD_Role_ID or -1 */ public RoleId getFirstUserRoleId() { getRecipients(false); final UserId userId = UserId.ofRepoIdOrNull(getFirstAD_User_ID()); if (userId != null) { final RoleId firstRoleId = Services.get(IRoleDAO.class).retrieveFirstRoleIdForUserId(userId); return firstRoleId; } return null; } // getFirstUserAD_Role_ID /** * Get First User if exist * @return AD_User_ID or -1 */ public int getFirstAD_User_ID() { getRecipients(false); for (int i = 0; i < m_recipients.length; i++) { if (m_recipients[i].getAD_User_ID() != -1) return m_recipients[i].getAD_User_ID(); } return -1; } // getFirstAD_User_ID /** * @return unique list of recipient users */ public Set<UserId> getRecipientUsers() { MAlertRecipient[] recipients = getRecipients(false);
TreeSet<UserId> users = new TreeSet<>(); for (int i = 0; i < recipients.length; i++) { MAlertRecipient recipient = recipients[i]; if (recipient.getAD_User_ID() >= 0) // System == 0 { users.add(UserId.ofRepoId(recipient.getAD_User_ID())); } final RoleId roleId = RoleId.ofRepoIdOrNull(recipient.getAD_Role_ID()); if (roleId != null) // SystemAdministrator == 0 { final Set<UserId> allRoleUserIds = Services.get(IRoleDAO.class).retrieveUserIdsForRoleId(roleId); users.addAll(allRoleUserIds); } } return users; } /** * String Representation * @return info */ @Override public String toString () { StringBuffer sb = new StringBuffer ("MAlert["); sb.append(get_ID()) .append("-").append(getName()) .append(",Valid=").append(isValid()); if (m_rules != null) sb.append(",Rules=").append(m_rules.length); if (m_recipients != null) sb.append(",Recipients=").append(m_recipients.length); sb.append ("]"); return sb.toString (); } // toString } // MAlert
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAlert.java
1
请完成以下Java代码
protected I_AD_MigrationStep getAD_MigrationStep() { return step; } /** * Get current migration executor context. * * @return {@link IMigrationExecutorContext} migrationExecutorContext */ protected IMigrationExecutorContext getMigrationExecutorContext() { return migrationExecutorContext; } /** * Get current properties context. * * @return {@link Properties} ctx */ protected Properties getCtx() { return migrationExecutorContext.getCtx(); } /** * Log error messages as WARNING and normal ones as INFO. * * @param msg * @param resolution * @param isError */ protected final void log(final String msg, final String resolution, final boolean isError)
{ final StringBuilder sb = new StringBuilder(); sb.append("Step ").append(step.getSeqNo()); if (!Check.isEmpty(msg, true)) { sb.append(": ").append(msg.trim()); } if (resolution != null) { sb.append(" [").append(resolution).append("]"); } if(isError) { logger.error(sb.toString()); } else { logger.info(sb.toString()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\AbstractMigrationStepExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public class JSONDataEntryRecord { Map<Integer, LocalDate> dates; Map<Integer, DataEntryListValueId> listValues; Map<Integer, BigDecimal> numbers; Map<Integer, String> strings; Map<Integer, Boolean> yesNos; Map<Integer, CreatedUpdatedInfo> createdUpdatedInfos; @Builder @JsonCreator
private JSONDataEntryRecord( @Singular @JsonProperty("dates") final Map<Integer, LocalDate> dates, @Singular @JsonProperty("listValues") final Map<Integer, DataEntryListValueId> listValues, @Singular @JsonProperty("numbers") final Map<Integer, BigDecimal> numbers, @Singular @JsonProperty("strings") final Map<Integer, String> strings, @Singular @JsonProperty("yesNos") final Map<Integer, Boolean> yesNos, @Singular @JsonProperty("createdUpdatedInfos") final Map<Integer, CreatedUpdatedInfo> createdUpdatedInfos) { this.dates = dates; this.listValues = listValues; this.numbers = numbers; this.strings = strings; this.yesNos = yesNos; this.createdUpdatedInfos = createdUpdatedInfos; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\json\JSONDataEntryRecord.java
2
请完成以下Java代码
public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public HttpHeaders getHttpHeaders() { return httpHeaders; } public String getHttpHeadersAsString() { return httpHeaders != null ? httpHeaders.formatAsString() : null; } public void setHttpHeaders(HttpHeaders httpHeaders) { this.httpHeaders = httpHeaders; } public String getBody() { return body; } public void setBody(String body) { this.body = body; }
public byte[] getBodyBytes() { return bodyBytes; } public void setBodyBytes(byte[] bodyBytes) { this.bodyBytes = bodyBytes; } public boolean isBodyResponseHandled() { return bodyResponseHandled; } public void setBodyResponseHandled(boolean bodyResponseHandled) { this.bodyResponseHandled = bodyResponseHandled; } }
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\api\HttpResponse.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder .defineType(TextAnnotation.class, BPMN_ELEMENT_TEXT_ANNOTATION).namespaceUri(BPMN20_NS) .extendsType(Artifact.class) .instanceProvider(new ModelTypeInstanceProvider<TextAnnotation>() { public TextAnnotation newInstance(ModelTypeInstanceContext context) { return new TextAnnotationImpl(context); } }); textFormatAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_TEXT_FORMAT) .defaultValue("text/plain") .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); textChild = sequenceBuilder.element(Text.class) .build(); typeBuilder.build(); } public TextAnnotationImpl(ModelTypeInstanceContext context) { super(context);
} public String getTextFormat() { return textFormatAttribute.getValue(this); } public void setTextFormat(String textFormat) { textFormatAttribute.setValue(this, textFormat); } public Text getText() { return textChild.getChild(this); } public void setText(Text text) { textChild.setChild(this, text); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\TextAnnotationImpl.java
1
请完成以下Java代码
public String getCreationDate() { return creationDate; } public void setCreationDate(String creationDate) { this.creationDate = creationDate; } public String getEventType() { return eventType; } public void setEventType(String eventType) { this.eventType = eventType; }
public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } }
repos\tutorials-master\netflix-modules\hollow\src\main\java\com\baeldung\hollow\model\MonitoringEvent.java
1
请在Spring Boot框架中完成以下Java代码
public Region timestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; return this; } /** * Der Zeitstempel der letzten Änderung * @return timestamp **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getTimestamp() { return timestamp; } public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Region region = (Region) o; return Objects.equals(this._id, region._id) && Objects.equals(this.label, region.label) && Objects.equals(this.parent, region.parent) && Objects.equals(this.timestamp, region.timestamp); } @Override public int hashCode() { return Objects.hash(_id, label, parent, timestamp); } @Override public String toString() {
StringBuilder sb = new StringBuilder(); sb.append("class Region {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" label: ").append(toIndentedString(label)).append("\n"); sb.append(" parent: ").append(toIndentedString(parent)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Region.java
2
请完成以下Java代码
public long size() { return topLevelRowsById.size(); } public List<PurchaseRow> getPage(final int firstRow, final int pageLength) { return topLevelRowsById.values().stream() .skip(firstRow >= 0 ? firstRow : 0) .limit(pageLength > 0 ? pageLength : DEFAULT_PAGE_LENGTH) .collect(ImmutableList.toImmutableList()); } public List<PurchaseRow> getAll() { // there are not so many, so we can afford to return all of them return ImmutableList.copyOf(topLevelRowsById.values()); } public PurchaseRow getById(@NonNull final DocumentId rowId) throws EntityNotFoundException { return getById(PurchaseRowId.fromDocumentId(rowId)); } public PurchaseRow getById(@NonNull final PurchaseRowId rowId) throws EntityNotFoundException { if (rowId.isGroupRowId()) { return getToplevelRowById(rowId); } else if (rowId.isLineRowId()) { return getToplevelRowById(rowId.toGroupRowId()) .getIncludedRowById(rowId); } else { return getToplevelRowById(rowId.toGroupRowId()) .getIncludedRowById(rowId.toLineRowId()) .getIncludedRowById(rowId); } } private PurchaseRow getToplevelRowById(@NonNull final PurchaseRowId topLevelRowId) { final PurchaseRow topLevelRow = topLevelRowsById.get(topLevelRowId); if (topLevelRow != null) { return topLevelRow; } throw new EntityNotFoundException("topLevelRow not found") .appendParametersToMessage() .setParameter("topLevelRowId", topLevelRowId); } public Stream<? extends IViewRow> streamTopLevelRowsByIds(@NonNull final DocumentIdsSelection rowIds) { if (rowIds.isAll()) { return topLevelRowsById.values().stream(); } return rowIds.stream().map(this::getById); } void patchRow( @NonNull final PurchaseRowId idOfRowToPatch, @NonNull final PurchaseRowChangeRequest request) { final PurchaseGroupRowEditor editorToUse = PurchaseRow::changeIncludedRow;
updateRow(idOfRowToPatch, request, editorToUse); } private void updateRow( @NonNull final PurchaseRowId idOfRowToPatch, @NonNull final PurchaseRowChangeRequest request, @NonNull final PurchaseGroupRowEditor editor) { topLevelRowsById.compute(idOfRowToPatch.toGroupRowId(), (groupRowId, groupRow) -> { if (groupRow == null) { throw new EntityNotFoundException("Row not found").appendParametersToMessage().setParameter("rowId", groupRowId); } final PurchaseRow newGroupRow = groupRow.copy(); if (idOfRowToPatch.isGroupRowId()) { final PurchaseRowId includedRowId = null; editor.edit(newGroupRow, includedRowId, request); } else { final PurchaseRowId includedRowId = idOfRowToPatch; editor.edit(newGroupRow, includedRowId, request); } return newGroupRow; }); } @FunctionalInterface private static interface PurchaseGroupRowEditor { void edit(final PurchaseRow editableGroupRow, final PurchaseRowId includedRowId, final PurchaseRowChangeRequest request); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseRowsCollection.java
1
请在Spring Boot框架中完成以下Java代码
public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } @ApiModelProperty(example = "14") public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } @ApiModelProperty(example = "15") public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } @ApiModelProperty(example = "cmmn") public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } @ApiModelProperty(example = "16") public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId;
} @ApiModelProperty(example = "someTenantId") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\task\TaskResponse.java
2
请完成以下Java代码
public int getM_HU_PackagingCode_LU_Fallback_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PackagingCode_LU_Fallback_ID); } @Override public de.metas.handlingunits.model.I_M_HU_PI_Item getM_HU_PI_Item() { return get_ValueAsPO(COLUMNNAME_M_HU_PI_Item_ID, de.metas.handlingunits.model.I_M_HU_PI_Item.class); } @Override public void setM_HU_PI_Item(final de.metas.handlingunits.model.I_M_HU_PI_Item M_HU_PI_Item) { set_ValueFromPO(COLUMNNAME_M_HU_PI_Item_ID, de.metas.handlingunits.model.I_M_HU_PI_Item.class, M_HU_PI_Item); } @Override public void setM_HU_PI_Item_ID (final int M_HU_PI_Item_ID) { if (M_HU_PI_Item_ID < 1) set_Value (COLUMNNAME_M_HU_PI_Item_ID, null); else set_Value (COLUMNNAME_M_HU_PI_Item_ID, M_HU_PI_Item_ID); } @Override public int getM_HU_PI_Item_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_ID); } @Override public void setM_HU_PI_Item_Product_ID (final int M_HU_PI_Item_Product_ID) { if (M_HU_PI_Item_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_Product_ID, M_HU_PI_Item_Product_ID); } @Override public int getM_HU_PI_Item_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_Product_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 setName (final @Nullable java.lang.String Name) { set_ValueNoCheck (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty()
{ final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_Value (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Item_Product.java
1
请完成以下Java代码
protected String getActiveValue(String originalValue, String propertyName, ObjectNode taskElementProperties) { String activeValue = originalValue; if (taskElementProperties != null) { JsonNode overrideValueNode = taskElementProperties.get(propertyName); if (overrideValueNode != null) { if (overrideValueNode.isNull()) { activeValue = null; } else { activeValue = overrideValueNode.asText(); } } } return activeValue; } protected List<String> getActiveValueList( List<String> originalValues, String propertyName, ObjectNode taskElementProperties ) { List<String> activeValues = originalValues;
if (taskElementProperties != null) { JsonNode overrideValuesNode = taskElementProperties.get(propertyName); if (overrideValuesNode != null) { if (overrideValuesNode.isNull() || !overrideValuesNode.isArray() || overrideValuesNode.size() == 0) { activeValues = null; } else { activeValues = new ArrayList<String>(); for (JsonNode valueNode : overrideValuesNode) { activeValues.add(valueNode.asText()); } } } } return activeValues; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\TaskActivityBehavior.java
1
请完成以下Java代码
public void setDistrict(final String district) { this.district = district; this.districtSet = true; } public void setRegion(final String region) { this.region = region; this.regionSet = true; } public void setCountryCode(final String countryCode) { this.countryCode = countryCode; this.countryCodeSet = true; } public void setGln(final String gln) { this.gln = gln; this.glnSet = true; } public void setShipTo(final Boolean shipTo) { this.shipTo = shipTo; this.shipToSet = true; } public void setShipToDefault(final Boolean shipToDefault) { this.shipToDefault = shipToDefault; this.shipToDefaultSet = true; }
public void setBillTo(final Boolean billTo) { this.billTo = billTo; this.billToSet = true; } public void setBillToDefault(final Boolean billToDefault) { this.billToDefault = billToDefault; this.billToDefaultSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestLocation.java
1
请完成以下Java代码
public void updateFromRecipientId(@NonNull final I_C_Doc_Outbound_Log docOutboundlogRecord) { final DocOutBoundRecipientId userId = DocOutBoundRecipientId.ofRepoIdOrNull(docOutboundlogRecord.getCurrentEMailRecipient_ID()); if (userId == null) { docOutboundlogRecord.setCurrentEMailAddress(null); return; } final DocOutBoundRecipient user = docOutBoundRecipientService.getById(userId); final String documentEmail = docOutBoundService.getDocumentEmail(docOutboundlogRecord); final String userEmailAddress = user.getEmailAddress(); final boolean propagateToDocOutboundLog = orderEmailPropagationSysConfigRepository.isPropagateToDocOutboundLog( ClientAndOrgId.ofClientAndOrg(docOutboundlogRecord.getAD_Client_ID(), docOutboundlogRecord.getAD_Org_ID())); if (propagateToDocOutboundLog && (Check.isNotBlank(documentEmail))) { docOutboundlogRecord.setCurrentEMailAddress(documentEmail); } else if (!Check.isBlank(userEmailAddress)) { docOutboundlogRecord.setCurrentEMailAddress(userEmailAddress); } else { final String locationEmail = docOutBoundService.getLocationEmail(docOutboundlogRecord); docOutboundlogRecord.setCurrentEMailAddress(locationEmail); } docOutboundlogRecord.setIsInvoiceEmailEnabled(user.isInvoiceAsEmail()); // might be true even if the mailaddress is empty! } // this column is not user-editable, so we don't need it to be a callout @ModelChange( // timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, // ifColumnsChanged = I_C_Doc_Outbound_Log.COLUMNNAME_C_BPartner_ID) public void updateFromBPartnerId(@NonNull final I_C_Doc_Outbound_Log docOutboundlogRecord) { if (docOutboundlogRecord.getC_BPartner_ID() <= 0)
{ // reset everything docOutboundlogRecord.setCurrentEMailRecipient_ID(-1); docOutboundlogRecord.setCurrentEMailAddress(null); docOutboundlogRecord.setIsInvoiceEmailEnabled(false); return; } final int invoiceTableId = Services.get(IADTableDAO.class).retrieveTableId(I_C_Invoice.Table_Name); if (docOutboundlogRecord.getAD_Table_ID() != invoiceTableId) { docOutboundlogRecord.setIsInvoiceEmailEnabled(false); return; } final I_C_BPartner bpartnerRecord = loadOutOfTrx(docOutboundlogRecord.getC_BPartner_ID(), I_C_BPartner.class); docOutboundlogRecord.setIsInvoiceEmailEnabled(StringUtils.toBoolean(bpartnerRecord.getIsInvoiceEmailEnabled())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\interceptor\C_Doc_Outbound_Log.java
1
请完成以下Java代码
private PriceListId getPharmacyPriceListIdOrNull() { if (externalSystemType == null || !externalSystemType.isAlberta() || Check.isBlank(externalSystemConfigValue)) { return null; } return externalSystemService.getByTypeAndValue(ExternalSystemType.Alberta, externalSystemConfigValue) .map(ExternalSystemParentConfig::getChildConfig) .map(ExternalSystemAlbertaConfig::cast) .map(ExternalSystemAlbertaConfig::getPharmacyPriceListId) .orElse(null); } @NonNull private JsonAlbertaPackagingUnit mapToJsonAlbertaPackagingUnit(@NonNull final AlbertaPackagingUnit albertaPackagingUnit) { return JsonAlbertaPackagingUnit.builder() .quantity(albertaPackagingUnit.getQuantity()) .unit(albertaPackagingUnit.getUnit()) .build(); } private void loadAndSetAlbertaRelatedInfo( @NonNull final ImmutableList.Builder<I_M_Product> productRecordsBuilder, @NonNull final HashSet<ProductId> loadedProductIds) { if (externalSystemType == null || !externalSystemType.isAlberta()) { return; } final Instant since = isSingleExport() ? Instant.now().plus(1, ChronoUnit.YEARS) //dev-note: lazy way of saying we are interested only in our product : this.since; final GetAlbertaProductsInfoRequest getAlbertaProductsInfoRequest = GetAlbertaProductsInfoRequest.builder() .since(since) .productIdSet(loadedProductIds) .pharmacyPriceListId(getPharmacyPriceListIdOrNull()) .build(); productId2AlbertaInfo = albertaProductService.getAlbertaInfoByProductId(getAlbertaProductsInfoRequest); final ImmutableSet<ProductId> productIdsLeftToLoaded = productId2AlbertaInfo .keySet() .stream() .filter(productId -> !loadedProductIds.contains(productId)) .collect(ImmutableSet.toImmutableSet()); servicesFacade.getProductsById(productIdsLeftToLoaded).forEach(productRecordsBuilder::add);
} @NonNull private Stream<I_M_Product> streamProductsToExport() { if (isSingleExport()) { Check.assumeNotNull(productIdentifier, "ProductIdentifier must be set in case of single export!"); final ProductId productId = productLookupService.resolveProductExternalIdentifier(productIdentifier, RestUtils.retrieveOrgIdOrDefault(orgCode)) .map(ProductAndHUPIItemProductId::getProductId) .orElseThrow(() -> new AdempiereException("Fail to resolve product external identifier") .appendParametersToMessage() .setParameter("ExternalIdentifier", productIdentifier)); return Stream.of(servicesFacade.getProductById(productId)); } else { return servicesFacade.streamAllProducts(since); } } private boolean isSingleExport() { return productIdentifier != null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\product\command\GetProductsCommand.java
1
请在Spring Boot框架中完成以下Java代码
public void setUpdated(OffsetDateTime updated) { this.updated = updated; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CustomerMapping customerMapping = (CustomerMapping) o; return Objects.equals(this._id, customerMapping._id) && Objects.equals(this.customerId, customerMapping.customerId) && Objects.equals(this.updated, customerMapping.updated); } @Override public int hashCode() { return Objects.hash(_id, customerId, updated); }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CustomerMapping {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" customerId: ").append(toIndentedString(customerId)).append("\n"); sb.append(" updated: ").append(toIndentedString(updated)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\CustomerMapping.java
2
请在Spring Boot框架中完成以下Java代码
public String getOrderedByPartyGLN() { return orderedByPartyGLN; } /** * Sets the value of the orderedByPartyGLN property. * * @param value * allowed object is * {@link String } * */ public void setOrderedByPartyGLN(String value) { this.orderedByPartyGLN = value; } /** * Gets the value of the acceptingPartyGLN property. * * @return * possible object is * {@link String } * */ public String getAcceptingPartyGLN() { return acceptingPartyGLN; } /** * Sets the value of the acceptingPartyGLN property. * * @param value * allowed object is * {@link String } * */ public void setAcceptingPartyGLN(String value) { this.acceptingPartyGLN = value; } /** * Gets the value of the contractNumber property. * * @return * possible object is * {@link String } * */ public String getContractNumber() { return contractNumber; } /** * Sets the value of the contractNumber property. * * @param value * allowed object is * {@link String } * */ public void setContractNumber(String value) { this.contractNumber = value; } /** * Gets the value of the thm property. * * @return * possible object is * {@link Boolean } * */ public Boolean isTHM() { return thm; } /** * Sets the value of the thm property. * * @param value * allowed object is * {@link Boolean } * */ public void setTHM(Boolean value) { this.thm = value; }
/** * Gets the value of the nonReturnableContainer property. * * @return * possible object is * {@link Boolean } * */ public Boolean isNonReturnableContainer() { return nonReturnableContainer; } /** * Sets the value of the nonReturnableContainer property. * * @param value * allowed object is * {@link Boolean } * */ public void setNonReturnableContainer(Boolean value) { this.nonReturnableContainer = value; } /** * Gets the value of the specialConditionCode property. * * @return * possible object is * {@link String } * */ public String getSpecialConditionCode() { return specialConditionCode; } /** * Sets the value of the specialConditionCode property. * * @param value * allowed object is * {@link String } * */ public void setSpecialConditionCode(String value) { this.specialConditionCode = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\INVOICListLineItemExtensionType.java
2
请在Spring Boot框架中完成以下Java代码
private boolean nullSafeEquals(Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } return o1.equals(o2); } private int nullSafeHashCode(Object o) { return (o != null) ? o.hashCode() : 0; } @Override public String toString() { StringBuilder string = new StringBuilder(this.name); buildToStringProperty(string, "type", this.type); buildToStringProperty(string, "sourceType", this.sourceType); buildToStringProperty(string, "description", this.description); buildToStringProperty(string, "defaultValue", this.defaultValue); buildToStringProperty(string, "deprecation", this.deprecation); return string.toString(); } private void buildToStringProperty(StringBuilder string, String property, Object value) { if (value != null) { string.append(" ").append(property).append(":").append(value); } } @Override public int compareTo(ItemMetadata o) { return getName().compareTo(o.getName()); } public static ItemMetadata newGroup(String name, String type, String sourceType, String sourceMethod) { return new ItemMetadata(ItemType.GROUP, name, null, type, sourceType, sourceMethod, null, null, null); } public static ItemMetadata newProperty(String prefix, String name, String type, String sourceType, String sourceMethod, String description, Object defaultValue, ItemDeprecation deprecation) { return new ItemMetadata(ItemType.PROPERTY, prefix, name, type, sourceType, sourceMethod, description, defaultValue, deprecation);
} public static String newItemMetadataPrefix(String prefix, String suffix) { return prefix.toLowerCase(Locale.ENGLISH) + ConventionUtils.toDashedCase(suffix); } /** * The item type. */ public enum ItemType { /** * Group item type. */ GROUP, /** * Property item type. */ PROPERTY } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ItemMetadata.java
2
请在Spring Boot框架中完成以下Java代码
public ReturnT<String> triggerJob(HttpServletRequest request, int id, String executorParam, String addressList) { // login user XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY); // trigger return xxlJobService.trigger(loginUser, id, executorParam, addressList); } @RequestMapping("/nextTriggerTime") @ResponseBody public ReturnT<List<String>> nextTriggerTime(String scheduleType, String scheduleConf) { XxlJobInfo paramXxlJobInfo = new XxlJobInfo(); paramXxlJobInfo.setScheduleType(scheduleType); paramXxlJobInfo.setScheduleConf(scheduleConf); List<String> result = new ArrayList<>(); try { Date lastTime = new Date(); for (int i = 0; i < 5; i++) {
lastTime = JobScheduleHelper.generateNextValidTime(paramXxlJobInfo, lastTime); if (lastTime != null) { result.add(DateUtil.formatDateTime(lastTime)); } else { break; } } } catch (Exception e) { logger.error(e.getMessage(), e); return new ReturnT<List<String>>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) + e.getMessage()); } return new ReturnT<List<String>>(result); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\JobInfoController.java
2
请在Spring Boot框架中完成以下Java代码
public class ActivityId implements RepoIdAware { int repoId; @JsonCreator public static ActivityId ofRepoId(final int repoId) { return new ActivityId(repoId); } @Nullable public static ActivityId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new ActivityId(repoId) : null; } public static int toRepoId(@Nullable final ActivityId id)
{ return id != null ? id.getRepoId() : -1; } private ActivityId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_Activity_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\acct\api\ActivityId.java
2
请完成以下Java代码
public I_M_HU_LUTU_Configuration createNewLUTUConfiguration(final I_PP_Order_BOMLine ppOrderBOMLine) { PPOrderUtil.assertReceipt(ppOrderBOMLine); final org.eevolution.model.I_PP_Order ppOrder = ppOrderBOMLine.getPP_Order(); final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(ppOrder.getC_BPartner_ID()); final I_M_HU_PI_Item_Product tuPIItemProduct = getM_HU_PI_Item_Product(ppOrderBOMLine); final ProductId cuProductId = ProductId.ofRepoId(ppOrderBOMLine.getM_Product_ID()); final UomId cuUOMId = Services.get(IPPOrderBOMBL.class).getBOMLineUOMId(ppOrderBOMLine); // LU/TU COnfiguration final ILUTUConfigurationFactory lutuConfigurationFactory = Services.get(ILUTUConfigurationFactory.class); final I_M_HU_LUTU_Configuration lutuConfiguration = lutuConfigurationFactory.createLUTUConfiguration( tuPIItemProduct, cuProductId, cuUOMId, bpartnerId, true); // noLUForVirtualTU == true => for a "virtual" TU, we want the LU-part of the lutuconfig to be empty by default updateLUTUConfigurationFromDocumentLine(lutuConfiguration, ppOrderBOMLine); return lutuConfiguration; } @Override public I_M_HU_PI_Item_Product getM_HU_PI_Item_Product(@NonNull final I_PP_Order_BOMLine ppOrderBOMLine) { final IHUPIItemProductDAO hupiItemProductDAO = Services.get(IHUPIItemProductDAO.class); final Properties ctx = InterfaceWrapperHelper.getCtx(ppOrderBOMLine); // // First, try getting the M_HU_Item_Product the ppOrder's M_HU_LUTU_Configuration { final I_M_HU_LUTU_Configuration lutuConfiguration = ppOrderBOMLine.getM_HU_LUTU_Configuration(); final I_M_HU_PI_Item_Product pip = lutuConfiguration != null ? ILUTUConfigurationFactory.extractHUPIItemProductOrNull(lutuConfiguration) : null; if (pip != null) { return pip; } } // // Fallback: return the virtual PI Item Product final I_M_HU_PI_Item_Product pipVirtual = hupiItemProductDAO.retrieveVirtualPIMaterialItemProduct(ctx); return pipVirtual;
} @Override public void updateLUTUConfigurationFromDocumentLine(@NonNull final I_M_HU_LUTU_Configuration lutuConfiguration, @NonNull final I_PP_Order_BOMLine documentLine) { final I_PP_Order ppOrder = InterfaceWrapperHelper.create(documentLine.getPP_Order(), I_PP_Order.class); PPOrderDocumentLUTUConfigurationHandler.instance.updateLUTUConfigurationFromDocumentLine(lutuConfiguration, ppOrder); } @Override public void setCurrentLUTUConfiguration(@NonNull final I_PP_Order_BOMLine documentLine, final I_M_HU_LUTU_Configuration lutuConfiguration) { documentLine.setM_HU_LUTU_Configuration(lutuConfiguration); } @Override public I_M_HU_LUTU_Configuration getCurrentLUTUConfigurationOrNull(@NonNull final I_PP_Order_BOMLine documentLine) { final I_M_HU_LUTU_Configuration lutuConfiguration = documentLine.getM_HU_LUTU_Configuration(); if (lutuConfiguration == null || lutuConfiguration.getM_HU_LUTU_Configuration_ID() <= 0) { return null; } return lutuConfiguration; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\PPOrderBOMLineDocumentLUTUConfigurationHandler.java
1
请完成以下Java代码
public CmmnParser getCmmnParser() { return cmmnParser; } public void setCmmnParser(CmmnParser cmmnParser) { this.cmmnParser = cmmnParser; } public CaseDefinitionDiagramHelper getCaseDefinitionDiagramHelper() { return caseDefinitionDiagramHelper; } public void setCaseDefinitionDiagramHelper(CaseDefinitionDiagramHelper caseDefinitionDiagramHelper) { this.caseDefinitionDiagramHelper = caseDefinitionDiagramHelper; } public boolean isUsePrefixId() { return usePrefixId; } public void setUsePrefixId(boolean usePrefixId) { this.usePrefixId = usePrefixId; } protected class CmmnParseContextImpl implements CmmnParseContext { protected final EngineResource resource; protected final boolean newDeployment; public CmmnParseContextImpl(EngineResource resource, boolean newDeployment) { this.resource = resource; this.newDeployment = newDeployment; } @Override public EngineResource resource() {
return resource; } @Override public boolean enableSafeXml() { return cmmnEngineConfiguration.isEnableSafeCmmnXml(); } @Override public String xmlEncoding() { return cmmnEngineConfiguration.getXmlEncoding(); } @Override public boolean validateXml() { // On redeploy, we assume it is validated at the first deploy return newDeployment && !cmmnEngineConfiguration.isDisableCmmnXmlValidation(); } @Override public boolean validateCmmnModel() { // On redeploy, we assume it is validated at the first deploy return newDeployment && validateXml(); } @Override public CaseValidator caseValidator() { return cmmnEngineConfiguration.getCaseValidator(); } } @Override public void undeploy(EngineDeployment parentDeployment, boolean cascade) { // Nothing to do } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\deployer\CmmnDeployer.java
1
请完成以下Java代码
public void setMemberIcon(String memberIcon) { this.memberIcon = memberIcon; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getCreateTime() { return createTime; } 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(", subjectId=").append(subjectId); sb.append(", memberNickName=").append(memberNickName); 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\CmsSubjectComment.java
1
请在Spring Boot框架中完成以下Java代码
public class XmlVat { @Nullable String vatNumber; @NonNull BigDecimal vat; @Singular List<XmlVatRate> vatRates; public XmlVat withMod(@Nullable final VatMod vatMod) { if (vatMod == null) { return this; } final XmlVatBuilder builder = XmlVat.builder(); if (vatMod.getVatNumber() != null) { builder.vatNumber(vatMod.getVatNumber()); }
// When it comes to the vat amount and rates, we don't just "patch", but replace the whole thing. return builder .vat(vatMod.getVat()) .clearVatRates() .vatRates(vatMod.getVatRates()) .build(); } @Value @Builder public static class VatMod { @NonNull BigDecimal vat; @Nullable String vatNumber; @Singular List<XmlVatRate> vatRates; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\request\model\payload\body\vat\XmlVat.java
2
请在Spring Boot框架中完成以下Java代码
public long getAmount() { return amount; } /** * Sets the value of the amount property. * */ public void setAmount(long value) { this.amount = value; } /** * Gets the value of the currency property. * * @return * possible object is * {@link String } * */ public String getCurrency() { return currency;
} /** * Sets the value of the currency property. * * @param value * allowed object is * {@link String } * */ public void setCurrency(String value) { this.currency = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\HigherInsurance.java
2
请完成以下Java代码
public void setDataEntry_Section_ID (int DataEntry_Section_ID) { if (DataEntry_Section_ID < 1) set_ValueNoCheck (COLUMNNAME_DataEntry_Section_ID, null); else set_ValueNoCheck (COLUMNNAME_DataEntry_Section_ID, Integer.valueOf(DataEntry_Section_ID)); } /** Get Sektion. @return Sektion */ @Override public int getDataEntry_Section_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_Section_ID); 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.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Line.java
1
请完成以下Java代码
public void setImported (final @Nullable java.sql.Timestamp Imported) { set_Value (COLUMNNAME_Imported, Imported); } @Override public java.sql.Timestamp getImported() { return get_ValueAsTimestamp(COLUMNNAME_Imported); } @Override public void setIsMatchAmounts (final boolean IsMatchAmounts) { set_Value (COLUMNNAME_IsMatchAmounts, IsMatchAmounts); } @Override public boolean isMatchAmounts()
{ return get_ValueAsBoolean(COLUMNNAME_IsMatchAmounts); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\org\adempiere\banking\model\X_C_BankStatement_Import_File.java
1
请完成以下Java代码
protected void closeJarFile() { synchronized (this.archiveLock) { this.archiveUseCount--; } } @Override protected boolean isMultiRelease() { Boolean multiRelease = this.multiRelease; if (multiRelease == null) { synchronized (this.archiveLock) { multiRelease = this.multiRelease; if (multiRelease == null) { // JarFile.isMultiRelease() is final so we must go to the manifest Manifest manifest = getManifest(); Attributes attributes = (manifest != null) ? manifest.getMainAttributes() : null; multiRelease = (attributes != null) && attributes.containsKey(MULTI_RELEASE); this.multiRelease = multiRelease; } } } return multiRelease; } @Override public void gc() { synchronized (this.archiveLock) { if (this.archive != null && this.archiveUseCount == 0) { try { if (!this.useCaches) {
this.archive.close(); } } catch (IOException ex) { // Ignore } this.archive = null; this.archiveEntries = null; } } } private JarURLConnection connect() throws IOException { URLConnection connection = this.url.openConnection(); ResourceUtils.useCachesIfNecessary(connection); Assert.state(connection instanceof JarURLConnection, () -> "URL '%s' did not return a JAR connection".formatted(this.url)); connection.connect(); return (JarURLConnection) connection; } }
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\servlet\NestedJarResourceSet.java
1
请完成以下Java代码
public String toString() { return ObjectUtils.toString(this); } private final void updateFromAction() { final String displayName = action.getDisplayName(); setText(displayName); // setToolTipText(displayName); setOpaque(false); setChecked(action.isToggled()); } public final boolean isChecked() { return this.isSelected(); } private final void setChecked(final boolean checked) { this.setSelected(checked); } protected void onActionPerformed() { if (!isEnabled()) { return; }
setEnabled(false); try { action.setToggled(isChecked()); action.execute(); } catch (Exception e) { final int windowNo = Env.getWindowNo(this); Services.get(IClientUI.class).error(windowNo, e); } finally { setEnabled(true); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\sideactions\swing\CheckableSideActionComponent.java
1
请完成以下Java代码
public void setActive(final Boolean active) { this.active = active; activeSet = true; } public void setSeqNo(final Integer seqNo) { this.seqNo = seqNo; seqNoSet = true; } public void setProductNo(final String productNo) { this.productNo = productNo; productNoSet = true; } public void setDescription(final String description) { this.description = description; descriptionSet = true; } public void setCuEAN(final String cuEAN) { this.cuEAN = cuEAN; cuEANSet = true; } public void setGtin(final String gtin) { this.gtin = gtin; gtinSet = true; } public void setCustomerLabelName(final String customerLabelName) { this.customerLabelName = customerLabelName; customerLabelNameSet = true; } public void setIngredients(final String ingredients) { this.ingredients = ingredients; ingredientsSet = true; } public void setCurrentVendor(final Boolean currentVendor) { this.currentVendor = currentVendor; currentVendorSet = true; } public void setExcludedFromSales(final Boolean excludedFromSales) { this.excludedFromSales = excludedFromSales; excludedFromSalesSet = true; }
public void setExclusionFromSalesReason(final String exclusionFromSalesReason) { this.exclusionFromSalesReason = exclusionFromSalesReason; exclusionFromSalesReasonSet = true; } public void setDropShip(final Boolean dropShip) { this.dropShip = dropShip; dropShipSet = true; } public void setUsedForVendor(final Boolean usedForVendor) { this.usedForVendor = usedForVendor; usedForVendorSet = true; } public void setExcludedFromPurchase(final Boolean excludedFromPurchase) { this.excludedFromPurchase = excludedFromPurchase; excludedFromPurchaseSet = true; } public void setExclusionFromPurchaseReason(final String exclusionFromPurchaseReason) { this.exclusionFromPurchaseReason = exclusionFromPurchaseReason; exclusionFromPurchaseReasonSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-product\src\main\java\de\metas\common\product\v2\request\JsonRequestBPartnerProductUpsert.java
1
请完成以下Java代码
public void setEnabledCustom(final boolean enabledCustom) { if (this.enabledCustom == enabledCustom) { return; } this.enabledCustom = enabledCustom; update(); } public void setEnabledByCaptureSequence(final LocationCaptureSequence captureSequence) { final boolean enabled = captureSequence.hasPart(partName); setEnabledByCaptureSequence(enabled); } private void setEnabledByCaptureSequence(final boolean enabledByCaptureSequence) { if (this.enabledByCaptureSequence == enabledByCaptureSequence) { return; } this.enabledByCaptureSequence = enabledByCaptureSequence; update(); } private final void update() { final boolean enabled = enabledCustom && enabledByCaptureSequence; label.setEnabled(enabled); label.setVisible(enabled); field.setEnabled(enabled); field.setVisible(enabled); }
public void setLabelText(final String labelText) { label.setText(labelText); } public JLabel getLabel() { return label; } public JComponent getField() { return field; } } } // VLocationDialog
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLocationDialog.java
1
请完成以下Java代码
public String getDbName() { return dbName; } @Override public String getDbUser() { return dbUser; } @Override public String getDbPassword() { return dbPassword; } @Override public IScriptsRegistry getScriptsRegistry() { return scriptsRegistry; } @Override public Connection getConnection() { // // First time => driver initialization
if (conn == null) { final ISQLDatabaseDriver dbDriver = SQLDatabaseDriverFactory.get().getSQLDatabaseDriver(dbType); if (dbDriver == null) { throw new IllegalStateException("No driver found for database type: " + dbType); } } try { if (conn != null && !conn.isClosed()) { return conn; } final ISQLDatabaseDriver dbDriver = SQLDatabaseDriverFactory.get().getSQLDatabaseDriver(dbType); conn = dbDriver.getConnection(dbHostname, dbPort, dbName, dbUser, dbPassword); conn.setAutoCommit(true); } catch (final SQLException e) { throw new RuntimeException("Failed to get a JDBC connection. Please check your config for : " + this, e); } return conn; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\impl\SQLDatabase.java
1
请完成以下Java代码
public class C_OrderLine { private final DimensionService dimensionService = SpringContextHolder.instance.getBean(DimensionService.class); private final OrderGroupRepository orderGroupRepo = SpringContextHolder.instance.getBean(OrderGroupRepository.class); private final IProductAcctDAO productAcctDAO = Services.get(IProductAcctDAO.class); private final IProductBL productBL = Services.get(IProductBL.class); @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_M_Product_ID, I_C_OrderLine.COLUMNNAME_C_Order_CompensationGroup_ID }) public void updateActivity(final I_C_OrderLine orderLine) { if (InterfaceWrapperHelper.isCopy(orderLine)) { // let the activity be copied from the source. return; } final ActivityId groupActivityId = getGroupActivityId(orderLine); orderLine.setC_Activity_ID(ActivityId.toRepoId(groupActivityId)); if (orderLine.getC_Activity_ID() > 0) { return; // was already set, so don't try to auto-fill it } final ProductId productId = ProductId.ofRepoIdOrNull(orderLine.getM_Product_ID()); if (productId == null) { return; } // IsDiverse flag orderLine.setIsDiverse(productBL.isDiverse(productId)); // Activity final ActivityId productActivityId = productAcctDAO.retrieveActivityForAcct( ClientId.ofRepoId(orderLine.getAD_Client_ID()), OrgId.ofRepoId(orderLine.getAD_Org_ID()), productId); if (productActivityId == null) { return; } final Dimension orderLineDimension = dimensionService.getFromRecord(orderLine); if (orderLineDimension == null) { //nothing to do return; }
dimensionService.updateRecord(orderLine, orderLineDimension.withActivityId(productActivityId)); } private ActivityId getGroupActivityId(final I_C_OrderLine orderLine) { if (orderLine.getC_Order_CompensationGroup_ID() <= 0) { return null; } final GroupId groupId = OrderGroupRepository.extractGroupIdOrNull(orderLine); if (groupId == null) { return null; } final Group group = orderGroupRepo.retrieveGroupIfExists(groupId); if (group == null) { return null; } return group.getActivityId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\activity\model\validator\C_OrderLine.java
1
请完成以下Java代码
public class AD_User_TabCallout extends TabCalloutAdapter { private final IMKTGChannelDao mktgChannelDao = Services.get(IMKTGChannelDao.class); private final IUserDAO userDAO = Services.get(IUserDAO.class); private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); private static final AdMessageKey MSG_CAN_NOT_REMOVE_CHANNEL = AdMessageKey.of("de.metas.marketing.base.userMarketingChannelRemovalError"); private static final String SYS_CONFIG_MARKETING_CHANNELS_ENFORCED = "de.metas.marketing.EnforceUserHasMarketingChannels"; @Override public void onSave(final ICalloutRecord calloutRecord) { final I_AD_User user = calloutRecord.getModel(I_AD_User.class); if (!isMarketingChannelsUseEnforced(user.getAD_Client_ID(), user.getAD_Org_ID())) { return; } if (userDAO.isSystemUser(UserId.ofRepoId(user.getAD_User_ID()))) { return;
} boolean canBeSaved = true; if (mktgChannelDao.retrieveMarketingChannelsCountForUser(UserId.ofRepoId(user.getAD_User_ID())) <= 0) { canBeSaved = false; } if (!canBeSaved) { throw new AdempiereException(MSG_CAN_NOT_REMOVE_CHANNEL).markAsUserValidationError(); } } private boolean isMarketingChannelsUseEnforced(int clientID, int orgID) { return sysConfigBL.getBooleanValue(SYS_CONFIG_MARKETING_CHANNELS_ENFORCED, false, clientID, orgID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\callout\AD_User_TabCallout.java
1
请完成以下Java代码
public void setPP_Maturing_Candidates_v_ID (final int PP_Maturing_Candidates_v_ID) { if (PP_Maturing_Candidates_v_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Maturing_Candidates_v_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Maturing_Candidates_v_ID, PP_Maturing_Candidates_v_ID); } @Override public int getPP_Maturing_Candidates_v_ID() { return get_ValueAsInt(COLUMNNAME_PP_Maturing_Candidates_v_ID); } @Override public org.eevolution.model.I_PP_Order_Candidate getPP_Order_Candidate() { return get_ValueAsPO(COLUMNNAME_PP_Order_Candidate_ID, org.eevolution.model.I_PP_Order_Candidate.class); } @Override public void setPP_Order_Candidate(final org.eevolution.model.I_PP_Order_Candidate PP_Order_Candidate) { set_ValueFromPO(COLUMNNAME_PP_Order_Candidate_ID, org.eevolution.model.I_PP_Order_Candidate.class, PP_Order_Candidate); } @Override public void setPP_Order_Candidate_ID (final int PP_Order_Candidate_ID) { if (PP_Order_Candidate_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_Candidate_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_Candidate_ID, PP_Order_Candidate_ID); } @Override public int getPP_Order_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Candidate_ID); } @Override public org.eevolution.model.I_PP_Product_BOMVersions getPP_Product_BOMVersions() { return get_ValueAsPO(COLUMNNAME_PP_Product_BOMVersions_ID, org.eevolution.model.I_PP_Product_BOMVersions.class); } @Override public void setPP_Product_BOMVersions(final org.eevolution.model.I_PP_Product_BOMVersions PP_Product_BOMVersions) { set_ValueFromPO(COLUMNNAME_PP_Product_BOMVersions_ID, org.eevolution.model.I_PP_Product_BOMVersions.class, PP_Product_BOMVersions); }
@Override public void setPP_Product_BOMVersions_ID (final int PP_Product_BOMVersions_ID) { if (PP_Product_BOMVersions_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, PP_Product_BOMVersions_ID); } @Override public int getPP_Product_BOMVersions_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_BOMVersions_ID); } @Override public void setPP_Product_Planning_ID (final int PP_Product_Planning_ID) { if (PP_Product_Planning_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Product_Planning_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Product_Planning_ID, PP_Product_Planning_ID); } @Override public int getPP_Product_Planning_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_Planning_ID); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PP_Maturing_Candidates_v.java
1
请完成以下Java代码
public void setParamValue (final java.lang.String ParamValue) { set_Value (COLUMNNAME_ParamValue, ParamValue); } @Override public java.lang.String getParamValue() { return get_ValueAsString(COLUMNNAME_ParamValue); } @Override public org.compiere.model.I_PP_ComponentGenerator getPP_ComponentGenerator() { return get_ValueAsPO(COLUMNNAME_PP_ComponentGenerator_ID, org.compiere.model.I_PP_ComponentGenerator.class); } @Override public void setPP_ComponentGenerator(final org.compiere.model.I_PP_ComponentGenerator PP_ComponentGenerator) { set_ValueFromPO(COLUMNNAME_PP_ComponentGenerator_ID, org.compiere.model.I_PP_ComponentGenerator.class, PP_ComponentGenerator); } @Override public void setPP_ComponentGenerator_ID (final int PP_ComponentGenerator_ID) { if (PP_ComponentGenerator_ID < 1) set_Value (COLUMNNAME_PP_ComponentGenerator_ID, null); else set_Value (COLUMNNAME_PP_ComponentGenerator_ID, PP_ComponentGenerator_ID); }
@Override public int getPP_ComponentGenerator_ID() { return get_ValueAsInt(COLUMNNAME_PP_ComponentGenerator_ID); } @Override public void setPP_ComponentGenerator_Param_ID (final int PP_ComponentGenerator_Param_ID) { if (PP_ComponentGenerator_Param_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_ComponentGenerator_Param_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_ComponentGenerator_Param_ID, PP_ComponentGenerator_Param_ID); } @Override public int getPP_ComponentGenerator_Param_ID() { return get_ValueAsInt(COLUMNNAME_PP_ComponentGenerator_Param_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PP_ComponentGenerator_Param.java
1
请完成以下Java代码
private IQueryBuilder<I_C_Flatrate_Term> existingSubscriptionsQueryBuilder(@NonNull final OrgId orgId, @NonNull final BPartnerId bPartnerId, @NonNull final Instant date) { return queryBL.createQueryBuilder(I_C_Flatrate_Term.class) .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_AD_Org_ID, orgId) .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID, bPartnerId) .addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Quit.getCode()) .addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Voided.getCode()) .addCompareFilter(I_C_Flatrate_Term.COLUMNNAME_EndDate, Operator.GREATER, date); } @Override public boolean bpartnerHasExistingRunningTerms(@NonNull final I_C_Flatrate_Term flatrateTerm) { if (flatrateTerm.getC_Order_Term_ID() <= 0) {
return true; // if this term has no C_Order_Term_ID, then it *is* one of those running terms } final Instant instant = TimeUtil.asInstant(flatrateTerm.getC_Order_Term().getDateOrdered()); final IQueryBuilder<I_C_Flatrate_Term> queryBuilder = // existingSubscriptionsQueryBuilder(OrgId.ofRepoId(flatrateTerm.getAD_Org_ID()), BPartnerId.ofRepoId(flatrateTerm.getBill_BPartner_ID()), instant); queryBuilder.addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_C_Order_Term_ID, flatrateTerm.getC_Order_Term_ID()); return queryBuilder.create() .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\FlatrateDAO.java
1
请完成以下Java代码
public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setRevision (final @Nullable java.lang.String Revision) { set_Value (COLUMNNAME_Revision, Revision); } @Override public java.lang.String getRevision() { return get_ValueAsString(COLUMNNAME_Revision); } @Override public org.compiere.model.I_AD_Sequence getSerialNo_Sequence() { return get_ValueAsPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class); } @Override public void setSerialNo_Sequence(final org.compiere.model.I_AD_Sequence SerialNo_Sequence) { set_ValueFromPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class, SerialNo_Sequence); } @Override public void setSerialNo_Sequence_ID (final int SerialNo_Sequence_ID) { if (SerialNo_Sequence_ID < 1) set_Value (COLUMNNAME_SerialNo_Sequence_ID, null); else set_Value (COLUMNNAME_SerialNo_Sequence_ID, SerialNo_Sequence_ID); } @Override public int getSerialNo_Sequence_ID()
{ return get_ValueAsInt(COLUMNNAME_SerialNo_Sequence_ID); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_BOM.java
1
请完成以下Java代码
public class PostDao { private Logger logger = Logger.getLogger(PostController.class.getName()); private SessionFactory sessionFactory; public PostDao() {} @Inject public PostDao(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Object add(Post post) { Session session = sessionFactory.openSession(); session.beginTransaction(); Object id = session.save(post); session.getTransaction().commit(); session.close(); return id; } public Post findById(int id) {
Session session = sessionFactory.openSession(); session.beginTransaction(); Post post = (Post) session.get(Post.class, id); session.getTransaction().commit(); session.close(); return post; } public List<Post> all() { Session session = sessionFactory.openSession(); session.beginTransaction(); List<Post> posts = (List<Post>) session.createQuery("FROM Post p").list(); session.getTransaction().commit(); session.close(); return posts; } }
repos\tutorials-master\web-modules\vraptor\src\main\java\com\baeldung\daos\PostDao.java
1
请完成以下Java代码
public static String buildStringRestriction(@Nullable final String criteriaFunction, final String columnSQL, @Nullable final Object value, final boolean isIdentifier, final List<Object> params) { final String valueStr = prepareSearchString(value, isIdentifier); String whereClause; if (Check.isBlank(criteriaFunction)) { whereClause = "UPPER(" + DBConstants.FUNC_unaccent_string(columnSQL) + ")" + " LIKE" + " UPPER(" + DBConstants.FUNC_unaccent_string("?") + ")"; } else { //noinspection ConstantConditions whereClause = "UPPER(" + DBConstants.FUNC_unaccent_string(columnSQL) + ")" + " LIKE " + "UPPER(" + DBConstants.FUNC_unaccent_string(criteriaFunction.replaceFirst(columnSQL, "?")) + ")"; } params.add(valueStr); return whereClause; } public static String buildStringRestriction(final String columnSQL, final int displayType, final Object value, final Object valueTo, final boolean isRange, final List<Object> params) { final StringBuffer where = new StringBuffer(); if (isRange) { if (value != null || valueTo != null) where.append(" ("); if (value != null) { where.append(columnSQL).append(">?"); params.add(value); } if (valueTo != null) { if (value != null) where.append(" AND "); where.append(columnSQL).append("<?"); params.add(valueTo); } if (value != null || valueTo != null) where.append(") "); } else { where.append(columnSQL).append("=?"); params.add(value); } return where.toString(); } public static String prepareSearchString(final Object value) { return prepareSearchString(value, false); } public static String prepareSearchString(final Object value, final boolean isIdentifier)
{ if (value == null || value.toString().length() == 0) { return null; } String valueStr; if (isIdentifier) { // metas-2009_0021_AP1_CR064: begin valueStr = ((String)value).trim(); if (!valueStr.startsWith("%")) valueStr = "%" + value; // metas-2009_0021_AP1_CR064: end if (!valueStr.endsWith("%")) valueStr += "%"; } else { valueStr = (String)value; if (valueStr.startsWith("%")) { ; // nothing } else if (valueStr.endsWith("%")) { ; // nothing } else if (valueStr.indexOf("%") < 0) { valueStr = "%" + valueStr + "%"; } else { ; // nothing } } return valueStr; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\FindHelper.java
1
请在Spring Boot框架中完成以下Java代码
final class RedirectParameters { private final String id; private final Issuer issuer; private final String algorithm; private final byte[] signature; private final byte[] content; RedirectParameters(Map<String, String> parameters, String parametersQuery, RequestAbstractType request) { this.id = request.getID(); this.issuer = request.getIssuer(); this.algorithm = parameters.get(Saml2ParameterNames.SIG_ALG); if (parameters.get(Saml2ParameterNames.SIGNATURE) != null) { this.signature = Saml2Utils.samlDecode(parameters.get(Saml2ParameterNames.SIGNATURE)); } else { this.signature = null; } Map<String, String> queryParams = UriComponentsBuilder.newInstance() .query(parametersQuery) .build(true) .getQueryParams() .toSingleValueMap(); String relayState = parameters.get(Saml2ParameterNames.RELAY_STATE); this.content = getContent(Saml2ParameterNames.SAML_REQUEST, relayState, queryParams); } RedirectParameters(Map<String, String> parameters, String parametersQuery, StatusResponseType response) { this.id = response.getID(); this.issuer = response.getIssuer(); this.algorithm = parameters.get(Saml2ParameterNames.SIG_ALG); if (parameters.get(Saml2ParameterNames.SIGNATURE) != null) { this.signature = Saml2Utils.samlDecode(parameters.get(Saml2ParameterNames.SIGNATURE)); } else { this.signature = null; } Map<String, String> queryParams = UriComponentsBuilder.newInstance() .query(parametersQuery) .build(true) .getQueryParams() .toSingleValueMap(); String relayState = parameters.get(Saml2ParameterNames.RELAY_STATE); this.content = getContent(Saml2ParameterNames.SAML_RESPONSE, relayState, queryParams); } static byte[] getContent(String samlObject, String relayState, final Map<String, String> queryParams) { if (Objects.nonNull(relayState)) { return String .format("%s=%s&%s=%s&%s=%s", samlObject, queryParams.get(samlObject), Saml2ParameterNames.RELAY_STATE, queryParams.get(Saml2ParameterNames.RELAY_STATE), Saml2ParameterNames.SIG_ALG, queryParams.get(Saml2ParameterNames.SIG_ALG)) .getBytes(StandardCharsets.UTF_8); } else { return String .format("%s=%s&%s=%s", samlObject, queryParams.get(samlObject), Saml2ParameterNames.SIG_ALG, queryParams.get(Saml2ParameterNames.SIG_ALG)) .getBytes(StandardCharsets.UTF_8); } } String getId() { return this.id;
} Issuer getIssuer() { return this.issuer; } byte[] getContent() { return this.content; } String getAlgorithm() { return this.algorithm; } byte[] getSignature() { return this.signature; } boolean hasSignature() { return this.signature != null; } } } interface DecryptionConfigurer { void decrypt(XMLObject object); } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\internal\OpenSamlOperations.java
2
请完成以下Java代码
private String extractMailContent(final UserNotificationRequest request) { final body htmlBody = new body(); final String htmlBodyString = extractContentText(request, /* html */true); if (!Check.isEmpty(htmlBodyString)) { Splitter.on("\n") .splitToList(htmlBodyString.trim()) .forEach(htmlLine -> htmlBody.addElement(new ClearElement(htmlLine)).addElement(new br())); } return new html().addElement(htmlBody).toString(); } private NotificationMessageFormatter prepareMessageFormatter(final UserNotificationRequest request) { final NotificationMessageFormatter formatter = NotificationMessageFormatter.newInstance(); final TargetAction targetAction = request.getTargetAction(); if (targetAction instanceof TargetRecordAction) { final TargetRecordAction targetRecordAction = TargetRecordAction.cast(targetAction); final TableRecordReference targetRecord = targetRecordAction.getRecord(); final String targetRecordDisplayText = targetRecordAction.getRecordDisplayText(); if (!Check.isEmpty(targetRecordDisplayText))
{ formatter.recordDisplayText(targetRecord, targetRecordDisplayText); } final AdWindowId targetWindowId = targetRecordAction.getAdWindowId().orElse(null); if (targetWindowId != null) { formatter.recordWindowId(targetRecord, targetWindowId); } } else if (targetAction instanceof TargetViewAction) { final TargetViewAction targetViewAction = TargetViewAction.cast(targetAction); final String viewURL = WebuiURLs.newInstance().getViewUrl(targetViewAction.getAdWindowId(), targetViewAction.getViewId()); formatter.bottomUrl(viewURL); } return formatter; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\NotificationSenderTemplate.java
1
请完成以下Java代码
public class PP_Order_SyncTo_LeichMehl extends PP_Order_SyncTo_ExternalSystem { private final ExportPPOrderToLeichMehlService exportPPOrderToLeichMehlService = SpringContextHolder.instance.getBean(ExportPPOrderToLeichMehlService.class); private static final String PARAM_EXTERNAL_SYSTEM_CONFIG_LEICHMEHL_ID = I_ExternalSystem_Config_LeichMehl.COLUMNNAME_ExternalSystem_Config_LeichMehl_ID; @Param(parameterName = PARAM_EXTERNAL_SYSTEM_CONFIG_LEICHMEHL_ID) private int externalSystemConfigLeichMehlId; @Override protected ExternalSystemType getExternalSystemType() { return ExternalSystemType.LeichUndMehl; } @Override protected IExternalSystemChildConfigId getExternalSystemChildConfigId() {
return ExternalSystemLeichMehlConfigId.ofRepoId(externalSystemConfigLeichMehlId); } @Override protected String getExternalSystemParam() { return PARAM_EXTERNAL_SYSTEM_CONFIG_LEICHMEHL_ID; } @Override protected ExportToExternalSystemService getExportPPOrderToExternalSystem() { return exportPPOrderToLeichMehlService; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\leichmehl\export\pporder\PP_Order_SyncTo_LeichMehl.java
1
请完成以下Java代码
private static class DefaultGLCategories { private final ImmutableMap<GLCategoryType, GLCategory> byCategoryType; private final ImmutableList<GLCategory> list; DefaultGLCategories(final ImmutableList<GLCategory> list) { this.byCategoryType = Maps.uniqueIndex(list, GLCategory::getCategoryType); this.list = list; } public Optional<GLCategoryId> getByCategoryType(@NonNull final GLCategoryType categoryType) { final GLCategory category = byCategoryType.get(categoryType); if (category != null)
{ return Optional.of(category.getId()); } return getDefaultId(); } public Optional<GLCategoryId> getDefaultId() { return !list.isEmpty() ? Optional.of(list.get(0).getId()) : Optional.empty(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\GLCategoryRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonOutOfStockNoticeRequest { @ApiModelProperty( value = "Identifier of the product in question. Can be\n" + "* a plain `<M_Product_ID>`,\n" + "* the M_Product.Value as `<val-M_Product.Value>`\n" + "* or something like `ext-<ExternalSystemName>-<M_Product_ID.ExternalId>`") @NonNull @JsonProperty("productIdentifier") String productIdentifier; @ApiModelProperty( value = "Optional; Specifies if metasfresh shall create and complete an inventory document for this out of stock notice. Default if omitted: `true`") @JsonInclude(JsonInclude.Include.NON_NULL) @NonNull Boolean createInventory; @ApiModelProperty( value = "Optional; Specifies if unprocessed shipment schedules with with this request's warehouse, product ans attributes shall be closed. Default if omitted: `true`") @JsonInclude(JsonInclude.Include.NON_NULL) @NonNull Boolean closePendingShipmentSchedules; @ApiModelProperty( value = "AD_Org.value") @Nullable @JsonProperty("orgCode") String orgCode; @Nullable
@JsonProperty("attributeSetInstance") @JsonInclude(JsonInclude.Include.NON_NULL) JsonAttributeSetInstance attributeSetInstance; @Builder public JsonOutOfStockNoticeRequest( @NonNull @JsonProperty("productIdentifier") final String productIdentifier, @Nullable @JsonProperty("attributeSetInstance") final JsonAttributeSetInstance attributeSetInstance, @Nullable @JsonProperty("orgCode") final String orgCode, @Nullable @JsonProperty("createInventory") final Boolean createInventory, @Nullable @JsonProperty("closePendingShipmentSchedules") final Boolean closePendingShipmentSchedules) { this.orgCode = orgCode; this.productIdentifier = productIdentifier; this.attributeSetInstance = attributeSetInstance; this.createInventory = CoalesceUtil.coalesceNotNull(createInventory, Boolean.TRUE); this.closePendingShipmentSchedules = CoalesceUtil.coalesceNotNull(closePendingShipmentSchedules, Boolean.TRUE); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v2\warehouse\JsonOutOfStockNoticeRequest.java
2
请在Spring Boot框架中完成以下Java代码
protected VariableServiceConfiguration getVariableServiceConfiguration() { String engineType = getEngineType(variableInstanceEntity.getScopeType()); Map<String, AbstractEngineConfiguration> engineConfigurationMap = Context.getCommandContext().getEngineConfigurations(); AbstractEngineConfiguration engineConfiguration = engineConfigurationMap.get(engineType); if (engineConfiguration == null) { for (AbstractEngineConfiguration possibleEngineConfiguration : engineConfigurationMap.values()) { if (possibleEngineConfiguration instanceof HasVariableServiceConfiguration) { engineConfiguration = possibleEngineConfiguration; } } } if (engineConfiguration == null) { throw new FlowableException("Could not find engine configuration with variable service configuration"); }
if (!(engineConfiguration instanceof HasVariableServiceConfiguration)) { throw new FlowableException("Variable entity engine scope has no variable service configuration " + engineType); } return (VariableServiceConfiguration) engineConfiguration.getServiceConfigurations().get(EngineConfigurationConstants.KEY_VARIABLE_SERVICE_CONFIG); } protected String getEngineType(String scopeType) { if (StringUtils.isNotEmpty(scopeType)) { return scopeType; } else { return ScopeTypes.BPMN; } } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\TraceableObject.java
2
请在Spring Boot框架中完成以下Java代码
public class Review implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String content; @ManyToOne(fetch = FetchType.LAZY) private Book book; @ManyToOne(fetch = FetchType.LAZY) private Article article; @ManyToOne(fetch = FetchType.LAZY) private Magazine magazine; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; }
public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public Article getArticle() { return article; } public void setArticle(Article article) { this.article = article; } public Magazine getMagazine() { return magazine; } public void setMagazine(Magazine magazine) { this.magazine = magazine; } @Override public String toString() { return "Review{" + "id=" + id + ", content=" + content + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootChooseOnlyOneAssociation\src\main\java\com\bookstore\entity\Review.java
2
请完成以下Java代码
public void setAD_User_SortPref_Hdr_ID (int AD_User_SortPref_Hdr_ID) { if (AD_User_SortPref_Hdr_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_SortPref_Hdr_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_SortPref_Hdr_ID, Integer.valueOf(AD_User_SortPref_Hdr_ID)); } /** Get Sortierbegriff pro Benutzer. @return Sortierbegriff pro Benutzer */ @Override public int getAD_User_SortPref_Hdr_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_SortPref_Hdr_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sortierbegriff pro Benutzer Position. @param AD_User_SortPref_Line_ID Sortierbegriff pro Benutzer Position */ @Override public void setAD_User_SortPref_Line_ID (int AD_User_SortPref_Line_ID) { if (AD_User_SortPref_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_SortPref_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_SortPref_Line_ID, Integer.valueOf(AD_User_SortPref_Line_ID)); } /** Get Sortierbegriff pro Benutzer Position. @return Sortierbegriff pro Benutzer Position */ @Override public int getAD_User_SortPref_Line_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_SortPref_Line_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Spaltenname. @param ColumnName Name der Spalte in der Datenbank */ @Override public void setColumnName (java.lang.String ColumnName) { set_Value (COLUMNNAME_ColumnName, ColumnName); } /** Get Spaltenname. @return Name der Spalte in der Datenbank */ @Override public java.lang.String getColumnName () { return (java.lang.String)get_Value(COLUMNNAME_ColumnName); } /** Set Aufsteigender. @param IsAscending Aufsteigender */ @Override public void setIsAscending (boolean IsAscending)
{ set_Value (COLUMNNAME_IsAscending, Boolean.valueOf(IsAscending)); } /** Get Aufsteigender. @return Aufsteigender */ @Override public boolean isAscending () { Object oo = get_Value(COLUMNNAME_IsAscending); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_SortPref_Line.java
1
请在Spring Boot框架中完成以下Java代码
public HistoricTaskLogEntryBuilder timeStamp(Date timeStamp) { this.timeStamp = timeStamp; return this; } @Override public HistoricTaskLogEntryBuilder userId(String userId) { this.userId = userId; return this; } @Override public HistoricTaskLogEntryBuilder data(String data) { this.data = data; return this; } @Override public HistoricTaskLogEntryBuilder processInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; return this; } @Override public HistoricTaskLogEntryBuilder processDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; return this; } @Override public HistoricTaskLogEntryBuilder executionId(String executionId) { this.executionId = executionId; return this; } @Override public HistoricTaskLogEntryBuilder scopeId(String scopeId) { this.scopeId = scopeId; return this; } @Override public HistoricTaskLogEntryBuilder scopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; return this; } @Override public HistoricTaskLogEntryBuilder subScopeId(String subScopeId) { this.subScopeId = subScopeId; return this; } @Override public HistoricTaskLogEntryBuilder scopeType(String scopeType) { this.scopeType = scopeType; return this; } @Override public HistoricTaskLogEntryBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } @Override public String getType() { return type; }
@Override public String getTaskId() { return taskId; } @Override public Date getTimeStamp() { return timeStamp; } @Override public String getUserId() { return userId; } @Override public String getData() { return data; } @Override public String getExecutionId() { return executionId; } @Override public String getProcessInstanceId() { return processInstanceId; } @Override public String getProcessDefinitionId() { return processDefinitionId; } @Override public String getScopeId() { return scopeId; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } @Override public String getSubScopeId() { return subScopeId; } @Override public String getScopeType() { return scopeType; } @Override public String getTenantId() { return tenantId; } @Override public void create() { // add is not supported by default throw new RuntimeException("Operation is not supported"); } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\BaseHistoricTaskLogEntryBuilderImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } public void setTenantId(String tenantId) {
this.tenantId = tenantId; } public String getTenantId() { return tenantId; } public void setCategory(String category) { this.category = category; } public String getCategory() { return category; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskInstanceResponse.java
2
请完成以下Spring Boot application配置
# mongodb \u914D\u7F6E spring.data.mongodb.uri=mongodb://192.168.0.75:20000/manage #spring.data.mongodb.uri=mongodb://localhost:27017/manage # \u6D4B\u8BD5\u73AF\u5883\u53D6\u6D88thymeleaf\u7F13\u5B58 spring.thymeleaf.cache=false spring.session.store-type=redis # \u8BBE\u7F6Esession\u5931\u6548\u65F6\u95F4 spring.session.timeout=3600 # Redis\u670D\u52A1\u5668\u5730\u5740 spring.redis.host=192.168.0.71 # Redis\u670D\u52A1\u5668\u8FDE\u63A5\u7AEF\u53E3 spring.redis.port=6379 # Redis\u670D\u52A1\u5668\u8FDE\u63A5\u5BC6\u7801\uFF08\u9ED8\u8BA4\u4E3A\u7A7A\uFF09 spring.redis.password= # \u8FDE\u63A5\u6C60\u6700\u5927\u8FDE\u63A5\u6570\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09 \u9ED8\u8BA4 8 spring.redis.lettuce.pool.max-active=8 # \u8FDE\u63A5\u6C60\u6700\u5927\u963B\u585E\u7B49\u5F85\u65F6\u95F4\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09 \u9ED8\u8BA4 -1 spring.redis.lettuce.pool.max-wait=-1 # \u8FDE\u63A5\u6C60\u4E2D\u7684\u6
700\u5927\u7A7A\u95F2\u8FDE\u63A5 \u9ED8\u8BA4 8 spring.redis.lettuce.pool.max-idle=8 # \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5 \u9ED8\u8BA4 0 spring.redis.lettuce.pool.min-idle=0 # \u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09 spring.redis.timeout=0 spring.mail.host=smtp.126.com spring.mail.username=youremail@126.com spring.mail.password=yourpass spring.mail.default-encoding=UTF-8
repos\spring-boot-leaning-master\2.x_42_courses\第 5-8 课: 综合实战客户管理系统(二)\user-manage-plus\src\main\resources\application.properties
2
请完成以下Java代码
public int size() { return documentList.size(); } @Override public void clear() { documentList.clear(); } @Override public IDataSet shrink(int[] idMap) { Iterator<Document> iterator = iterator(); while (iterator.hasNext()) { Document document = iterator.next(); FrequencyMap<Integer> tfMap = new FrequencyMap<Integer>(); for (Map.Entry<Integer, int[]> entry : document.tfMap.entrySet()) {
Integer feature = entry.getKey(); if (idMap[feature] == -1) continue; tfMap.put(idMap[feature], entry.getValue()); } // 检查是否是空白文档 if (tfMap.size() == 0) iterator.remove(); else document.tfMap = tfMap; } return this; } @Override public Iterator<Document> iterator() { return documentList.iterator(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\corpus\MemoryDataSet.java
1
请完成以下Java代码
private List<I_M_PackageLine> getPackageLine(int M_Package_ID) { String whereClause = I_M_PackageLine.COLUMNNAME_M_Package_ID + " = ?"; return new Query(Env.getCtx(), I_M_PackageLine.Table_Name, whereClause, null) .setClient_ID() .setParameters(M_Package_ID) .list(I_M_PackageLine.class); } @Override public int getAD_Client_ID() { return m_AD_Client_ID; } @Override public void initialize(ModelValidationEngine engine, MClient client) { if (client != null) { m_AD_Client_ID = client.getAD_Client_ID(); } // engine.addDocValidate(MMShipperTransportation.Table_Name, this); } @Override public String login(int arg0, int arg1, int arg2) { return null; } @Override public String modelChange(PO arg0, int arg1) throws Exception { return null; } private String sendEMail(final MADBoilerPlate text, final MInOut io, final I_AD_User orderUser) { final Properties ctx = Env.getCtx(); MADBoilerPlate.sendEMail(new IEMailEditor() { @Override public Object getBaseObject() { return io; } @Override public int getAD_Table_ID() { return io.get_Table_ID(); } @Override public int getRecord_ID() { return io.get_ID(); } @Override public EMail sendEMail(I_AD_User from, String toEmail, String subject, final BoilerPlateContext attributes) { final BoilerPlateContext attributesEffective = attributes.toBuilder() .setSourceDocumentFromObject(io) .build(); // String message = text.getTextSnippetParsed(attributesEffective); // if (Check.isEmpty(message, true)) { return null; } // final StringTokenizer st = new StringTokenizer(toEmail, " ,;", false); EMailAddress to = EMailAddress.ofString(st.nextToken()); MClient client = MClient.get(ctx, Env.getAD_Client_ID(ctx)); if (orderUser != null) { to = EMailAddress.ofString(orderUser.getEMail()); }
EMail email = client.createEMail( to, text.getName(), message, true); if (email == null) { throw new AdempiereException("Cannot create email. Check log."); } while (st.hasMoreTokens()) { email.addTo(EMailAddress.ofString(st.nextToken())); } send(email); return email; } }, false); return ""; } private void send(EMail email) { int maxRetries = p_SMTPRetriesNo > 0 ? p_SMTPRetriesNo : 0; int count = 0; do { final EMailSentStatus emailSentStatus = email.send(); count++; if (emailSentStatus.isSentOK()) { return; } // Timeout => retry if (emailSentStatus.isSentConnectionError() && count < maxRetries) { log.warn("SMTP error: {} [ Retry {}/{} ]", emailSentStatus, count, maxRetries); } else { throw new EMailSendException(emailSentStatus); } } while (true); } private void setNotified(I_M_PackageLine packageLine) { InterfaceWrapperHelper.getPO(packageLine).set_ValueOfColumn("IsSentMailNotification", true); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\model\validator\ShipperTransportationMailNotification.java
1
请在Spring Boot框架中完成以下Java代码
public class EDIImpCCurrencyLookupISOCodeType { @XmlElement(name = "ISO_Code", required = true) protected String isoCode; /** * Gets the value of the isoCode property. * * @return * possible object is * {@link String } * */ public String getISOCode() { return isoCode;
} /** * Sets the value of the isoCode property. * * @param value * allowed object is * {@link String } * */ public void setISOCode(String value) { this.isoCode = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIImpCCurrencyLookupISOCodeType.java
2
请完成以下Java代码
public MetricsRegistry getMetricsRegistry() { return metricsRegistry; } public CommandExecutor getCommandExecutor() { return commandExecutor; } public MetricsCollectionTask getMetricsCollectionTask() { return metricsCollectionTask; } public void setMetricsCollectionTask(MetricsCollectionTask metricsCollectionTask) { this.metricsCollectionTask = metricsCollectionTask; } public void setReporterId(String reporterId) { this.reporterId = reporterId; if (metricsCollectionTask != null) { metricsCollectionTask.setReporter(reporterId); } }
protected class ReportDbMetricsValueCmd implements Command<Void> { protected String name; protected long value; public ReportDbMetricsValueCmd(String name, long value) { this.name = name; this.value = value; } @Override public Void execute(CommandContext commandContext) { commandContext.getMeterLogManager().insert(new MeterLogEntity(name, reporterId, value, ClockUtil.getCurrentTime())); return null; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\reporter\DbMetricsReporter.java
1
请完成以下Java代码
public final class NullLookupDataSource implements LookupDataSource { public static final transient NullLookupDataSource instance = new NullLookupDataSource(); private NullLookupDataSource() { } @Override public DocumentZoomIntoInfo getDocumentZoomInto(final int id) { throw new UnsupportedOperationException(); } @Override public LookupValuesPage findEntities(final Evaluatee ctx, final String filter, final int firstRow, final int pageLength) { return LookupValuesPage.EMPTY; } @Override public LookupValuesPage findEntities(final Evaluatee ctx, final int pageLength) { return LookupValuesPage.EMPTY; } @Override public LookupValue findById(final Object id) { return toUnknownLookupValue(id); } @Nullable private static LookupValue toUnknownLookupValue(final Object id) { if (id == null) { return null; } if (id instanceof Integer) { return IntegerLookupValue.unknown((int)id); } else { return StringLookupValue.unknown(id.toString()); } }
@Override public @NonNull LookupValuesList findByIdsOrdered(final @NonNull Collection<?> ids) { if (ids.isEmpty()) { return LookupValuesList.EMPTY; } return ids.stream() .map(NullLookupDataSource::toUnknownLookupValue) .filter(Objects::nonNull) .collect(LookupValuesList.collect()); } @Override public List<CCacheStats> getCacheStats() { return ImmutableList.of(); } @Override public void cacheInvalidate() { } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\NullLookupDataSource.java
1
请完成以下Java代码
public class UserCredentialsDto { protected String password; protected String authenticatedUserPassword; // transformers ////////////////////////////////// public static UserCredentialsDto fromUser(User user) { UserCredentialsDto result = new UserCredentialsDto(); result.setPassword(user.getPassword()); return result; } // getters / setters /////////////////////////////
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAuthenticatedUserPassword() { return authenticatedUserPassword; } public void setAuthenticatedUserPassword(String authenticatedUserPassword) { this.authenticatedUserPassword = authenticatedUserPassword; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\UserCredentialsDto.java
1
请完成以下Java代码
public HUEditorViewBuilder setParameters(final Map<String, Object> parameters) { parameters.forEach(this::setParameter); return this; } ImmutableMap<String, Object> getParameters() { return parameters != null ? ImmutableMap.copyOf(parameters) : ImmutableMap.of(); } @Nullable public <T> T getParameter(@NonNull final String name) { if (parameters == null) { return null; } @SuppressWarnings("unchecked") final T value = (T)parameters.get(name); return value; } public void assertParameterSet(final String name) { final Object value = getParameter(name); if (value == null) { throw new AdempiereException("Parameter " + name + " is expected to be set in " + parameters + " for " + this); } } public HUEditorViewBuilder setHUEditorViewRepository(final HUEditorViewRepository huEditorViewRepository) { this.huEditorViewRepository = huEditorViewRepository; return this; }
HUEditorViewBuffer createRowsBuffer(@NonNull final SqlDocumentFilterConverterContext context) { final ViewId viewId = getViewId(); final DocumentFilterList stickyFilters = getStickyFilters(); final DocumentFilterList filters = getFilters(); if (HUEditorViewBuffer_HighVolume.isHighVolume(stickyFilters)) { return new HUEditorViewBuffer_HighVolume(viewId, huEditorViewRepository, stickyFilters, filters, getOrderBys(), context); } else { return new HUEditorViewBuffer_FullyCached(viewId, huEditorViewRepository, stickyFilters, filters, getOrderBys(), context); } } public HUEditorViewBuilder setUseAutoFilters(final boolean useAutoFilters) { this.useAutoFilters = useAutoFilters; return this; } public boolean isUseAutoFilters() { return useAutoFilters; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorViewBuilder.java
1
请完成以下Java代码
public boolean isUp() { return STATUS_UP.equals(status); } public boolean isOffline() { return STATUS_OFFLINE.equals(status); } public boolean isDown() { return STATUS_DOWN.equals(status); } public boolean isUnknown() { return STATUS_UNKNOWN.equals(status); } public static Comparator<String> severity() { return Comparator.comparingInt(STATUS_ORDER::indexOf); } @SuppressWarnings("unchecked") public static StatusInfo from(Map<String, ?> body) { Map<String, ?> details = Collections.emptyMap();
/* * Key "details" is present when accessing Spring Boot Actuator Health using * Accept-Header {@link org.springframework.boot.actuate.endpoint.ApiVersion#V2}. */ if (body.containsKey("details")) { details = (Map<String, ?>) body.get("details"); } else if (body.containsKey("components")) { details = (Map<String, ?>) body.get("components"); } return StatusInfo.valueOf((String) body.get("status"), details); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\domain\values\StatusInfo.java
1
请完成以下Java代码
public class Quote { private String symbol; private double price; /** * @return the symbol */ public String getSymbol() { return symbol; } /** * @param symbol the symbol to set */ public void setSymbol(String symbol) { this.symbol = symbol;
} /** * @return the price */ public double getPrice() { return price; } /** * @param price the price to set */ public void setPrice(double price) { this.price = price; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway\src\main\java\com\baeldung\springcloudgateway\oauth\backend\domain\Quote.java
1
请完成以下Java代码
private XMLPersonType createXmlPersonType(@NonNull final PersonType person) { return XMLPersonType.builder() .familyName(person.getFamilyname()) .givenName(person.getGivenname()) .build(); } private XmlRejected createXmlRejected(@NonNull final RejectedType rejected) { final XmlRejectedBuilder rejectedBuilder = XmlRejected.builder(); rejectedBuilder.explanation(rejected.getExplanation()) .statusIn(rejected.getStatusIn()) .statusOut(rejected.getStatusOut()); if (rejected.getError() != null && !rejected.getError().isEmpty()) { rejectedBuilder.errors(createXmlErrors(rejected.getError())); } return rejectedBuilder.build(); }
private List<XmlError> createXmlErrors(@NonNull final List<ErrorType> error) { final ImmutableList.Builder<XmlError> errorsBuilder = ImmutableList.builder(); for (final ErrorType errorType : error) { final XmlError xmlError = XmlError .builder() .code(errorType.getCode()) .errorValue(errorType.getErrorValue()) .recordId(errorType.getRecordId()) .text(errorType.getText()) .validValue(errorType.getValidValue()) .build(); errorsBuilder.add(xmlError); } return errorsBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\Invoice440ToCrossVersionModelTool.java
1
请在Spring Boot框架中完成以下Java代码
private <T> Optional<T> getBeanOrNull(Class<T> type) { ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class); if (context == null) { return Optional.empty(); } try { return Optional.of(context.getBean(type)); } catch (NoSuchBeanDefinitionException ex) { return Optional.empty(); } } private MapUserCredentialRepository userCredentialRepository() { return new MapUserCredentialRepository(); }
private PublicKeyCredentialUserEntityRepository userEntityRepository() { return new MapPublicKeyCredentialUserEntityRepository(); } private WebAuthnRelyingPartyOperations webAuthnRelyingPartyOperations( PublicKeyCredentialUserEntityRepository userEntities, UserCredentialRepository userCredentials) { Optional<WebAuthnRelyingPartyOperations> webauthnOperationsBean = getBeanOrNull( WebAuthnRelyingPartyOperations.class); String rpName = (this.rpName != null) ? this.rpName : this.rpId; return webauthnOperationsBean .orElseGet(() -> new Webauthn4JRelyingPartyOperations(userEntities, userCredentials, PublicKeyCredentialRpEntity.builder().id(this.rpId).name(rpName).build(), this.allowedOrigins)); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\WebAuthnConfigurer.java
2
请完成以下Java代码
public Map<String, Mapping> getInputs() { return inputs; } public void setInputs(Map<String, Mapping> inputs) { this.inputs = inputs; } public Mapping getInputMapping(String inputName) { return inputs.get(inputName); } public Map<String, Mapping> getOutputs() { return outputs; } public void setOutputs(Map<String, Mapping> outputs) { this.outputs = outputs; } public MappingType getMappingType() { return mappingType; } public void setMappingType(MappingType mappingType) {
this.mappingType = mappingType; } public enum MappingType { MAP_ALL, MAP_ALL_INPUTS, MAP_ALL_OUTPUTS, } public boolean isEphemeral() { return this.ephemeral; } public void setEphemeral(boolean ephemeral) { this.ephemeral = ephemeral; } }
repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\ProcessVariablesMapping.java
1
请在Spring Boot框架中完成以下Java代码
public class ShipmentScheduleDeletedHandler implements MaterialEventHandler<ShipmentScheduleDeletedEvent> { private static final Logger logger = LogManager.getLogger(ShipmentScheduleDeletedHandler.class); private final CandidateChangeService candidateChangeHandler; private final CandidateRepositoryRetrieval candidateRepository; public ShipmentScheduleDeletedHandler( @NonNull final CandidateChangeService candidateChangeHandler, @NonNull final CandidateRepositoryRetrieval candidateRepository) { this.candidateChangeHandler = candidateChangeHandler; this.candidateRepository = candidateRepository; } @Override public Collection<Class<? extends ShipmentScheduleDeletedEvent>> getHandledEventType() { return ImmutableList.of(ShipmentScheduleDeletedEvent.class); } @Override public void handleEvent(@NonNull final ShipmentScheduleDeletedEvent event) { final DemandDetailsQuery demandDetailsQuery = DemandDetailsQuery.ofShipmentScheduleId(event.getShipmentScheduleId()); final CandidatesQuery candidatesQuery = CandidatesQuery .builder()
.type(CandidateType.DEMAND) .businessCase(CandidateBusinessCase.SHIPMENT) .demandDetailsQuery(demandDetailsQuery) .build(); final Candidate candidate = candidateRepository.retrieveLatestMatchOrNull(candidatesQuery); if (candidate == null) { Loggables.withLogger(logger, Level.DEBUG).addLog("Found no records to change for shipmentScheduleId={}", event.getShipmentScheduleId()); return; } final DemandDetail updatedDemandDetail = candidate.getDemandDetail().toBuilder() .shipmentScheduleId(IdConstants.NULL_REPO_ID) .qty(ZERO) .build(); final Candidate updatedCandidate = candidate.toBuilder() .quantity(ZERO) .businessCaseDetail(updatedDemandDetail) .build(); candidateChangeHandler.onCandidateNewOrChange(updatedCandidate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\shipmentschedule\ShipmentScheduleDeletedHandler.java
2
请在Spring Boot框架中完成以下Java代码
private boolean checkNeedConvert(boolean mediaTypes) { //1.检查开关是否开启 if ("true".equals(ConfigConstants.getMediaConvertDisable())) { return mediaTypes; } return false; } private static String convertToMp4(String filePath, String outFilePath, FileAttribute fileAttribute) throws Exception { FFmpegFrameGrabber frameGrabber = FFmpegFrameGrabber.createDefault(filePath); Frame captured_frame; FFmpegFrameRecorder recorder = null; try { File desFile = new File(outFilePath); //判断一下防止重复转换 if (desFile.exists()) { return outFilePath; } if (fileAttribute.isCompressFile()) { //判断 是压缩包的创建新的目录 int index = outFilePath.lastIndexOf("/"); //截取最后一个斜杠的前面的内容 String folder = outFilePath.substring(0, index); File path = new File(folder); //目录不存在 创建新的目录 if (!path.exists()) { path.mkdirs(); } } frameGrabber.start(); recorder = new FFmpegFrameRecorder(outFilePath, frameGrabber.getImageWidth(), frameGrabber.getImageHeight(), frameGrabber.getAudioChannels()); // recorder.setImageHeight(640); // recorder.setImageWidth(480); recorder.setFormat(mp4); recorder.setFrameRate(frameGrabber.getFrameRate()); recorder.setSampleRate(frameGrabber.getSampleRate()); //视频编码属性配置 H.264 H.265 MPEG recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); //设置视频比特率,单位:b recorder.setVideoBitrate(frameGrabber.getVideoBitrate()); recorder.setAspectRatio(frameGrabber.getAspectRatio()); // 设置音频通用编码格式 recorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC); //设置音频比特率,单位:b (比特率越高,清晰度/音质越好,当然文件也就越大 128000 = 182kb)
recorder.setAudioBitrate(frameGrabber.getAudioBitrate()); recorder.setAudioOptions(frameGrabber.getAudioOptions()); recorder.setAudioChannels(frameGrabber.getAudioChannels()); recorder.start(); while (true) { captured_frame = frameGrabber.grabFrame(); if (captured_frame == null) { System.out.println("转码完成:" + filePath); break; } recorder.record(captured_frame); } } catch (Exception e) { logger.error("Failed to convert video file to mp4: {}", filePath, e); return null; } finally { if (recorder != null) { //关闭 recorder.stop(); recorder.close(); } frameGrabber.stop(); frameGrabber.close(); } return outFilePath; } }
repos\kkFileView-master\server\src\main\java\cn\keking\service\impl\MediaFilePreviewImpl.java
2
请完成以下Java代码
public class C_RfQ { @Init public void registerCallout() { Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this); } @Init void configureCopyWithDetailsSupport() { CopyRecordFactory.enableForTableName(I_C_RfQ.Table_Name); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void beforeSave(final I_C_RfQ rfq) { final IRfQWorkDatesAware workDatesAware = InterfaceWrapperHelper.create(rfq, IRfQWorkDatesAware.class); RfQWorkDatesUtil.updateWorkDates(workDatesAware); } @CalloutMethod(columnNames = I_C_RfQ.COLUMNNAME_DateWorkStart, skipIfCopying = true) public void onDateWorkStart(final I_C_RfQ rfq) { final IRfQWorkDatesAware workDatesAware = InterfaceWrapperHelper.create(rfq, IRfQWorkDatesAware.class); RfQWorkDatesUtil.updateFromDateWorkStart(workDatesAware); } @CalloutMethod(columnNames = I_C_RfQ.COLUMNNAME_DateWorkComplete, skipIfCopying = true) public void onDateWorkComplete(final I_C_RfQ rfq) { final IRfQWorkDatesAware workDatesAware = InterfaceWrapperHelper.create(rfq, IRfQWorkDatesAware.class); RfQWorkDatesUtil.updateFromDateWorkComplete(workDatesAware); }
@CalloutMethod(columnNames = I_C_RfQ.COLUMNNAME_DeliveryDays, skipIfCopying = true) public void onDeliveryDays(final I_C_RfQ rfq) { if (InterfaceWrapperHelper.isNull(rfq, I_C_RfQ.COLUMNNAME_DeliveryDays)) { return; } final IRfQWorkDatesAware workDatesAware = InterfaceWrapperHelper.create(rfq, IRfQWorkDatesAware.class); RfQWorkDatesUtil.updateFromDeliveryDays(workDatesAware); } @CalloutMethod(columnNames = I_C_RfQ.COLUMNNAME_C_RfQ_Topic_ID, skipIfCopying = true) public void onC_RfQTopic(final I_C_RfQ rfq) { final I_C_RfQ_Topic rfqTopic = rfq.getC_RfQ_Topic(); if (rfqTopic == null) { return; } final String rfqTypeDefault = rfqTopic.getRfQType(); if (rfqTypeDefault != null) { rfq.setRfQType(rfqTypeDefault); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\model\interceptor\C_RfQ.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityFilterConfig { protected PathFilterConfig pathFilter; public PathFilterConfig getPathFilter() { return pathFilter; } public void setPathFilter(PathFilterConfig pathFilter) { this.pathFilter = pathFilter; } public static class PathFilterConfig { protected List<PathMatcherConfig> deniedPaths = new ArrayList<PathMatcherConfig>(); protected List<PathMatcherConfig> allowedPaths = new ArrayList<PathMatcherConfig>(); public List<PathMatcherConfig> getDeniedPaths() { return deniedPaths; } public void setDeniedPaths(List<PathMatcherConfig> protectedPaths) { this.deniedPaths = protectedPaths; } public List<PathMatcherConfig> getAllowedPaths() { return allowedPaths; } public void setAllowedPaths(List<PathMatcherConfig> allowedPaths) { this.allowedPaths = allowedPaths; } } public static class PathMatcherConfig { protected String path; protected String methods; protected String authorizer; public String getPath() { return path; } public void setPath(String path) {
this.path = path; } public String getMethods() { return methods; } public void setMethods(String methods) { this.methods = methods; } public String getAuthorizer() { return authorizer; } public void setAuthorizer(String authorizer) { this.authorizer = authorizer; } public String[] getParsedMethods() { if(methods == null || methods.isEmpty() || methods.equals("*") || methods.toUpperCase().equals("ALL")) { return new String[0]; } else { return methods.split(","); } } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\SecurityFilterConfig.java
2
请完成以下Java代码
public void setAD_Column_ID (int AD_Column_ID) { if (AD_Column_ID < 1) set_Value (COLUMNNAME_AD_Column_ID, null); else set_Value (COLUMNNAME_AD_Column_ID, Integer.valueOf(AD_Column_ID)); } /** Get Column. @return Column in the table */ public int getAD_Column_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Column_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Index Column. @param AD_Index_Column_ID Index Column */ public void setAD_Index_Column_ID (int AD_Index_Column_ID) { if (AD_Index_Column_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Index_Column_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Index_Column_ID, Integer.valueOf(AD_Index_Column_ID)); } /** Get Index Column. @return Index Column */ public int getAD_Index_Column_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Index_Column_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_Index_Table getAD_Index_Table() throws RuntimeException { return (I_AD_Index_Table)MTable.get(getCtx(), I_AD_Index_Table.Table_Name) .getPO(getAD_Index_Table_ID(), get_TrxName()); } /** Set Table Index. @param AD_Index_Table_ID Table Index */ public void setAD_Index_Table_ID (int AD_Index_Table_ID) { if (AD_Index_Table_ID < 1) set_Value (COLUMNNAME_AD_Index_Table_ID, null); else set_Value (COLUMNNAME_AD_Index_Table_ID, Integer.valueOf(AD_Index_Table_ID)); } /** Get Table Index. @return Table Index */ public int getAD_Index_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Index_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Column SQL. @param ColumnSQL Virtual Column (r/o) */ public void setColumnSQL (String ColumnSQL) { set_Value (COLUMNNAME_ColumnSQL, ColumnSQL); } /** Get Column SQL. @return Virtual Column (r/o) */ public String getColumnSQL () { return (String)get_Value(COLUMNNAME_ColumnSQL); } /** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entity Type. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Index_Column.java
1
请完成以下Java代码
public static boolean isTerminal(ArrayList<Configuration> beam) { for (Configuration configuration : beam) if (!configuration.state.isTerminalState()) return false; return true; } public static void commitAction(int action, int label, float score, ArrayList<Integer> dependencyRelations, Configuration newConfig) { if (action == 0) { shift(newConfig.state); newConfig.addAction(0); } else if (action == 1) { reduce(newConfig.state); newConfig.addAction(1); } else if (action == 2) { rightArc(newConfig.state, label);
newConfig.addAction(3 + label); } else if (action == 3) { leftArc(newConfig.state, label); newConfig.addAction(3 + dependencyRelations.size() + label); } else if (action == 4) { unShift(newConfig.state); newConfig.addAction(2); } newConfig.setScore(score); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\transition\parser\ArcEager.java
1
请完成以下Java代码
public abstract class AbstractJpaDAO<T extends Serializable> { private Class<T> clazz; @PersistenceContext private EntityManager entityManager; public final void setClazz(final Class<T> clazzToSet) { this.clazz = clazzToSet; } public T findOne(final long id) { return entityManager.find(clazz, id); } @SuppressWarnings("unchecked") public List<T> findAll() { return entityManager.createQuery("from " + clazz.getName()).getResultList(); } public void create(final T entity) { entityManager.persist(entity); } public T update(final T entity) { return entityManager.merge(entity); } public void delete(final T entity) { entityManager.remove(entity); } public void deleteById(final long entityId) { final T entity = findOne(entityId); delete(entity); }
public long countAllRowsUsingHibernateCriteria() { Session session = entityManager.unwrap(Session.class); Criteria criteria = session.createCriteria(clazz); criteria.setProjection(Projections.rowCount()); Long count = (Long) criteria.uniqueResult(); return count != null ? count : 0L; } public long getFooCountByBarNameUsingHibernateCriteria(String barName) { Session session = entityManager.unwrap(Session.class); Criteria criteria = session.createCriteria(clazz); criteria.createAlias("bar", "b"); criteria.add(Restrictions.eq("b.name", barName)); criteria.setProjection(Projections.rowCount()); return (Long) criteria.uniqueResult(); } public long getFooCountByBarNameAndFooNameUsingHibernateCriteria(String barName, String fooName) { Session session = entityManager.unwrap(Session.class); Criteria criteria = session.createCriteria(clazz); criteria.createAlias("bar", "b"); criteria.add(Restrictions.eq("b.name", barName)); criteria.add(Restrictions.eq("name", fooName)); criteria.setProjection(Projections.rowCount()); return (Long) criteria.uniqueResult(); } }
repos\tutorials-master\persistence-modules\spring-hibernate-5\src\main\java\com\baeldung\hibernate\cache\dao\AbstractJpaDAO.java
1
请完成以下Java代码
public InboundEventDeserializer<T> getInboundEventDeserializer() { return inboundEventDeserializer; } public void setInboundEventDeserializer(InboundEventDeserializer<T> inboundEventDeserializer) { this.inboundEventDeserializer = inboundEventDeserializer; } public InboundEventKeyDetector<T> getInboundEventKeyDetector() { return inboundEventKeyDetector; } public void setInboundEventKeyDetector(InboundEventKeyDetector<T> inboundEventKeyDetector) { this.inboundEventKeyDetector = inboundEventKeyDetector; } public InboundEventTenantDetector<T> getInboundEventTenantDetector() { return inboundEventTenantDetector; } public void setInboundEventTenantDetector(InboundEventTenantDetector<T> inboundEventTenantDetector) {
this.inboundEventTenantDetector = inboundEventTenantDetector; } public InboundEventPayloadExtractor<T> getInboundEventPayloadExtractor() { return inboundEventPayloadExtractor; } public void setInboundEventPayloadExtractor(InboundEventPayloadExtractor<T> inboundEventPayloadExtractor) { this.inboundEventPayloadExtractor = inboundEventPayloadExtractor; } public InboundEventTransformer getInboundEventTransformer() { return inboundEventTransformer; } public void setInboundEventTransformer(InboundEventTransformer inboundEventTransformer) { this.inboundEventTransformer = inboundEventTransformer; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\pipeline\DefaultInboundEventProcessingPipeline.java
1
请完成以下Java代码
public class ContextServlet extends HttpServlet { protected static final String PATH = "/context"; protected static final String LABEL_FROM_HTTP_SERVLET = "1) From HttpServlet: "; protected static final String LABEL_FROM_SERVLET_CONFIG = "2) From ServletConfig: "; protected static final String LABEL_FROM_HTTP_SERVLET_REQUEST = "3) From HttpServletRequest: "; protected static final String LABEL_FROM_HTTP_SESSION = "4) From HttpSession: "; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setContentType("text/plain"); // 1. Direct Access From the Servlet ServletContext contextFromServlet = this.getServletContext(); resp.getWriter() .println(LABEL_FROM_HTTP_SERVLET + contextFromServlet); resp.getWriter() .println(); // 2. Accessing Through the ServletConfig ServletConfig config = this.getServletConfig(); ServletContext contextFromConfig = config.getServletContext(); resp.getWriter() .println(LABEL_FROM_SERVLET_CONFIG + contextFromConfig); resp.getWriter() .println();
// 3. Getting the Context From the HttpServletRequest (Servlet 3.0+) ServletContext contextFromRequest = req.getServletContext(); resp.getWriter() .println(LABEL_FROM_HTTP_SERVLET_REQUEST + contextFromRequest); resp.getWriter() .println(); // 4. Retrieving Through the Session Object ServletContext contextFromSession = req.getSession() .getServletContext(); resp.getWriter() .println(LABEL_FROM_HTTP_SESSION + contextFromSession); } }
repos\tutorials-master\web-modules\jakarta-servlets-2\src\main\java\com\baeldung\context\ContextServlet.java
1
请在Spring Boot框架中完成以下Java代码
public class CommentController { @Resource private CommentService commentService; @GetMapping("/comments") public String list(HttpServletRequest request) { request.setAttribute("path", "comments"); return "admin/comment"; } @GetMapping("/comments/list") @ResponseBody public Result list(@RequestParam Map<String, Object> params) { if (ObjectUtils.isEmpty(params.get("page")) || ObjectUtils.isEmpty(params.get("limit"))) { return ResultGenerator.genFailResult("参数异常!"); } PageQueryUtil pageUtil = new PageQueryUtil(params); return ResultGenerator.genSuccessResult(commentService.getCommentsPage(pageUtil)); } @PostMapping("/comments/checkDone") @ResponseBody public Result checkDone(@RequestBody Integer[] ids) { if (ids.length < 1) { return ResultGenerator.genFailResult("参数异常!");
} if (commentService.checkDone(ids)) { return ResultGenerator.genSuccessResult(); } else { return ResultGenerator.genFailResult("审核失败"); } } @PostMapping("/comments/delete") @ResponseBody public Result delete(@RequestBody Integer[] ids) { if (ids.length < 1) { return ResultGenerator.genFailResult("参数异常!"); } if (commentService.deleteBatch(ids)) { return ResultGenerator.genSuccessResult(); } else { return ResultGenerator.genFailResult("刪除失败"); } } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\controller\admin\CommentController.java
2
请完成以下Java代码
public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } public boolean isInheritBusinessKey() { return inheritBusinessKey; } public void setInheritBusinessKey(boolean inheritBusinessKey) { this.inheritBusinessKey = inheritBusinessKey; } public boolean isUseLocalScopeForOutParameters() { return useLocalScopeForOutParameters; } public void setUseLocalScopeForOutParameters(boolean useLocalScopeForOutParameters) { this.useLocalScopeForOutParameters = useLocalScopeForOutParameters; } public boolean isCompleteAsync() { return completeAsync; } public void setCompleteAsync(boolean completeAsync) { this.completeAsync = completeAsync; } public Boolean getFallbackToDefaultTenant() { return fallbackToDefaultTenant; } public void setFallbackToDefaultTenant(Boolean fallbackToDefaultTenant) { this.fallbackToDefaultTenant = fallbackToDefaultTenant; } public void setCalledElementType(String calledElementType) { this.calledElementType = calledElementType; } public String getCalledElementType() { return calledElementType; } public String getProcessInstanceIdVariableName() { return processInstanceIdVariableName; } public void setProcessInstanceIdVariableName(String processInstanceIdVariableName) {
this.processInstanceIdVariableName = processInstanceIdVariableName; } @Override public CallActivity clone() { CallActivity clone = new CallActivity(); clone.setValues(this); return clone; } public void setValues(CallActivity otherElement) { super.setValues(otherElement); setCalledElement(otherElement.getCalledElement()); setCalledElementType(otherElement.getCalledElementType()); setBusinessKey(otherElement.getBusinessKey()); setInheritBusinessKey(otherElement.isInheritBusinessKey()); setInheritVariables(otherElement.isInheritVariables()); setSameDeployment(otherElement.isSameDeployment()); setUseLocalScopeForOutParameters(otherElement.isUseLocalScopeForOutParameters()); setCompleteAsync(otherElement.isCompleteAsync()); setFallbackToDefaultTenant(otherElement.getFallbackToDefaultTenant()); inParameters = new ArrayList<>(); if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) { for (IOParameter parameter : otherElement.getInParameters()) { inParameters.add(parameter.clone()); } } outParameters = new ArrayList<>(); if (otherElement.getOutParameters() != null && !otherElement.getOutParameters().isEmpty()) { for (IOParameter parameter : otherElement.getOutParameters()) { outParameters.add(parameter.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\CallActivity.java
1
请完成以下Java代码
public int size() { return variables.size(); } }; } public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("{\n"); for (Entry<String, TypedValue> variable : variables.entrySet()) { stringBuilder.append(" "); stringBuilder.append(variable.getKey()); stringBuilder.append(" => "); stringBuilder.append(variable.getValue()); stringBuilder.append("\n"); } stringBuilder.append("}"); return stringBuilder.toString(); } public boolean equals(Object obj) { return asValueMap().equals(obj); } public int hashCode() { return asValueMap().hashCode(); }
public Map<String, Object> asValueMap() { return new HashMap<String, Object>(this); } public TypedValue resolve(String variableName) { return getValueTyped(variableName); } public boolean containsVariable(String variableName) { return containsKey(variableName); } public VariableContext asVariableContext() { return this; } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\VariableMapImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class InvoiceLineId implements RepoIdAware { @JsonCreator public static InvoiceLineId ofRepoId(final int repoId) { return new InvoiceLineId(repoId); } public static InvoiceLineId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new InvoiceLineId(repoId) : null; } @NonNull public static Optional<InvoiceLineId> ofRepoIdOptional(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } int repoId; private InvoiceLineId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_InvoiceLine_ID"); } @JsonValue @Override public int getRepoId()
{ return repoId; } public static int toRepoId(@Nullable final InvoiceLineId invoiceLineId) { return toRepoIdOr(invoiceLineId, -1); } public static int toRepoIdOr(@Nullable final InvoiceLineId invoiceLineId, final int defaultValue) { return invoiceLineId != null ? invoiceLineId.getRepoId() : defaultValue; } public static boolean equals(@Nullable final InvoiceLineId id1, @Nullable final InvoiceLineId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\invoice\InvoiceLineId.java
2
请完成以下Java代码
private void moveHandlingUnit(final I_M_HU hu, final LocatorId locatorToId) { final SourceHUsService sourceHuService = SourceHUsService.get(); // // Make sure HU's current locator is the locator from which we need to move // final int huLocatorIdOld = hu.getM_Locator_ID(); final LocatorId locatorFromId = IHandlingUnitsBL.extractLocatorId(hu); // If already moved, then do nothing. if (Objects.equals(locatorFromId, locatorToId)) { return; } final HuId huId = HuId.ofRepoId(hu.getM_HU_ID()); final boolean isSourceHU = sourceHuService.isSourceHu(huId); if (isSourceHU) { sourceHuService.deleteSourceHuMarker(huId); } // // Update HU's Locator // FIXME: refactor this and have a common way of setting HU's locator hu.setM_Locator_ID(locatorToId.getRepoId()); // Activate HU (not needed, but we want to be sure) // (even if we do reversals) // NOTE: as far as we know, HUContext won't be used by setHUStatus, because the // status "active" doesn't // trigger a movement to/from empties warehouse. In this case a movement is
// already created from a lager to another. // So no HU leftovers. final IContextAware contextProvider = InterfaceWrapperHelper.getContextAware(hu); final IMutableHUContext huContext = huContextFactory.createMutableHUContext(contextProvider); huStatusBL.setHUStatus(huContext, hu, X_M_HU.HUSTATUS_Active); // Save changed HU handlingUnitsDAO.saveHU(hu); final I_M_Locator locatorTo = warehousesDAO.getLocatorById(locatorToId); final I_M_Warehouse warehouseTo = warehousesDAO.getById(WarehouseId.ofRepoId(locatorTo.getM_Warehouse_ID())); if (warehouseTo.isReceiveAsSourceHU()) { sourceHuService.addSourceHuMarker(huId); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\movement\api\impl\HUMovementBL.java
1
请完成以下Java代码
public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** 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 Name. @param Name Alphanumeric identifier of the entity */
@Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_C_BPartner_Allotment.java
1
请完成以下Java代码
private synchronized AdempiereDatabase getDatabaseOrNull() { return _database; } /** * Get Connection String * * @return connection string or empty string if database was not initialized */ public String getConnectionURL() { final AdempiereDatabase db = getDatabaseOrNull(); if (db != null) { return db.getConnectionURL(this); } else { return ""; } } // getConnectionURL /** * Acquires a database Connection. * <p> * Sets the {@link #isDatabaseOK()} flag. * * @param autoCommit true if auto-commit connection * @param transactionIsolation Connection transaction level * @return database connection */ public Connection getConnection(final boolean autoCommit, final int transactionIsolation) { final AdempiereDatabase db = getDatabase(); // creates connection if not already exist if (db == null) { throw new DBNoConnectionException("No AdempiereDatabase found"); } Connection conn = null; boolean connOk = false; try { conn = db.getCachedConnection(this, autoCommit, transactionIsolation); if (conn == null) { // shall not happen throw new DBNoConnectionException(); } // Mark the database connection status as OK _okDB = true; connOk = true; return conn; } catch (final UnsatisfiedLinkError ule) { _okDB = false; final String msg = ule.getLocalizedMessage() + " -> Did you set the LD_LIBRARY_PATH ? - " + getConnectionURL(); throw new DBNoConnectionException(msg, ule); } catch (final Exception ex) { _okDB = false; throw DBNoConnectionException.wrapIfNeeded(ex); } finally { if (!connOk) { DB.close(conn); } } } // getConnection /** * Get Transaction Isolation Info
* * @return transaction isolation name */ @SuppressWarnings("unused") private static String getTransactionIsolationInfo(int transactionIsolation) { if (transactionIsolation == Connection.TRANSACTION_NONE) { return "NONE"; } if (transactionIsolation == Connection.TRANSACTION_READ_COMMITTED) { return "READ_COMMITTED"; } if (transactionIsolation == Connection.TRANSACTION_READ_UNCOMMITTED) { return "READ_UNCOMMITTED"; } if (transactionIsolation == Connection.TRANSACTION_REPEATABLE_READ) { return "REPEATABLE_READ"; } if (transactionIsolation == Connection.TRANSACTION_SERIALIZABLE) { return "SERIALIZABLE"; } return "<?" + transactionIsolation + "?>"; } // getTransactionIsolationInfo @Override public Object clone() throws CloneNotSupportedException { CConnection c = (CConnection)super.clone(); return c; } } // CConnection
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\CConnection.java
1
请完成以下Java代码
public class ELException extends RuntimeException { @Serial private static final long serialVersionUID = -6228042809457459161L; /** * Creates an ELException with no detail message */ public ELException() { super(); } /** * Creates an ELException with the provided detail message. * * @param message the detail message */ public ELException(String message) { super(message); } /** * Creates an ELException with the given cause *
* @param cause the originating cause of this exception */ public ELException(Throwable cause) { super(cause); } /** * Creates an ELException with the given detail message and root cause. * * @param message the detail message * @param cause the originating cause of this exception */ public ELException(String message, Throwable cause) { super(message, cause); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\ELException.java
1
请在Spring Boot框架中完成以下Java代码
public void setConfigFields( @NonNull final FTSConfigId configId, @NonNull final Set<ESFieldName> esFieldNames) { final HashMap<ESFieldName, I_ES_FTS_Config_Field> records = queryBL.createQueryBuilder(I_ES_FTS_Config_Field.class) .addEqualsFilter(I_ES_FTS_Config_Field.COLUMNNAME_ES_FTS_Config_ID, configId) .create() .stream() .collect(GuavaCollectors.toHashMapByKey(record -> ESFieldName.ofString(record.getES_FieldName()))); for (final ESFieldName esFieldName : esFieldNames) { I_ES_FTS_Config_Field record = records.remove(esFieldName); if (record == null) { record = InterfaceWrapperHelper.newInstance(I_ES_FTS_Config_Field.class); record.setES_FTS_Config_ID(configId.getRepoId()); record.setES_FieldName(esFieldName.getAsString()); } record.setIsActive(true); InterfaceWrapperHelper.saveRecord(record); } InterfaceWrapperHelper.deleteAll(records.values()); } // // // ---------------------------------- // // public static class FTSConfigsMap { @Getter private final ImmutableList<FTSConfig> configs; private final ImmutableMap<String, FTSConfig> configsByESIndexName; private final ImmutableMap<FTSConfigId, FTSConfig> configsById;
@Getter private final FTSConfigSourceTablesMap sourceTables; private FTSConfigsMap( @NonNull final List<FTSConfig> configs, @NonNull final FTSConfigSourceTablesMap sourceTables) { this.configs = ImmutableList.copyOf(configs); this.configsByESIndexName = Maps.uniqueIndex(configs, FTSConfig::getEsIndexName); this.configsById = Maps.uniqueIndex(configs, FTSConfig::getId); this.sourceTables = sourceTables .filter(sourceTable -> configsById.containsKey(sourceTable.getFtsConfigId())); // only active configs } public Optional<FTSConfig> getByESIndexName(@NonNull final String esIndexName) { return Optional.ofNullable(configsByESIndexName.get(esIndexName)); } public FTSConfig getById(@NonNull final FTSConfigId ftsConfigId) { final FTSConfig config = configsById.get(ftsConfigId); if (config == null) { throw new AdempiereException("No config found for " + ftsConfigId); } return config; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\FTSConfigRepository.java
2
请完成以下Java代码
public void setP_UsageVariance_Acct (int P_UsageVariance_Acct) { set_Value (COLUMNNAME_P_UsageVariance_Acct, Integer.valueOf(P_UsageVariance_Acct)); } /** Get Usage Variance. @return The Usage Variance account is the account used Manufacturing Order */ @Override public int getP_UsageVariance_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_P_UsageVariance_Acct); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ValidCombination getP_WIP_A() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_P_WIP_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setP_WIP_A(org.compiere.model.I_C_ValidCombination P_WIP_A) { set_ValueFromPO(COLUMNNAME_P_WIP_Acct, org.compiere.model.I_C_ValidCombination.class, P_WIP_A); } /** Set Work In Process. @param P_WIP_Acct The Work in Process account is the account used Manufacturing Order */ @Override public void setP_WIP_Acct (int P_WIP_Acct)
{ set_Value (COLUMNNAME_P_WIP_Acct, Integer.valueOf(P_WIP_Acct)); } /** Get Work In Process. @return The Work in Process account is the account used Manufacturing Order */ @Override public int getP_WIP_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_P_WIP_Acct); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Acct.java
1
请完成以下Java代码
public Object getValue(VariableScope variableScope) { ELContext elContext = Context.getProcessEngineConfiguration() .getExpressionManager() .getElContext(variableScope); return getValueFromContext(elContext, Context.getProcessEngineConfiguration().getDelegateInterceptor()); } @Override public void setValue(Object value, VariableScope variableScope) { ELContext elContext = Context.getProcessEngineConfiguration() .getExpressionManager() .getElContext(variableScope); try { ExpressionSetInvocation invocation = new ExpressionSetInvocation(valueExpression, elContext, value); Context.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation(invocation); } catch (Exception e) { throw new ActivitiException("Error while evaluating expression: " + expressionText, e); } } @Override public String toString() { if (valueExpression != null) { return valueExpression.getExpressionString(); } return super.toString(); } @Override public String getExpressionText() { return expressionText;
} @Override public Object getValue( ExpressionManager expressionManager, DelegateInterceptor delegateInterceptor, Map<String, Object> availableVariables ) { ELContext elContext = expressionManager.getElContext(availableVariables); return getValueFromContext(elContext, delegateInterceptor); } private Object getValueFromContext(ELContext elContext, DelegateInterceptor delegateInterceptor) { try { ExpressionGetInvocation invocation = new ExpressionGetInvocation(valueExpression, elContext); delegateInterceptor.handleInvocation(invocation); return invocation.getInvocationResult(); } catch (PropertyNotFoundException pnfe) { throw new ActivitiException("Unknown property used in expression: " + expressionText, pnfe); } catch (MethodNotFoundException mnfe) { throw new ActivitiException("Unknown method used in expression: " + expressionText, mnfe); } catch (Exception ele) { throw new ActivitiException("Error while evaluating expression: " + expressionText, ele); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\el\JuelExpression.java
1
请完成以下Java代码
public int getDoc_User_ID(@NonNull final DocumentTableFields docFields) { return extractDunningDoc(docFields).getCreatedBy(); } @Override public LocalDate getDocumentDate(@NonNull final DocumentTableFields docFields) { return TimeUtil.asLocalDate(extractDunningDoc(docFields).getDunningDate()); } /** * Sets the <code>Processed</code> flag of the given <code>dunningDoc</code> and sets the <code>IsDunningDocProcessed</code> flag of the dunning candidates that are the sources of dunning doc's * lines. * <p> * Assumes that the given doc is not yet processed. */ @Override public String completeIt(@NonNull final DocumentTableFields docFields) { final I_C_DunningDoc dunningDocRecord = extractDunningDoc(docFields); dunningDocRecord.setDocAction(IDocument.ACTION_ReActivate); if (dunningDocRecord.isProcessed()) { throw new DunningException("@Processed@=@Y@"); } final IDunningDAO dunningDao = Services.get(IDunningDAO.class); final List<I_C_DunningDoc_Line> lines = dunningDao.retrieveDunningDocLines(dunningDocRecord); final IDunningBL dunningBL = Services.get(IDunningBL.class); for (final I_C_DunningDoc_Line line : lines) { for (final I_C_DunningDoc_Line_Source source : dunningDao.retrieveDunningDocLineSources(line)) { dunningBL.processSourceAndItsCandidates(dunningDocRecord, source); } line.setProcessed(true);
InterfaceWrapperHelper.save(line); } // // Delivery stop (https://github.com/metasfresh/metasfresh/issues/2499) dunningBL.makeDeliveryStopIfNeeded(dunningDocRecord); dunningDocRecord.setProcessed(true); return IDocument.STATUS_Completed; } @Override public void reactivateIt(@NonNull final DocumentTableFields docFields) { final I_C_DunningDoc dunningDocRecord = extractDunningDoc(docFields); dunningDocRecord.setProcessed(false); dunningDocRecord.setDocAction(IDocument.ACTION_Complete); } private static I_C_DunningDoc extractDunningDoc(@NonNull final DocumentTableFields docFields) { return InterfaceWrapperHelper.create(docFields, I_C_DunningDoc.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\DunningDocDocumentHandler.java
1
请完成以下Java代码
public Stream<CostElementId> streamCostElementIds() { return pricesByElementId.keySet().stream(); } public BOMCostElementPrice getCostElementPriceOrNull(@NonNull final CostElementId costElementId) { return pricesByElementId.get(costElementId); } public void clearOwnCostPrice(@NonNull final CostElementId costElementId) { final BOMCostElementPrice elementCostPrice = getCostElementPriceOrNull(costElementId); if (elementCostPrice != null) { elementCostPrice.clearOwnCostPrice(); } } public void setComponentsCostPrice( @NonNull final CostAmount costPrice, @NonNull final CostElementId costElementId) { pricesByElementId.computeIfAbsent(costElementId, k -> BOMCostElementPrice.zero(costElementId, costPrice.getCurrencyId(), uomId)) .setComponentsCostPrice(costPrice); } public void clearComponentsCostPrice(@NonNull final CostElementId costElementId)
{ final BOMCostElementPrice elementCostPrice = getCostElementPriceOrNull(costElementId); if (elementCostPrice != null) { elementCostPrice.clearComponentsCostPrice(); } } ImmutableList<BOMCostElementPrice> getElementPrices() { return ImmutableList.copyOf(pricesByElementId.values()); } <T extends RepoIdAware> Stream<T> streamIds(@NonNull final Class<T> idType) { return getElementPrices() .stream() .map(elementCostPrice -> elementCostPrice.getId(idType)) .filter(Objects::nonNull); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\costing\BOMCostPrice.java
1
请完成以下Java代码
public AppDeployment deploy(AppDeploymentBuilderImpl deploymentBuilder) { return commandExecutor.execute(new DeployCmd(deploymentBuilder)); } @Override public AppDefinition getAppDefinition(String appDefinitionId) { return commandExecutor.execute(new GetDeploymentAppDefinitionCmd(appDefinitionId)); } @Override public AppModel getAppModel(String appDefinitionId) { return commandExecutor.execute(new GetAppModelCmd(appDefinitionId)); } @Override public String convertAppModelToJson(String appDefinitionId) { return commandExecutor.execute(new GetAppModelJsonCmd(appDefinitionId)); } @Override public void deleteDeployment(String deploymentId, boolean cascade) {
commandExecutor.execute(new DeleteDeploymentCmd(deploymentId, cascade)); } @Override public AppDeploymentQuery createDeploymentQuery() { return configuration.getAppDeploymentEntityManager().createDeploymentQuery(); } @Override public AppDefinitionQuery createAppDefinitionQuery() { return configuration.getAppDefinitionEntityManager().createAppDefinitionQuery(); } @Override public void setAppDefinitionCategory(String appDefinitionId, String category) { commandExecutor.execute(new SetAppDefinitionCategoryCmd(appDefinitionId, category)); } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\AppRepositoryServiceImpl.java
1
请完成以下Java代码
public Object put(Object key, Object value) { return getDelegate().put(key, value); } @Override public Object remove(Object key) { return getDelegate().remove(key); } @Override public void putAll(Map<? extends Object, ? extends Object> t) { getDelegate().putAll(t); } @Override public void clear() { getDelegate().clear(); } @Override public Object clone() { return getDelegate().clone(); } @Override public String toString() { return getDelegate().toString(); } @Override public Set<Object> keySet() { return getDelegate().keySet(); } @Override public Set<java.util.Map.Entry<Object, Object>> entrySet() { return getDelegate().entrySet(); } @Override public Collection<Object> values() { return getDelegate().values(); } @Override public boolean equals(Object o) { return getDelegate().equals(o); } @SuppressWarnings("deprecation") @Override public void save(OutputStream out, String comments) { getDelegate().save(out, comments); } @Override public int hashCode() { return getDelegate().hashCode(); }
@Override public void store(Writer writer, String comments) throws IOException { getDelegate().store(writer, comments); } @Override public void store(OutputStream out, String comments) throws IOException { getDelegate().store(out, comments); } @Override public void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException { getDelegate().loadFromXML(in); } @Override public void storeToXML(OutputStream os, String comment) throws IOException { getDelegate().storeToXML(os, comment); } @Override public void storeToXML(OutputStream os, String comment, String encoding) throws IOException { getDelegate().storeToXML(os, comment, encoding); } @Override public String getProperty(String key) { return getDelegate().getProperty(key); } @Override public String getProperty(String key, String defaultValue) { return getDelegate().getProperty(key, defaultValue); } @Override public Enumeration<?> propertyNames() { return getDelegate().propertyNames(); } @Override public Set<String> stringPropertyNames() { return getDelegate().stringPropertyNames(); } @Override public void list(PrintStream out) { getDelegate().list(out); } @Override public void list(PrintWriter out) { getDelegate().list(out); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\AbstractPropertiesProxy.java
1
请完成以下Java代码
public static void agentmain(String agentArgs, Instrumentation inst) { LOGGER.info("[Agent] In agentmain method"); String className = "com.baeldung.instrumentation.application.MyAtm"; transformClass(className,inst); } private static void transformClass(String className, Instrumentation instrumentation) { Class<?> targetCls = null; ClassLoader targetClassLoader = null; // see if we can get the class using forName try { targetCls = Class.forName(className); targetClassLoader = targetCls.getClassLoader(); transform(targetCls, targetClassLoader, instrumentation); return; } catch (Exception ex) { LOGGER.error("Class [{}] not found with Class.forName"); } // otherwise iterate all loaded classes and find what we want for(Class<?> clazz: instrumentation.getAllLoadedClasses()) { if(clazz.getName().equals(className)) {
targetCls = clazz; targetClassLoader = targetCls.getClassLoader(); transform(targetCls, targetClassLoader, instrumentation); return; } } throw new RuntimeException("Failed to find class [" + className + "]"); } private static void transform(Class<?> clazz, ClassLoader classLoader, Instrumentation instrumentation) { AtmTransformer dt = new AtmTransformer(clazz.getName(), classLoader); instrumentation.addTransformer(dt, true); try { instrumentation.retransformClasses(clazz); } catch (Exception ex) { throw new RuntimeException("Transform failed for class: [" + clazz.getName() + "]", ex); } } }
repos\tutorials-master\core-java-modules\core-java-jvm\src\main\java\com\baeldung\instrumentation\agent\MyInstrumentationAgent.java
1
请在Spring Boot框架中完成以下Java代码
public V2 getV2() { return this.v2; } public static class V1 { /** * ID of the custom device that is exporting metrics to Dynatrace. */ private @Nullable String deviceId; /** * Group for exported metrics. Used to specify custom device group name in the * Dynatrace UI. */ private @Nullable String group; /** * Technology type for exported metrics. Used to group metrics under a logical * technology name in the Dynatrace UI. */ private String technologyType = "java"; public @Nullable String getDeviceId() { return this.deviceId; } public void setDeviceId(@Nullable String deviceId) { this.deviceId = deviceId; } public @Nullable String getGroup() { return this.group; } public void setGroup(@Nullable String group) { this.group = group; } public String getTechnologyType() { return this.technologyType; } public void setTechnologyType(String technologyType) { this.technologyType = technologyType; } } public static class V2 { /** * Default dimensions that are added to all metrics in the form of key-value * pairs. These are overwritten by Micrometer tags if they use the same key. */ private @Nullable Map<String, String> defaultDimensions; /** * Whether to enable Dynatrace metadata export. */ private boolean enrichWithDynatraceMetadata = true; /** * Prefix string that is added to all exported metrics. */ private @Nullable String metricKeyPrefix;
/** * Whether to fall back to the built-in micrometer instruments for Timer and * DistributionSummary. */ private boolean useDynatraceSummaryInstruments = true; /** * Whether to export meter metadata (unit and description) to the Dynatrace * backend. */ private boolean exportMeterMetadata = true; public @Nullable Map<String, String> getDefaultDimensions() { return this.defaultDimensions; } public void setDefaultDimensions(@Nullable Map<String, String> defaultDimensions) { this.defaultDimensions = defaultDimensions; } public boolean isEnrichWithDynatraceMetadata() { return this.enrichWithDynatraceMetadata; } public void setEnrichWithDynatraceMetadata(Boolean enrichWithDynatraceMetadata) { this.enrichWithDynatraceMetadata = enrichWithDynatraceMetadata; } public @Nullable String getMetricKeyPrefix() { return this.metricKeyPrefix; } public void setMetricKeyPrefix(@Nullable String metricKeyPrefix) { this.metricKeyPrefix = metricKeyPrefix; } public boolean isUseDynatraceSummaryInstruments() { return this.useDynatraceSummaryInstruments; } public void setUseDynatraceSummaryInstruments(boolean useDynatraceSummaryInstruments) { this.useDynatraceSummaryInstruments = useDynatraceSummaryInstruments; } public boolean isExportMeterMetadata() { return this.exportMeterMetadata; } public void setExportMeterMetadata(boolean exportMeterMetadata) { this.exportMeterMetadata = exportMeterMetadata; } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\dynatrace\DynatraceProperties.java
2
请在Spring Boot框架中完成以下Java代码
public int getCompactionThreshold() { return this.compactionThreshold; } public void setCompactionThreshold(int compactionThreshold) { this.compactionThreshold = compactionThreshold; } public DirectoryProperties[] getDirectory() { return this.directoryProperties; } public void setDirectory(DirectoryProperties[] directoryProperties) { this.directoryProperties = directoryProperties; } public float getDiskUsageCriticalPercentage() { return this.diskUsageCriticalPercentage; } public void setDiskUsageCriticalPercentage(float diskUsageCriticalPercentage) { this.diskUsageCriticalPercentage = diskUsageCriticalPercentage; } public float getDiskUsageWarningPercentage() { return this.diskUsageWarningPercentage; } public void setDiskUsageWarningPercentage(float diskUsageWarningPercentage) { this.diskUsageWarningPercentage = diskUsageWarningPercentage; } public long getMaxOplogSize() { return this.maxOplogSize; } public void setMaxOplogSize(long maxOplogSize) { this.maxOplogSize = maxOplogSize;
} public int getQueueSize() { return this.queueSize; } public void setQueueSize(int queueSize) { this.queueSize = queueSize; } public long getTimeInterval() { return this.timeInterval; } public void setTimeInterval(long timeInterval) { this.timeInterval = timeInterval; } public int getWriteBufferSize() { return this.writeBufferSize; } public void setWriteBufferSize(int writeBufferSize) { this.writeBufferSize = writeBufferSize; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\DiskStoreProperties.java
2
请完成以下Java代码
protected final void appendParameters(final TranslatableStringBuilder message) { final ITranslatableString parametersStr = buildParametersString(); if (TranslatableStrings.isBlank(parametersStr)) { return; } if (!message.isEmpty()) { message.append("\n"); } message.append(parametersStr); } public String getMDC(@NonNull final String name) { return mdcContextMap.get(name); } /** * Marks this exception as user validation error. * In case an exception is a user validation error, the framework assumes the message is user friendly and can be displayed directly. * More, the webui auto-saving will not hide/ignore this error put it will propagate it directly to user. */ @OverridingMethodsMustInvokeSuper public AdempiereException markAsUserValidationError() { userValidationError = true; return this; }
public final boolean isUserValidationError() { return userValidationError; } public static boolean isUserValidationError(final Throwable ex) { return (ex instanceof AdempiereException) && ((AdempiereException)ex).isUserValidationError(); } /** * Fluent version of {@link #addSuppressed(Throwable)} */ public AdempiereException suppressing(@NonNull final Throwable exception) { addSuppressed(exception); return this; } /** * Override with a method returning false if your exception is more of a signal than an error * and shall not clutter the log when it is caught and rethrown by the transaction manager. * <p> * To be invoked by {@link AdempiereException#isThrowableLoggedInTrxManager(Throwable)}. */ protected boolean isLoggedInTrxManager() { return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\exceptions\AdempiereException.java
1
请完成以下Java代码
public long getWaitTime() { if (idleLevel > 0) { return calculateIdleTime(); } else if (backoffLevel > 0) { return calculateBackoffTime(); } else if (executionSaturated) { return executionSaturationWaitTime; } else { return 0; } } protected long calculateIdleTime() { if (idleLevel <= 0) { return 0; } else if (idleLevel >= maxIdleLevel) { return maxIdleWaitTime; } else { return (long) (baseIdleWaitTime * Math.pow(idleIncreaseFactor, idleLevel - 1)); } } protected long calculateBackoffTime() { long backoffTime = 0; if (backoffLevel <= 0) { backoffTime = 0; } else if (backoffLevel >= maxBackoffLevel) {
backoffTime = maxBackoffWaitTime; } else { backoffTime = (long) (baseBackoffWaitTime * Math.pow(backoffIncreaseFactor, backoffLevel - 1)); } if (applyJitter) { // add a bounded random jitter to avoid multiple job acquisitions getting exactly the same // polling interval backoffTime += Math.random() * (backoffTime / 2); } return backoffTime; } @Override public int getNumJobsToAcquire(String processEngine) { Integer numJobsToAcquire = jobsToAcquire.get(processEngine); if (numJobsToAcquire != null) { return numJobsToAcquire; } else { return baseNumJobsToAcquire; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\BackoffJobAcquisitionStrategy.java
1