instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
@Override
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_InfoWindow_From[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Info Window From.
@param AD_InfoWindow_From_ID Info Window From */
@Override
public void setAD_InfoWindow_From_ID (int AD_InfoWindow_From_ID)
{
if (AD_InfoWindow_From_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_InfoWindow_From_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_InfoWindow_From_ID, Integer.valueOf(AD_InfoWindow_From_ID));
}
/** Get Info Window From.
@return Info Window From */
@Override
public int getAD_InfoWindow_From_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_InfoWindow_From_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_InfoWindow getAD_InfoWindow() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_InfoWindow_ID, org.compiere.model.I_AD_InfoWindow.class);
}
@Override
public void setAD_InfoWindow(org.compiere.model.I_AD_InfoWindow AD_InfoWindow)
{
set_ValueFromPO(COLUMNNAME_AD_InfoWindow_ID, org.compiere.model.I_AD_InfoWindow.class, AD_InfoWindow);
}
/** Set Info-Fenster.
@param AD_InfoWindow_ID
Info and search/select Window
*/
@Override
public void setAD_InfoWindow_ID (int AD_InfoWindow_ID)
{
if (AD_InfoWindow_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_InfoWindow_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_InfoWindow_ID, Integer.valueOf(AD_InfoWindow_ID));
}
/** Get Info-Fenster.
@return Info and search/select Window
*/ | @Override
public int getAD_InfoWindow_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_InfoWindow_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Sql FROM.
@param FromClause
SQL FROM clause
*/
@Override
public void setFromClause (java.lang.String FromClause)
{
set_Value (COLUMNNAME_FromClause, FromClause);
}
/** Get Sql FROM.
@return SQL FROM clause
*/
@Override
public java.lang.String getFromClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_FromClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoWindow_From.java | 1 |
请完成以下Java代码 | public class OAuth2AuthorizationGrantAuthenticationToken extends AbstractAuthenticationToken {
@Serial
private static final long serialVersionUID = -1715946281123199051L;
private final AuthorizationGrantType authorizationGrantType;
private final Authentication clientPrincipal;
private final Map<String, Object> additionalParameters;
/**
* Sub-class constructor.
* @param authorizationGrantType the authorization grant type
* @param clientPrincipal the authenticated client principal
* @param additionalParameters the additional parameters
*/
protected OAuth2AuthorizationGrantAuthenticationToken(AuthorizationGrantType authorizationGrantType,
Authentication clientPrincipal, @Nullable Map<String, Object> additionalParameters) {
super(Collections.emptyList());
Assert.notNull(authorizationGrantType, "authorizationGrantType cannot be null");
Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
this.authorizationGrantType = authorizationGrantType;
this.clientPrincipal = clientPrincipal;
this.additionalParameters = Collections.unmodifiableMap(
(additionalParameters != null) ? new HashMap<>(additionalParameters) : Collections.emptyMap());
}
/**
* Returns the authorization grant type.
* @return the authorization grant type
*/
public AuthorizationGrantType getGrantType() { | return this.authorizationGrantType;
}
@Override
public Object getPrincipal() {
return this.clientPrincipal;
}
@Override
public Object getCredentials() {
return "";
}
/**
* Returns the additional parameters.
* @return the additional parameters
*/
public Map<String, Object> getAdditionalParameters() {
return this.additionalParameters;
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AuthorizationGrantAuthenticationToken.java | 1 |
请完成以下Java代码 | public void addActionListener(final ActionListener listener)
{
m_text.addActionListener(listener);
} // addActionListener
/**
* Action Listener Interface
*
* @param listener
*/
public void removeActionListener(final ActionListener listener)
{
m_text.removeActionListener(listener);
} // removeActionListener
/**
* Set Field/WindowNo
*
* @param mField field
*/
@Override
public void setField(final GridField mField)
{
m_field = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
/** Grid Field */
private GridField m_field = null;
/**
* Get Field
*
* @return gridField
*/
@Override
public GridField getField()
{
return m_field;
} // getField
@Override
public void keyPressed(final KeyEvent e)
{
}
@Override
public void keyTyped(final KeyEvent e)
{
}
/**
* Key Released. if Escape Restore old Text
*
* @param e event
* @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
*/
@Override
public void keyReleased(final KeyEvent e)
{
if (LogManager.isLevelFinest())
{
log.trace("Key=" + e.getKeyCode() + " - " + e.getKeyChar() + " -> " + m_text.getText());
} | // ESC
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
{
m_text.setText(m_initialText);
}
else if (e.getKeyChar() == KeyEvent.CHAR_UNDEFINED)
{
return;
}
m_setting = true;
try
{
String clear = m_text.getText();
if (clear.length() > m_fieldLength)
{
clear = clear.substring(0, m_fieldLength);
}
fireVetoableChange(m_columnName, m_oldText, clear);
}
catch (final PropertyVetoException pve)
{
}
m_setting = false;
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VFile | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VFile.java | 1 |
请完成以下Java代码 | protected void configureFactory(DocumentBuilderFactory dbf) {
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
dbf.setAttribute(JAXP_SCHEMA_SOURCE, new String[] {
ReflectUtil.getResource(DMN_15_SCHEMA_LOCATION, DmnParser.class.getClassLoader()).toString(),
ReflectUtil.getResource(DMN_14_SCHEMA_LOCATION, DmnParser.class.getClassLoader()).toString(),
ReflectUtil.getResource(DMN_13_SCHEMA_LOCATION, DmnParser.class.getClassLoader()).toString(),
ReflectUtil.getResource(DMN_12_SCHEMA_LOCATION, DmnParser.class.getClassLoader()).toString(),
ReflectUtil.getResource(DMN_11_SCHEMA_LOCATION, DmnParser.class.getClassLoader()).toString(),
ReflectUtil.getResource(DMN_11_ALTERNATIVE_SCHEMA_LOCATION, DmnParser.class.getClassLoader()).toString()
});
super.configureFactory(dbf);
}
@Override
protected DmnModelInstanceImpl createModelInstance(DomDocument document) {
return new DmnModelInstanceImpl((ModelImpl) Dmn.INSTANCE.getDmnModel(), Dmn.INSTANCE.getDmnModelBuilder(), document);
} | @Override
public DmnModelInstanceImpl parseModelFromStream(InputStream inputStream) {
try {
return (DmnModelInstanceImpl) super.parseModelFromStream(inputStream);
}
catch (ModelParseException e) {
throw new DmnModelException("Unable to parse model", e);
}
}
@Override
public DmnModelInstanceImpl getEmptyModel() {
return (DmnModelInstanceImpl) super.getEmptyModel();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\DmnParser.java | 1 |
请完成以下Spring Boot application配置 | spring.application.name=spring-boot-persistence-mongodb-2
server.port=8082
spring.mongodb.embedded.version=4.4.9
#spring boot mongodb
spring.data.mongodb.host=localhost
spring.data.mongodb.port=0
spring.data.mongodb.database=springboot-mongo
spring.thymeleaf.cache=false
spring.servlet.multipart.max-file-size= | 256MB
spring.servlet.multipart.max-request-size=256MB
spring.servlet.multipart.enabled=true
spring.data.mongodb.uri=mongodb://localhost | repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public class OrderPaySchedule
{
@NonNull @Getter OrderId orderId;
@NonNull @Getter private final ImmutableList<OrderPayScheduleLine> lines;
private OrderPaySchedule(@NonNull final OrderId orderId, @NonNull final List<OrderPayScheduleLine> lines)
{
this.orderId = orderId;
this.lines = ImmutableList.copyOf(lines);
}
public static OrderPaySchedule ofList(@NonNull final OrderId orderId, @NonNull final List<OrderPayScheduleLine> lines)
{
return new OrderPaySchedule(orderId, lines);
}
public static Collector<OrderPayScheduleLine, ?, Optional<OrderPaySchedule>> collect()
{
return GuavaCollectors.collectUsingListAccumulator((lines) -> {
if (lines.isEmpty())
{
return Optional.empty();
}
final OrderId orderId = lines.get(0).getOrderId();
return Optional.of(new OrderPaySchedule(orderId, lines));
});
}
public OrderPayScheduleLine getLineByPaymentTermBreakId(@NonNull final PaymentTermBreakId paymentTermBreakId)
{
return lines.stream()
.filter(line -> PaymentTermBreakId.equals(line.getPaymentTermBreakId(), paymentTermBreakId))
.findFirst()
.orElseThrow(() -> new AdempiereException("No line found for " + paymentTermBreakId));
}
public OrderPayScheduleLine getLineById(@NonNull final OrderPayScheduleId payScheduleLineId)
{
return lines.stream()
.filter(line -> line.getId().equals(payScheduleLineId))
.findFirst()
.orElseThrow(() -> new AdempiereException("OrderPayScheduleLine not found for ID: " + payScheduleLineId));
} | public void updateStatusFromContext(final OrderSchedulingContext context)
{
final PaymentTerm paymentTerm = context.getPaymentTerm();
for (final OrderPayScheduleLine line : lines)
{
if (line.getStatus().isPending())
{
final PaymentTermBreak termBreak = paymentTerm.getBreakById(line.getPaymentTermBreakId());
final DueDateAndStatus dueDateAndStatus = context.computeDueDate(termBreak);
line.applyAndProcess(dueDateAndStatus);
}
}
}
public void markAsPaid(final OrderPayScheduleId orderPayScheduleId)
{
final OrderPayScheduleLine line = getLineById(orderPayScheduleId);
final DueDateAndStatus dueDateAndStatus = DueDateAndStatus.paid(line.getDueDate());
line.applyAndProcess(dueDateAndStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\OrderPaySchedule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DeviceMapping serialNumber(String serialNumber) {
this.serialNumber = serialNumber;
return this;
}
/**
* eindeutige Seriennumer aus WaWi
* @return serialNumber
**/
@Schema(example = "2005-F540053-EB-0430", required = true, description = "eindeutige Seriennumer aus WaWi")
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public DeviceMapping updated(OffsetDateTime updated) {
this.updated = updated;
return this;
}
/**
* Der Zeitstempel der letzten Änderung
* @return updated
**/
@Schema(example = "2020-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung")
public OffsetDateTime getUpdated() {
return updated;
}
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;
}
DeviceMapping deviceMapping = (DeviceMapping) o;
return Objects.equals(this._id, deviceMapping._id) &&
Objects.equals(this.serialNumber, deviceMapping.serialNumber) &&
Objects.equals(this.updated, deviceMapping.updated);
}
@Override
public int hashCode() {
return Objects.hash(_id, serialNumber, updated);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DeviceMapping {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" serialNumber: ").append(toIndentedString(serialNumber)).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-article-api\src\main\java\io\swagger\client\model\DeviceMapping.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ContractLine getContractLineForProductOrNull(final Product product)
{
for (final ContractLine contractLine : getContractLines())
{
if (Product.COMPARATOR_Id.compare(contractLine.getProduct(), product) != 0)
{
continue;
}
return contractLine;
}
return null;
}
public Collection<Product> getProducts()
{
final Set<Product> products = new TreeSet<>(Product.COMPARATOR_Id);
for (final ContractLine contractLine : getContractLines())
{
if (contractLine.isDeleted())
{
continue;
} | final Product product = contractLine.getProduct();
if (product.isDeleted())
{
continue;
}
products.add(product);
}
return products;
}
public boolean matchesDate(final LocalDate date)
{
return DateUtils.between(date, getDateFrom(), getDateTo());
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Contract.java | 2 |
请完成以下Java代码 | public TransactionParty2 createTransactionParty2() {
return new TransactionParty2();
}
/**
* Create an instance of {@link TransactionPrice2Choice }
*
*/
public TransactionPrice2Choice createTransactionPrice2Choice() {
return new TransactionPrice2Choice();
}
/**
* Create an instance of {@link TransactionQuantities1Choice }
*
*/
public TransactionQuantities1Choice createTransactionQuantities1Choice() {
return new TransactionQuantities1Choice();
}
/**
* Create an instance of {@link TransactionReferences2 }
* | */
public TransactionReferences2 createTransactionReferences2() {
return new TransactionReferences2();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Document }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link Document }{@code >}
*/
@XmlElementDecl(namespace = "urn:iso:std:iso:20022:tech:xsd:camt.053.001.02", name = "Document")
public JAXBElement<Document> createDocument(Document value) {
return new JAXBElement<Document>(_Document_QNAME, Document.class, null, value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ObjectFactory.java | 1 |
请完成以下Java代码 | public class VariableScopeResolver implements Resolver {
protected ProcessEngineConfigurationImpl processEngineConfiguration;
protected VariableContainer scopeContainer;
protected VariableContainer inputVariableContainer;
protected String variableScopeKey = "execution";
protected static final Map<String, Function<ProcessEngineConfiguration, ?>> SERVICE_RESOLVERS = Map.of(
"processEngineConfiguration", Function.identity(),
"runtimeService", ProcessEngineConfiguration::getRuntimeService,
"taskService", ProcessEngineConfiguration::getTaskService,
"repositoryService", ProcessEngineConfiguration::getRepositoryService,
"managementService", ProcessEngineConfiguration::getManagementService,
"historyService", ProcessEngineConfiguration::getHistoryService,
"formService", ProcessEngineConfiguration::getFormService,
"identityServiceKey", ProcessEngineConfiguration::getIdentityService
);
public VariableScopeResolver(ProcessEngineConfigurationImpl processEngineConfiguration, VariableContainer scopeContainer,
VariableContainer inputVariableContainer) {
this.processEngineConfiguration = processEngineConfiguration;
if (scopeContainer == null) {
throw new FlowableIllegalArgumentException("scopeContainer cannot be null");
}
if (scopeContainer instanceof ExecutionEntity) {
variableScopeKey = "execution";
} else if (scopeContainer instanceof TaskEntity) {
variableScopeKey = "task";
} else {
throw new FlowableException("unsupported variable scope type: " + scopeContainer.getClass().getName());
}
this.scopeContainer = scopeContainer;
this.inputVariableContainer = inputVariableContainer; | }
@Override
public boolean containsKey(Object key) {
return variableScopeKey.equals(key) || inputVariableContainer.hasVariable((String) key)
|| SERVICE_RESOLVERS.containsKey(key) && processEngineConfiguration.isServicesEnabledInScripting();
}
@Override
public Object get(Object key) {
if (variableScopeKey.equals(key)) {
return scopeContainer;
} else if (SERVICE_RESOLVERS.containsKey((String) key)) {
if (processEngineConfiguration.isServicesEnabledInScripting()) {
return SERVICE_RESOLVERS.get(key).apply(processEngineConfiguration);
} else {
throw new FlowableException("The service '" + key + "' is not available in the current context. Please enable services in scripting.");
}
}
return inputVariableContainer.getVariable((String) key);
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\scripting\VariableScopeResolver.java | 1 |
请完成以下Java代码 | public Builder audience(Collection<String> audience) {
return claim(JwtClaimNames.AUD, audience);
}
/**
* Use this expiration in the resulting {@link Jwt}
* @param expiresAt The expiration to use
* @return the {@link Builder} for further configurations
*/
public Builder expiresAt(Instant expiresAt) {
this.claim(JwtClaimNames.EXP, expiresAt);
return this;
}
/**
* Use this identifier in the resulting {@link Jwt}
* @param jti The identifier to use
* @return the {@link Builder} for further configurations
*/
public Builder jti(String jti) {
this.claim(JwtClaimNames.JTI, jti);
return this;
}
/**
* Use this issued-at timestamp in the resulting {@link Jwt}
* @param issuedAt The issued-at timestamp to use
* @return the {@link Builder} for further configurations
*/
public Builder issuedAt(Instant issuedAt) {
this.claim(JwtClaimNames.IAT, issuedAt);
return this;
}
/**
* Use this issuer in the resulting {@link Jwt}
* @param issuer The issuer to use
* @return the {@link Builder} for further configurations
*/
public Builder issuer(String issuer) {
this.claim(JwtClaimNames.ISS, issuer);
return this;
}
/**
* Use this not-before timestamp in the resulting {@link Jwt}
* @param notBefore The not-before timestamp to use
* @return the {@link Builder} for further configurations
*/ | public Builder notBefore(Instant notBefore) {
this.claim(JwtClaimNames.NBF, notBefore);
return this;
}
/**
* Use this subject in the resulting {@link Jwt}
* @param subject The subject to use
* @return the {@link Builder} for further configurations
*/
public Builder subject(String subject) {
this.claim(JwtClaimNames.SUB, subject);
return this;
}
/**
* Build the {@link Jwt}
* @return The constructed {@link Jwt}
*/
public Jwt build() {
Instant iat = toInstant(this.claims.get(JwtClaimNames.IAT));
Instant exp = toInstant(this.claims.get(JwtClaimNames.EXP));
return new Jwt(this.tokenValue, iat, exp, this.headers, this.claims);
}
private Instant toInstant(Object timestamp) {
if (timestamp != null) {
Assert.isInstanceOf(Instant.class, timestamp, "timestamps must be of type Instant");
}
return (Instant) timestamp;
}
}
} | repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\Jwt.java | 1 |
请完成以下Java代码 | public void setPostingType (java.lang.String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get Buchungsart.
@return The type of posted amount for the transaction
*/
@Override
public java.lang.String getPostingType ()
{
return (java.lang.String)get_Value(COLUMNNAME_PostingType);
}
/** Set Verarbeiten.
@param Processing Verarbeiten */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public org.compiere.model.I_C_ElementValue getUser1() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser1(org.compiere.model.I_C_ElementValue User1)
{
set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1);
}
/** Set Nutzer 1.
@param User1_ID
User defined list element #1
*/
@Override
public void setUser1_ID (int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID));
}
/** Get Nutzer 1.
@return User defined list element #1
*/
@Override
public int getUser1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ElementValue getUser2() throws RuntimeException | {
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser2(org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
/** Set Nutzer 2.
@param User2_ID
User defined list element #2
*/
@Override
public void setUser2_ID (int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID));
}
/** Get Nutzer 2.
@return User defined list element #2
*/
@Override
public int getUser2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Distribution.java | 1 |
请完成以下Java代码 | private Set<String> getAllowedDocActions(final ClientId adClientId, final DocTypeId docTypeId)
{
final ArrayKey key = Util.mkKey(adClientId, docTypeId);
return docActionsAllowed.computeIfAbsent(key, (k) -> retrieveAllowedDocActions(adClientId, docTypeId));
}
private Set<String> retrieveAllowedDocActions(final ClientId adClientId, final DocTypeId docTypeId)
{
final List<Object> sqlParams = new ArrayList<>();
sqlParams.add(adClientId);
sqlParams.add(docTypeId);
final String sql = "SELECT rl.Value FROM AD_Document_Action_Access a"
+ " INNER JOIN AD_Ref_List rl ON (rl.AD_Reference_ID=135 and rl.AD_Ref_List_ID=a.AD_Ref_List_ID)"
+ " WHERE a.IsActive='Y' AND a.AD_Client_ID=? AND a.C_DocType_ID=?" // #1,2
+ " AND " + getIncludedRolesWhereClause("a.AD_Role_ID", sqlParams);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
DB.setParameters(pstmt, sqlParams);
rs = pstmt.executeQuery();
final ImmutableSet.Builder<String> options = ImmutableSet.builder();
while (rs.next())
{
final String op = rs.getString(1);
options.add(op);
}
return options.build();
}
catch (final SQLException e)
{
throw new DBException(e, sql, sqlParams);
}
finally
{
DB.close(rs, pstmt);
}
}
@Override
public void applyActionAccess(final DocActionOptionsContext optionsCtx)
{
retainDocActionsWithAccess(optionsCtx);
final String targetDocAction = optionsCtx.getDocActionToUse();
if (targetDocAction != null && !IDocument.ACTION_None.equals(targetDocAction))
{
final Set<String> options = optionsCtx.getDocActions();
final Boolean access;
if (options.contains(targetDocAction))
{
access = true;
}
else
{
access = null; // legacy
}
if (optionsCtx.getDocTypeId() != null)
{
rolePermLoggingBL().logDocActionAccess(getRoleId(), optionsCtx.getDocTypeId(), targetDocAction, access);
} | }
optionsCtx.setDocActionToUse(targetDocAction);
}
/**
* Get Role Where Clause.
* It will look something like myalias.AD_Role_ID IN (?, ?, ?).
*
* @param roleColumnSQL role columnname or role column SQL (e.g. myalias.AD_Role_ID)
* @param params a list where the method will put SQL parameters.
* If null, this method will generate a not parametrized query
* @return role SQL where clause
*/
@Override
public String getIncludedRolesWhereClause(final String roleColumnSQL, final List<Object> params)
{
final StringBuilder whereClause = new StringBuilder();
for (final RoleId adRoleId : allRoleIds)
{
if (whereClause.length() > 0)
{
whereClause.append(",");
}
if (params != null)
{
whereClause.append("?");
params.add(adRoleId);
}
else
{
whereClause.append(adRoleId.getRepoId());
}
}
//
whereClause.insert(0, roleColumnSQL + " IN (").append(")");
return whereClause.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\UserRolePermissions.java | 1 |
请完成以下Java代码 | public static String getCaseDiagramResourceName(String cmmnFileResource, String caseKey, String diagramSuffix) {
String cmmnFileResourceBase = stripCmmnFileSuffix(cmmnFileResource);
return cmmnFileResourceBase + caseKey + "." + diagramSuffix;
}
/**
* Finds the name of a resource for the diagram for a case definition. Assumes that the case definition's key and (CMMN) resource name are already set.
*
* <p>
* It will first look for an image resource which matches the case specifically, before resorting to an image resource which matches the CMMN 1.1 xml file resource.
*
* <p>
* Example: if the deployment contains a CMMN 1.1 xml resource called 'abc.cmmn.xml' containing only one case with key 'myCase', then this method will look for an image resources
* called 'abc.myCase.png' (or .jpg, or .gif, etc.) or 'abc.png' if the previous one wasn't found.
*
* <p>
* Example 2: if the deployment contains a CMMN 1.1 xml resource called 'abc.cmmn.xml' containing three cases (with keys a, b and c), then this method will first look for an image resource
* called 'abc.a.png' before looking for 'abc.png' (likewise for b and c). Note that if abc.a.png, abc.b.png and abc.c.png don't exist, all cases will have the same image: abc.png.
*
* @return name of an existing resource, or null if no matching image resource is found in the resources.
*/
public static String getCaseDiagramResourceNameFromDeployment(
CaseDefinitionEntity caseDefinition, Map<String, EngineResource> resources) {
if (StringUtils.isEmpty(caseDefinition.getResourceName())) {
throw new IllegalStateException("Provided case definition must have its resource name set.");
}
String cmmnResourceBase = stripCmmnFileSuffix(caseDefinition.getResourceName());
String key = caseDefinition.getKey(); | for (String diagramSuffix : DIAGRAM_SUFFIXES) {
String possibleName = cmmnResourceBase + key + "." + diagramSuffix;
if (resources.containsKey(possibleName)) {
return possibleName;
}
possibleName = cmmnResourceBase + diagramSuffix;
if (resources.containsKey(possibleName)) {
return possibleName;
}
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\deployer\ResourceNameUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MenuEntity implements Serializable {
/** 主键 */
private String id;
/** 菜单名称 */
private String menuName;
/** 菜单对应页面的URL */
private String url;
/** 父菜单的ID */
private String parentId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getParentId() { | return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
@Override
public String toString() {
return "MenuEntity{" +
"id='" + id + '\'' +
", menuName='" + menuName + '\'' +
", url='" + url + '\'' +
", parentId='" + parentId + '\'' +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\MenuEntity.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int update(Long id, UmsMemberReceiveAddress address) {
address.setId(null);
UmsMember currentMember = memberService.getCurrentMember();
UmsMemberReceiveAddressExample example = new UmsMemberReceiveAddressExample();
example.createCriteria().andMemberIdEqualTo(currentMember.getId()).andIdEqualTo(id);
if(address.getDefaultStatus()==null){
address.setDefaultStatus(0);
}
if(address.getDefaultStatus()==1){
//先将原来的默认地址去除
UmsMemberReceiveAddress record= new UmsMemberReceiveAddress();
record.setDefaultStatus(0);
UmsMemberReceiveAddressExample updateExample = new UmsMemberReceiveAddressExample();
updateExample.createCriteria()
.andMemberIdEqualTo(currentMember.getId())
.andDefaultStatusEqualTo(1);
addressMapper.updateByExampleSelective(record,updateExample);
}
return addressMapper.updateByExampleSelective(address,example);
}
@Override | public List<UmsMemberReceiveAddress> list() {
UmsMember currentMember = memberService.getCurrentMember();
UmsMemberReceiveAddressExample example = new UmsMemberReceiveAddressExample();
example.createCriteria().andMemberIdEqualTo(currentMember.getId());
return addressMapper.selectByExample(example);
}
@Override
public UmsMemberReceiveAddress getItem(Long id) {
UmsMember currentMember = memberService.getCurrentMember();
UmsMemberReceiveAddressExample example = new UmsMemberReceiveAddressExample();
example.createCriteria().andMemberIdEqualTo(currentMember.getId()).andIdEqualTo(id);
List<UmsMemberReceiveAddress> addressList = addressMapper.selectByExample(example);
if(!CollectionUtils.isEmpty(addressList)){
return addressList.get(0);
}
return null;
}
} | repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\UmsMemberReceiveAddressServiceImpl.java | 2 |
请完成以下Java代码 | public static ShipmentScheduleAndJobScheduleId ofRepoIdsOrNull(final int shipmentScheduleRepoId, final int pickingJobScheduleRepoId)
{
final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoIdOrNull(shipmentScheduleRepoId);
if (shipmentScheduleId == null)
{
return null;
}
return of(shipmentScheduleId, PickingJobScheduleId.ofRepoIdOrNull(pickingJobScheduleRepoId));
}
@NonNull
public static ShipmentScheduleAndJobScheduleId ofRepoIds(final int shipmentScheduleRepoId, final int pickingJobScheduleRepoId)
{
final ShipmentScheduleAndJobScheduleId id = ofRepoIdsOrNull(shipmentScheduleRepoId, pickingJobScheduleRepoId);
if (id == null)
{
throw new AdempiereException("No " + ShipmentScheduleAndJobScheduleId.class + " found for shipmentScheduleRepoId=" + shipmentScheduleRepoId + " and pickingJobScheduleRepoId=" + pickingJobScheduleRepoId);
}
return id;
}
public static ShipmentScheduleAndJobScheduleId ofShipmentScheduleId(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
return of(shipmentScheduleId, null);
}
@Override
@Deprecated
public String toString() {return toJsonString();}
@JsonValue
public String toJsonString()
{
return jobScheduleId != null
? shipmentScheduleId.getRepoId() + "_" + jobScheduleId.getRepoId()
: "" + shipmentScheduleId.getRepoId();
}
@JsonCreator
public static ShipmentScheduleAndJobScheduleId ofJsonString(@NonNull final String json)
{
try
{
final int idx = json.indexOf("_");
if (idx > 0)
{
return of(
ShipmentScheduleId.ofRepoId(Integer.parseInt(json.substring(0, idx))),
PickingJobScheduleId.ofRepoId(Integer.parseInt(json.substring(idx + 1)))
); | }
else
{
return of(
ShipmentScheduleId.ofRepoId(Integer.parseInt(json)),
null
);
}
}
catch (Exception ex)
{
throw new AdempiereException("Invalid JSON: " + json, ex);
}
}
public TableRecordReference toTableRecordReference()
{
return jobScheduleId != null ? jobScheduleId.toTableRecordReference() : shipmentScheduleId.toTableRecordReference();
}
public boolean isJobSchedule() {return jobScheduleId != null;}
@Override
public int compareTo(@NotNull final ShipmentScheduleAndJobScheduleId other)
{
return this.toJsonString().compareTo(other.toJsonString());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\picking\api\ShipmentScheduleAndJobScheduleId.java | 1 |
请完成以下Java代码 | public void setValue (final java.lang.String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setValueMax (final @Nullable BigDecimal ValueMax)
{
set_Value (COLUMNNAME_ValueMax, ValueMax);
}
@Override | public BigDecimal getValueMax()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMax);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValueMin (final @Nullable BigDecimal ValueMin)
{
set_Value (COLUMNNAME_ValueMin, ValueMin);
}
@Override
public BigDecimal getValueMin()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMin);
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_M_Attribute.java | 1 |
请完成以下Java代码 | public ProcessDefinitionEntity findProcessDefinitionByKeyAndVersionAndTenantId(
String processDefinitionKey,
Integer processDefinitionVersion,
String tenantId
) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("processDefinitionKey", processDefinitionKey);
params.put("processDefinitionVersion", processDefinitionVersion);
params.put("tenantId", tenantId);
List<ProcessDefinitionEntity> results = getDbSqlSession().selectList(
"selectProcessDefinitionsByKeyAndVersionAndTenantId",
params
);
if (results.size() == 1) {
return results.get(0);
} else if (results.size() > 1) {
throw new ActivitiException(
"There are " +
results.size() +
" process definitions with key = '" +
processDefinitionKey +
"' and version = '" +
processDefinitionVersion +
"'."
);
}
return null;
}
@Override
@SuppressWarnings("unchecked")
public List<ProcessDefinition> findProcessDefinitionsByNativeQuery(
Map<String, Object> parameterMap,
int firstResult,
int maxResults | ) {
return getDbSqlSession().selectListWithRawParameter(
"selectProcessDefinitionByNativeQuery",
parameterMap,
firstResult,
maxResults
);
}
@Override
public long findProcessDefinitionCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectProcessDefinitionCountByNativeQuery", parameterMap);
}
@Override
public void updateProcessDefinitionTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateProcessDefinitionTenantIdForDeploymentId", params);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisProcessDefinitionDataManager.java | 1 |
请完成以下Java代码 | public void run(String localTrxName) throws Exception
{
success[0] = save0(localTrxName);
}
});
return success[0];
}
private final boolean save0 (String trxName)
{
if (m_value == null
|| (!(m_value instanceof String || m_value instanceof byte[]))
|| (m_value instanceof String && m_value.toString().length() == 0)
|| (m_value instanceof byte[] && ((byte[])m_value).length == 0)
)
{
StringBuilder sql = new StringBuilder("UPDATE ")
.append(m_tableName)
.append(" SET ").append(m_columnName)
.append("=null WHERE ").append(m_whereClause);
int no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), trxName);
log.debug("save [" + trxName + "] #" + no + " - no data - set to null - " + m_value);
if (no == 0)
log.warn("[" + trxName + "] - not updated - " + sql);
return true;
}
final String sql;
final Object[] sqlParams;
if(MigrationScriptFileLoggerHolder.isEnabled())
{
final String valueBase64enc = BaseEncoding.base64().encode((byte[])m_value);
sql = "UPDATE " + m_tableName + " SET " + m_columnName + "=DECODE(" + DB.TO_STRING(valueBase64enc) + ", 'base64') WHERE " + m_whereClause;
sqlParams = new Object[] {};
}
else
{
sql = "UPDATE " + m_tableName + " SET " + m_columnName + "=? WHERE " + m_whereClause;
sqlParams = new Object[]{m_value};
}
PreparedStatement pstmt = null;
boolean success = true;
try
{
pstmt = DB.prepareStatement(sql, trxName);
DB.setParameters(pstmt, sqlParams);
final int no = pstmt.executeUpdate();
if (no != 1)
{
log.warn("[" + trxName + "] - Not updated #" + no + " - " + sql);
success = false;
} | }
catch (Throwable e)
{
log.error("[" + trxName + "] - " + sql, e);
success = false;
}
finally
{
DB.close(pstmt);
pstmt = null;
}
return success;
} // save
/**
* String Representation
* @return info
*/
@Override
public String toString()
{
StringBuffer sb = new StringBuffer("PO_LOB[");
sb.append(m_tableName).append(".").append(m_columnName)
.append(",DisplayType=").append(m_displayType)
.append("]");
return sb.toString();
} // toString
} // PO_LOB | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\PO_LOB.java | 1 |
请完成以下Java代码 | public void setCarrier_Service_ID (final int Carrier_Service_ID)
{
if (Carrier_Service_ID < 1)
set_ValueNoCheck (COLUMNNAME_Carrier_Service_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Carrier_Service_ID, Carrier_Service_ID);
}
@Override
public int getCarrier_Service_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_Service_ID);
}
@Override
public void setExternalId (final java.lang.String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public java.lang.String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_Value (COLUMNNAME_M_Shipper_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); | }
@Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_Service.java | 1 |
请完成以下Java代码 | public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
@Override
public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
@Override
public void setAD_User_Login_ID (int AD_User_Login_ID)
{
if (AD_User_Login_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_Login_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_Login_ID, Integer.valueOf(AD_User_Login_ID));
}
@Override
public int getAD_User_Login_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_Login_ID);
}
@Override
public void setHostKey (java.lang.String HostKey)
{
set_Value (COLUMNNAME_HostKey, HostKey);
}
@Override
public java.lang.String getHostKey()
{
return (java.lang.String)get_Value(COLUMNNAME_HostKey);
}
@Override
public void setPassword (java.lang.String Password)
{ | set_Value (COLUMNNAME_Password, Password);
}
@Override
public java.lang.String getPassword()
{
return (java.lang.String)get_Value(COLUMNNAME_Password);
}
@Override
public void setUserName (java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return (java.lang.String)get_Value(COLUMNNAME_UserName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_User_Login.java | 1 |
请完成以下Java代码 | public class BPartnerProductBL implements IBPartnerProductBL
{
private static final String MSG_ProductSalesExclusionError = "ProductSalesExclusionError";
private static final String MSG_ProductPurchaseExclusionError = "ProductPurchaseExclusionError";
private final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
private final IBPartnerProductDAO bpProductDAO = Services.get(IBPartnerProductDAO.class);
private final IMsgBL msgBL = Services.get(IMsgBL.class);
public void assertNotExcludedFromTransaction(@NonNull final SOTrx soTrx, @NonNull final ProductId productId, @NonNull final BPartnerId partnerId)
{
if (soTrx.isSales())
{
assertNotExcludedFromSaleToCustomer(productId, partnerId);
}
else
{
assertNotExcludedFromPurchaseFromVendor(productId, partnerId);
}
}
private void assertNotExcludedFromSaleToCustomer(@NonNull final ProductId productId, @NonNull final BPartnerId partnerId)
{
bpProductDAO.getExcludedFromSaleToCustomer(productId, partnerId)
.ifPresent(productExclude -> this.throwException(productExclude, AdMessageKey.of(MSG_ProductSalesExclusionError)));
}
private void assertNotExcludedFromPurchaseFromVendor(@NonNull final ProductId productId, @NonNull final BPartnerId partnerId)
{
bpProductDAO.getExcludedFromPurchaseFromVendor(productId, partnerId)
.ifPresent(productExclude -> this.throwException(productExclude, AdMessageKey.of(MSG_ProductPurchaseExclusionError)));
}
private void throwException(@NonNull final ProductExclude productExclude, @NonNull final AdMessageKey adMessage)
{
final String partnerName = bpartnerDAO.getBPartnerNameById(productExclude.getBpartnerId());
final String msg = msgBL.getMsg(adMessage,
ImmutableList.of(partnerName, productExclude.getReason()));
throw new AdempiereException(msg);
}
@Override
public void setProductCodeFieldsFromGTIN(@NonNull final I_C_BPartner_Product record, @Nullable final GTIN gtin)
{
final EAN13 ean13 = gtin != null ? gtin.toEAN13().orElse(null) : null; | record.setGTIN(gtin != null ? gtin.getAsString() : null);
record.setEAN_CU(ean13 != null ? ean13.getAsString() : null);
record.setUPC(gtin != null ? gtin.getAsString() : null);
if (gtin != null)
{
record.setEAN13_ProductCode(null);
}
}
@Override
public void setProductCodeFieldsFromEAN13ProductCode(@NonNull final I_C_BPartner_Product record, @Nullable final EAN13ProductCode ean13ProductCode)
{
record.setEAN13_ProductCode(ean13ProductCode != null ? ean13ProductCode.getAsString() : null);
if (ean13ProductCode != null)
{
record.setGTIN(null);
record.setEAN_CU(null);
record.setUPC(null);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner_product\impl\BPartnerProductBL.java | 1 |
请完成以下Java代码 | public void setQty_Attribute_ID (final int Qty_Attribute_ID)
{
if (Qty_Attribute_ID < 1)
set_Value (COLUMNNAME_Qty_Attribute_ID, null);
else
set_Value (COLUMNNAME_Qty_Attribute_ID, Qty_Attribute_ID);
}
@Override
public int getQty_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_Qty_Attribute_ID);
}
@Override
public void setQtyBatch (final @Nullable BigDecimal QtyBatch)
{
set_Value (COLUMNNAME_QtyBatch, QtyBatch);
}
@Override
public BigDecimal getQtyBatch()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBatch);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyBOM (final @Nullable BigDecimal QtyBOM)
{
set_Value (COLUMNNAME_QtyBOM, QtyBOM);
}
@Override
public BigDecimal getQtyBOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setScrap (final @Nullable BigDecimal Scrap)
{
set_Value (COLUMNNAME_Scrap, Scrap);
}
@Override
public BigDecimal getScrap()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Scrap);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setShowSubBOMIngredients (final boolean ShowSubBOMIngredients)
{
set_Value (COLUMNNAME_ShowSubBOMIngredients, ShowSubBOMIngredients);
}
@Override
public boolean isShowSubBOMIngredients()
{
return get_ValueAsBoolean(COLUMNNAME_ShowSubBOMIngredients);
}
@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);
}
/**
* VariantGroup AD_Reference_ID=540490
* Reference name: VariantGroup
*/
public static final int VARIANTGROUP_AD_Reference_ID=540490;
/** 01 = 01 */
public static final String VARIANTGROUP_01 = "01";
/** 02 = 02 */
public static final String VARIANTGROUP_02 = "02";
/** 03 = 03 */
public static final String VARIANTGROUP_03 = "03";
/** 04 = 04 */
public static final String VARIANTGROUP_04 = "04";
/** 05 = 05 */
public static final String VARIANTGROUP_05 = "05";
/** 06 = 06 */
public static final String VARIANTGROUP_06 = "06";
/** 07 = 07 */
public static final String VARIANTGROUP_07 = "07";
/** 08 = 08 */
public static final String VARIANTGROUP_08 = "08";
/** 09 = 09 */
public static final String VARIANTGROUP_09 = "09";
@Override
public void setVariantGroup (final @Nullable java.lang.String VariantGroup)
{
set_Value (COLUMNNAME_VariantGroup, VariantGroup);
}
@Override
public java.lang.String getVariantGroup()
{
return get_ValueAsString(COLUMNNAME_VariantGroup);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Product_BOMLine.java | 1 |
请完成以下Java代码 | public List<T> findAll() {
return getCurrentSession().createQuery("from " + clazz.getName()).getResultList();
}
@Override
public void create(final T entity) {
Preconditions.checkNotNull(entity);
getCurrentSession().saveOrUpdate(entity);
}
@Override
public T update(final T entity) {
Preconditions.checkNotNull(entity);
return (T) getCurrentSession().merge(entity);
}
@Override
public void delete(final T entity) {
Preconditions.checkNotNull(entity); | getCurrentSession().delete(entity);
}
@Override
public void deleteById(final long entityId) {
final T entity = findOne(entityId);
Preconditions.checkState(entity != null);
delete(entity);
}
protected Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\manytomany\dao\common\AbstractHibernateDao.java | 1 |
请完成以下Java代码 | public void setAD_User_Substitute_ID (int AD_User_Substitute_ID)
{
if (AD_User_Substitute_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_Substitute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_Substitute_ID, Integer.valueOf(AD_User_Substitute_ID));
}
/** Get Vertreter.
@return Substitute of the user
*/
@Override
public int getAD_User_Substitute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_Substitute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** 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);
}
@Override
public org.compiere.model.I_AD_User getSubstitute() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Substitute_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSubstitute(org.compiere.model.I_AD_User Substitute)
{
set_ValueFromPO(COLUMNNAME_Substitute_ID, org.compiere.model.I_AD_User.class, Substitute);
} | /** Set Ersatz.
@param Substitute_ID
Entity which can be used in place of this entity
*/
@Override
public void setSubstitute_ID (int Substitute_ID)
{
if (Substitute_ID < 1)
set_Value (COLUMNNAME_Substitute_ID, null);
else
set_Value (COLUMNNAME_Substitute_ID, Integer.valueOf(Substitute_ID));
}
/** Get Ersatz.
@return Entity which can be used in place of this entity
*/
@Override
public int getSubstitute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Substitute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Gültig ab.
@param ValidFrom
Valid from including this date (first day)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Valid from including this date (first day)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Valid to including this date (last day)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Valid to including this date (last day)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Substitute.java | 1 |
请完成以下Java代码 | public int getRecord_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_Attribute_ID);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setValueDate (final @Nullable java.sql.Timestamp ValueDate)
{
set_Value (COLUMNNAME_ValueDate, ValueDate);
}
@Override
public java.sql.Timestamp getValueDate()
{
return get_ValueAsTimestamp(COLUMNNAME_ValueDate);
}
@Override
public void setValueNumber (final @Nullable BigDecimal ValueNumber)
{
set_Value (COLUMNNAME_ValueNumber, ValueNumber);
} | @Override
public BigDecimal getValueNumber()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValueString (final @Nullable java.lang.String ValueString)
{
set_Value (COLUMNNAME_ValueString, ValueString);
}
@Override
public java.lang.String getValueString()
{
return get_ValueAsString(COLUMNNAME_ValueString);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Record_Attribute.java | 1 |
请完成以下Java代码 | public class OrderLinesAggregator extends MapReduceAggregator<OrderLineAggregation, PurchaseCandidate>
{
private final I_C_Order order;
public OrderLinesAggregator(final I_C_Order purchaseOrder)
{
super();
this.order = purchaseOrder;
setItemAggregationKeyBuilder(new IAggregationKeyBuilder<PurchaseCandidate>()
{
@Override
public String buildKey(final PurchaseCandidate item)
{
return item.getLineAggregationKey().toString();
}
@Override
public boolean isSame(PurchaseCandidate item1, PurchaseCandidate item2)
{
throw new UnsupportedOperationException(); // shall not be called
}
@Override
public List<String> getDependsOnColumnNames()
{
throw new UnsupportedOperationException(); // shall not be called
}
});
}
@Override
public String toString() | {
return ObjectUtils.toString(this);
}
@Override
protected OrderLineAggregation createGroup(final Object itemHashKey, final PurchaseCandidate candidate)
{
return new OrderLineAggregation(order);
}
@Override
protected void closeGroup(final OrderLineAggregation orderLineCandidate)
{
orderLineCandidate.build();
}
@Override
protected void addItemToGroup(final OrderLineAggregation purchaseOrderLine, final PurchaseCandidate candidate)
{
purchaseOrderLine.add(candidate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\OrderLinesAggregator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FreightCostId implements RepoIdAware
{
int repoId;
@JsonCreator
public static FreightCostId ofRepoId(final int repoId)
{
return new FreightCostId(repoId);
}
public static FreightCostId ofRepoIdOrNull(@Nullable final int repoId)
{
return repoId > 0 ? new FreightCostId(repoId) : null;
}
public static int toRepoId(final FreightCostId id)
{
return id != null ? id.getRepoId() : -1; | }
private FreightCostId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_FreightCost_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
public static boolean equals(final FreightCostId id1, final FreightCostId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\freighcost\FreightCostId.java | 2 |
请完成以下Java代码 | public String getCompressFileKey() {
return compressFileKey;
}
public void setCompressFileKey(String compressFileKey) {
this.compressFileKey = compressFileKey;
}
public String getName() {
return name;
}
public String getCacheName() {
return cacheName;
}
public String getCacheListName() {
return cacheListName;
}
public String getOutFilePath() {
return outFilePath;
}
public String getOriginFilePath() {
return originFilePath;
}
public boolean isHtmlView() {
return isHtmlView;
}
public void setCacheName(String cacheName) {
this.cacheName = cacheName;
}
public void setCacheListName(String cacheListName) {
this.cacheListName = cacheListName;
}
public void setOutFilePath(String outFilePath) {
this.outFilePath = outFilePath;
}
public void setOriginFilePath(String originFilePath) {
this.originFilePath = originFilePath;
}
public void setHtmlView(boolean isHtmlView) {
this.isHtmlView = isHtmlView;
}
public void setName(String name) {
this.name = name;
} | public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Boolean getSkipDownLoad() {
return skipDownLoad;
}
public void setSkipDownLoad(Boolean skipDownLoad) {
this.skipDownLoad = skipDownLoad;
}
public String getTifPreviewType() {
return tifPreviewType;
}
public void setTifPreviewType(String previewType) {
this.tifPreviewType = previewType;
}
public Boolean forceUpdatedCache() {
return forceUpdatedCache;
}
public void setForceUpdatedCache(Boolean forceUpdatedCache) {
this.forceUpdatedCache = forceUpdatedCache;
}
public String getKkProxyAuthorization() {
return kkProxyAuthorization;
}
public void setKkProxyAuthorization(String kkProxyAuthorization) {
this.kkProxyAuthorization = kkProxyAuthorization;
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\model\FileAttribute.java | 1 |
请完成以下Java代码 | public class KafkaChannelMessageListenerAdapter implements AcknowledgingConsumerAwareMessageListener<Object, Object> {
protected EventRegistry eventRegistry;
protected InboundChannelModel inboundChannelModel;
public KafkaChannelMessageListenerAdapter(EventRegistry eventRegistry, InboundChannelModel inboundChannelModel) {
this.eventRegistry = eventRegistry;
this.inboundChannelModel = inboundChannelModel;
}
@Override
public void onMessage(ConsumerRecord<Object, Object> data, Acknowledgment acknowledgment, Consumer<?, ?> consumer) {
// This can easily be the default MessageListener.
// However, the Spring Kafka retry mechanism requires this to be AcknowledgingConsumerAwareMessageListener
eventRegistry.eventReceived(inboundChannelModel, new KafkaConsumerRecordInboundEvent(data));
if (acknowledgment != null) {
acknowledgment.acknowledge();
}
}
public EventRegistry getEventRegistry() {
return eventRegistry; | }
public void setEventRegistry(EventRegistry eventRegistry) {
this.eventRegistry = eventRegistry;
}
public InboundChannelModel getInboundChannelModel() {
return inboundChannelModel;
}
public void setInboundChannelModel(InboundChannelModel inboundChannelModel) {
this.inboundChannelModel = inboundChannelModel;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\kafka\KafkaChannelMessageListenerAdapter.java | 1 |
请完成以下Java代码 | public Criteria andDetailIn(List<String> values) {
addCriterion("detail in", values, "detail");
return (Criteria) this;
}
public Criteria andDetailNotIn(List<String> values) {
addCriterion("detail not in", values, "detail");
return (Criteria) this;
}
public Criteria andDetailBetween(String value1, String value2) {
addCriterion("detail between", value1, value2, "detail");
return (Criteria) this;
}
public Criteria andDetailNotBetween(String value1, String value2) {
addCriterion("detail not between", value1, value2, "detail");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() { | return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductVertifyRecordExample.java | 1 |
请完成以下Java代码 | public void disposeHU(
@RequestParam("huId") final int huRepoId,
@RequestParam("reasonCode") final String reasonCodeStr)
{
assertActionAccess(HUManagerAction.Dispose);
final HuId huId = HuId.ofRepoId(huRepoId);
final QtyRejectedReasonCode reasonCode = QtyRejectedReasonCode.ofCode(reasonCodeStr);
inventoryCandidateService.createDisposeCandidates(huId, reasonCode);
}
@PostMapping("/changeQty")
public ResponseEntity<JsonGetSingleHUResponse> changeHUQty(@RequestBody @NonNull final JsonHUQtyChangeRequest request)
{
assertActionAccess(HUManagerAction.ChangeQty);
final HuId huId = handlingUnitsService.updateQty(request);
return handlingUnitsService.getByIdSupplier(
() -> GetByIdRequest.builder()
.huId(huId)
.expectedQRCode(HUQRCode.fromNullable(request.getHuQRCode()))
.build()
);
}
@PostMapping("/move")
public void moveHU(@RequestBody @NonNull final JsonMoveHURequest request)
{
assertActionAccess(HUManagerAction.Move);
handlingUnitsService.move(MoveHURequest.builder()
.huId(request.getHuId())
.huQRCode(HUQRCode.fromNullable(request.getHuQRCode()))
.numberOfTUs(request.getNumberOfTUs())
.targetQRCode(request.getTargetQRCode())
.build());
}
@PostMapping("/bulk/move")
public void bulkMove(@RequestBody @NonNull final JsonBulkMoveHURequest request)
{
assertActionAccess(HUManagerAction.BulkActions); | handlingUnitsService.bulkMove(
BulkMoveHURequest.builder()
.huQrCodes(request.getHuQRCodes().stream()
.map(HUQRCode::fromGlobalQRCodeJsonString)
.collect(ImmutableList.toImmutableList()))
.targetQRCode(ScannedCode.ofString(request.getTargetQRCode()))
.build()
);
}
@PostMapping("/huLabels/print")
public JsonPrintHULabelResponse printHULabels(@RequestBody @NonNull final JsonPrintHULabelRequest request)
{
assertActionAccess(HUManagerAction.PrintLabels);
try (final FrontendPrinter frontendPrinter = FrontendPrinter.start())
{
handlingUnitsService.printHULabels(request);
final FrontendPrinterData printData = frontendPrinter.getDataAndClear();
return JsonPrintHULabelResponse.builder()
.printData(JsonPrintHULabelResponse.JsonPrintDataItem.of(printData))
.build();
}
}
@GetMapping("/huLabels/printingOptions")
public List<JsonHULabelPrintingOption> getPrintingOptions()
{
final String adLanguage = Env.getADLanguageOrBaseLanguage();
return handlingUnitsService.getLabelPrintingOptions(adLanguage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\mobileui\HUManagerRestController.java | 1 |
请完成以下Java代码 | public final class LoggableTrxItemExceptionHandler implements ITrxItemExceptionHandler
{
private static final Logger logger = LogManager.getLogger(LoggableTrxItemExceptionHandler.class);
public static final LoggableTrxItemExceptionHandler instance = new LoggableTrxItemExceptionHandler();
private LoggableTrxItemExceptionHandler()
{
}
@Override
public void onNewChunkError(final Throwable e, final Object item)
{
Loggables.withLogger(logger, Level.DEBUG).addLog("Error while trying to create a new chunk for item={}; exception={}", item, e);
}
@Override
public void onItemError(final Throwable e, final Object item)
{
Loggables.withLogger(logger, Level.DEBUG).addLog("Error while trying to process item={}; exception={}", item, e);
}
@Override
public void onCompleteChunkError(final Throwable e)
{
Loggables.withLogger(logger, Level.DEBUG).addLog("Error while completing current chunk; exception={}", e); | }
@Override
public void afterCompleteChunkError(final Throwable e)
{
// nothing to do.
// error was already logged by onCompleteChunkError
}
@Override
public void onCommitChunkError(final Throwable e)
{
Loggables.withLogger(logger, Level.DEBUG).addLog("Processor failed to commit current chunk => rollback transaction; exception={}", e);
}
@Override
public void onCancelChunkError(final Throwable e)
{
Loggables.withLogger(logger, Level.DEBUG).addLog("Error while cancelling current chunk. Ignored; exception={}", e);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\LoggableTrxItemExceptionHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final T100 other = (T100)obj;
if (contractValue == null)
{
if (other.contractValue != null)
{
return false;
}
}
else if (!contractValue.equals(other.contractValue))
{
return false;
}
if (messageNo == null)
{
if (other.messageNo != null)
{
return false;
}
}
else if (!messageNo.equals(other.messageNo))
{
return false;
}
if (partner == null)
{
if (other.partner != null)
{
return false;
}
}
else if (!partner.equals(other.partner))
{
return false; | }
if (record == null)
{
if (other.record != null)
{
return false;
}
}
else if (!record.equals(other.record))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "T100 [record=" + record + ", partner=" + partner + ", messageNo=" + messageNo + ", contractValue=" + contractValue + "]";
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\compudata\T100.java | 2 |
请完成以下Java代码 | public LocalDate calculateNextDateToInvoice(@NonNull final LocalDate deliveryDate)
{
final int offset = Integer.max(getInvoiceDistance() - 1, 0);
switch (getFrequency())
{
case DAILY:
return computeNextDailyInvoiceDate(deliveryDate, offset);
case WEEKLY:
return computeNextWeeklyInvoiceDate(deliveryDate, offset);
case TWICE_MONTHLY:
return computeNextTwiceMonthlyInvoiceDate(deliveryDate);
case MONTLY:
return computeNextMonthlyInvoiceDate(deliveryDate, offset);
default:
throw new AdempiereException(this + " has unsupported frequency '" + getFrequency() + "'");
}
}
private LocalDate computeNextDailyInvoiceDate(@NonNull final LocalDate deliveryDate, final int offset)
{
return deliveryDate.plus(offset, ChronoUnit.DAYS);
}
private LocalDate computeNextWeeklyInvoiceDate(@NonNull final LocalDate deliveryDate, final int offset)
{
final LocalDate dateToInvoice;
final LocalDate nextDateWithInvoiceWeekDay = deliveryDate.with(nextOrSame(getInvoiceDayOfWeek()));
if (!nextDateWithInvoiceWeekDay.isAfter(deliveryDate))
{
dateToInvoice = nextDateWithInvoiceWeekDay.plus(1 + offset, ChronoUnit.WEEKS);
}
else
{
dateToInvoice = nextDateWithInvoiceWeekDay.plus(offset, ChronoUnit.WEEKS);
}
return dateToInvoice;
}
private LocalDate computeNextTwiceMonthlyInvoiceDate(@NonNull final LocalDate deliveryDate)
{
final LocalDate dateToInvoice;
final LocalDate middleDayOfMonth = deliveryDate.withDayOfMonth(15);
// tasks 08484, 08869
if (deliveryDate.isAfter(middleDayOfMonth))
{
dateToInvoice = deliveryDate.with(lastDayOfMonth());
}
else
{ | dateToInvoice = middleDayOfMonth;
}
return dateToInvoice;
}
private LocalDate computeNextMonthlyInvoiceDate(
@NonNull final LocalDate deliveryDate,
final int offset)
{
final LocalDate dateToInvoice;
final int invoiceDayOfMonthToUse = Integer.min(deliveryDate.lengthOfMonth(), getInvoiceDayOfMonth());
final LocalDate deliveryDateWithDayOfMonth = deliveryDate.withDayOfMonth(invoiceDayOfMonthToUse);
if (!deliveryDateWithDayOfMonth.isAfter(deliveryDate))
{
dateToInvoice = deliveryDateWithDayOfMonth.plus(1 + offset, ChronoUnit.MONTHS);
}
else
{
dateToInvoice = deliveryDateWithDayOfMonth.plus(offset, ChronoUnit.MONTHS);
}
return dateToInvoice;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceSchedule.java | 1 |
请完成以下Java代码 | public <T> T convert(Object value, Class<T> type) {
return converter.convert(value, type);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Bindings) {
Bindings other = (Bindings) obj;
return (
Arrays.equals(functions, other.functions) &&
Arrays.equals(variables, other.variables) &&
converter.equals(other.converter)
);
}
return false;
}
@Override
public int hashCode() {
return (Arrays.hashCode(functions) ^ Arrays.hashCode(variables) ^ converter.hashCode());
}
private void writeObject(ObjectOutputStream out) throws IOException, ClassNotFoundException {
out.defaultWriteObject();
MethodWrapper[] wrappers = new MethodWrapper[functions.length];
for (int i = 0; i < wrappers.length; i++) {
wrappers[i] = new MethodWrapper(functions[i]);
}
out.writeObject(wrappers); | }
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
MethodWrapper[] wrappers = (MethodWrapper[]) in.readObject();
if (wrappers.length == 0) {
functions = NO_FUNCTIONS;
} else {
functions = new Method[wrappers.length];
for (int i = 0; i < functions.length; i++) {
functions[i] = wrappers[i].method;
}
}
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\Bindings.java | 1 |
请完成以下Java代码 | private BigDecimal parseNumber(@Nullable final String valueStr)
{
if (valueStr == null || valueStr.isEmpty())
{
return null;
}
try
{
final String numberStringNormalized = normalizeNumberString(valueStr);
BigDecimal bd = new BigDecimal(numberStringNormalized);
if (divideBy100)
{
// NOTE: assumed two decimal scale
bd = bd.divide(Env.ONEHUNDRED, 2, BigDecimal.ROUND_HALF_UP);
}
return bd;
}
catch (final NumberFormatException ex)
{
throw new AdempiereException("@Invalid@ @Number@: " + valueStr, ex);
}
}
private boolean parseYesNo(String valueStr)
{
return StringUtils.toBoolean(valueStr, false);
}
private String normalizeNumberString(String info)
{
if (Check.isEmpty(info, true))
{
return "0";
}
final boolean hasPoint = info.indexOf('.') != -1;
boolean hasComma = info.indexOf(',') != -1;
// delete thousands
if (hasComma && decimalSeparator.isDot())
{
info = info.replace(',', ' ');
}
if (hasPoint && decimalSeparator.isComma())
{
info = info.replace('.', ' ');
}
hasComma = info.indexOf(',') != -1;
// replace decimal | if (hasComma && decimalSeparator.isComma())
{
info = info.replace(',', '.');
}
// remove everything but digits & '.' & '-'
char[] charArray = info.toCharArray();
final StringBuilder sb = new StringBuilder();
for (char element : charArray)
{
if (Character.isDigit(element) || element == '.' || element == '-')
{
sb.append(element);
}
}
final String numberStringNormalized = sb.toString().trim();
if (numberStringNormalized.isEmpty())
{
return "0";
}
return numberStringNormalized;
}
} // ImpFormatFow | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\format\ImpFormatColumn.java | 1 |
请完成以下Java代码 | public class NativeProcessDefinitionQueryImpl
extends AbstractNativeQuery<NativeProcessDefinitionQuery, ProcessDefinition>
implements NativeProcessDefinitionQuery {
private static final long serialVersionUID = 1L;
public NativeProcessDefinitionQueryImpl(CommandContext commandContext) {
super(commandContext);
}
public NativeProcessDefinitionQueryImpl(CommandExecutor commandExecutor) {
super(commandExecutor);
}
// results //////////////////////////////////////////////////////////////// | public List<ProcessDefinition> executeList(
CommandContext commandContext,
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return commandContext
.getProcessDefinitionEntityManager()
.findProcessDefinitionsByNativeQuery(parameterMap, firstResult, maxResults);
}
public long executeCount(CommandContext commandContext, Map<String, Object> parameterMap) {
return commandContext.getProcessDefinitionEntityManager().findProcessDefinitionCountByNativeQuery(parameterMap);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\NativeProcessDefinitionQueryImpl.java | 1 |
请完成以下Java代码 | default XmlService withMod(@Nullable final ServiceMod serviceMod)
{
if (serviceMod == null)
{
return this;
}
return withModNonNull(serviceMod);
}
String getName();
XMLGregorianCalendar getDateBegin();
XmlService withModNonNull(ServiceMod serviceMod);
BigDecimal getAmount();
BigDecimal getExternalFactor();
@Value
public static class ServiceModWithSelector
{
/** recordId is the selector for the XmlService to which this mod shall be applied. */
Integer recordId;
ServiceMod serviceMod;
@Value
public static class ServiceMod
{
@NonNull
BigDecimal amount;
}
@Builder | public ServiceModWithSelector(
@NonNull final Integer recordId,
@Nullable final BigDecimal amount)
{
this.recordId = recordId;
if (amount != null)
{
this.serviceMod = new ServiceMod(amount);
}
else
{
this.serviceMod = null;
}
}
}
} | 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\XmlService.java | 1 |
请完成以下Java代码 | public final class AsyncUtils {
private static final Logger LOG = LoggerFactory.getLogger(AsyncUtils.class);
public static <R> CompletableFuture<R> newFailedFuture(Throwable ex) {
CompletableFuture<R> future = new CompletableFuture<>();
future.completeExceptionally(ex);
return future;
}
public static <R> CompletableFuture<List<R>> sequenceFuture(List<CompletableFuture<R>> futures) {
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.thenApply(v -> futures.stream()
.map(AsyncUtils::getValue)
.filter(Objects::nonNull)
.collect(Collectors.toList())
);
}
public static <R> CompletableFuture<List<R>> sequenceSuccessFuture(List<CompletableFuture<R>> futures) {
return CompletableFuture.supplyAsync(() -> futures.parallelStream()
.map(AsyncUtils::getValue)
.filter(Objects::nonNull) | .collect(Collectors.toList())
);
}
public static <T> T getValue(CompletableFuture<T> future) {
try {
return future.get(10, TimeUnit.SECONDS);
} catch (Exception ex) {
LOG.error("getValue for async result failed", ex);
}
return null;
}
public static boolean isSuccessFuture(CompletableFuture future) {
return future.isDone() && !future.isCompletedExceptionally() && !future.isCancelled();
}
private AsyncUtils() {}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\util\AsyncUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonLine
{
@JsonProperty("Number")
int number;
@JsonProperty("LineWeight")
Integer lineWeight;
@JsonProperty("PkgWeight")
Integer pkgWeight;
@JsonProperty("DimensionalWeight")
Integer dimensionalWeight;
@JsonProperty("Height")
Integer height;
@JsonProperty("Length")
Integer length;
@JsonProperty("Width")
Integer width;
@JsonProperty("LineVol")
Long lineVol;
@JsonProperty("PkgVol")
Long pkgVol;
@JsonProperty("Loadmeter")
Integer loadmeter;
@JsonProperty("GoodsType")
Integer goodsTypeID;
@JsonProperty("GoodsTypeName")
String goodsTypeName; | @JsonProperty("GoodsTypeKey1")
String goodsTypeKey1;
@JsonProperty("GoodsTypeKey2")
String goodsTypeKey2;
@JsonProperty("RecycleCount")
Integer recycleCount;
@JsonProperty("RecycleTypeID")
Integer recycleTypeID;
@JsonProperty("RecycleTypeName")
String recycleTypeName;
@JsonProperty("LineUnits")
List<JsonLineUnit> lineUnits;
@JsonProperty("Pkgs")
@Singular
List<JsonPackage> pkgs;
@JsonProperty("References")
@Singular
List<JsonReference> references;
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\json\JsonLine.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private String[] addDict(String dictName,String lowAppId, Integer tenantId) {
SysDict dict = new SysDict();
dict.setDictName(dictName);
dict.setDictCode(RandomUtil.randomString(10));
dict.setDelFlag(Integer.valueOf(CommonConstant.STATUS_0));
dict.setLowAppId(lowAppId);
dict.setTenantId(tenantId);
baseMapper.insert(dict);
String[] dictResult = new String[]{dict.getId(), dict.getDictCode()};
return dictResult;
}
/**
* 添加字典子项
* @param id
* @param dictItemList
*/
private void addDictItem(String id,List<SysDictItem> dictItemList) {
if(null!=dictItemList && dictItemList.size()>0){
for (SysDictItem dictItem:dictItemList) {
SysDictItem sysDictItem = new SysDictItem();
BeanUtils.copyProperties(dictItem,sysDictItem);
sysDictItem.setDictId(id);
sysDictItem.setId("");
sysDictItem.setStatus(Integer.valueOf(CommonConstant.STATUS_1));
sysDictItemMapper.insert(sysDictItem);
}
} | }
/**
* 更新字典子项
* @param id
* @param dictItemList
*/
private void updateDictItem(String id,List<SysDictItem> dictItemList){
//先删除在新增 因为排序可能不一致
LambdaQueryWrapper<SysDictItem> query = new LambdaQueryWrapper<>();
query.eq(SysDictItem::getDictId,id);
sysDictItemMapper.delete(query);
//新增子项
this.addDictItem(id,dictItemList);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysDictServiceImpl.java | 2 |
请完成以下Java代码 | public class TonePinyinString2PinyinConverter
{
/**
* 带音调的字母到Pinyin的map
*/
static Map<String, Pinyin> mapKey;
/**
* 带数字音调的字幕到Pinyin的map
*/
static Map<String, Pinyin> mapNumberKey;
static Trie trie;
static
{
mapNumberKey = new TreeMap<String, Pinyin>();
mapKey = new TreeMap<String, Pinyin>();
for (Pinyin pinyin : Integer2PinyinConverter.pinyins)
{
mapNumberKey.put(pinyin.toString(), pinyin);
String pinyinWithToneMark = pinyin.getPinyinWithToneMark();
String pinyinWithoutTone = pinyin.getPinyinWithoutTone();
Pinyin tone5 = String2PinyinConverter.convert2Tone5(pinyin);
mapKey.put(pinyinWithToneMark, pinyin);
mapKey.put(pinyinWithoutTone, tone5);
}
trie = new Trie().remainLongest();
trie.addAllKeyword(mapKey.keySet());
}
/**
* 这个拼音是否合格
* @param singlePinyin
* @return
*/
public static boolean valid(String singlePinyin)
{
if (mapNumberKey.containsKey(singlePinyin)) return true;
return false;
}
public static Pinyin convertFromToneNumber(String singlePinyin)
{
return mapNumberKey.get(singlePinyin);
}
public static List<Pinyin> convert(String[] pinyinArray)
{
List<Pinyin> pinyinList = new ArrayList<Pinyin>(pinyinArray.length);
for (int i = 0; i < pinyinArray.length; i++)
{
pinyinList.add(mapKey.get(pinyinArray[i]));
}
return pinyinList; | }
public static Pinyin convert(String singlePinyin)
{
return mapKey.get(singlePinyin);
}
/**
*
* @param tonePinyinText
* @return
*/
public static List<Pinyin> convert(String tonePinyinText, boolean removeNull)
{
List<Pinyin> pinyinList = new LinkedList<Pinyin>();
Collection<Token> tokenize = trie.tokenize(tonePinyinText);
for (Token token : tokenize)
{
Pinyin pinyin = mapKey.get(token.getFragment());
if (removeNull && pinyin == null) continue;
pinyinList.add(pinyin);
}
return pinyinList;
}
/**
* 这些拼音是否全部合格
* @param pinyinStringArray
* @return
*/
public static boolean valid(String[] pinyinStringArray)
{
for (String p : pinyinStringArray)
{
if (!valid(p)) return false;
}
return true;
}
public static List<Pinyin> convertFromToneNumber(String[] pinyinArray)
{
List<Pinyin> pinyinList = new ArrayList<Pinyin>(pinyinArray.length);
for (String py : pinyinArray)
{
pinyinList.add(convertFromToneNumber(py));
}
return pinyinList;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\py\TonePinyinString2PinyinConverter.java | 1 |
请完成以下Java代码 | public void validateCandidatesOnDunningGraceChange(final I_C_Invoice invoice)
{
final Timestamp dunningGraceDate = invoice.getDunningGrace();
logger.debug("DunningGraceDate: {}", dunningGraceDate);
final IDunningDAO dunningDAO = Services.get(IDunningDAO.class);
final IDunningBL dunningBL = Services.get(IDunningBL.class);
final Properties ctx = InterfaceWrapperHelper.getCtx(invoice);
final String trxName = InterfaceWrapperHelper.getTrxName(invoice);
final IDunningContext context = dunningBL.createDunningContext(ctx,
null, // dunningLevel
null, // dunningDate
trxName);
final I_C_Dunning_Candidate callerCandidate = InterfaceWrapperHelper.getDynAttribute(invoice, C_Dunning_Candidate.POATTR_CallerPO);
//
// Gets dunning candidates for specific invoice, to check if they are still viable.
final List<I_C_Dunning_Candidate> candidates = dunningDAO.retrieveDunningCandidates(
context,
getTableId(I_C_Invoice.class),
invoice.getC_Invoice_ID());
for (final I_C_Dunning_Candidate candidate : candidates)
{
if (callerCandidate != null && callerCandidate.getC_Dunning_Candidate_ID() == candidate.getC_Dunning_Candidate_ID())
{
// skip the caller candidate to avoid cycles
continue;
}
if (candidate.isProcessed())
{
logger.debug("Skip processed candidate: {}", candidate); | continue;
}
if (dunningBL.isExpired(candidate, dunningGraceDate))
{
logger.debug("Deleting expired candidate: {}", candidate);
InterfaceWrapperHelper.delete(candidate);
}
else
{
logger.debug("Updating DunningGrace for candidate: {}", candidate);
candidate.setDunningGrace(invoice.getDunningGrace());
InterfaceWrapperHelper.save(candidate);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\invoice\model\validator\C_Invoice.java | 1 |
请完成以下Java代码 | public class Movie {
private String name;
private String director;
private float rating;
public Movie(String name, String director, float rating) {
this.name = name;
this.director = director;
this.rating = rating;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name; | }
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
} | repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\customiterators\Movie.java | 1 |
请完成以下Java代码 | public @NonNull String getSourceTableName()
{
return I_C_OLCand.Table_Name;
}
@Override
public List<String> getSourceColumnNames()
{
return SOURCE_COLUMN_NAMES;
}
/**
* Obtains the given olCand's pricing result and resets the olCand's ASI with the list of {@link IPricingResult#getPricingAttributes()}.
* <p>
* About corner cases:
* <ul>
* <li>if there is no dynamic-attribute pricing result (of if the price was not calculated!), it does nothing. Rationale: this implementation's job is to sync/reset the result of a successful
* price calculation with the olCand's ASI. If there is no such pricing result, we assume that this method's service is not wanted.
* <li>if the pricing result has no pricing attributes, then the olCand gets an "empty" ASI with no attribute instances
* <li>if the olCand has already an ASI, then that ASI is discarded and ignored.
* <li>We do <b>not</b> care if the attribute set of the olCand's product matches the attribute values of the pricing result. Rationale: we assume that the pricing result was created for this
* olCand and its quantity, PIIP, date etc. and in particular also for its product.
* </ul>
*
* @see DefaultOLCandValidator#getPreviouslyCalculatedPricingResultOrNull(I_C_OLCand)
*/
@Override
public void modelChanged(final Object model)
{
final I_C_OLCand olCand = InterfaceWrapperHelper.create(model, I_C_OLCand.class);
final IPricingResult pricingResult = DefaultOLCandValidator.getPreviouslyCalculatedPricingResultOrNull(olCand);
if (pricingResult == null || !pricingResult.isCalculated())
{
return; // nothing to do
} | final IAttributeSetInstanceAware asiAware = attributeSetInstanceAwareFactoryService.createOrNull(olCand);
Check.assumeNotNull(asiAware,
"We have an asiAware for C_OLCand {}, because we implemented and registered the factory {}",
olCand, OLCandASIAwareFactory.class.getName());
asiAware.setM_AttributeSetInstance(null); // reset, because we want getCreateASI to give us a new ASI
final List<IPricingAttribute> pricingAttributes = pricingResult.getPricingAttributes();
if (!pricingAttributes.isEmpty())
{
attributeSetInstanceBL.getCreateASI(asiAware);
attributePricingBL.addToASI(asiAware, pricingAttributes);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\spi\impl\OLCandPricingASIListener.java | 1 |
请完成以下Java代码 | public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) {
System.out.println("Sending Email...");
try {
//sendEmail();
sendEmailWithAttachment();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
void sendEmail() {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setTo("1@gmail.com", "2@yahoo.com");
msg.setSubject("Testing from Spring Boot");
msg.setText("Hello World \n Spring Boot Email");
javaMailSender.send(msg);
} | void sendEmailWithAttachment() throws MessagingException, IOException {
MimeMessage msg = javaMailSender.createMimeMessage();
// true = multipart message
MimeMessageHelper helper = new MimeMessageHelper(msg, true);
helper.setTo("1@gmail.com");
helper.setSubject("Testing from Spring Boot");
// default = text/plain
//helper.setText("Check attachment for image!");
// true = text/html
helper.setText("<h1>Check attachment for image!</h1>", true);
//FileSystemResource file = new FileSystemResource(new File("classpath:android.png"));
//Resource resource = new ClassPathResource("android.png");
//InputStream input = resource.getInputStream();
//ResourceUtils.getFile("classpath:android.png");
helper.addAttachment("my_photo.png", new ClassPathResource("android.png"));
javaMailSender.send(msg);
}
} | repos\spring-boot-master\email\src\main\java\com\mkyong\Application.java | 1 |
请完成以下Java代码 | protected boolean isEndpointTypeExposed(Class<?> beanType) {
MergedAnnotations annotations = MergedAnnotations.from(beanType, SearchStrategy.SUPERCLASS);
return annotations.isPresent(ControllerEndpoint.class) || annotations.isPresent(RestControllerEndpoint.class);
}
@Override
protected ExposableControllerEndpoint createEndpoint(Object endpointBean, EndpointId id, Access defaultAccess,
Collection<Operation> operations) {
String rootPath = PathMapper.getRootPath(this.endpointPathMappers, id);
return new DiscoveredControllerEndpoint(this, endpointBean, id, rootPath, defaultAccess);
}
@Override
protected Operation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod,
OperationInvoker invoker) {
throw new IllegalStateException("ControllerEndpoints must not declare operations");
}
@Override
protected OperationKey createOperationKey(Operation operation) {
throw new IllegalStateException("ControllerEndpoints must not declare operations");
} | @Override
protected boolean isInvocable(ExposableControllerEndpoint endpoint) {
return true;
}
static class ControllerEndpointDiscovererRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.reflection()
.registerType(ControllerEndpointFilter.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\annotation\ControllerEndpointDiscoverer.java | 1 |
请完成以下Java代码 | public class CustomsInvoiceUserNotificationsProducer
{
public static final CustomsInvoiceUserNotificationsProducer newInstance()
{
return new CustomsInvoiceUserNotificationsProducer();
}
/** Topic used to send notifications about shipments/receipts that were generated/reversed asynchronously */
public static final Topic EVENTBUS_TOPIC = Topic.builder()
.name("de.metas.customs.UserNotifications")
.type(Type.DISTRIBUTED)
.build();
private static final AdWindowId WINDOW_CUSTOMS_INVOICE = AdWindowId.ofRepoId(540643); // FIXME: HARDCODED
private static final AdMessageKey MSG_Event_CustomsInvoiceGenerated = AdMessageKey.of("Event_CustomsInvoiceGenerated");
private CustomsInvoiceUserNotificationsProducer()
{
}
public CustomsInvoiceUserNotificationsProducer notifyGenerated(final Collection<CustomsInvoice> customInvoices)
{
if (customInvoices == null || customInvoices.isEmpty())
{
return this;
}
postNotifications(customInvoices.stream()
.map(this::createUserNotification)
.collect(ImmutableList.toImmutableList()));
return this;
}
public final CustomsInvoiceUserNotificationsProducer notifyGenerated(@NonNull final CustomsInvoice customsInvoice)
{
notifyGenerated(ImmutableList.of(customsInvoice));
return this;
}
private final UserNotificationRequest createUserNotification(@NonNull final CustomsInvoice customsInvoice)
{
final TableRecordReference customsInvoiceRef = toTableRecordRef(customsInvoice);
return newUserNotificationRequest()
.recipientUserId(getNotificationRecipientUserId(customsInvoice))
.contentADMessage(MSG_Event_CustomsInvoiceGenerated)
.contentADMessageParam(customsInvoiceRef) | .targetAction(TargetRecordAction.ofRecordAndWindow(customsInvoiceRef, WINDOW_CUSTOMS_INVOICE))
.build();
}
private static TableRecordReference toTableRecordRef(final CustomsInvoice customsInvoice)
{
return TableRecordReference.of(I_C_Customs_Invoice.Table_Name, customsInvoice.getId());
}
private final UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest()
{
return UserNotificationRequest.builder()
.topic(EVENTBUS_TOPIC);
}
private final UserId getNotificationRecipientUserId(final CustomsInvoice customsInvoice)
{
//
// In case of reversal i think we shall notify the current user too
if (customsInvoice.getDocStatus().isReversedOrVoided())
{
return customsInvoice.getLastUpdatedBy();
}
//
// Fallback: notify only the creator
else
{
return customsInvoice.getCreatedBy();
}
}
private void postNotifications(final List<UserNotificationRequest> notifications)
{
Services.get(INotificationBL.class).sendAfterCommit(notifications);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\customs\event\CustomsInvoiceUserNotificationsProducer.java | 1 |
请完成以下Java代码 | public @Nullable Object getProperty(String name) {
if (StringUtils.hasLength(name)) {
for (Mapping mapping : MAPPINGS) {
String prefix = mapping.getPrefix();
if (name.startsWith(prefix)) {
String postfix = name.substring(prefix.length());
AnsiElement element = mapping.getElement(postfix);
if (element != null) {
return (this.encode) ? AnsiOutput.encode(element) : element;
}
}
}
}
return null;
}
/**
* Mapping between a name and the pseudo property source.
*/
private abstract static class Mapping {
private final String prefix;
Mapping(String prefix) {
this.prefix = prefix;
}
String getPrefix() {
return this.prefix;
}
abstract @Nullable AnsiElement getElement(String postfix);
}
/**
* {@link Mapping} for {@link AnsiElement} enums.
*/
private static class EnumMapping<E extends Enum<E> & AnsiElement> extends Mapping {
private final Set<E> enums;
EnumMapping(String prefix, Class<E> enumType) {
super(prefix);
this.enums = EnumSet.allOf(enumType);
}
@Override
@Nullable AnsiElement getElement(String postfix) { | for (Enum<?> candidate : this.enums) {
if (candidate.name().equals(postfix)) {
return (AnsiElement) candidate;
}
}
return null;
}
}
/**
* {@link Mapping} for {@link Ansi8BitColor}.
*/
private static class Ansi8BitColorMapping extends Mapping {
private final IntFunction<Ansi8BitColor> factory;
Ansi8BitColorMapping(String prefix, IntFunction<Ansi8BitColor> factory) {
super(prefix);
this.factory = factory;
}
@Override
@Nullable AnsiElement getElement(String postfix) {
if (containsOnlyDigits(postfix)) {
try {
return this.factory.apply(Integer.parseInt(postfix));
}
catch (IllegalArgumentException ex) {
// Ignore
}
}
return null;
}
private boolean containsOnlyDigits(String postfix) {
for (int i = 0; i < postfix.length(); i++) {
if (!Character.isDigit(postfix.charAt(i))) {
return false;
}
}
return !postfix.isEmpty();
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ansi\AnsiPropertySource.java | 1 |
请完成以下Java代码 | public class StoreInitializer {
public StoreInitializer(StoreRepository repository, MongoOperations operations) throws Exception {
if (repository.count() != 0) {
return;
}
var indexDefinitions = IndexResolver.create(operations.getConverter().getMappingContext())
.resolveIndexFor(Store.class);
indexDefinitions.forEach(operations.indexOps(Store.class)::createIndex);
var stores = readStores();
log.info("Importing {} stores into MongoDB…", stores.size());
repository.saveAll(stores);
log.info("Successfully imported {} stores.", repository.count());
}
/**
* Reads a file {@code starbucks.csv} from the class path and parses it into {@link Store} instances about to be
* persisted.
*
* @return
* @throws Exception
*/
private static List<Store> readStores() throws Exception {
var resource = new ClassPathResource("starbucks.csv");
var scanner = new Scanner(resource.getInputStream());
var line = scanner.nextLine();
scanner.close();
// DelimitedLineTokenizer defaults to comma as its delimiter
var tokenizer = new DelimitedLineTokenizer();
tokenizer.setNames(line.split(","));
tokenizer.setStrict(false);
var lineMapper = new DefaultLineMapper<Store>(); | lineMapper.setFieldSetMapper(fields -> {
var location = new Point(fields.readDouble("Longitude"), fields.readDouble("Latitude"));
var address = new Address(fields.readString("Street Address"), fields.readString("City"),
fields.readString("Zip"), location);
return new Store(UUID.randomUUID(), fields.readString("Name"), address);
});
var itemReader = new FlatFileItemReader<>(lineMapper);
itemReader.setResource(resource);
lineMapper.setLineTokenizer(tokenizer);
itemReader.setLineMapper(lineMapper);
itemReader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy());
itemReader.setLinesToSkip(1);
itemReader.open(new ExecutionContext());
List<Store> stores = new ArrayList<>();
Store store = null;
do {
store = itemReader.read();
if (store != null) {
stores.add(store);
}
} while (store != null);
return stores;
}
} | repos\spring-data-examples-main\rest\starbucks\src\main\java\example\springdata\rest\stores\StoreInitializer.java | 1 |
请完成以下Java代码 | public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Letzter Wareneingang.
@param LastReceiptDate Letzter Wareneingang */
@Override
public void setLastReceiptDate (java.sql.Timestamp LastReceiptDate)
{
set_ValueNoCheck (COLUMNNAME_LastReceiptDate, LastReceiptDate);
}
/** Get Letzter Wareneingang.
@return Letzter Wareneingang */
@Override
public java.sql.Timestamp getLastReceiptDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_LastReceiptDate);
}
/** Set Letzte Lieferung.
@param LastShipDate Letzte Lieferung */
@Override
public void setLastShipDate (java.sql.Timestamp LastShipDate)
{
set_ValueNoCheck (COLUMNNAME_LastShipDate, LastShipDate);
}
/** Get Letzte Lieferung.
@return Letzte Lieferung */
@Override
public java.sql.Timestamp getLastShipDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_LastShipDate); | }
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
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_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (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();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product_Stats_InOut_Online_v.java | 1 |
请完成以下Java代码 | public final int getResultSetConcurrency() throws SQLException
{
return delegate.getResultSetConcurrency();
}
@Override
public final int getResultSetType() throws SQLException
{
return delegate.getResultSetType();
}
@Override
public final void addBatch(final String sql) throws SQLException
{
delegate.addBatch(sql);
}
@Override
public final void clearBatch() throws SQLException
{
delegate.clearBatch();
}
@Override
public final int[] executeBatch() throws SQLException
{
return trace(delegate::executeBatch);
}
@Override
public final Connection getConnection() throws SQLException
{
return delegate.getConnection();
}
@Override
public final boolean getMoreResults(final int current) throws SQLException
{
return delegate.getMoreResults(current);
}
@Override
public final ResultSet getGeneratedKeys() throws SQLException
{
return delegate.getGeneratedKeys();
}
@Override
public final int executeUpdate(final String sql, final int autoGeneratedKeys) throws SQLException
{
return trace(sql, () -> delegate.executeUpdate(sql, autoGeneratedKeys));
}
@Override
public final int executeUpdate(final String sql, final int[] columnIndexes) throws SQLException
{
return trace(sql, () -> delegate.executeUpdate(sql, columnIndexes));
}
@Override
public final int executeUpdate(final String sql, final String[] columnNames) throws SQLException
{
return trace(sql, () -> delegate.executeUpdate(sql, columnNames));
} | @Override
public final boolean execute(final String sql, final int autoGeneratedKeys) throws SQLException
{
return trace(sql, () -> delegate.execute(sql, autoGeneratedKeys));
}
@Override
public final boolean execute(final String sql, final int[] columnIndexes) throws SQLException
{
return trace(sql, () -> delegate.execute(sql, columnIndexes));
}
@Override
public final boolean execute(final String sql, final String[] columnNames) throws SQLException
{
return trace(sql, () -> delegate.execute(sql, columnNames));
}
@Override
public final int getResultSetHoldability() throws SQLException
{
return delegate.getResultSetHoldability();
}
@Override
public final boolean isClosed() throws SQLException
{
return delegate.isClosed();
}
@Override
public final void setPoolable(final boolean poolable) throws SQLException
{
delegate.setPoolable(poolable);
}
@Override
public final boolean isPoolable() throws SQLException
{
return delegate.isPoolable();
}
@Override
public final void closeOnCompletion() throws SQLException
{
delegate.closeOnCompletion();
}
@Override
public final boolean isCloseOnCompletion() throws SQLException
{
return delegate.isCloseOnCompletion();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\sql\impl\TracingStatement.java | 1 |
请完成以下Java代码 | public class ProcessInstanceMigrationStatusJobHandler extends AbstractProcessInstanceMigrationJobHandler {
public static final String TYPE = "process-migration-status";
@Override
public String getType() {
return TYPE;
}
@Override
public void execute(JobEntity job, String configuration, VariableScope variableScope, CommandContext commandContext) {
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
BatchService batchService = processEngineConfiguration.getBatchServiceConfiguration().getBatchService();
String batchId = getBatchIdFromHandlerCfg(configuration);
Batch batch = batchService.getBatch(batchId);
List<BatchPart> batchParts = batchService.findBatchPartsByBatchId(batchId);
int completedBatchParts = 0;
int failedBatchParts = 0;
for (BatchPart batchPart : batchParts) {
if (batchPart.getCompleteTime() != null) {
completedBatchParts++;
if (ProcessInstanceBatchMigrationResult.RESULT_FAIL.equals(batchPart.getStatus())) {
failedBatchParts++;
}
}
} | if (completedBatchParts == batchParts.size()) {
batchService.completeBatch(batch.getId(), ProcessInstanceBatchMigrationResult.STATUS_COMPLETED);
job.setRepeat(null);
} else {
if (batchParts.size() == 0) {
updateBatchStatus(batch, "No batch parts", batchService);
job.setRepeat(null);
} else {
int completedPercentage = completedBatchParts / batchParts.size() * 100;
updateBatchStatus(batch, completedPercentage + "% completed, " + failedBatchParts + " failed", batchService);
}
}
}
protected void updateBatchStatus(Batch batch, String status, BatchService batchService) {
((BatchEntity) batch).setStatus(ProcessInstanceBatchMigrationResult.STATUS_COMPLETED);
batchService.updateBatch(batch);
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\jobexecutor\ProcessInstanceMigrationStatusJobHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void saveFile(Path filePath, InputStream inputStream) throws IOException {
LOG.info("saveFile: {}", filePath);
Path resolvedFilePath = this.fileStorageLocation.resolve(filePath).normalize();
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
File targetFile = resolvedFilePath.toFile();
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
}
@Override
public void delete(Path filePath) throws IOException {
LOG.info("delete: {}", filePath);
Path resolvedFilePath = this.fileStorageLocation.resolve(filePath).normalize();
LOG.info("deleting: {}", resolvedFilePath.toString()); | if (Files.isDirectory(resolvedFilePath)) {
FileSystemUtils.deleteRecursively(resolvedFilePath);
} else {
Files.delete(resolvedFilePath);
}
}
@Override
public void createDirectory(Path filePath) throws IOException {
LOG.info("createDirectory: {}", filePath);
Path resolvedFilePath = this.fileStorageLocation.resolve(filePath).normalize();
Files.createDirectories(resolvedFilePath);
}
} | repos\spring-examples-java-17\spring-fileserver\src\main\java\itx\examples\springboot\fileserver\services\FileServiceImpl.java | 2 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<Book> getBooks() { | return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
@PreRemove
private void authorRemove() {
deleted = true;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", name=" + name
+ ", genre=" + genre + ", age=" + age + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootSoftDeletes\src\main\java\com\bookstore\entity\Author.java | 1 |
请完成以下Java代码 | public final class ClassReference<T>
{
public static final <T> ClassReference<T> of(@NonNull final Class<T> clazz)
{
return new ClassReference<>(clazz);
}
public static final <T> ClassReference<T> ofClassname(@NonNull final String classname)
{
try
{
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
@SuppressWarnings("unchecked")
final Class<T> clazz = (Class<T>)classLoader.loadClass(classname);
return new ClassReference<>(clazz);
}
catch (final Exception ex)
{
throw new IllegalArgumentException("Cannot load " + classname, ex);
}
}
private final String classname;
private final transient AtomicReference<WeakReference<Class<T>>> clazzRef;
private ClassReference(@NonNull final Class<T> clazz)
{
this.classname = clazz.getName();
this.clazzRef = new AtomicReference<>(new WeakReference<>(clazz));
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(classname)
.toString();
}
public Class<T> getReferencedClass()
{
// Get if not expired
{ | final WeakReference<Class<T>> weakRef = clazzRef.get();
final Class<T> clazz = weakRef != null ? weakRef.get() : null;
if (clazz != null)
{
return clazz;
}
}
// Load the class
try
{
@SuppressWarnings("unchecked")
final Class<T> clazzNew = (Class<T>)Thread.currentThread().getContextClassLoader().loadClass(classname);
clazzRef.set(new WeakReference<>(clazzNew));
return clazzNew;
}
catch (final ClassNotFoundException ex)
{
throw new IllegalStateException("Cannot load expired class: " + classname, ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\reflect\ClassReference.java | 1 |
请完成以下Java代码 | public final void setDelegates(ProducerListener<K, V>... delegates) {
Assert.notNull(delegates, "'delegates' cannot be null");
Assert.noNullElements(delegates, "'delegates' cannot contain null elements");
this.delegates.clear();
this.delegates.addAll(Arrays.asList(delegates));
}
protected List<ProducerListener<K, V>> getDelegates() {
return this.delegates;
}
public void addDelegate(ProducerListener<K, V> delegate) {
this.delegates.add(delegate);
} | public boolean removeDelegate(ProducerListener<K, V> delegate) {
return this.delegates.remove(delegate);
}
@Override
public void onSuccess(ProducerRecord<K, V> producerRecord, RecordMetadata recordMetadata) {
this.delegates.forEach(d -> d.onSuccess(producerRecord, recordMetadata));
}
@Override
public void onError(ProducerRecord<K, V> producerRecord, @Nullable RecordMetadata recordMetadata, Exception exception) {
this.delegates.forEach(d -> d.onError(producerRecord, recordMetadata, exception));
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\CompositeProducerListener.java | 1 |
请完成以下Java代码 | public int getAD_Role_Included_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_Included_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Role getIncluded_Role() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Included_Role_ID, org.compiere.model.I_AD_Role.class);
}
@Override
public void setIncluded_Role(org.compiere.model.I_AD_Role Included_Role)
{
set_ValueFromPO(COLUMNNAME_Included_Role_ID, org.compiere.model.I_AD_Role.class, Included_Role);
}
/** Set Included Role.
@param Included_Role_ID Included Role */
@Override
public void setIncluded_Role_ID (int Included_Role_ID)
{
if (Included_Role_ID < 1)
set_ValueNoCheck (COLUMNNAME_Included_Role_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Included_Role_ID, Integer.valueOf(Included_Role_ID));
}
/** Get Included Role. | @return Included Role */
@Override
public int getIncluded_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Included_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
@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_Role_Included.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_M_Package getM_Package() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class);
}
@Override
public void setM_Package(org.compiere.model.I_M_Package M_Package)
{
set_ValueFromPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class, M_Package);
}
/** Set Packstück.
@param M_Package_ID
Shipment Package
*/
@Override
public void setM_Package_ID (int M_Package_ID)
{
if (M_Package_ID < 1)
set_Value (COLUMNNAME_M_Package_ID, null); | else
set_Value (COLUMNNAME_M_Package_ID, Integer.valueOf(M_Package_ID));
}
/** Get Packstück.
@return Shipment Package
*/
@Override
public int getM_Package_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Package_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_DeliveryOrderLine_Package.java | 1 |
请完成以下Java代码 | public int getParameterAsInt()
{
return getParameterAsInt(0);
}
public int getParameterAsInt(final int defaultValueWhenNull)
{
return toInt(m_Parameter, defaultValueWhenNull);
}
public <T extends RepoIdAware> T getParameterAsRepoId(@NonNull final Function<Integer, T> mapper)
{
return mapper.apply(getParameterAsInt(-1));
}
@Nullable
public <T extends RepoIdAware> T getParameterAsRepoId(@NonNull final Class<T> type)
{
return RepoIdAwares.ofRepoIdOrNull(getParameterAsInt(-1), type);
}
public int getParameter_ToAsInt()
{
return getParameter_ToAsInt(0);
}
public int getParameter_ToAsInt(final int defaultValueWhenNull)
{
return toInt(m_Parameter_To, defaultValueWhenNull);
}
private static int toInt(@Nullable final Object value, final int defaultValueWhenNull)
{
if (value == null)
{
return defaultValueWhenNull;
}
else if (value instanceof Number)
{
return ((Number)value).intValue();
}
else if (value instanceof RepoIdAware)
{
return ((RepoIdAware)value).getRepoId();
}
else
{
final BigDecimal bd = new BigDecimal(value.toString());
return bd.intValue();
}
}
public boolean getParameterAsBoolean()
{
return StringUtils.toBoolean(m_Parameter);
}
@Nullable
public Boolean getParameterAsBooleanOrNull()
{
return StringUtils.toBoolean(m_Parameter, null);
}
@Nullable
public Boolean getParameterAsBoolean(@Nullable Boolean defaultValue)
{
return StringUtils.toBoolean(m_Parameter, defaultValue);
}
public boolean getParameter_ToAsBoolean()
{
return StringUtils.toBoolean(m_Parameter_To);
}
@Nullable
public Timestamp getParameterAsTimestamp()
{
return TimeUtil.asTimestamp(m_Parameter); | }
@Nullable
public Timestamp getParameter_ToAsTimestamp()
{
return TimeUtil.asTimestamp(m_Parameter_To);
}
@Nullable
public LocalDate getParameterAsLocalDate()
{
return TimeUtil.asLocalDate(m_Parameter);
}
@Nullable
public LocalDate getParameter_ToAsLocalDate()
{
return TimeUtil.asLocalDate(m_Parameter_To);
}
@Nullable
public ZonedDateTime getParameterAsZonedDateTime()
{
return TimeUtil.asZonedDateTime(m_Parameter);
}
@Nullable
public Instant getParameterAsInstant()
{
return TimeUtil.asInstant(m_Parameter);
}
@Nullable
public ZonedDateTime getParameter_ToAsZonedDateTime()
{
return TimeUtil.asZonedDateTime(m_Parameter_To);
}
@Nullable
public BigDecimal getParameterAsBigDecimal()
{
return toBigDecimal(m_Parameter);
}
@Nullable
public BigDecimal getParameter_ToAsBigDecimal()
{
return toBigDecimal(m_Parameter_To);
}
@Nullable
private static BigDecimal toBigDecimal(@Nullable final Object value)
{
if (value == null)
{
return null;
}
else if (value instanceof BigDecimal)
{
return (BigDecimal)value;
}
else if (value instanceof Integer)
{
return BigDecimal.valueOf((Integer)value);
}
else
{
return new BigDecimal(value.toString());
}
}
} // ProcessInfoParameter | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessInfoParameter.java | 1 |
请完成以下Java代码 | private Set<ResourceId> retrieveCountingPlants()
{
return resourceService.getActivePlantIds();
}
private void addCockpitRowsToResult(
@NonNull final DimensionSpec dimensionSpec,
@NonNull final Map<MainRowBucketId, MainRowWithSubRows> result)
{
for (final I_MD_Cockpit cockpitRecord : request.getCockpitRecords())
{
final MainRowBucketId mainRowBucketId = MainRowBucketId.createInstanceForCockpitRecord(cockpitRecord);
final MainRowWithSubRows mainRowBucket = result.computeIfAbsent(mainRowBucketId, this::newMainRowWithSubRows);
mainRowBucket.addCockpitRecord(cockpitRecord, dimensionSpec, request.getDetailsRowAggregation());
}
}
private void addStockRowsToResult(
@NonNull final DimensionSpec dimensionSpec,
@NonNull final Map<MainRowBucketId, MainRowWithSubRows> result)
{
for (final I_MD_Stock stockRecord : request.getStockRecords())
{
final MainRowBucketId mainRowBucketId = MainRowBucketId.createInstanceForStockRecord(stockRecord, request.getDate());
final MainRowWithSubRows mainRowBucket = result.computeIfAbsent(mainRowBucketId, this::newMainRowWithSubRows);
mainRowBucket.addStockRecord(stockRecord, dimensionSpec, request.getDetailsRowAggregation());
}
}
private void addQuantitiesRowsToResult(
@NonNull final DimensionSpec dimensionSpec,
@NonNull final Map<MainRowBucketId, MainRowWithSubRows> result)
{
for (final ProductWithDemandSupply qtyRecord : request.getQuantitiesRecords())
{
final MainRowBucketId mainRowBucketId = MainRowBucketId.createInstanceForQuantitiesRecord(qtyRecord, request.getDate());
final MainRowWithSubRows mainRowBucket = result.computeIfAbsent(mainRowBucketId, this::newMainRowWithSubRows);
mainRowBucket.addQuantitiesRecord(qtyRecord, dimensionSpec, request.getDetailsRowAggregation());
}
} | private MainRowWithSubRows newMainRowWithSubRows(@NonNull final MainRowBucketId mainRowBucketId)
{
final Money maxPurchasePrice = purchaseLastMaxPriceProvider.getPrice(
PurchaseLastMaxPriceRequest.builder()
.productId(mainRowBucketId.getProductId())
.evalDate(mainRowBucketId.getDate())
.build())
.getMaxPurchasePrice();
final MFColor procurementStatusColor = getProcurementStatusColor(mainRowBucketId.getProductId()).orElse(null);
return MainRowWithSubRows.builder()
.cache(cache)
.rowLookups(rowLookups)
.productIdAndDate(mainRowBucketId)
.procurementStatusColor(procurementStatusColor)
.maxPurchasePrice(maxPurchasePrice)
.build();
}
private Optional<MFColor> getProcurementStatusColor(@NonNull final ProductId productId)
{
return adReferenceService.getRefListById(PROCUREMENTSTATUS_Reference_ID)
.getItemByValue(cache.getProductById(productId).getProcurementStatus())
.map(ADRefListItem::getColorId)
.map(colorRepository::getColorById);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\rowfactory\MaterialCockpitRowFactory.java | 1 |
请完成以下Java代码 | public void setQtyReserved (BigDecimal QtyReserved)
{
set_Value (COLUMNNAME_QtyReserved, QtyReserved);
}
/** Get Reserved Quantity.
@return Reserved Quantity
*/
public BigDecimal getQtyReserved ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReserved);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Quantity to Order.
@param QtyToOrder Quantity to Order */
public void setQtyToOrder (BigDecimal QtyToOrder)
{
set_Value (COLUMNNAME_QtyToOrder, QtyToOrder);
}
/** Get Quantity to Order.
@return Quantity to Order */
public BigDecimal getQtyToOrder ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToOrder);
if (bd == null)
return Env.ZERO;
return bd;
}
/** ReplenishmentCreate AD_Reference_ID=329 */
public static final int REPLENISHMENTCREATE_AD_Reference_ID=329;
/** Purchase Order = POO */
public static final String REPLENISHMENTCREATE_PurchaseOrder = "POO";
/** Requisition = POR */
public static final String REPLENISHMENTCREATE_Requisition = "POR";
/** Inventory Move = MMM */
public static final String REPLENISHMENTCREATE_InventoryMove = "MMM";
/** Distribution Order = DOO */
public static final String REPLENISHMENTCREATE_DistributionOrder = "DOO";
/** Set Create.
@param ReplenishmentCreate
Create from Replenishment
*/
public void setReplenishmentCreate (String ReplenishmentCreate)
{
set_Value (COLUMNNAME_ReplenishmentCreate, ReplenishmentCreate);
} | /** Get Create.
@return Create from Replenishment
*/
public String getReplenishmentCreate ()
{
return (String)get_Value(COLUMNNAME_ReplenishmentCreate);
}
/** ReplenishType AD_Reference_ID=164 */
public static final int REPLENISHTYPE_AD_Reference_ID=164;
/** Maintain Maximum Level = 2 */
public static final String REPLENISHTYPE_MaintainMaximumLevel = "2";
/** Manual = 0 */
public static final String REPLENISHTYPE_Manual = "0";
/** Reorder below Minimum Level = 1 */
public static final String REPLENISHTYPE_ReorderBelowMinimumLevel = "1";
/** Custom = 9 */
public static final String REPLENISHTYPE_Custom = "9";
/** Set Replenish Type.
@param ReplenishType
Method for re-ordering a product
*/
public void setReplenishType (String ReplenishType)
{
set_Value (COLUMNNAME_ReplenishType, ReplenishType);
}
/** Get Replenish Type.
@return Method for re-ordering a product
*/
public String getReplenishType ()
{
return (String)get_Value(COLUMNNAME_ReplenishType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_Replenish.java | 1 |
请完成以下Java代码 | public class EntityLoadError implements Serializable {
private static final long serialVersionUID = 7538450180582109391L;
private String type;
private EntityId source;
private EntityId target;
private String message;
public static EntityLoadError credentialsError(EntityId sourceId) {
return EntityLoadError.builder().type("DEVICE_CREDENTIALS_CONFLICT").source(sourceId).build();
}
public static EntityLoadError referenceEntityError(EntityId sourceId, EntityId targetId) {
return EntityLoadError.builder().type("MISSING_REFERENCED_ENTITY").source(sourceId).target(targetId).build(); | }
public static EntityLoadError runtimeError(Throwable e) {
return runtimeError(e, null);
}
public static EntityLoadError runtimeError(Throwable e, EntityId externalId) {
String message = e.getMessage();
if (StringUtils.isEmpty(message)) {
message = "unexpected error (" + ClassUtils.getShortClassName(e.getClass()) + ")";
}
return EntityLoadError.builder().type("RUNTIME").message(message).source(externalId).build();
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\sync\vc\EntityLoadError.java | 1 |
请完成以下Java代码 | public class BeanExamples {
public static List<CsvBean> beanBuilderExample(Path path, Class<? extends CsvBean> clazz) throws Exception {
CsvTransfer csvTransfer = new CsvTransfer();
try (Reader reader = Files.newBufferedReader(path)) {
CsvToBean<CsvBean> cb = new CsvToBeanBuilder<CsvBean>(reader)
.withType(clazz)
.build();
csvTransfer.setCsvList(cb.parse());
}
return csvTransfer.getCsvList();
}
public static String writeCsvFromBean(Path path) throws Exception {
List<CsvBean> sampleData = Arrays.asList( | new WriteExampleBean("Test1", "sample", "data"),
new WriteExampleBean("Test2", "ipso", "facto")
);
try (Writer writer = new FileWriter(path.toString())) {
StatefulBeanToCsv<CsvBean> sbc = new StatefulBeanToCsvBuilder<CsvBean>(writer)
.withQuotechar('\'')
.build();
sbc.write(sampleData);
}
return Helpers.readFile(path);
}
} | repos\tutorials-master\libraries-data-io\src\main\java\com\baeldung\libraries\opencsv\examples\sync\BeanExamples.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DatabaseConfig {
private static final Logger LOG = LoggerFactory.getLogger(DatabaseConfig.class);
private Connection connection;
public DatabaseConfig() {
try {
Class.forName("org.h2.Driver");
String url = "jdbc:h2:mem:testdb";
connection = DriverManager.getConnection(url, "sa", "");
} catch (ClassNotFoundException | SQLException e) {
LOG.error(e.getMessage());
}
}
public Connection getConnection() {
return connection;
}
public void init() {
createTables();
createViews(); | }
private void createTables() {
try {
connection.createStatement().executeUpdate("create table CUSTOMER (ID int primary key auto_increment, NAME VARCHAR(45))");
connection.createStatement().executeUpdate("create table CUST_ADDRESS (ID VARCHAR(36), CUST_ID int, ADDRESS VARCHAR(45), FOREIGN KEY (CUST_ID) REFERENCES CUSTOMER(ID))");
} catch (SQLException e) {
LOG.error(e.getMessage());
}
}
private void createViews() {
try {
connection.createStatement().executeUpdate("CREATE VIEW CUSTOMER_VIEW AS SELECT * FROM CUSTOMER");
} catch (SQLException e) {
LOG.error(e.getMessage());
}
}
} | repos\tutorials-master\persistence-modules\core-java-persistence-4\src\main\java\com\baeldung\jdbcmetadata\DatabaseConfig.java | 2 |
请完成以下Java代码 | public int getC_UOM_ID()
{
return olCandEffectiveValuesBL.getEffectiveUomId(olCand).getRepoId();
}
@Override
public void setC_UOM_ID(final int uomId)
{
values.setUomId(UomId.ofRepoIdOrNull(uomId));
// NOTE: uom is mandatory
// we assume orderLine's UOM is correct
if (uomId > 0)
{
olCand.setPrice_UOM_Internal_ID(uomId);
}
}
@Override
public BigDecimal getQtyTU()
{
return Quantitys.toBigDecimalOrNull(olCandEffectiveValuesBL.getQtyItemCapacity_Effective(olCand));
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
values.setQtyTU(qtyPacks); | }
@Override
public int getC_BPartner_ID()
{
final BPartnerId bpartnerId = olCandEffectiveValuesBL.getBPartnerEffectiveId(olCand);
return BPartnerId.toRepoId(bpartnerId);
}
@Override
public void setC_BPartner_ID(final int partnerId)
{
olCand.setC_BPartner_Override_ID(partnerId);
values.setBpartnerId(BPartnerId.ofRepoIdOrNull(partnerId));
}
@Override
public boolean isInDispute()
{
// order line has no IsInDispute flag
return values.isInDispute();
}
@Override
public void setInDispute(final boolean inDispute)
{
values.setInDispute(inDispute);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OLCandHUPackingAware.java | 1 |
请完成以下Java代码 | public void setCompletedAfter(Date completedAfter) {
this.completedAfter = completedAfter;
}
@CamundaQueryParam(value = "completedBefore", converter = DateConverter.class)
public void setCompletedBefore(Date completedBefore) {
this.completedBefore = completedBefore;
}
@CamundaQueryParam("groupBy")
public void setGroupBy(String groupby) {
this.groupby = groupby;
}
protected void applyFilters(HistoricTaskInstanceReport reportQuery) {
if (completedBefore != null) {
reportQuery.completedBefore(completedBefore);
}
if (completedAfter != null) {
reportQuery.completedAfter(completedAfter);
}
if(REPORT_TYPE_DURATION.equals(reportType)) {
if(periodUnit == null) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "periodUnit is null");
} | }
}
protected HistoricTaskInstanceReport createNewReportQuery(ProcessEngine engine) {
return engine.getHistoryService().createHistoricTaskInstanceReport();
}
public List<HistoricTaskInstanceReportResult> executeCompletedReport(ProcessEngine engine) {
HistoricTaskInstanceReport reportQuery = createNewReportQuery(engine);
applyFilters(reportQuery);
if(PROCESS_DEFINITION.equals(groupby)) {
return reportQuery.countByProcessDefinitionKey();
} else if( TASK_NAME.equals(groupby) ){
return reportQuery.countByTaskName();
} else {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "groupBy parameter has invalid value: " + groupby);
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricTaskInstanceReportQueryDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<String> saveTools(String id, String tools) {
if (oConvertUtils.isEmpty(id)) {
return Result.error("插件ID不能为空");
}
AiragMcp mcp = this.getById(id);
if (mcp == null) {
return Result.error("未找到对应的插件");
}
// 验证是否为插件类型
String category = mcp.getCategory();
if (oConvertUtils.isEmpty(category)) {
category = "mcp"; // 兼容旧数据
}
if (!"plugin".equalsIgnoreCase(category)) {
return Result.error("只有插件类型才能保存工具");
}
// 更新tools字段
mcp.setTools(tools);
// 更新metadata中的tool_count
try {
com.alibaba.fastjson.JSONArray toolsArray = com.alibaba.fastjson.JSONArray.parseArray(tools);
int toolCount = toolsArray != null ? toolsArray.size() : 0;
// 解析现有metadata
JSONObject metadata = new JSONObject();
if (oConvertUtils.isNotEmpty(mcp.getMetadata())) {
try {
JSONObject metadataJson = JSONObject.parseObject(mcp.getMetadata());
if (metadataJson != null) {
metadata.putAll(metadataJson);
}
} catch (Exception e) {
log.warn("解析metadata失败,将重新创建: {}", mcp.getMetadata()); | }
}
// 更新tool_count
metadata.put("tool_count", toolCount);
// 保存metadata
mcp.setMetadata(metadata.toJSONString());
} catch (Exception e) {
log.warn("更新工具数量失败: {}", e.getMessage());
// 即使更新tool_count失败,也不影响保存tools
}
this.updateById(mcp);
return Result.OK("保存成功");
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\llm\service\impl\AiragMcpServiceImpl.java | 2 |
请完成以下Java代码 | class CompositeLoggable2 implements ILoggable
{
@NonNull
public static ILoggable compose(@Nullable final ILoggable loggable1, @Nullable final ILoggable loggable2)
{
if (NullLoggable.isNull(loggable1))
{
return NullLoggable.boxIfNull(loggable2);
}
else if (NullLoggable.isNull(loggable2))
{
return loggable1;
}
else
{
return new CompositeLoggable2(loggable1, loggable2);
}
}
@NonNull private final ILoggable loggable1;
@NonNull private final ILoggable loggable2;
private CompositeLoggable2(@NonNull final ILoggable loggable1, @NonNull final ILoggable loggable2)
{
this.loggable1 = loggable1;
this.loggable2 = loggable2;
}
@Override
public ILoggable addLog(final String msg, final Object... msgParameters)
{
loggable1.addLog(msg, msgParameters); | loggable2.addLog(msg, msgParameters);
return this;
}
@Override
public void flush()
{
loggable1.flush();
loggable2.flush();
}
@Override
public ILoggable addTableRecordReferenceLog(final ITableRecordReference recordRef, final String type, final String trxName)
{
loggable1.addTableRecordReferenceLog(recordRef, type, trxName);
loggable2.addTableRecordReferenceLog(recordRef, type, trxName);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\CompositeLoggable2.java | 1 |
请完成以下Java代码 | public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID);
}
@Override
public int getM_ShipmentSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQty (final @Nullable 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 setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{ | return get_ValueAsInt(COLUMNNAME_SeqNo);
}
/**
* Status AD_Reference_ID=540002
* Reference name: C_SubscriptionProgress Status
*/
public static final int STATUS_AD_Reference_ID=540002;
/** Planned = P */
public static final String STATUS_Planned = "P";
/** Open = O */
public static final String STATUS_Open = "O";
/** Delivered = D */
public static final String STATUS_Delivered = "D";
/** InPicking = C */
public static final String STATUS_InPicking = "C";
/** Done = E */
public static final String STATUS_Done = "E";
/** Delayed = H */
public static final String STATUS_Delayed = "H";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_SubscriptionProgress.java | 1 |
请完成以下Java代码 | public java.lang.String getSQL_From()
{
return get_ValueAsString(COLUMNNAME_SQL_From);
}
@Override
public void setSQL_GroupAndOrderBy (final @Nullable java.lang.String SQL_GroupAndOrderBy)
{
set_Value (COLUMNNAME_SQL_GroupAndOrderBy, SQL_GroupAndOrderBy);
}
@Override
public java.lang.String getSQL_GroupAndOrderBy()
{
return get_ValueAsString(COLUMNNAME_SQL_GroupAndOrderBy);
}
@Override
public void setSQL_WhereClause (final @Nullable java.lang.String SQL_WhereClause)
{
set_Value (COLUMNNAME_SQL_WhereClause, SQL_WhereClause);
} | @Override
public java.lang.String getSQL_WhereClause()
{
return get_ValueAsString(COLUMNNAME_SQL_WhereClause);
}
@Override
public void setWEBUI_KPI_ID (final int WEBUI_KPI_ID)
{
if (WEBUI_KPI_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, WEBUI_KPI_ID);
}
@Override
public int getWEBUI_KPI_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_KPI.java | 1 |
请完成以下Java代码 | protected void handleSubTaskCount(TaskService taskService, TaskInfo originalTaskEntity) {
if (CountingEntityUtil.isTaskRelatedEntityCountEnabled(task)) {
// Parent task is set, none was set before or it's a new subtask
if (task.getParentTaskId() != null && (originalTaskEntity == null || originalTaskEntity.getParentTaskId() == null)) {
TaskEntity parentTaskEntity = taskService.getTask(task.getParentTaskId());
if (CountingEntityUtil.isTaskRelatedEntityCountEnabled(parentTaskEntity)) {
CountingTaskEntity countingParentTaskEntity = (CountingTaskEntity) parentTaskEntity;
countingParentTaskEntity.setSubTaskCount(countingParentTaskEntity.getSubTaskCount() + 1);
parentTaskEntity.forceUpdate();
}
// Parent task removed and was set before
} else if (task.getParentTaskId() == null && originalTaskEntity != null && originalTaskEntity.getParentTaskId() != null) {
TaskEntity parentTaskEntity = taskService.getTask(originalTaskEntity.getParentTaskId());
if (CountingEntityUtil.isTaskRelatedEntityCountEnabled(parentTaskEntity)) {
CountingTaskEntity countingParentTaskEntity = (CountingTaskEntity) parentTaskEntity;
countingParentTaskEntity.setSubTaskCount(countingParentTaskEntity.getSubTaskCount() - 1);
parentTaskEntity.forceUpdate();
}
// Parent task was changed
} else if (task.getParentTaskId() != null && originalTaskEntity.getParentTaskId() != null
&& !task.getParentTaskId().equals(originalTaskEntity.getParentTaskId())) {
TaskEntity originalParentTaskEntity = taskService.getTask(originalTaskEntity.getParentTaskId());
if (CountingEntityUtil.isTaskRelatedEntityCountEnabled(originalParentTaskEntity)) {
CountingTaskEntity countingOriginalParentTaskEntity = (CountingTaskEntity) originalParentTaskEntity;
countingOriginalParentTaskEntity.setSubTaskCount(countingOriginalParentTaskEntity.getSubTaskCount() - 1); | originalParentTaskEntity.forceUpdate();
}
TaskEntity parentTaskEntity = taskService.getTask(task.getParentTaskId());
if (CountingEntityUtil.isTaskRelatedEntityCountEnabled(parentTaskEntity)) {
CountingTaskEntity countingParentTaskEntity = (CountingTaskEntity) parentTaskEntity;
countingParentTaskEntity.setSubTaskCount(countingParentTaskEntity.getSubTaskCount() + 1);
parentTaskEntity.forceUpdate();
}
}
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\SaveTaskCmd.java | 1 |
请完成以下Java代码 | public class ConnectionPerChannelPublisher implements Callable<Long> {
private static final Logger log = LoggerFactory.getLogger(ConnectionPerChannelPublisher.class);
private final ConnectionFactory factory;
private final int workerCount;
private final int iterations;
private final int payloadSize;
ConnectionPerChannelPublisher(ConnectionFactory factory, int workerCount, int iterations, int payloadSize) {
this.factory = factory;
this.workerCount = workerCount;
this.iterations = iterations;
this.payloadSize = payloadSize;
}
public static void main(String[] args) {
if (args.length != 4) {
System.err.println("Usage: java " + ConnectionPerChannelPublisher.class.getName() + " <host> <#channels> <#messages> <payloadSize>");
System.exit(1);
}
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(args[0]);
int workerCount = Integer.parseInt(args[1]);
int iterations = Integer.parseInt(args[2]);
int payloadSize = Integer.parseInt(args[3]);
// run the benchmark 10x and get the average throughput
LongSummaryStatistics summary = IntStream.range(0, 9)
.mapToObj(idx -> new ConnectionPerChannelPublisher(factory, workerCount, iterations, payloadSize))
.map(p -> p.call())
.collect(Collectors.summarizingLong((l) -> l));
log.info("[I66] workers={}, throughput={}", workerCount, (int)Math.floor(summary.getAverage()));
}
@Override
public Long call() {
try {
List<Worker> workers = new ArrayList<>();
CountDownLatch counter = new CountDownLatch(workerCount);
for (int i = 0; i < workerCount; i++) {
Connection conn = factory.newConnection();
workers.add(new Worker("queue_" + i, conn, iterations, counter, payloadSize));
} | ExecutorService executor = new ThreadPoolExecutor(workerCount, workerCount, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(workerCount, true));
long start = System.currentTimeMillis();
log.info("[I61] Starting {} workers...", workers.size());
executor.invokeAll(workers);
if (counter.await(5, TimeUnit.MINUTES)) {
long elapsed = System.currentTimeMillis() - start;
log.info("[I59] Tasks completed: #workers={}, #iterations={}, elapsed={}ms, stats={}", workerCount, iterations, elapsed);
return throughput(workerCount, iterations, elapsed);
} else {
throw new RuntimeException("[E61] Timeout waiting workers to complete");
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private static long throughput(int workerCount, int iterations, long elapsed) {
return (iterations * workerCount * 1000) / elapsed;
}
} | repos\tutorials-master\messaging-modules\rabbitmq\src\main\java\com\baeldung\benchmark\ConnectionPerChannelPublisher.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setBrandLogoUrl(String brandLogoUrl) {
this.brandLogoUrl = brandLogoUrl;
}
public String getCompanyEntityId() {
return companyEntityId;
}
public void setCompanyEntityId(String companyEntityId) {
this.companyEntityId = companyEntityId;
}
public int getSort() {
return sort;
} | public void setSort(int sort) {
this.sort = sort;
}
@Override
public String toString() {
return "BrandInsertReq{" +
"id='" + id + '\'' +
", brand='" + brand + '\'' +
", brandLogoUrl='" + brandLogoUrl + '\'' +
", companyEntityId='" + companyEntityId + '\'' +
", sort=" + sort +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\product\BrandInsertReq.java | 2 |
请完成以下Java代码 | public boolean isZero() {return intValue == 0;}
public boolean isPositive() {return intValue > 0;}
public boolean isOne() {return intValue == 1;}
public QtyTU add(@NonNull final QtyTU toAdd)
{
if (this.intValue == 0)
{
return toAdd;
}
else if (toAdd.intValue == 0)
{
return this;
}
else
{
return ofInt(this.intValue + toAdd.intValue);
}
}
public QtyTU subtractOrZero(@NonNull final QtyTU toSubtract)
{
if (toSubtract.intValue == 0)
{
return this;
}
else
{
return ofInt(Math.max(this.intValue - toSubtract.intValue, 0));
}
}
public QtyTU min(@NonNull final QtyTU other)
{
return this.intValue <= other.intValue ? this : other;
}
public Quantity computeQtyCUsPerTUUsingTotalQty(@NonNull final Quantity qtyCUsTotal) | {
if (isZero())
{
throw new AdempiereException("Cannot determine Qty CUs/TU when QtyTU is zero of total CUs " + qtyCUsTotal);
}
else if (isOne())
{
return qtyCUsTotal;
}
else
{
return qtyCUsTotal.divide(toInt());
}
}
public Quantity computeTotalQtyCUsUsingQtyCUsPerTU(@NonNull final Quantity qtyCUsPerTU)
{
return qtyCUsPerTU.multiply(toInt());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\QtyTU.java | 1 |
请完成以下Java代码 | public class SecureServer {
public static void main(String[] args) {
final Map<String, char[]> users = new HashMap<>(2);
users.put("root", "password".toCharArray());
users.put("admin", "password".toCharArray());
final IdentityManager idm = new CustomIdentityManager(users);
Undertow server = Undertow.builder()
.addHttpListener(8080, "localhost")
.setHandler(addSecurity(SecureServer::setExchange, idm)).build();
server.start();
}
private static void setExchange(HttpServerExchange exchange) {
final SecurityContext context = exchange.getSecurityContext(); | exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), IoCallback.END_EXCHANGE);
}
private static HttpHandler addSecurity(final HttpHandler toWrap, final IdentityManager identityManager) {
HttpHandler handler = toWrap;
handler = new AuthenticationCallHandler(handler);
handler = new AuthenticationConstraintHandler(handler);
final List<AuthenticationMechanism> mechanisms = Collections
.singletonList(new BasicAuthenticationMechanism("Baeldung_Realm"));
handler = new AuthenticationMechanismsHandler(handler, mechanisms);
handler = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, identityManager, handler);
return handler;
}
} | repos\tutorials-master\server-modules\undertow\src\main\java\com\baeldung\undertow\secure\SecureServer.java | 1 |
请完成以下Java代码 | public int ysize()
{
return 0;
}
public double prob(int i, int j)
{
return 0.0;
}
public double prob(int i)
{
return 0.0;
}
public double prob()
{
return 0.0;
}
public double alpha(int i, int j)
{
return 0.0;
}
public double beta(int i, int j)
{
return 0.0;
}
public double emissionCost(int i, int j)
{
return 0.0;
}
public double nextTransitionCost(int i, int j, int k)
{
return 0.0;
}
public double prevTransitionCost(int i, int j, int k)
{
return 0.0;
}
public double bestCost(int i, int j)
{
return 0.0;
}
public List<Integer> emissionVector(int i, int j)
{
return null;
}
public List<Integer> nextTransitionVector(int i, int j, int k)
{
return null;
}
public List<Integer> prevTransitionVector(int i, int j, int k)
{
return null;
}
public double Z()
{
return 0.0;
}
public boolean parse()
{
return true;
} | public boolean empty()
{
return true;
}
public boolean clear()
{
return true;
}
public boolean next()
{
return true;
}
public String parse(String str)
{
return "";
}
public String toString()
{
return "";
}
public String toString(String result, int size)
{
return "";
}
public String parse(String str, int size)
{
return "";
}
public String parse(String str, int size1, String result, int size2)
{
return "";
}
// set token-level penalty. It would be useful for implementing
// Dual decompositon decoding.
// e.g.
// "Dual Decomposition for Parsing with Non-Projective Head Automata"
// Terry Koo Alexander M. Rush Michael Collins Tommi Jaakkola David Sontag
public void setPenalty(int i, int j, double penalty)
{
}
public double penalty(int i, int j)
{
return 0.0;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\Tagger.java | 1 |
请完成以下Java代码 | public boolean isFullPayload() {
return isFullPayload;
}
public void setFullPayload(boolean isFullPayload) {
this.isFullPayload = isFullPayload;
}
public static EventPayload fullPayload(String name) {
EventPayload payload = new EventPayload();
payload.name = name;
payload.setFullPayload(true);
return payload;
}
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public boolean isMetaParameter() {
return metaParameter;
}
public void setMetaParameter(boolean metaParameter) {
this.metaParameter = metaParameter;
}
@JsonIgnore
public boolean isNotForBody() {
return header || isFullPayload || metaParameter;
} | @Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EventPayload that = (EventPayload) o;
return Objects.equals(name, that.name) && Objects.equals(type, that.type) && correlationParameter == that.correlationParameter
&& header == that.header && isFullPayload == that.isFullPayload && metaParameter == that.metaParameter;
}
@Override
public int hashCode() {
return Objects.hash(name, type);
}
} | repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\EventPayload.java | 1 |
请完成以下Java代码 | public SearchControls getSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setTimeLimit(30000);
return searchControls;
}
public String getGroupTypeAttribute() {
return groupTypeAttribute;
}
public void setGroupTypeAttribute(String groupTypeAttribute) {
this.groupTypeAttribute = groupTypeAttribute;
}
public boolean isAllowAnonymousLogin() {
return allowAnonymousLogin;
}
public void setAllowAnonymousLogin(boolean allowAnonymousLogin) {
this.allowAnonymousLogin = allowAnonymousLogin;
}
public boolean isAuthorizationCheckEnabled() {
return authorizationCheckEnabled; | }
public void setAuthorizationCheckEnabled(boolean authorizationCheckEnabled) {
this.authorizationCheckEnabled = authorizationCheckEnabled;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public boolean isPasswordCheckCatchAuthenticationException() {
return passwordCheckCatchAuthenticationException;
}
public void setPasswordCheckCatchAuthenticationException(boolean passwordCheckCatchAuthenticationException) {
this.passwordCheckCatchAuthenticationException = passwordCheckCatchAuthenticationException;
}
} | repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\LdapConfiguration.java | 1 |
请完成以下Java代码 | public String getId() {
return variableId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getTaskId() {
return taskId;
}
@Override
public String getBatchId() {
return null;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public String getErrorMessage() {
return errorMessage;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTypeName() {
if(value != null) {
return value.getType().getName();
} | else {
return null;
}
}
public String getName() {
return name;
}
public Object getValue() {
if(value != null) {
return value.getValue();
}
else {
return null;
}
}
public TypedValue getTypedValue() {
return value;
}
public ProcessEngineServices getProcessEngineServices() {
return Context.getProcessEngineConfiguration().getProcessEngine();
}
public ProcessEngine getProcessEngine() {
return Context.getProcessEngineConfiguration().getProcessEngine();
}
public static DelegateCaseVariableInstanceImpl fromVariableInstance(VariableInstance variableInstance) {
DelegateCaseVariableInstanceImpl delegateInstance = new DelegateCaseVariableInstanceImpl();
delegateInstance.variableId = variableInstance.getId();
delegateInstance.processDefinitionId = variableInstance.getProcessDefinitionId();
delegateInstance.processInstanceId = variableInstance.getProcessInstanceId();
delegateInstance.executionId = variableInstance.getExecutionId();
delegateInstance.caseExecutionId = variableInstance.getCaseExecutionId();
delegateInstance.caseInstanceId = variableInstance.getCaseInstanceId();
delegateInstance.taskId = variableInstance.getTaskId();
delegateInstance.activityInstanceId = variableInstance.getActivityInstanceId();
delegateInstance.tenantId = variableInstance.getTenantId();
delegateInstance.errorMessage = variableInstance.getErrorMessage();
delegateInstance.name = variableInstance.getName();
delegateInstance.value = variableInstance.getTypedValue();
return delegateInstance;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\listener\DelegateCaseVariableInstanceImpl.java | 1 |
请完成以下Java代码 | public final Color getColor(final String name, final Color defaultColor)
{
Color color = UIManager.getColor(buildUIDefaultsKey(name));
if (color == null && uiSubClassID != null)
{
color = UIManager.getColor(name);
}
if (color == null)
{
color = defaultColor;
}
return color;
}
public final Color getColor(final String name)
{
final Color defaultColor = null;
return getColor(name, defaultColor);
}
public final Border getBorder(final String name, final Border defaultBorder)
{
Border border = UIManager.getBorder(buildUIDefaultsKey(name));
if (border == null && uiSubClassID != null)
{
border = UIManager.getBorder(name);
}
if (border == null)
{
border = defaultBorder;
}
return border;
}
private final String buildUIDefaultsKey(final String name)
{
return buildUIDefaultsKey(uiSubClassID, name);
}
private static final String buildUIDefaultsKey(final String uiSubClassID, final String name)
{
if (uiSubClassID == null)
{
return name;
}
else
{
return uiSubClassID + "." + name;
}
}
public boolean getBoolean(final String name, final boolean defaultValue)
{
Object value = UIManager.getDefaults().get(buildUIDefaultsKey(name));
if (value instanceof Boolean)
{
return (boolean)value;
}
if (uiSubClassID != null)
{
value = UIManager.getDefaults().get(name);
if (value instanceof Boolean)
{
return (boolean)value;
}
}
return defaultValue;
}
/**
* Convert all keys from given UI defaults key-value list by applying the <code>uiSubClassID</code> prefix to them.
*
* @param uiSubClassID
* @param keyValueList
* @return converted <code>keyValueList</code> | */
public static final Object[] applyUISubClassID(final String uiSubClassID, final Object[] keyValueList)
{
if (keyValueList == null || keyValueList.length <= 0)
{
return keyValueList;
}
Check.assumeNotEmpty(uiSubClassID, "uiSubClassID not empty");
final Object[] keyValueListConverted = new Object[keyValueList.length];
for (int i = 0, max = keyValueList.length; i < max; i += 2)
{
final Object keyOrig = keyValueList[i];
final Object value = keyValueList[i + 1];
final Object key;
if (keyOrig instanceof String)
{
key = buildUIDefaultsKey(uiSubClassID, (String)keyOrig);
}
else
{
key = keyOrig;
}
keyValueListConverted[i] = key;
keyValueListConverted[i + 1] = value;
}
return keyValueListConverted;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\UISubClassIDHelper.java | 1 |
请完成以下Java代码 | public String getValue() {
return value;
}
/**
* Find by name.
*
* @param name the name
* @return the weekday if found else null
*/
public static Weekday findByName(String name) {
Weekday result = null;
for (Weekday day : values()) {
if (day.name().equalsIgnoreCase(name)) {
result = day;
break;
}
}
return result;
} | /**
* Find by value.
*
* @param value the value
* @return the weekday if found else null
*/
public static Weekday findByValue(String value) {
Weekday result = null;
for (Weekday day : values()) {
if (day.getValue().equalsIgnoreCase(value)) {
result = day;
break;
}
}
return result;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-types\src\main\java\com\baeldung\enums\Weekday.java | 1 |
请完成以下Java代码 | public final class DebugModeUtil {
public static final int DEBUG_MODE_DEFAULT_DURATION_MINUTES = 15;
private DebugModeUtil() {
}
public static int getMaxDebugAllDuration(int tenantProfileDuration, int systemDefaultDuration) {
if (tenantProfileDuration > 0) {
return tenantProfileDuration;
} else {
return systemDefaultDuration > 0 ? systemDefaultDuration : DEBUG_MODE_DEFAULT_DURATION_MINUTES;
}
}
public static boolean isDebugAllAvailable(HasDebugSettings debugSettingsAware) {
var debugSettings = debugSettingsAware.getDebugSettings();
return debugSettings != null && debugSettings.getAllEnabledUntil() > System.currentTimeMillis();
}
public static boolean isDebugAvailable(HasDebugSettings debugSettingsAware, String nodeConnection) {
if (isDebugAllAvailable(debugSettingsAware)) {
return true;
} else {
var debugSettings = debugSettingsAware.getDebugSettings();
return debugSettings != null && debugSettings.isFailuresEnabled() && TbNodeConnectionType.FAILURE.equals(nodeConnection); | }
}
public static boolean isDebugFailuresAvailable(HasDebugSettings debugSettingsAware, Set<String> nodeConnections) {
if (isDebugAllAvailable(debugSettingsAware)) {
return true;
} else {
var debugSettings = debugSettingsAware.getDebugSettings();
return debugSettings != null && nodeConnections != null && debugSettings.isFailuresEnabled() && nodeConnections.contains(TbNodeConnectionType.FAILURE);
}
}
public static boolean isDebugFailuresAvailable(HasDebugSettings debugSettingsAware) {
if (isDebugAllAvailable(debugSettingsAware)) {
return true;
} else {
var debugSettings = debugSettingsAware.getDebugSettings();
return debugSettings != null && debugSettings.isFailuresEnabled();
}
}
} | repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\DebugModeUtil.java | 1 |
请完成以下Java代码 | public void deleteByRequestId(TenantId tenantId, NotificationRequestId requestId) {
notificationRepository.deleteByRequestId(requestId.getId());
}
@Override
public void deleteByRecipientId(TenantId tenantId, UserId recipientId) {
notificationRepository.deleteByRecipientId(recipientId.getId());
}
@Override
public void createPartition(NotificationEntity entity) {
partitioningRepository.createPartitionIfNotExists(ModelConstants.NOTIFICATION_TABLE_NAME,
entity.getCreatedTime(), TimeUnit.HOURS.toMillis(partitionSizeInHours));
} | @Override
protected Class<NotificationEntity> getEntityClass() {
return NotificationEntity.class;
}
@Override
protected JpaRepository<NotificationEntity, UUID> getRepository() {
return notificationRepository;
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationDao.java | 1 |
请完成以下Java代码 | public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
return new GatewayMultipartHttpServletRequest(request);
}
private static boolean isGatewayRequest(HttpServletRequest request) {
return request.getAttribute(MvcUtils.GATEWAY_ROUTE_ID_ATTR) != null
|| request.getAttribute(MvcUtils.GATEWAY_REQUEST_URL_ATTR) != null;
}
/**
* StandardMultipartHttpServletRequest wrapper that will not parse multipart if it is
* a gateway request. A gateway request has certain request attributes set.
*/
static class GatewayMultipartHttpServletRequest extends StandardMultipartHttpServletRequest {
GatewayMultipartHttpServletRequest(HttpServletRequest request) {
super(request, true);
} | @Override
protected void initializeMultipart() {
if (!isGatewayRequest(getRequest())) {
super.initializeMultipart();
}
}
@Override
public Map<String, String[]> getParameterMap() {
if (isGatewayRequest(getRequest())) {
return Collections.emptyMap();
}
return super.getParameterMap();
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayMvcMultipartResolver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getTypeName() {
return TYPE_NAME;
}
@Override
public boolean isCachable() {
return true;
}
@Override
public Object getValue(ValueFields valueFields) {
String textValue = valueFields.getTextValue();
if (textValue == null) {
return null;
}
return UUID.fromString(textValue);
} | @Override
public void setValue(Object value, ValueFields valueFields) {
if (value != null) {
valueFields.setTextValue(value.toString());
} else {
valueFields.setTextValue(null);
}
}
@Override
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return UUID.class.isAssignableFrom(value.getClass());
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\UUIDType.java | 2 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Employee> getEmployees() { | return this.employees;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Company company = (Company) o;
return Objects.equals(id, company.id) &&
Objects.equals(name, company.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
} | repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\proxy\Company.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void add(int index, HistoricVariableInstanceEntity e) {
super.add(index, e);
initializeVariable(e);
}
@Override
public boolean add(HistoricVariableInstanceEntity e) {
initializeVariable(e);
return super.add(e);
}
@Override
public boolean addAll(Collection<? extends HistoricVariableInstanceEntity> c) {
for (HistoricVariableInstanceEntity e : c) {
initializeVariable(e);
}
return super.addAll(c);
}
@Override | public boolean addAll(int index, Collection<? extends HistoricVariableInstanceEntity> c) {
for (HistoricVariableInstanceEntity e : c) {
initializeVariable(e);
}
return super.addAll(index, c);
}
/**
* If the passed {@link HistoricVariableInstanceEntity} is a binary variable and the command-context is active, the variable value is fetched to ensure the byte-array is populated.
*/
protected void initializeVariable(HistoricVariableInstanceEntity e) {
if (Context.getCommandContext() != null && e != null && e.getVariableType() != null) {
e.getValue();
// make sure JPA entities are cached for later retrieval
if (JPAEntityVariableType.TYPE_NAME.equals(e.getVariableType().getTypeName()) || JPAEntityListVariableType.TYPE_NAME.equals(e.getVariableType().getTypeName())) {
((CacheableVariable) e.getVariableType()).setForceCacheable(true);
}
}
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\HistoricVariableInitializingList.java | 2 |
请完成以下Java代码 | public Date getSubmittedDate() {
return submittedDate;
}
public void setSubmittedDate(Date submittedDate) {
this.submittedDate = submittedDate;
}
public String getSelectedOutcome() {
return selectedOutcome;
}
public void setSelectedOutcome(String selectedOutcome) {
this.selectedOutcome = selectedOutcome;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) { | this.scopeId = scopeId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\flowable-engine-main\modules\flowable-form-api\src\main\java\org\flowable\form\api\FormInstanceInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ModelAndView toLogin(HttpServletRequest request, HttpServletResponse response,ModelAndView modelAndView) {
if (loginService.ifLogin(request, response) != null) {
modelAndView.setView(new RedirectView("/",true,false));
return modelAndView;
}
return new ModelAndView("login");
}
@RequestMapping(value="login", method=RequestMethod.POST)
@ResponseBody
@PermissionLimit(limit=false)
public ReturnT<String> loginDo(HttpServletRequest request, HttpServletResponse response, String userName, String password, String ifRemember){
boolean ifRem = (ifRemember!=null && ifRemember.trim().length()>0 && "on".equals(ifRemember))?true:false;
return loginService.login(request, response, userName, password, ifRem);
}
@RequestMapping(value="logout", method=RequestMethod.POST)
@ResponseBody
@PermissionLimit(limit=false)
public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response){
return loginService.logout(request, response);
} | @RequestMapping("/help")
public String help() {
/*if (!PermissionInterceptor.ifLogin(request)) {
return "redirect:/toLogin";
}*/
return "help";
}
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\IndexController.java | 2 |
请完成以下Java代码 | public void setEditable (boolean edit)
{
m_textPane.setEditable(edit);
}
/**
* Editable
* @return true if editable
*/
public boolean isEditable()
{
return m_textPane.isEditable();
}
/**
* Set Text Margin
* @param m insets
*/
public void setMargin (Insets m)
{
if (m_textPane != null)
m_textPane.setMargin(m);
} // setMargin
/**
* Set Opaque
* @param isOpaque opaque
*/
@Override
public void setOpaque (boolean isOpaque)
{
// JScrollPane & Viewport is always not Opaque
if (m_textPane == null) // during init of JScrollPane
super.setOpaque(isOpaque);
else
m_textPane.setOpaque(isOpaque);
} // setOpaque
/**
* Add Focus Listener
* @param l listener
*/
@Override
public void addFocusListener (FocusListener l)
{
if (m_textPane == null) // during init
super.addFocusListener(l);
else
m_textPane.addFocusListener(l);
}
/**
* Add Mouse Listener
* @param l listner
*/
@Override
public void addMouseListener (MouseListener l)
{
m_textPane.addMouseListener(l);
}
/**
* Add Key Listener
* @param l listner
*/
@Override
public void addKeyListener (KeyListener l)
{
m_textPane.addKeyListener(l);
}
/**
* Add Input Method Listener
* @param l listener
*/
@Override
public void addInputMethodListener (InputMethodListener l)
{
m_textPane.addInputMethodListener(l);
}
/**
* Get Input Method Requests | * @return requests
*/
@Override
public InputMethodRequests getInputMethodRequests()
{
return m_textPane.getInputMethodRequests();
}
/**
* Set Input Verifier
* @param l verifyer
*/
@Override
public void setInputVerifier (InputVerifier l)
{
m_textPane.setInputVerifier(l);
}
// metas: begin
public String getContentType()
{
if (m_textPane != null)
return m_textPane.getContentType();
return null;
}
private void setHyperlinkListener()
{
if (hyperlinkListenerClass == null)
{
return;
}
try
{
final HyperlinkListener listener = (HyperlinkListener)hyperlinkListenerClass.newInstance();
m_textPane.addHyperlinkListener(listener);
}
catch (Exception e)
{
log.warn("Cannot instantiate hyperlink listener - " + hyperlinkListenerClass, e);
}
}
private static Class<?> hyperlinkListenerClass;
static
{
final String hyperlinkListenerClassname = "de.metas.adempiere.gui.ADHyperlinkHandler";
try
{
hyperlinkListenerClass = Thread.currentThread().getContextClassLoader().loadClass(hyperlinkListenerClassname);
}
catch (Exception e)
{
log.warn("Cannot instantiate hyperlink listener - " + hyperlinkListenerClassname, e);
}
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return copyPasteSupport;
}
// metas: end
} // CTextPane | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextPane.java | 1 |
请完成以下Java代码 | public Builder firstName(String firstName) {
this.firstName = firstName;
return this;
}
public Builder lastName(String lastName) {
this.lastName = lastName;
return this;
}
public Builder email(String email) {
this.email = email;
return this;
} | public Builder username(String username) {
this.username = username;
return this;
}
public Builder id(Long id) {
this.id = id;
return this;
}
public User build() {
return new User(firstName, lastName, email, username, id);
}
}
} | repos\tutorials-master\patterns-modules\design-patterns-behavioral-2\src\main\java\com\baeldung\fluentinterface\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() { return null; }
};
SSLContext sslContext = SSLContext.getInstance("TLS");
trustManagers = new TrustManager[]{ trustAll };
hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) { return true; }
};
} else if (sslCaCert != null) {
char[] password = null; // Any password will work.
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert);
if (certificates.isEmpty()) {
throw new IllegalArgumentException("expected non-empty set of trusted certificates");
}
KeyStore caKeyStore = newEmptyKeyStore(password);
int index = 0;
for (Certificate certificate : certificates) {
String certificateAlias = "ca" + Integer.toString(index++);
caKeyStore.setCertificateEntry(certificateAlias, certificate);
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(caKeyStore);
trustManagers = trustManagerFactory.getTrustManagers();
}
if (keyManagers != null || trustManagers != null) {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, new SecureRandom());
httpClient.setSslSocketFactory(sslContext.getSocketFactory()); | } else {
httpClient.setSslSocketFactory(null);
}
httpClient.setHostnameVerifier(hostnameVerifier);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, password);
return keyStore;
} catch (IOException e) {
throw new AssertionError(e);
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\ApiClient.java | 2 |
请完成以下Java代码 | public BigDecimal getVatRate() {
return vatRate;
}
/**
* Sets the value of the vatRate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVatRate(BigDecimal value) {
this.vatRate = value;
}
/**
* Gets the value of the amount property.
*
* @return
* possible object is
* {@link String }
*
*/
public BigDecimal getAmount() {
return amount;
}
/**
* Sets the value of the amount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAmount(BigDecimal value) {
this.amount = value;
}
/**
* Gets the value of the vat property.
*
* @return | * possible object is
* {@link String }
*
*/
public BigDecimal getVat() {
return vat;
}
/**
* Sets the value of the vat property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVat(BigDecimal value) {
this.vat = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\VatRateType.java | 1 |
请完成以下Spring Boot application配置 | # Whether to enable Redis repositories.
spring.data.redis.repositories.enabled=true
# Redis server host, default localhost
spring.redis.host=loca | lhost
# Redis server port. default 6379
spring.redis.port=6379 | repos\spring-data-examples-main\redis\repositories\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Meta Author.
@param Meta_Author
Author of the content
*/
public void setMeta_Author (String Meta_Author)
{
set_Value (COLUMNNAME_Meta_Author, Meta_Author);
}
/** Get Meta Author.
@return Author of the content
*/
public String getMeta_Author ()
{
return (String)get_Value(COLUMNNAME_Meta_Author);
}
/** Set Meta Content Type.
@param Meta_Content
Defines the type of content i.e. "text/html; charset=UTF-8"
*/
public void setMeta_Content (String Meta_Content)
{
set_Value (COLUMNNAME_Meta_Content, Meta_Content);
}
/** Get Meta Content Type.
@return Defines the type of content i.e. "text/html; charset=UTF-8"
*/
public String getMeta_Content ()
{
return (String)get_Value(COLUMNNAME_Meta_Content);
}
/** Set Meta Copyright.
@param Meta_Copyright
Contains Copyright information for the content
*/
public void setMeta_Copyright (String Meta_Copyright)
{
set_Value (COLUMNNAME_Meta_Copyright, Meta_Copyright);
}
/** Get Meta Copyright.
@return Contains Copyright information for the content
*/
public String getMeta_Copyright ()
{
return (String)get_Value(COLUMNNAME_Meta_Copyright);
}
/** Set Meta Publisher.
@param Meta_Publisher
Meta Publisher defines the publisher of the content
*/
public void setMeta_Publisher (String Meta_Publisher)
{
set_Value (COLUMNNAME_Meta_Publisher, Meta_Publisher);
}
/** Get Meta Publisher.
@return Meta Publisher defines the publisher of the content
*/
public String getMeta_Publisher () | {
return (String)get_Value(COLUMNNAME_Meta_Publisher);
}
/** Set Meta RobotsTag.
@param Meta_RobotsTag
RobotsTag defines how search robots should handle this content
*/
public void setMeta_RobotsTag (String Meta_RobotsTag)
{
set_Value (COLUMNNAME_Meta_RobotsTag, Meta_RobotsTag);
}
/** Get Meta RobotsTag.
@return RobotsTag defines how search robots should handle this content
*/
public String getMeta_RobotsTag ()
{
return (String)get_Value(COLUMNNAME_Meta_RobotsTag);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WebProject.java | 1 |
请完成以下Spring Boot application配置 | app:
id: demo-application-profiles # 使用的 Apollo 的项目(应用)编号
apollo:
meta: http://127.0.0.1:8080 # Apollo Meta Server 地址
bootstrap:
enabled: true # 是否开启 Apollo 配置预加载功能。默认为 false。
eagerLoad:
enable: true # 是否 | 开启 Apollo 支持日志级别的加载时机。默认为 false。
namespaces: application # 使用的 Apollo 的命名空间,默认为 application。 | repos\SpringBoot-Labs-master\lab-45\lab-45-apollo-demo-profiles\src\main\resources\application-dev.yaml | 2 |
请完成以下Java代码 | public String getCCM_Success ()
{
return (String)get_Value(COLUMNNAME_CCM_Success);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/ | public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\callcenter\model\X_CCM_Bundle_Result.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.