instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class HUManagerProfileLayoutSectionList
{
public static final HUManagerProfileLayoutSectionList DEFAULT = new HUManagerProfileLayoutSectionList(ImmutableList.of(
HUManagerProfileLayoutSection.DisplayName,
HUManagerProfileLayoutSection.QRCode,
HUManagerProfileLayoutSection.Locator,
HUManagerProfileLayoutSection.HUStatus,
HUManagerProfileLayoutSection.Product,
HUManagerProfileLayoutSection.Qty,
HUManagerProfileLayoutSection.ClearanceStatus,
HUManagerProfileLayoutSection.Attributes
));
@NonNull private final ImmutableList<HUManagerProfileLayoutSection> list;
@NonNull private final transient ImmutableList<String> asStringList;
private HUManagerProfileLayoutSectionList(@NonNull final ImmutableList<HUManagerProfileLayoutSection> list)
{ | this.list = Check.assumeNotEmpty(list, "list is not empty");
this.asStringList = list.stream()
.map(HUManagerProfileLayoutSection::getCode)
.collect(ImmutableList.toImmutableList());
}
public static Collector<HUManagerProfileLayoutSection, ?, HUManagerProfileLayoutSectionList> collectOrDefault()
{
return GuavaCollectors.collectUsingListAccumulator(list -> list.isEmpty()
? DEFAULT
: new HUManagerProfileLayoutSectionList(ImmutableList.copyOf(list)));
}
public List<String> toStringList() {return asStringList;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\mobileui\config\HUManagerProfileLayoutSectionList.java | 1 |
请完成以下Java代码 | public byte[] serialize(String topic, Object data) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("NullAway") // Dataflow analysis limitation
@Override
public byte[] serialize(String topic, Headers headers, Object data) {
if (data == null) {
return null;
}
byte[] value = null;
String selectorKey = selectorKey();
Header header = headers.lastHeader(selectorKey);
if (header != null) {
value = header.value();
}
if (value == null) {
value = trySerdes(data);
if (value == null) {
throw new IllegalStateException("No '" + selectorKey
+ "' header present and type (" + data.getClass().getName()
+ ") is not supported by Serdes");
}
try {
headers.add(new RecordHeader(selectorKey, value));
}
catch (IllegalStateException e) {
LOGGER.debug(e, () -> "Could not set header for type " + data.getClass());
}
}
String selector = new String(value).replaceAll("\"", "");
@SuppressWarnings("unchecked")
Serializer<Object> serializer = (Serializer<Object>) this.delegates.get(selector);
if (serializer == null) {
throw new IllegalStateException(
"No serializer found for '" + selectorKey + "' header with value '" + selector + "'");
}
return serializer.serialize(topic, headers, data);
}
private String selectorKey() {
return this.forKeys ? KEY_SERIALIZATION_SELECTOR : VALUE_SERIALIZATION_SELECTOR; | }
/*
* Package for testing.
*/
@SuppressWarnings("NullAway") // Dataflow analysis limitation
byte[] trySerdes(Object data) {
try {
Serde<? extends Object> serdeFrom = Serdes.serdeFrom(data.getClass());
Serializer<?> serializer = serdeFrom.serializer();
serializer.configure(this.autoConfigs, this.forKeys);
String key = data.getClass().getName();
this.delegates.put(key, serializer);
return key.getBytes();
}
catch (IllegalStateException e) {
return null;
}
}
@Override
public void close() {
this.delegates.values().forEach(Serializer::close);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\DelegatingSerializer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public User findByEmail(String email){
return userRepository.findByEmail(email);
}
@Override
public User save(UserRegistrationDto registration) {
User user = new User();
user.setFirstName(registration.getFirstName());
user.setLastName(registration.getLastName());
user.setEmail(registration.getEmail());
user.setPassword(passwordEncoder.encode(registration.getPassword()));
user.setRoles(Arrays.asList(new Role("ROLE_USER")));
return userRepository.save(user);
}
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userRepository.findByEmail(email); | if (user == null){
throw new UsernameNotFoundException("Invalid username or password.");
}
return new org.springframework.security.core.userdetails.User(user.getEmail(),
user.getPassword(),
mapRolesToAuthorities(user.getRoles()));
}
private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Role> roles){
return roles.stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toList());
}
} | repos\Spring-Boot-Advanced-Projects-main\Springboot-Registration-Page\src\main\java\aspera\registration\service\UserServiceImpl.java | 2 |
请完成以下Java代码 | public boolean isClosed() {
return isClosedAttribute.getValue(this);
}
public void setClosed(boolean isClosed) {
isClosedAttribute.setValue(this, isClosed);
}
public Collection<Participant> getParticipants() {
return participantCollection.get(this);
}
public Collection<MessageFlow> getMessageFlows() {
return messageFlowCollection.get(this);
}
public Collection<Artifact> getArtifacts() {
return artifactCollection.get(this);
}
public Collection<ConversationNode> getConversationNodes() {
return conversationNodeCollection.get(this);
}
public Collection<ConversationAssociation> getConversationAssociations() {
return conversationAssociationCollection.get(this);
}
public Collection<ParticipantAssociation> getParticipantAssociations() { | return participantAssociationCollection.get(this);
}
public Collection<MessageFlowAssociation> getMessageFlowAssociations() {
return messageFlowAssociationCollection.get(this);
}
public Collection<CorrelationKey> getCorrelationKeys() {
return correlationKeyCollection.get(this);
}
public Collection<ConversationLink> getConversationLinks() {
return conversationLinkCollection.get(this);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CollaborationImpl.java | 1 |
请完成以下Java代码 | public String toString() {
return this.text;
}
/**
* Load {@link PemContent} from the given content (either the PEM content itself or a
* reference to the resource to load).
* @param content the content to load
* @param resourceLoader the resource loader used to load content
* @return a new {@link PemContent} instance or {@code null}
* @throws IOException on IO error
*/
static @Nullable PemContent load(@Nullable String content, ResourceLoader resourceLoader) throws IOException {
if (!StringUtils.hasLength(content)) {
return null;
}
if (isPresentInText(content)) {
return new PemContent(content);
}
try (InputStream in = resourceLoader.getResource(content).getInputStream()) {
return load(in);
}
catch (IOException | UncheckedIOException ex) {
throw new IOException("Error reading certificate or key from file '%s'".formatted(content), ex);
}
}
/**
* Load {@link PemContent} from the given {@link Path}.
* @param path a path to load the content from
* @return the loaded PEM content
* @throws IOException on IO error
*/
public static PemContent load(Path path) throws IOException {
Assert.notNull(path, "'path' must not be null");
try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ)) {
return load(in);
}
}
/** | * Load {@link PemContent} from the given {@link InputStream}.
* @param in an input stream to load the content from
* @return the loaded PEM content
* @throws IOException on IO error
*/
public static PemContent load(InputStream in) throws IOException {
return of(StreamUtils.copyToString(in, StandardCharsets.UTF_8));
}
/**
* Return a new {@link PemContent} instance containing the given text.
* @param text the text containing PEM encoded content
* @return a new {@link PemContent} instance
*/
@Contract("!null -> !null")
public static @Nullable PemContent of(@Nullable String text) {
return (text != null) ? new PemContent(text) : null;
}
/**
* Return if PEM content is present in the given text.
* @param text the text to check
* @return if the text includes PEM encoded content.
*/
public static boolean isPresentInText(@Nullable String text) {
return text != null && PEM_HEADER.matcher(text).find() && PEM_FOOTER.matcher(text).find();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\pem\PemContent.java | 1 |
请完成以下Java代码 | public class DefaultTransportDeviceProfileCache implements TransportDeviceProfileCache {
private final Lock deviceProfileFetchLock = new ReentrantLock();
private final ConcurrentMap<DeviceProfileId, DeviceProfile> deviceProfiles = new ConcurrentHashMap<>();
private TransportService transportService;
@Lazy
@Autowired
public void setTransportService(TransportService transportService) {
this.transportService = transportService;
}
@Override
public DeviceProfile getOrCreate(DeviceProfileId id, TransportProtos.DeviceProfileProto proto) {
DeviceProfile profile = deviceProfiles.get(id);
if (profile == null) {
profile = ProtoUtils.fromProto(proto);
deviceProfiles.put(id, profile);
}
return profile;
}
@Override
public DeviceProfile get(DeviceProfileId id) {
return this.getDeviceProfile(id);
}
@Override
public void put(DeviceProfile profile) {
deviceProfiles.put(profile.getId(), profile);
}
@Override
public DeviceProfile put(TransportProtos.DeviceProfileProto proto) {
DeviceProfile deviceProfile = ProtoUtils.fromProto(proto); | put(deviceProfile);
return deviceProfile;
}
@Override
public void evict(DeviceProfileId id) {
deviceProfiles.remove(id);
}
private DeviceProfile getDeviceProfile(DeviceProfileId id) {
DeviceProfile profile = deviceProfiles.get(id);
if (profile == null) {
deviceProfileFetchLock.lock();
try {
TransportProtos.GetEntityProfileRequestMsg msg = TransportProtos.GetEntityProfileRequestMsg.newBuilder()
.setEntityType(EntityType.DEVICE_PROFILE.name())
.setEntityIdMSB(id.getId().getMostSignificantBits())
.setEntityIdLSB(id.getId().getLeastSignificantBits())
.build();
TransportProtos.GetEntityProfileResponseMsg entityProfileMsg = transportService.getEntityProfile(msg);
profile = ProtoUtils.fromProto(entityProfileMsg.getDeviceProfile());
this.put(profile);
} finally {
deviceProfileFetchLock.unlock();
}
}
return profile;
}
} | repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\service\DefaultTransportDeviceProfileCache.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getInfo1() {
return info1;
}
/**
* Sets the value of the info1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInfo1(String value) {
this.info1 = value;
}
/**
* Gets the value of the info2 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInfo2() {
return info2;
}
/**
* Sets the value of the info2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInfo2(String value) {
this.info2 = value;
}
/**
* Gets the value of the returns property.
*
* @return | * possible object is
* {@link Boolean }
*
*/
public Boolean isReturns() {
return returns;
}
/**
* Sets the value of the returns property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setReturns(Boolean value) {
this.returns = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Parcel.java | 2 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonIgnore
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobilephone() {
return mobilephone;
}
public void setMobilephone(String mobilephone) {
this.mobilephone = mobilephone;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
} | public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getDisabled() {
return disabled;
}
public void setDisabled(Integer disabled) {
this.disabled = disabled;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
} | repos\springBoot-master\springboot-swagger-ui\src\main\java\com\abel\example\bean\User.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.add("ddOrderLine", ddOrderLine)
.add("isASITo", isASITo)
.toString();
}
@Override
public I_M_Product getM_Product()
{
final IProductBL productBL = Services.get(IProductBL.class);
return productBL.getById(ProductId.ofRepoId(ddOrderLine.getM_Product_ID()));
}
@Override
public int getM_Product_ID()
{
return ddOrderLine.getM_Product_ID();
}
@Override
public I_M_AttributeSetInstance getM_AttributeSetInstance()
{
return isASITo ? ddOrderLine.getM_AttributeSetInstanceTo() : ddOrderLine.getM_AttributeSetInstance();
}
@Override
public int getM_AttributeSetInstance_ID()
{
return isASITo ? ddOrderLine.getM_AttributeSetInstanceTo_ID() : ddOrderLine.getM_AttributeSetInstance_ID();
} | @Override
public void setM_AttributeSetInstance(final I_M_AttributeSetInstance asi)
{
if (isASITo)
{
ddOrderLine.setM_AttributeSetInstanceTo(asi);
}
else
{
ddOrderLine.setM_AttributeSetInstance(asi);
}
}
@Override
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
if (isASITo)
{
ddOrderLine.setM_AttributeSetInstanceTo_ID(M_AttributeSetInstance_ID);
}
else
{
ddOrderLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\producer\DDOrderLineAttributeSetInstanceAware.java | 1 |
请完成以下Java代码 | public Stream<InventoryReference> streamReferences(InventoryQuery query)
{
final ImmutableList<I_M_Inventory> inventories = inventoryDAO.stream(query).collect(ImmutableList.toImmutableList());
return inventories.stream().map(this::toInventoryJobReference);
}
private InventoryReference toInventoryJobReference(final I_M_Inventory inventory)
{
return InventoryReference.builder()
.inventoryId(extractInventoryId(inventory))
.documentNo(inventory.getDocumentNo())
.movementDate(extractMovementDate(inventory))
.warehouseId(WarehouseId.ofRepoId(inventory.getM_Warehouse_ID()))
.responsibleId(extractResponsibleId(inventory))
.build();
} | public void updateByQuery(@NonNull final InventoryQuery query, @NonNull final UnaryOperator<Inventory> updater)
{
final ImmutableList<I_M_Inventory> inventoriesRecords = inventoryDAO.stream(query).collect(ImmutableList.toImmutableList());
if (inventoriesRecords.isEmpty()) {return;}
warmUp(inventoriesRecords);
for (final I_M_Inventory inventoryRecord : inventoriesRecords)
{
final Inventory inventory = toInventory(inventoryRecord);
final Inventory inventoryChanged = updater.apply(inventory);
if (!Objects.equals(inventory, inventoryChanged))
{
saveInventory(inventoryChanged);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryLoaderAndSaver.java | 1 |
请完成以下Java代码 | public void mergeTUs()
{
huTrxBL.createHUContextProcessorExecutor(huContextInitial).run((IHUContextProcessor)huContext0 -> {
// Make a copy of the processing context, we will need to modify it
final IMutableHUContext huContext = huContext0.copyAsMutable();
// Register our split HUTrxListener because this "merge" operation is similar with a split
// More, this will allow our listeners to execute on-split operations (e.g. linking the newly created VHU to same document as the source VHU).
huContext.getTrxListeners().addListener(HUSplitBuilderTrxListener.instance);
mergeTUs0(huContext);
return IHUContextProcessor.NULL_RESULT; // we don't care about the result
});
}
private void mergeTUs0(final IHUContext huContext)
{
final IAllocationRequest allocationRequest = createMergeAllocationRequest(huContext);
//
// Source: Selected handling units
final IAllocationSource source = HUListAllocationSourceDestination.of(sourceHUs);
//
// Destination: Handling unit we want to merge on
final IAllocationDestination destination = HUListAllocationSourceDestination.of(targetHU);
//
// Perform allocation
HULoader.of(source, destination)
.setAllowPartialUnloads(true) // force allow partial unloads when merging
.setAllowPartialLoads(true) // force allow partial loads when merging
.load(allocationRequest); // execute it; we don't care about the result
//
// Destroy HUs which had their storage emptied
for (final I_M_HU sourceHU : sourceHUs)
{
handlingUnitsBL.destroyIfEmptyStorage(huContext, sourceHU);
}
} | /**
* Create an allocation request for the cuQty of the builder
*
* @param huContext
* @param referencedModel referenced model to be used in created request
* @return created request
*/
private IAllocationRequest createMergeAllocationRequest(final IHUContext huContext)
{
final ZonedDateTime date = SystemTime.asZonedDateTime();
return AllocationUtils.createQtyRequest(
huContext,
cuProductId, // Product
Quantity.of(cuQty, cuUOM), // quantity
date, // Date
cuTrxReferencedModel, // Referenced model
false // force allocation
);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\TUMergeBuilder.java | 1 |
请完成以下Java代码 | private int deleteFactAcctSummary(final String where)
{
final String trxName = getContext().getTrxName();
// delete
final String sql = "DELETE FROM Fact_Acct_Summary fas " + where;
log.debug("Delete sql: " + sql);
final int deletedNo = DB.executeUpdateAndThrowExceptionOnFail(sql, trxName);
return deletedNo;
}
private List<String> getDimensionColumnNames(final I_PA_ReportCube paReportCube)
{
final List<String> values = new ArrayList<String>();
if (paReportCube.isProductDim())
values.add("M_Product_ID");
if (paReportCube.isBPartnerDim())
values.add("C_BPartner_ID");
if (paReportCube.isProjectDim())
values.add("C_Project_ID");
if (paReportCube.isOrgTrxDim())
values.add("AD_OrgTrx_ID");
if (paReportCube.isSalesRegionDim())
values.add("C_SalesRegion_ID");
if (paReportCube.isActivityDim())
values.add("C_Activity_ID");
if (paReportCube.isCampaignDim())
values.add("C_Campaign_ID");
if (paReportCube.isLocToDim())
values.add("C_LocTo_ID");
if (paReportCube.isLocFromDim()) | values.add("C_LocFrom_ID");
if (paReportCube.isUser1Dim())
values.add("User1_ID");
if (paReportCube.isUser2Dim())
values.add("User2_ID");
if (paReportCube.isUserElement1Dim())
values.add("UserElement1_ID");
if (paReportCube.isUserElement2Dim())
values.add("UserElement2_ID");
if (paReportCube.isSubAcctDim())
values.add("C_SubAcct_ID");
if (paReportCube.isProjectPhaseDim())
values.add("C_ProjectPhase_ID");
if (paReportCube.isProjectTaskDim())
values.add("C_ProjectTask_ID");
// --(CASE v.IsGL_Category_ID WHEN 'Y' THEN f."GL_Category_ID END) GL_Category_ID
return values;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\cube\impl\FactAcctCubeUpdater.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer("MProduct[");
sb.append(get_ID()).append("-").append(getValue()).append("_").append(getName())
.append("]");
return sb.toString();
} // toString
@Override
protected boolean beforeSave(boolean newRecord)
{
// Reset Stocked if not Item
// AZ Goodwill: Bug Fix isStocked always return false
// if (isStocked() && !PRODUCTTYPE_Item.equals(getProductType()))
if (!PRODUCTTYPE_Item.equals(getProductType()))
{
setIsStocked(false);
}
// UOM reset
if (m_precision != null && is_ValueChanged("C_UOM_ID"))
{
m_precision = null;
}
return true;
} // beforeSave
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
if (!success)
{
return success;
}
// Value/Name change in Account
if (!newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name")))
{
MAccount.updateValueDescription(getCtx(), "M_Product_ID=" + getM_Product_ID(), get_TrxName());
}
// Name/Description Change in Asset MAsset.setValueNameDescription
if (!newRecord && (is_ValueChanged("Name") || is_ValueChanged("Description")))
{
String sql = DB.convertSqlToNative("UPDATE A_Asset a "
+ "SET (Name, Description)="
+ "(SELECT SUBSTR((SELECT bp.Name FROM C_BPartner bp WHERE bp.C_BPartner_ID=a.C_BPartner_ID) || ' - ' || p.Name,1,60), p.Description "
+ "FROM M_Product p "
+ "WHERE p.M_Product_ID=a.M_Product_ID) "
+ "WHERE IsActive='Y'"
// + " AND GuaranteeDate > now()"
+ " AND M_Product_ID=" + getM_Product_ID());
int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName());
log.debug("Asset Description updated #" + no);
}
// New - Acct, Tree, Old Costing
if (newRecord)
{
if(!this.isCopying()) | {
insert_Accounting(I_M_Product_Acct.Table_Name,
I_M_Product_Category_Acct.Table_Name,
"p.M_Product_Category_ID=" + getM_Product_Category_ID());
}
else
{
log.info("This M_Product is created via CopyRecordSupport; -> don't insert the default _acct records");
}
insert_Tree(X_AD_Tree.TREETYPE_Product);
}
// Product category changed, then update the accounts
if (!newRecord && is_ValueChanged(I_M_Product.COLUMNNAME_M_Product_Category_ID))
{
update_Accounting(I_M_Product_Acct.Table_Name,
I_M_Product_Category_Acct.Table_Name,
"p.M_Product_Category_ID=" + getM_Product_Category_ID());
}
return true;
} // afterSave
@Override
protected boolean beforeDelete()
{
if (PRODUCTTYPE_Resource.equals(getProductType()) && getS_Resource_ID() > 0)
{
throw new AdempiereException("@S_Resource_ID@<>0");
}
//
return delete_Accounting("M_Product_Acct");
} // beforeDelete
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MProduct.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private final String name;
private final String email;
public User() {
this.name = "";
this.email = "";
}
public User(String name, String email) {
this.name = name;
this.email = email;
}
public long getId() {
return id; | }
public String getName() {
return name;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
return "User{" + "id=" + id + ", name=" + name + ", email=" + email + '}';
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\application\entities\User.java | 2 |
请完成以下Java代码 | public boolean isAttachmentStorable(@NonNull final AttachmentEntry attachmentEntry)
{
final StoreAttachmentServiceImpl service = extractFor(attachmentEntry);
if (service == null)
{
return false;
}
return service.isAttachmentStorable(attachmentEntry);
}
/**
* @return false if there is no StoreAttachmentService to take care of the given attachmentEntry.
*/
public boolean storeAttachment(@NonNull final AttachmentEntry attachmentEntry)
{
final ILoggable loggable = Loggables.withLogger(logger, Level.DEBUG);
final StoreAttachmentServiceImpl service = extractFor(attachmentEntry);
if (service == null)
{
loggable.addLog("StoreAttachmentService - no StoreAttachmentServiceImpl found for attachment={}", attachmentEntry);
return false;
}
final URI storageIdentifier = service.storeAttachment(attachmentEntry); | loggable.addLog("StoreAttachmentService - stored attachment to URI={}; storeAttachmentServiceImpl={}, attachment={}", storageIdentifier, service, attachmentEntry);
for (final AttachmentStoredListener attachmentStoredListener : attachmentStoredListeners)
{
attachmentStoredListener.attachmentWasStored(attachmentEntry, storageIdentifier);
}
return true;
}
private StoreAttachmentServiceImpl extractFor(@NonNull final AttachmentEntry attachmentEntry)
{
for (final StoreAttachmentServiceImpl storeAttachmentService : storeAttachmentServices)
{
if (storeAttachmentService.appliesTo(attachmentEntry))
{
return storeAttachmentService;
}
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\storeattachment\StoreAttachmentService.java | 1 |
请完成以下Java代码 | public int getM_PriceList_Version_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PriceList_Version_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Product Price Vendor Break.
@param M_ProductPriceVendorBreak_ID Product Price Vendor Break */
public void setM_ProductPriceVendorBreak_ID (int M_ProductPriceVendorBreak_ID)
{
if (M_ProductPriceVendorBreak_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ProductPriceVendorBreak_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ProductPriceVendorBreak_ID, Integer.valueOf(M_ProductPriceVendorBreak_ID));
}
/** Get Product Price Vendor Break.
@return Product Price Vendor Break */
public int getM_ProductPriceVendorBreak_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductPriceVendorBreak_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Limit Price.
@param PriceLimit
Lowest price for a product
*/
public void setPriceLimit (BigDecimal PriceLimit)
{
set_Value (COLUMNNAME_PriceLimit, PriceLimit);
}
/** Get Limit Price.
@return Lowest price for a product
*/
public BigDecimal getPriceLimit ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceLimit);
if (bd == null)
return Env.ZERO; | return bd;
}
/** Set List Price.
@param PriceList
List Price
*/
public void setPriceList (BigDecimal PriceList)
{
set_Value (COLUMNNAME_PriceList, PriceList);
}
/** Get List Price.
@return List Price
*/
public BigDecimal getPriceList ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceList);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Standard Price.
@param PriceStd
Standard Price
*/
public void setPriceStd (BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
/** Get Standard Price.
@return Standard Price
*/
public BigDecimal getPriceStd ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ProductPriceVendorBreak.java | 1 |
请完成以下Java代码 | public String getTenantId() {
return tenantId;
}
@Override
public Set<String> getVariableNames() {
return variables.keySet();
}
@Override
public Map<String, Object> getPlanItemInstanceLocalVariables() {
return localVariables;
}
@Override
public PlanItem getPlanItem() { | return planItem;
}
@Override
public String toString() {
return new StringJoiner(", ", getClass().getSimpleName() + "[", "]")
.add("id='" + id + "'")
.add("planItemDefinitionId='" + planItemDefinitionId + "'")
.add("elementId='" + elementId + "'")
.add("caseInstanceId='" + caseInstanceId + "'")
.add("caseDefinitionId='" + caseDefinitionId + "'")
.add("tenantId='" + tenantId + "'")
.toString();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delegate\ReadOnlyDelegatePlanItemInstanceImpl.java | 1 |
请完成以下Java代码 | protected String doIt()
{
patchEditableRow(createChangeRequest(getSingleSelectedRow()));
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
invalidateView();
}
private PricingConditionsRowChangeRequest createChangeRequest(@NonNull final PricingConditionsRow templateRow)
{
final PricingConditionsBreak templatePricingConditionsBreak = templateRow.getPricingConditionsBreak();
PriceSpecification price = templatePricingConditionsBreak.getPriceSpecification();
if (price.isNoPrice())
{
// In case row does not have a price then use BPartner's pricing system
final BPartnerId bpartnerId = templateRow.getBpartnerId();
final SOTrx soTrx = SOTrx.ofBoolean(templateRow.isCustomer());
price = createBasePricingSystemPrice(bpartnerId, soTrx);
}
final Percent discount = templatePricingConditionsBreak.getDiscount();
final PaymentTermId paymentTermIdOrNull = templatePricingConditionsBreak.getPaymentTermIdOrNull();
final Percent paymentDiscountOverrideOrNull = templatePricingConditionsBreak.getPaymentDiscountOverrideOrNull();
return PricingConditionsRowChangeRequest.builder()
.priceChange(CompletePriceChange.of(price)) | .discount(discount)
.paymentTermId(Optional.ofNullable(paymentTermIdOrNull))
.paymentDiscount(Optional.ofNullable(paymentDiscountOverrideOrNull))
.sourcePricingConditionsBreakId(templatePricingConditionsBreak.getId())
.build();
}
private PriceSpecification createBasePricingSystemPrice(final BPartnerId bpartnerId, final SOTrx soTrx)
{
final PricingSystemId pricingSystemId = bpartnersRepo.retrievePricingSystemIdOrNull(bpartnerId, soTrx);
if (pricingSystemId == null)
{
return PriceSpecification.none();
}
return PriceSpecification.basePricingSystem(pricingSystemId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\process\PricingConditionsView_CopyRowToEditable.java | 1 |
请完成以下Java代码 | private boolean isEligibleToBeDisplayed(final Event event)
{
final int loginUserId = Env.getAD_User_ID(getCtx());
return event.hasRecipient(loginUserId);
}
private NotificationItem toNotificationItem(final Event event)
{
//
// Build summary text
final String summaryTrl = msgBL.getMsg(getCtx(), MSG_Notification_Summary_Default, new Object[] { Adempiere.getName() });
final UserNotification notification = UserNotificationUtils.toUserNotification(event);
//
// Build detail message
final StringBuilder detailBuf = new StringBuilder();
{
// Add plain detail if any
final String detailPlain = notification.getDetailPlain();
if (!Check.isEmpty(detailPlain, true))
{
detailBuf.append(detailPlain.trim());
}
// Translate, parse and add detail (AD_Message).
final String detailADMessage = notification.getDetailADMessage();
if (!Check.isEmpty(detailADMessage, true)) | {
final String detailTrl = msgBL.getMsg(getCtx(), detailADMessage);
final String detailTrlParsed = EventHtmlMessageFormat.newInstance()
.setArguments(notification.getDetailADMessageParams())
.format(detailTrl);
if (!Check.isEmpty(detailTrlParsed, true))
{
if (detailBuf.length() > 0)
{
detailBuf.append("<br>");
}
detailBuf.append(detailTrlParsed);
}
}
}
return NotificationItem.builder()
.setSummary(summaryTrl)
.setDetail(detailBuf.toString())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\notifications\SwingEventNotifierFrame.java | 1 |
请完成以下Java代码 | public static FutureClearingAmountMap ofGLJournal(
@NonNull final SAPGLJournal glJournal,
@NonNull final CurrencyCodeToCurrencyIdBiConverter currencyCodeConverter)
{
return glJournal.getLines()
.stream()
.map(line -> extractFutureClearingAmount(line, currencyCodeConverter))
.filter(Objects::nonNull)
.collect(FutureClearingAmountMap.collect());
}
public static FutureClearingAmountMap ofList(final List<FutureClearingAmount> list)
{
return !list.isEmpty()
? new FutureClearingAmountMap(list)
: EMPTY;
}
public static Collector<FutureClearingAmount, ?, FutureClearingAmountMap> collect()
{
return GuavaCollectors.collectUsingListAccumulator(FutureClearingAmountMap::ofList);
}
@Nullable
@VisibleForTesting
static FutureClearingAmount extractFutureClearingAmount(
@NonNull final SAPGLJournalLine sapGLJournalLine,
@NonNull final CurrencyIdToCurrencyCodeConverter currencyCodeConverter)
{
final FAOpenItemTrxInfo openItemTrxInfo = sapGLJournalLine.getOpenItemTrxInfo();
if (openItemTrxInfo == null)
{
return null;
}
if (!openItemTrxInfo.isClearing())
{
return null; | }
final Amount amount = sapGLJournalLine.getAmount()
.negateIf(sapGLJournalLine.getPostingSign().isCredit())
.toAmount(currencyCodeConverter::getCurrencyCodeByCurrencyId);
return FutureClearingAmount.builder()
.key(openItemTrxInfo.getKey())
.amountSrc(amount)
.build();
}
public Optional<Amount> getAmountSrc(final FAOpenItemKey key) {return getByKey(key).map(FutureClearingAmount::getAmountSrc);}
@NonNull
private Optional<FutureClearingAmount> getByKey(final FAOpenItemKey key) {return Optional.ofNullable(byKey.get(key));}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\gljournal_sap\select_open_items\FutureClearingAmountMap.java | 1 |
请完成以下Java代码 | public boolean isDeferred() {
return deferred;
}
/**
* Expressions are compared using the concept of a <em>structural id</em>:
* variable and function names are anonymized such that two expressions with
* same tree structure will also have the same structural id and vice versa.
* Two value expressions are equal if
* <ol>
* <li>their structural id's are equal</li>
* <li>their bindings are equal</li>
* <li>their expected types are equal</li>
* </ol>
*/
@Override
public boolean equals(Object obj) {
if (obj != null && obj.getClass() == getClass()) {
TreeValueExpression other = (TreeValueExpression) obj;
if (!builder.equals(other.builder)) {
return false;
}
if (type != other.type) {
return false;
}
return (getStructuralId().equals(other.getStructuralId()) && bindings.equals(other.bindings));
}
return false;
}
@Override
public int hashCode() { | return getStructuralId().hashCode();
}
@Override
public String toString() {
return "TreeValueExpression(" + expr + ")";
}
/**
* Print the parse tree.
* @param writer
*/
public void dump(PrintWriter writer) {
NodePrinter.dump(writer, node);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
try {
node = builder.build(expr).getRoot();
} catch (ELException e) {
throw new IOException(e.getMessage());
}
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\TreeValueExpression.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TbRuleEngineProducerService {
private final PartitionService partitionService;
public void sendToRuleEngine(TbQueueProducer<TbProtoQueueMsg<ToRuleEngineMsg>> producer,
TenantId tenantId, TbMsg tbMsg, TbQueueCallback callback) {
List<TopicPartitionInfo> tpis = partitionService.resolveAll(ServiceType.TB_RULE_ENGINE, tbMsg.getQueueName(), tenantId, tbMsg.getOriginator());
if (tpis.size() > 1) {
UUID correlationId = UUID.randomUUID();
for (int i = 0; i < tpis.size(); i++) {
TopicPartitionInfo tpi = tpis.get(i);
Integer partition = tpi.getPartition().orElse(null);
UUID id = i > 0 ? UUID.randomUUID() : tbMsg.getId();
tbMsg = tbMsg.transform()
.id(id)
.correlationId(correlationId)
.partition(partition)
.build(); | sendToRuleEngine(producer, tpi, tenantId, tbMsg, i == tpis.size() - 1 ? callback : null);
}
} else {
sendToRuleEngine(producer, tpis.get(0), tenantId, tbMsg, callback);
}
}
private void sendToRuleEngine(TbQueueProducer<TbProtoQueueMsg<ToRuleEngineMsg>> producer, TopicPartitionInfo tpi,
TenantId tenantId, TbMsg tbMsg, TbQueueCallback callback) {
if (log.isTraceEnabled()) {
log.trace("[{}][{}] Pushing to topic {} message {}", tenantId, tbMsg.getOriginator(), tpi.getFullTopicName(), tbMsg);
}
ToRuleEngineMsg msg = ToRuleEngineMsg.newBuilder()
.setTbMsgProto(TbMsg.toProto(tbMsg))
.setTenantIdMSB(tenantId.getId().getMostSignificantBits())
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits()).build();
producer.send(tpi, new TbProtoQueueMsg<>(tbMsg.getId(), msg), callback);
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\common\TbRuleEngineProducerService.java | 2 |
请完成以下Java代码 | public Long getId() {
return this.id;
}
public String getText() {
return this.text;
}
public User getAuthor() {
return this.author;
}
public Post getPost() {
return this.post;
}
public void setId(Long id) {
this.id = id;
}
public void setText(String text) {
this.text = text;
}
public void setAuthor(User author) {
this.author = author;
} | public void setPost(Post post) {
this.post = post;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Comment comment = (Comment) o;
return Objects.equals(id, comment.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
public String toString() {
return "Comment(id=" + this.getId() + ", text=" + this.getText() + ", author=" + this.getAuthor() + ", post=" + this.getPost()
+ ")";
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-4\src\main\java\com\baeldung\listvsset\eager\list\fulldomain\Comment.java | 1 |
请完成以下Java代码 | public String getScore() {
if (gameContinues()) {
return getGameScore();
}
return "Win for " + leadingPlayer().name();
}
private String getGameScore() {
if (isScoreEqual()) {
return getEqualScore();
}
if (isAdvantage()) {
return "Advantage " + leadingPlayer().name();
}
return getSimpleScore();
}
private boolean isScoreEqual() {
return server.pointsDifference(receiver) == 0;
}
private boolean isAdvantage() {
return leadingPlayer().hasScoreBiggerThan(Score.FORTY)
&& Math.abs(server.pointsDifference(receiver)) == 1;
}
private boolean isGameFinished() {
return leadingPlayer().hasScoreBiggerThan(Score.FORTY)
&& Math.abs(server.pointsDifference(receiver)) >= 2;
} | private Player leadingPlayer() {
if (server.pointsDifference(receiver) > 0) {
return server;
}
return receiver;
}
private boolean gameContinues() {
return !isGameFinished();
}
private String getSimpleScore() {
return String.format("%s-%s", server.score(), receiver.score());
}
private String getEqualScore() {
if (server.hasScoreBiggerThan(Score.THIRTY)) {
return "Deuce";
}
return String.format("%s-All", server.score());
}
} | repos\tutorials-master\patterns-modules\clean-architecture\src\main\java\com\baeldung\pattern\richdomainmodel\TennisGame.java | 1 |
请完成以下Java代码 | public class PartyType {
@XmlAttribute(name = "ean_party", required = true)
protected String eanParty;
/**
* Gets the value of the eanParty property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEanParty() {
return eanParty; | }
/**
* Sets the value of the eanParty property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEanParty(String value) {
this.eanParty = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\PartyType.java | 1 |
请完成以下Java代码 | protected void handleInvocationInContext(final DelegateInvocation invocation) throws Exception {
CommandContext commandContext = Context.getCommandContext();
boolean wasAuthorizationCheckEnabled = commandContext.isAuthorizationCheckEnabled();
boolean wasUserOperationLogEnabled = commandContext.isUserOperationLogEnabled();
BaseDelegateExecution contextExecution = invocation.getContextExecution();
ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration();
boolean popExecutionContext = false;
try {
if (!configuration.isAuthorizationEnabledForCustomCode()) {
// the custom code should be executed without authorization
commandContext.disableAuthorizationCheck();
}
try {
commandContext.disableUserOperationLog();
try {
if (contextExecution != null && !isCurrentContextExecution(contextExecution)) {
popExecutionContext = setExecutionContext(contextExecution);
}
invocation.proceed();
}
finally {
if (popExecutionContext) {
Context.removeExecutionContext();
}
}
}
finally {
if (wasUserOperationLogEnabled) {
commandContext.enableUserOperationLog();
}
}
}
finally {
if (wasAuthorizationCheckEnabled) {
commandContext.enableAuthorizationCheck();
}
}
}
/**
* @return true if the execution context is modified by this invocation
*/
protected boolean setExecutionContext(BaseDelegateExecution execution) {
if (execution instanceof ExecutionEntity) {
Context.setExecutionContext((ExecutionEntity) execution);
return true;
} | else if (execution instanceof CaseExecutionEntity) {
Context.setExecutionContext((CaseExecutionEntity) execution);
return true;
}
return false;
}
protected boolean isCurrentContextExecution(BaseDelegateExecution execution) {
CoreExecutionContext<?> coreExecutionContext = Context.getCoreExecutionContext();
return coreExecutionContext != null && coreExecutionContext.getExecution() == execution;
}
protected ProcessApplicationReference getProcessApplicationForInvocation(final DelegateInvocation invocation) {
BaseDelegateExecution contextExecution = invocation.getContextExecution();
ResourceDefinitionEntity contextResource = invocation.getContextResource();
if (contextExecution != null) {
return ProcessApplicationContextUtil.getTargetProcessApplication((CoreExecution) contextExecution);
}
else if (contextResource != null) {
return ProcessApplicationContextUtil.getTargetProcessApplication(contextResource);
}
else {
return null;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\delegate\DefaultDelegateInterceptor.java | 1 |
请完成以下Java代码 | public class NoSuchSslBundleException extends RuntimeException {
private final String bundleName;
/**
* Create a new {@code SslBundleNotFoundException} instance.
* @param bundleName the name of the bundle that could not be found
* @param message the exception message
*/
public NoSuchSslBundleException(String bundleName, String message) {
this(bundleName, message, null);
}
/**
* Create a new {@code SslBundleNotFoundException} instance.
* @param bundleName the name of the bundle that could not be found
* @param message the exception message
* @param cause the exception cause | */
public NoSuchSslBundleException(String bundleName, String message, @Nullable Throwable cause) {
super(message, cause);
this.bundleName = bundleName;
}
/**
* Return the name of the bundle that was not found.
* @return the bundle name
*/
public String getBundleName() {
return this.bundleName;
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\NoSuchSslBundleException.java | 1 |
请完成以下Java代码 | public boolean loadPDF(final byte[] data)
{
return loadPDF(new ByteArrayInputStream(data));
}
public boolean loadPDF(final InputStream is)
{
if (tmpFile != null) {
tmpFile.delete();
}
try {
tmpFile = File.createTempFile("adempiere", ".pdf");
tmpFile.deleteOnExit();
} catch (IOException e) {
e.printStackTrace();
return false;
}
try {
final OutputStream os = new FileOutputStream(tmpFile);
try {
final byte[] buffer = new byte[32768];
for (int read; (read = is.read(buffer)) != -1; ) {
os.write(buffer, 0, read); | }
} catch (IOException e) {
e.printStackTrace();
} finally {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return loadPDF(tmpFile.getAbsolutePath());
}
@Override
protected void finalize() throws Throwable {
if (tmpFile != null) {
tmpFile.delete();
}
decoder.closePdfFile();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\pdf\viewer\PDFViewerBean.java | 1 |
请完成以下Java代码 | public void setAD_Table_ID (final int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, AD_Table_ID);
}
@Override
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public de.metas.async.model.I_C_Async_Batch getC_Async_Batch()
{
return get_ValueAsPO(COLUMNNAME_C_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class);
}
@Override
public void setC_Async_Batch(final de.metas.async.model.I_C_Async_Batch C_Async_Batch)
{
set_ValueFromPO(COLUMNNAME_C_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class, C_Async_Batch);
}
@Override
public void setC_Async_Batch_ID (final int C_Async_Batch_ID)
{
if (C_Async_Batch_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Async_Batch_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Async_Batch_ID, C_Async_Batch_ID);
}
@Override
public int getC_Async_Batch_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Async_Batch_ID);
}
@Override
public void setCountEnqueued (final int CountEnqueued)
{
set_ValueNoCheck (COLUMNNAME_CountEnqueued, CountEnqueued);
}
@Override
public int getCountEnqueued()
{
return get_ValueAsInt(COLUMNNAME_CountEnqueued);
}
@Override
public void setCountProcessed (final int CountProcessed)
{
set_ValueNoCheck (COLUMNNAME_CountProcessed, CountProcessed);
}
@Override | public int getCountProcessed()
{
return get_ValueAsInt(COLUMNNAME_CountProcessed);
}
@Override
public de.metas.async.model.I_C_Queue_PackageProcessor getC_Queue_PackageProcessor()
{
return get_ValueAsPO(COLUMNNAME_C_Queue_PackageProcessor_ID, de.metas.async.model.I_C_Queue_PackageProcessor.class);
}
@Override
public void setC_Queue_PackageProcessor(final de.metas.async.model.I_C_Queue_PackageProcessor C_Queue_PackageProcessor)
{
set_ValueFromPO(COLUMNNAME_C_Queue_PackageProcessor_ID, de.metas.async.model.I_C_Queue_PackageProcessor.class, C_Queue_PackageProcessor);
}
@Override
public void setC_Queue_PackageProcessor_ID (final int C_Queue_PackageProcessor_ID)
{
if (C_Queue_PackageProcessor_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Queue_PackageProcessor_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Queue_PackageProcessor_ID, C_Queue_PackageProcessor_ID);
}
@Override
public int getC_Queue_PackageProcessor_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Queue_PackageProcessor_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_RV_Async_batch_statistics.java | 1 |
请完成以下Java代码 | protected byte[] readBinaryContent(FileItemStream stream) {
InputStream inputStream = getInputStream(stream);
return IoUtil.readInputStream(inputStream, stream.getFieldName());
}
protected InputStream getInputStream(FileItemStream stream) {
try {
return stream.openStream();
} catch (IOException e) {
throw new RestException(Status.INTERNAL_SERVER_ERROR, e);
}
}
public String getFieldName() {
return fieldName;
}
public String getContentType() {
return contentType; | }
public String getTextContent() {
return textContent;
}
public byte[] getBinaryContent() {
return binaryContent;
}
public String getFileName() {
return fileName;
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\mapper\MultipartFormData.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HUAccessService
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final IProductBL productBL = Services.get(IProductBL.class);
private final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
private final IHUStatusBL huStatusBL = Services.get(IHUStatusBL.class);
public List<I_M_HU_Assignment> retrieveHuAssignments(@NonNull final Object model)
{
final TableRecordReference modelRef = TableRecordReference.of(model);
return queryBL.createQueryBuilder(I_M_HU_Assignment.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_HU_Assignment.COLUMNNAME_AD_Table_ID, modelRef.getAD_Table_ID())
.addEqualsFilter(I_M_HU_Assignment.COLUMNNAME_Record_ID, modelRef.getRecord_ID())
.orderBy()
.addColumn(I_M_HU_Assignment.COLUMN_M_HU_ID).endOrderBy()
.create()
.list();
}
public List<I_M_HU> retrieveVhus(@NonNull final HuId huId)
{
return handlingUnitsBL.getVHUs(huId);
}
public List<I_M_HU> retrieveVhus(@NonNull final I_M_HU hu)
{
return handlingUnitsBL.getVHUs(hu);
}
/**
* @return the {@code M_HU_ID} of the given {@code hu}'s topmost parent (or grandparent etc),
* <b>or</b>{@code -1} if the given {@code hu} is not "physical".
*/
public int retrieveTopLevelHuId(@NonNull final I_M_HU hu)
{
if (huStatusBL.isPhysicalHU(hu) || huStatusBL.isStatusShipped(hu))
{
return handlingUnitsBL.getTopLevelParent(hu).getM_HU_ID();
} | return -1;
}
public Optional<IPair<ProductId, Quantity>> retrieveProductAndQty(@NonNull final I_M_HU vhu)
{
final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory();
final IHUStorage vhuStorage = storageFactory.getStorage(vhu);
if (vhuStorage == null)
{
return Optional.empty();
}
final ProductId vhuProductId = vhuStorage.getSingleProductIdOrNull();
if (vhuProductId == null)
{
return Optional.empty();
}
final I_C_UOM stockingUOM = productBL.getStockUOM(vhuProductId);
final Quantity qty = vhuStorage.getQuantity(vhuProductId, stockingUOM);
return Optional.of(ImmutablePair.of(vhuProductId, qty));
}
public Optional<Quantity> retrieveProductQty(final HuId huId, final ProductId productId)
{
return retrieveProductAndQty(handlingUnitsBL.getById(huId))
.filter(productAndQty -> ProductId.equals(productAndQty.getLeft(), productId))
.map(IPair::getRight);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\trace\HUAccessService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String profileDisplay(Model model) {
String displayusername,displaypassword,displayemail,displayaddress;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ecommjava","root","");
PreparedStatement stmt = con.prepareStatement("select * from users where username = ?"+";");
String username = SecurityContextHolder.getContext().getAuthentication().getName();
stmt.setString(1, username);
ResultSet rst = stmt.executeQuery();
if(rst.next())
{
int userid = rst.getInt(1);
displayusername = rst.getString(2);
displayemail = rst.getString(3);
displaypassword = rst.getString(4);
displayaddress = rst.getString(5);
model.addAttribute("userid",userid);
model.addAttribute("username",displayusername);
model.addAttribute("email",displayemail);
model.addAttribute("password",displaypassword);
model.addAttribute("address",displayaddress);
}
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
System.out.println("Hello");
return "updateProfile";
}
@RequestMapping(value = "updateuser",method=RequestMethod.POST)
public String updateUserProfile(@RequestParam("userid") int userid,@RequestParam("username") String username, @RequestParam("email") String email, @RequestParam("password") String password, @RequestParam("address") String address)
{ | try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ecommjava","root","");
PreparedStatement pst = con.prepareStatement("update users set username= ?,email = ?,password= ?, address= ? where uid = ?;");
pst.setString(1, username);
pst.setString(2, email);
pst.setString(3, password);
pst.setString(4, address);
pst.setInt(5, userid);
int i = pst.executeUpdate();
Authentication newAuthentication = new UsernamePasswordAuthenticationToken(
username,
password,
SecurityContextHolder.getContext().getAuthentication().getAuthorities());
SecurityContextHolder.getContext().setAuthentication(newAuthentication);
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
return "redirect:index";
}
} | repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\controller\AdminController.java | 2 |
请完成以下Java代码 | public void setLieferscheinnummer(String value) {
this.lieferscheinnummer = value;
}
/**
* Gets the value of the pzn property.
*
*/
public long getPZN() {
return pzn;
}
/**
* Sets the value of the pzn property.
*
*/
public void setPZN(long value) {
this.pzn = value;
}
/**
* Gets the value of the retourenMenge property.
*
*/
public int getRetourenMenge() {
return retourenMenge;
}
/**
* Sets the value of the retourenMenge property.
*
*/
public void setRetourenMenge(int value) {
this.retourenMenge = value;
}
/**
* Gets the value of the retouregrund property.
*
* @return
* possible object is
* {@link RetoureGrund }
*
*/
public RetoureGrund getRetouregrund() {
return retouregrund;
}
/**
* Sets the value of the retouregrund property.
*
* @param value
* allowed object is
* {@link RetoureGrund }
*
*/
public void setRetouregrund(RetoureGrund value) { | this.retouregrund = value;
}
/**
* Gets the value of the charge property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCharge() {
return charge;
}
/**
* Sets the value of the charge property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCharge(String value) {
this.charge = value;
}
/**
* Gets the value of the verfalldatum property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getVerfalldatum() {
return verfalldatum;
}
/**
* Sets the value of the verfalldatum property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setVerfalldatum(XMLGregorianCalendar value) {
this.verfalldatum = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourePositionType.java | 1 |
请完成以下Java代码 | private void assertSameNotNullParentId(@NonNull final Collection<I_C_ElementValue> records)
{
if (records.isEmpty())
{
return;
}
ElementValueId commonParentId = null;
for (final I_C_ElementValue record : records)
{
final ElementValueId parentId = ElementValueId.ofRepoIdOrNull(record.getParent_ID());
if (parentId == null)
{
throw new AdempiereException("Element value has no parent set: " + record.getValue() + " (ID=" + record.getC_ElementValue_ID() + ")");
}
if (commonParentId == null)
{
commonParentId = parentId;
}
else if (!commonParentId.equals(parentId)) | {
throw new AdempiereException("Element values have different parents: " + records);
}
}
}
// TODO: introduce ChartOfAccountsId as parameter
public ImmutableSet<ElementValueId> getElementValueIdsBetween(final String accountValueFrom, final String accountValueTo)
{
final AccountValueComparisonMode comparisonMode = getAccountValueComparisonMode();
return elementValueRepository.getElementValueIdsBetween(accountValueFrom, accountValueTo, comparisonMode);
}
private AccountValueComparisonMode getAccountValueComparisonMode()
{
return AccountValueComparisonMode.ofNullableString(sysConfigBL.getValue(SYSCONFIG_AccountValueComparisonMode));
}
public ImmutableSet<ElementValueId> getOpenItemIds() {return elementValueRepository.getOpenItemIds();}
public IValidationRule isOpenItemRule() {return elementValueRepository.isOpenItemRule();}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\elementvalue\ElementValueService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof DataSource) {
logger.info(() -> "DataSource bean has been found: " + bean);
final ProxyFactory proxyFactory = new ProxyFactory(bean);
proxyFactory.setProxyTargetClass(true);
proxyFactory.addAdvice(new ProxyDataSourceInterceptor((DataSource) bean));
return proxyFactory.getProxy();
}
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
return bean;
}
private static class ProxyDataSourceInterceptor implements MethodInterceptor {
private final DataSource dataSource;
public ProxyDataSourceInterceptor(final DataSource dataSource) {
super();
SLF4JQueryLoggingListener listener = new SLF4JQueryLoggingListener() {
@Override
public void afterQuery(ExecutionInfo execInfo, List<QueryInfo> queryInfoList) {
// call query logging logic only when it took more than threshold
if (THRESHOLD_MILLIS <= execInfo.getElapsedTime()) {
logger.info("Slow SQL detected ...");
super.afterQuery(execInfo, queryInfoList);
}
}
};
listener.setLogLevel(SLF4JLogLevel.WARN); | this.dataSource = ProxyDataSourceBuilder.create(dataSource)
.name("DATA_SOURCE_PROXY")
.multiline()
.listener(listener)
.build();
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
final Method proxyMethod = ReflectionUtils.
findMethod(this.dataSource.getClass(),
invocation.getMethod().getName());
if (proxyMethod != null) {
return proxyMethod.invoke(this.dataSource, invocation.getArguments());
}
return invocation.proceed();
}
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootLogSlowQueries\src\main\java\com\bookstore\config\DatasourceProxyBeanPostProcessor.java | 2 |
请完成以下Java代码 | public class Role {
@Id @GeneratedValue
Long id;
private Collection<String> roles;
@StartNode
private Person person;
@EndNode
private Movie movie;
public Role() {
}
public Collection<String> getRoles() {
return roles;
}
public Person getPerson() {
return person;
} | public Movie getMovie() {
return movie;
}
public void setRoles(Collection<String> roles) {
this.roles = roles;
}
public void setPerson(Person person) {
this.person = person;
}
public void setMovie(Movie movie) {
this.movie = movie;
}
} | repos\tutorials-master\persistence-modules\neo4j\src\main\java\com\baeldung\neo4j\domain\Role.java | 1 |
请完成以下Java代码 | protected String getXMLElementName() {
return ELEMENT_EVENT_START;
}
@Override
protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception {
String formKey = xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_FORM_FORMKEY);
StartEvent startEvent = null;
if (
StringUtils.isNotEmpty(formKey) &&
model.getStartEventFormTypes() != null &&
model.getStartEventFormTypes().contains(formKey)
) {
startEvent = new AlfrescoStartEvent();
}
if (startEvent == null) {
startEvent = new StartEvent();
}
BpmnXMLUtil.addXMLLocation(startEvent, xtr);
startEvent.setInitiator(xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_EVENT_START_INITIATOR));
boolean interrupting = true;
String interruptingAttribute = xtr.getAttributeValue(null, ATTRIBUTE_EVENT_START_INTERRUPTING);
if (ATTRIBUTE_VALUE_FALSE.equalsIgnoreCase(interruptingAttribute)) {
interrupting = false;
}
startEvent.setInterrupting(interrupting);
startEvent.setFormKey(formKey);
parseChildElements(getXMLElementName(), startEvent, model, xtr);
return startEvent;
}
@Override
protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
StartEvent startEvent = (StartEvent) element; | writeQualifiedAttribute(ATTRIBUTE_EVENT_START_INITIATOR, startEvent.getInitiator(), xtw);
writeQualifiedAttribute(ATTRIBUTE_FORM_FORMKEY, startEvent.getFormKey(), xtw);
if (startEvent.getEventDefinitions() != null && startEvent.getEventDefinitions().size() > 0) {
writeDefaultAttribute(ATTRIBUTE_EVENT_START_INTERRUPTING, String.valueOf(startEvent.isInterrupting()), xtw);
}
}
@Override
protected boolean writeExtensionChildElements(
BaseElement element,
boolean didWriteExtensionStartElement,
XMLStreamWriter xtw
) throws Exception {
StartEvent startEvent = (StartEvent) element;
didWriteExtensionStartElement = writeFormProperties(startEvent, didWriteExtensionStartElement, xtw);
return didWriteExtensionStartElement;
}
@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
StartEvent startEvent = (StartEvent) element;
writeEventDefinitions(startEvent, startEvent.getEventDefinitions(), model, xtw);
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\StartEventXMLConverter.java | 1 |
请完成以下Java代码 | public static String getCurrentTelemetryKey(OtaPackageType type, OtaPackageKey key) {
return getTelemetryKey("current_", type, key);
}
private static String getTelemetryKey(String prefix, OtaPackageType type, OtaPackageKey key) {
return prefix + type.getKeyPrefix() + "_" + key.getValue();
}
public static String getTelemetryKey(OtaPackageType type, OtaPackageKey key) {
return type.getKeyPrefix() + "_" + key.getValue();
}
public static OtaPackageId getOtaPackageId(HasOtaPackage entity, OtaPackageType type) {
switch (type) {
case FIRMWARE:
return entity.getFirmwareId();
case SOFTWARE:
return entity.getSoftwareId(); | default:
log.warn("Unsupported ota package type: [{}]", type);
return null;
}
}
public static <T> T getByOtaPackageType(Supplier<T> firmwareSupplier, Supplier<T> softwareSupplier, OtaPackageType type) {
switch (type) {
case FIRMWARE:
return firmwareSupplier.get();
case SOFTWARE:
return softwareSupplier.get();
default:
throw new RuntimeException("Unsupported OtaPackage type: " + type);
}
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\ota\OtaPackageUtil.java | 1 |
请完成以下Java代码 | public IScriptExecutor createScriptExecutor(final IDatabase targetDatabase, final ScriptType scriptType)
{
final Class<? extends IScriptExecutor> scriptExecutorClass = getScriptExecutorClass(targetDatabase.getDbType(), scriptType);
if (scriptExecutorClass == null)
{
throw new ScriptException("No script executors found for " + scriptType)
.addParameter("Database", targetDatabase);
}
if (dryRunMode)
{
return new NullScriptExecutor(targetDatabase);
}
try
{
final IScriptExecutor executor = scriptExecutorClass.getConstructor(IDatabase.class).newInstance(targetDatabase);
return executor;
}
catch (final Exception e)
{
throw new ScriptException("Cannot instantiate executor class: " + scriptExecutorClass, e);
}
}
/**
* Enable/Disable dry run mode.
*
* If dry run mode is enabled then scripts won't be actually executed (i.e. {@link NullScriptExecutor} will be used)
*
* @param dryRunMode
*/
@Override
public void setDryRunMode(final boolean dryRunMode)
{
this.dryRunMode = dryRunMode; | }
/**
* @return true if dry run mode is enabled
* @see #setDryRunMode(boolean)
*/
@Override
public boolean isDryRunMode()
{
return dryRunMode;
}
@Value(staticConstructor = "of")
private static class ScriptExecutorKey
{
final String dbType;
final ScriptType scriptType;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\executor\impl\DefaultScriptExecutorFactory.java | 1 |
请完成以下Java代码 | protected final BigDecimal getQtyToSet()
{
BigDecimal qty;
if (_qtySet)
{
qty = _qty;
}
else
{
final IProductionMaterial productionMaterial = getProductionMaterial();
qty = productionMaterial.getQty();
}
return qty;
}
@Override
public final IQualityInspectionLineBuilder setNegateQty(final boolean negateQty)
{
_negateQty = negateQty;
return this;
}
protected final boolean isNegateQty()
{
return _negateQty;
}
@Override
public final IQualityInspectionLineBuilder setQtyProjected(final BigDecimal qtyProjected)
{
_qtyProjected = qtyProjected;
_qtyProjectedSet = true;
return this;
}
protected boolean isQtyProjectedSet()
{
return _qtyProjectedSet;
}
protected BigDecimal getQtyProjected()
{
return _qtyProjected;
}
@Override
public final IQualityInspectionLineBuilder setC_UOM(final I_C_UOM uom)
{
_uom = uom;
_uomSet = true;
return this;
}
protected final I_C_UOM getC_UOM()
{
if (_uomSet)
{
return _uom;
}
else
{
final IProductionMaterial productionMaterial = getProductionMaterial();
return productionMaterial.getC_UOM();
}
}
@Override
public final IQualityInspectionLineBuilder setPercentage(final BigDecimal percentage)
{
_percentage = percentage;
return this;
}
private BigDecimal getPercentage()
{
return _percentage;
}
@Override
public final IQualityInspectionLineBuilder setName(final String name) | {
_name = name;
return this;
}
protected final String getName()
{
return _name;
}
private IHandlingUnitsInfo getHandlingUnitsInfoToSet()
{
if (_handlingUnitsInfoSet)
{
return _handlingUnitsInfo;
}
return null;
}
@Override
public IQualityInspectionLineBuilder setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo)
{
_handlingUnitsInfo = handlingUnitsInfo;
_handlingUnitsInfoSet = true;
return this;
}
private IHandlingUnitsInfo getHandlingUnitsInfoProjectedToSet()
{
if (_handlingUnitsInfoProjectedSet)
{
return _handlingUnitsInfoProjected;
}
return null;
}
@Override
public IQualityInspectionLineBuilder setHandlingUnitsInfoProjected(final IHandlingUnitsInfo handlingUnitsInfo)
{
_handlingUnitsInfoProjected = handlingUnitsInfo;
_handlingUnitsInfoProjectedSet = true;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLineBuilder.java | 1 |
请完成以下Java代码 | public class ContractDiscount implements IPricingRule
{
private static final Logger logger = LogManager.getLogger(ContractDiscount.class);
@Override
public boolean applies(final IPricingContext pricingCtx, final IPricingResult result)
{
if (!result.isCalculated())
{
logger.debug("Cannot apply discount if the price was not calculated - {}", result);
return false;
}
if (result.isDisallowDiscount())
{
logger.debug("Discounts are not allowed [SKIP]");
return false;
}
final Object referencedObject = pricingCtx.getReferencedObject();
if (referencedObject == null)
{ | logger.debug("Not applying because pricingCtx has no referencedObject");
return false;
}
final I_C_Flatrate_Conditions conditions = ContractPricingUtil.getC_Flatrate_Conditions(referencedObject);
if (conditions == null)
{
logger.debug("Not applying because referencedObject='{}' has no C_Flatrate_Conditions", referencedObject);
return false;
}
return conditions.isFreeOfCharge();
}
@Override
public void calculate(final IPricingContext pricingCtx, final IPricingResult result)
{
result.setDiscount(Percent.ONE_HUNDRED);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\pricing\ContractDiscount.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void logUnconnectedRuntimeEnvironment(@NonNull Logger logger) {
if (logger.isInfoEnabled()) {
logger.info("No cluster was found; Spring Boot application is running in a [{}]"
+ " Cloud-managed Environment", getRuntimeEnvironmentName());
}
}
@Override
protected void configureTopology(@NonNull Environment environment,
@NonNull ConnectionEndpointList connectionEndpoints, int connectionCount) {
// do nothing!
}
}
public static class CloudFoundryClusterAvailableCondition extends AbstractCloudPlatformAvailableCondition {
protected static final String CLOUD_FOUNDRY_NAME = "CloudFoundry";
protected static final String RUNTIME_ENVIRONMENT_NAME = "VMware Tanzu GemFire for VMs";
@Override
protected String getCloudPlatformName() {
return CLOUD_FOUNDRY_NAME;
}
@Override
protected String getRuntimeEnvironmentName() {
return RUNTIME_ENVIRONMENT_NAME;
}
@Override
protected boolean isCloudPlatformActive(@NonNull Environment environment) {
return environment != null && CloudPlatform.CLOUD_FOUNDRY.isActive(environment);
}
}
public static class KubernetesClusterAvailableCondition extends AbstractCloudPlatformAvailableCondition {
protected static final String KUBERNETES_NAME = "Kubernetes";
protected static final String RUNTIME_ENVIRONMENT_NAME = "VMware Tanzu GemFire for K8S";
@Override
protected String getCloudPlatformName() {
return KUBERNETES_NAME;
}
@Override
protected String getRuntimeEnvironmentName() {
return RUNTIME_ENVIRONMENT_NAME;
}
@Override
protected boolean isCloudPlatformActive(@NonNull Environment environment) {
return environment != null && CloudPlatform.KUBERNETES.isActive(environment);
}
}
public static class StandaloneClusterAvailableCondition | extends ClusterAwareConfiguration.ClusterAwareCondition {
@Override
public synchronized boolean matches(@NonNull ConditionContext conditionContext,
@NonNull AnnotatedTypeMetadata typeMetadata) {
return isNotSupportedCloudPlatform(conditionContext)
&& super.matches(conditionContext, typeMetadata);
}
private boolean isNotSupportedCloudPlatform(@NonNull ConditionContext conditionContext) {
return conditionContext != null && isNotSupportedCloudPlatform(conditionContext.getEnvironment());
}
private boolean isNotSupportedCloudPlatform(@NonNull Environment environment) {
CloudPlatform activeCloudPlatform = environment != null
? CloudPlatform.getActive(environment)
: null;
return !isSupportedCloudPlatform(activeCloudPlatform);
}
private boolean isSupportedCloudPlatform(@NonNull CloudPlatform cloudPlatform) {
return cloudPlatform != null && SUPPORTED_CLOUD_PLATFORMS.contains(cloudPlatform);
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\ClusterAvailableConfiguration.java | 2 |
请完成以下Java代码 | public void delete(@NonNull final Document document)
{
trxManager.assertThreadInheritedTrxExists();
assertThisRepository(document.getEntityDescriptor());
DocumentPermissionsHelper.assertCanEdit(document, UserSession.getCurrentPermissions());
if (document.isNew())
{
throw new IllegalArgumentException("Cannot delete new document: " + document);
}
saveHandlers.delete(document);
}
@Override
public String retrieveVersion(final DocumentEntityDescriptor entityDescriptor, final int documentIdAsInt)
{
final SqlDocumentEntityDataBindingDescriptor binding = SqlDocumentEntityDataBindingDescriptor.cast(entityDescriptor.getDataBinding());
final String sql = binding.getSqlSelectVersionById()
.orElseThrow(() -> new AdempiereException("Versioning is not supported for " + entityDescriptor));
final Timestamp version = DB.getSQLValueTSEx(ITrx.TRXNAME_ThreadInherited, sql, documentIdAsInt);
return version == null ? VERSION_DEFAULT : String.valueOf(version.getTime());
}
@Override | public int retrieveLastLineNo(final DocumentQuery query)
{
logger.debug("Retrieving last LineNo: query={}", query);
final DocumentEntityDescriptor entityDescriptor = query.getEntityDescriptor();
assertThisRepository(entityDescriptor);
final SqlDocumentQueryBuilder sqlBuilder = SqlDocumentQueryBuilder.of(query);
final SqlAndParams sql = sqlBuilder.getSqlMaxLineNo();
return DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql.getSql(), sql.getSqlParams());
}
public boolean isReadonly(@NonNull final GridTabVO gridTabVO)
{
return saveHandlers.isReadonly(gridTabVO);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlDocumentsRepository.java | 1 |
请完成以下Java代码 | 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_M_RMA getRef_RMA() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Ref_RMA_ID, org.compiere.model.I_M_RMA.class);
}
@Override
public void setRef_RMA(org.compiere.model.I_M_RMA Ref_RMA)
{
set_ValueFromPO(COLUMNNAME_Ref_RMA_ID, org.compiere.model.I_M_RMA.class, Ref_RMA);
}
/** Set Referenced RMA.
@param Ref_RMA_ID Referenced RMA */
@Override
public void setRef_RMA_ID (int Ref_RMA_ID)
{
if (Ref_RMA_ID < 1)
set_Value (COLUMNNAME_Ref_RMA_ID, null);
else
set_Value (COLUMNNAME_Ref_RMA_ID, Integer.valueOf(Ref_RMA_ID));
}
/** Get Referenced RMA.
@return Referenced RMA */
@Override
public int getRef_RMA_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ref_RMA_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class); | }
@Override
public void setSalesRep(org.compiere.model.I_AD_User SalesRep)
{
set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep);
}
/** Set Vertriebsbeauftragter.
@param SalesRep_ID
Sales Representative or Company Agent
*/
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Vertriebsbeauftragter.
@return Sales Representative or Company Agent
*/
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_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_M_RMA.java | 1 |
请完成以下Java代码 | public class IoUtil {
public static byte[] readInputStream(InputStream inputStream, String inputStreamName) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[16 * 1024];
try {
int bytesRead = inputStream.read(buffer);
while (bytesRead != -1) {
outputStream.write(buffer, 0, bytesRead);
bytesRead = inputStream.read(buffer);
}
} catch (Exception e) {
throw new ActivitiException("couldn't read input stream " + inputStreamName, e);
}
return outputStream.toByteArray();
}
public static String readFileAsString(String filePath) {
byte[] buffer = new byte[(int) getFile(filePath).length()];
BufferedInputStream inputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(getFile(filePath)));
inputStream.read(buffer);
} catch (Exception e) {
throw new ActivitiException("Couldn't read file " + filePath + ": " + e.getMessage());
} finally {
IoUtil.closeSilently(inputStream);
}
return new String(buffer);
}
public static File getFile(String filePath) {
URL url = IoUtil.class.getClassLoader().getResource(filePath);
try {
return new File(url.toURI());
} catch (Exception e) {
throw new ActivitiException("Couldn't get file " + filePath + ": " + e.getMessage());
}
}
public static void writeStringToFile(String content, String filePath) { | BufferedOutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(getFile(filePath)));
outputStream.write(content.getBytes());
outputStream.flush();
} catch (Exception e) {
throw new ActivitiException("Couldn't write file " + filePath, e);
} finally {
IoUtil.closeSilently(outputStream);
}
}
/**
* Closes the given stream. The same as calling {@link InputStream#close()}, but errors while closing are silently ignored.
*/
public static void closeSilently(InputStream inputStream) {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ignore) {
// Exception is silently ignored
}
}
/**
* Closes the given stream. The same as calling {@link OutputStream#close()} , but errors while closing are silently ignored.
*/
public static void closeSilently(OutputStream outputStream) {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException ignore) {
// Exception is silently ignored
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\IoUtil.java | 1 |
请完成以下Java代码 | public void save(@NonNull final ReplenishInfo replenishInfo)
{
final I_M_Replenish replenishRecord = getRecordByIdentifier(replenishInfo.getIdentifier())
.orElseGet(() -> initNewRecord(replenishInfo.getIdentifier()));
final BigDecimal levelMin = replenishInfo.getMin().getStockQty().toBigDecimal();
final BigDecimal levelMax = replenishInfo.getMax().getStockQty().toBigDecimal();
replenishRecord.setLevel_Min(levelMin);
replenishRecord.setLevel_Max(levelMax.compareTo(levelMin) ==0 ? null : levelMax);
saveRecord(replenishRecord);
}
@NonNull
private I_M_Replenish initNewRecord(@NonNull final ReplenishInfo.Identifier identifier)
{
final I_M_Replenish replenishRecord = InterfaceWrapperHelper.newInstance(I_M_Replenish.class);
replenishRecord.setM_Product_ID(identifier.getProductId().getRepoId());
replenishRecord.setM_Warehouse_ID(identifier.getWarehouseId().getRepoId());
return replenishRecord;
} | @NonNull
private Optional<I_M_Replenish> getRecordByIdentifier(@NonNull final ReplenishInfo.Identifier identifier)
{
// if locator has been provided, give preference to replenish rules that are specific to that locator
final IQueryOrderBy locatorPreferenceOrderBy = queryBL.createQueryOrderByBuilder(I_M_Replenish.class)
.addColumn(I_M_Replenish.COLUMNNAME_M_Locator_ID, Ascending, identifier.getLocatorId() != null ? Last : First)
.createQueryOrderBy();
return queryBL.createQueryBuilder(I_M_Replenish.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_Replenish.COLUMNNAME_M_Product_ID, identifier.getProductId())
.addEqualsFilter(I_M_Replenish.COLUMNNAME_M_Warehouse_ID, identifier.getWarehouseId())
.addInArrayFilter(I_M_Replenish.COLUMNNAME_M_Locator_ID, identifier.getLocatorId(), null)
.create()
.setOrderBy(locatorPreferenceOrderBy)
.firstOnlyOptional(I_M_Replenish.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\material\replenish\ReplenishInfoRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Optional<String> getValue(@NonNull final String name, @NonNull final ClientAndOrgId clientAndOrgId)
{
final Optional<String> value = SpringContextHolder.instance.getProperty(name);
if (value.isPresent())
{
return value;
}
return getMap().getValueAsString(name, clientAndOrgId);
}
@Override
public List<String> retrieveNamesForPrefix(
@NonNull final String prefix,
@NonNull final ClientAndOrgId clientAndOrgId)
{
return getMap().getNamesForPrefix(prefix, clientAndOrgId);
}
private SysConfigMap getMap()
{
return cache.getOrLoad(0, this::retrieveMap);
}
private SysConfigMap retrieveMap()
{
final Stopwatch stopwatch = Stopwatch.createStarted();
final ImmutableListMultimap<String, SysConfigEntryValue> entryValuesByName = retrieveSysConfigEntryValues();
final ImmutableMap<String, SysConfigEntry> entiresByName = entryValuesByName.asMap()
.entrySet()
.stream()
.map(e -> SysConfigEntry.builder()
.name(e.getKey())
.entryValues(e.getValue())
.build())
.collect(ImmutableMap.toImmutableMap(
SysConfigEntry::getName,
entry -> entry
));
final SysConfigMap result = new SysConfigMap(entiresByName);
logger.info("Retrieved {} in {}", result, stopwatch.stop());
return result;
}
protected ImmutableListMultimap<String, SysConfigEntryValue> retrieveSysConfigEntryValues()
{ | final String sql = "SELECT Name, Value, AD_Client_ID, AD_Org_ID FROM AD_SysConfig"
+ " WHERE IsActive='Y'"
+ " ORDER BY Name, AD_Client_ID, AD_Org_ID";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
final ImmutableListMultimap.Builder<String, SysConfigEntryValue> resultBuilder = ImmutableListMultimap.builder();
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
rs = pstmt.executeQuery();
while (rs.next())
{
final String name = rs.getString("Name");
final String value = rs.getString("Value");
final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(
ClientId.ofRepoId(rs.getInt("AD_Client_ID")),
OrgId.ofRepoId(rs.getInt("AD_Org_ID")));
final SysConfigEntryValue entryValue = SysConfigEntryValue.of(value, clientAndOrgId);
resultBuilder.put(name, entryValue);
}
return resultBuilder.build();
}
catch (final SQLException ex)
{
throw new DBException(ex, sql);
}
finally
{
DB.close(rs, pstmt);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\SysConfigDAO.java | 2 |
请完成以下Java代码 | public ExecutionQueryImpl orderByProcessDefinitionKey() {
orderBy(new QueryOrderingProperty(QueryOrderingProperty.RELATION_PROCESS_DEFINITION, ExecutionQueryProperty.PROCESS_DEFINITION_KEY));
return this;
}
public ExecutionQuery orderByTenantId() {
orderBy(ExecutionQueryProperty.TENANT_ID);
return this;
}
//results ////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
ensureVariablesInitialized();
return commandContext
.getExecutionManager()
.findExecutionCountByQueryCriteria(this);
}
@Override
@SuppressWarnings("unchecked")
public List<Execution> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
ensureVariablesInitialized();
return (List) commandContext
.getExecutionManager()
.findExecutionsByQueryCriteria(this, page);
}
//getters ////////////////////////////////////////////////////
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getActivityId() {
return activityId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessInstanceIds() {
return null;
}
public String getBusinessKey() {
return businessKey;
} | public String getExecutionId() {
return executionId;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(SuspensionState suspensionState) {
this.suspensionState = suspensionState;
}
public List<EventSubscriptionQueryValue> getEventSubscriptions() {
return eventSubscriptions;
}
public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) {
this.eventSubscriptions = eventSubscriptions;
}
public String getIncidentId() {
return incidentId;
}
public String getIncidentType() {
return incidentType;
}
public String getIncidentMessage() {
return incidentMessage;
}
public String getIncidentMessageLike() {
return incidentMessageLike;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExecutionQueryImpl.java | 1 |
请完成以下Java代码 | public IntentEventListenerInstanceQuery caseDefinitionId(String caseDefinitionId) {
innerQuery.caseDefinitionId(caseDefinitionId);
return this;
}
@Override
public IntentEventListenerInstanceQuery elementId(String elementId) {
innerQuery.planItemInstanceElementId(elementId);
return this;
}
@Override
public IntentEventListenerInstanceQuery planItemDefinitionId(String planItemDefinitionId) {
innerQuery.planItemDefinitionId(planItemDefinitionId);
return this;
}
@Override
public IntentEventListenerInstanceQuery name(String name) {
innerQuery.planItemInstanceName(name);
return this;
}
@Override
public IntentEventListenerInstanceQuery stageInstanceId(String stageInstanceId) {
innerQuery.stageInstanceId(stageInstanceId);
return this;
}
@Override
public IntentEventListenerInstanceQuery stateAvailable() {
innerQuery.planItemInstanceStateAvailable();
return this;
}
@Override
public IntentEventListenerInstanceQuery stateSuspended() {
innerQuery.planItemInstanceState(PlanItemInstanceState.SUSPENDED);
return this;
}
@Override
public IntentEventListenerInstanceQuery orderByName() {
innerQuery.orderByName();
return this;
}
@Override
public IntentEventListenerInstanceQuery asc() {
innerQuery.asc();
return this;
}
@Override
public IntentEventListenerInstanceQuery desc() {
innerQuery.desc();
return this;
} | @Override
public IntentEventListenerInstanceQuery orderBy(QueryProperty property) {
innerQuery.orderBy(property);
return this;
}
@Override
public IntentEventListenerInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) {
innerQuery.orderBy(property, nullHandlingOnOrder);
return this;
}
@Override
public long count() {
return innerQuery.count();
}
@Override
public IntentEventListenerInstance singleResult() {
PlanItemInstance instance = innerQuery.singleResult();
return IntentEventListenerInstanceImpl.fromPlanItemInstance(instance);
}
@Override
public List<IntentEventListenerInstance> list() {
return convertPlanItemInstances(innerQuery.list());
}
@Override
public List<IntentEventListenerInstance> listPage(int firstResult, int maxResults) {
return convertPlanItemInstances(innerQuery.listPage(firstResult, maxResults));
}
protected List<IntentEventListenerInstance> convertPlanItemInstances(List<PlanItemInstance> instances) {
if (instances == null) {
return null;
}
return instances.stream().map(IntentEventListenerInstanceImpl::fromPlanItemInstance).collect(Collectors.toList());
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\IntentEventListenerInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public void reportAdded(ObjectType objectType) {
getObjectGauge(objectType).incrementAndGet();
}
@Override
public void reportRemoved(ObjectType objectType) {
getObjectGauge(objectType).decrementAndGet();
}
@Override
public void reportEntityDataQuery(TenantId tenantId, EntityDataQuery query, long timingNanos) {
checkTiming(tenantId, query, timingNanos);
getTimer("entityDataQueryTimer").record(timingNanos, TimeUnit.NANOSECONDS);
}
@Override
public void reportEntityCountQuery(TenantId tenantId, EntityCountQuery query, long timingNanos) {
checkTiming(tenantId, query, timingNanos);
getTimer("entityCountQueryTimer").record(timingNanos, TimeUnit.NANOSECONDS);
}
@Override
public void reportEdqsDataQuery(TenantId tenantId, EntityDataQuery query, long timingNanos) {
checkTiming(tenantId, query, timingNanos);
getTimer("edqsDataQueryTimer").record(timingNanos, TimeUnit.NANOSECONDS);
}
@Override
public void reportEdqsCountQuery(TenantId tenantId, EntityCountQuery query, long timingNanos) {
checkTiming(tenantId, query, timingNanos);
getTimer("edqsCountQueryTimer").record(timingNanos, TimeUnit.NANOSECONDS);
}
@Override
public void reportStringCompressed() {
getCounter("stringsCompressed").increment();
}
@Override
public void reportStringUncompressed() {
getCounter("stringsUncompressed").increment();
} | private void checkTiming(TenantId tenantId, EntityCountQuery query, long timingNanos) {
double timingMs = timingNanos / 1000_000.0;
String queryType = query instanceof EntityDataQuery ? "data" : "count";
if (timingMs < slowQueryThreshold) {
log.debug("[{}] Executed " + queryType + " query in {} ms: {}", tenantId, timingMs, query);
} else {
log.warn("[{}] Executed slow " + queryType + " query in {} ms: {}", tenantId, timingMs, query);
}
}
private StatsTimer getTimer(String name) {
return timers.computeIfAbsent(name, __ -> statsFactory.createStatsTimer("edqsTimers", name));
}
private StatsCounter getCounter(String name) {
return counters.computeIfAbsent(name, __ -> statsFactory.createStatsCounter("edqsCounters", name));
}
private AtomicInteger getObjectGauge(ObjectType objectType) {
return objectCounters.computeIfAbsent(objectType, type ->
statsFactory.createGauge("edqsGauges", "objectsCount", new AtomicInteger(), "objectType", type.name()));
}
} | repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\stats\DefaultEdqsStatsService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PriorityChannel alphabetically() {
return new PriorityChannel(1000, (left, right) -> ((File) left.getPayload()).getName()
.compareTo(((File) right.getPayload()).getName()));
}
// @Bean
public IntegrationFlow fileMoverWithPriorityChannel() {
return IntegrationFlow.from(sourceDirectory())
.filter(onlyJpgs())
.channel("alphabetically")
.handle(targetDirectory())
.get();
}
@Bean
public MessageHandler anotherTargetDirectory() {
FileWritingMessageHandler handler = new FileWritingMessageHandler(new File(OUTPUT_DIR2));
handler.setExpectReply(false); // end of pipeline, reply not needed
return handler;
}
@Bean
public MessageChannel holdingTank() {
return MessageChannels.queue().get();
}
// @Bean
public IntegrationFlow fileReader() {
return IntegrationFlow.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10)))
.filter(onlyJpgs())
.channel("holdingTank")
.get();
}
// @Bean
public IntegrationFlow fileWriter() {
return IntegrationFlow.from("holdingTank")
.bridge(e -> e.poller(Pollers.fixedRate(Duration.of(1, TimeUnit.SECONDS.toChronoUnit()), Duration.of(20, TimeUnit.SECONDS.toChronoUnit()))))
.handle(targetDirectory())
.get();
} | // @Bean
public IntegrationFlow anotherFileWriter() {
return IntegrationFlow.from("holdingTank")
.bridge(e -> e.poller(Pollers.fixedRate(Duration.of(2, TimeUnit.SECONDS.toChronoUnit()), Duration.of(10, TimeUnit.SECONDS.toChronoUnit()))))
.handle(anotherTargetDirectory())
.get();
}
public static void main(final String... args) {
final AbstractApplicationContext context = new AnnotationConfigApplicationContext(JavaDSLFileCopyConfig.class);
context.registerShutdownHook();
final Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a string and press <enter>: ");
while (true) {
final String input = scanner.nextLine();
if ("q".equals(input.trim())) {
context.close();
scanner.close();
break;
}
}
System.exit(0);
}
} | repos\tutorials-master\spring-integration\src\main\java\com\baeldung\dsl\JavaDSLFileCopyConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ShipmentDeclarationId implements RepoIdAware
{
@JsonCreator
public static ShipmentDeclarationId ofRepoId(final int repoId)
{
return new ShipmentDeclarationId(repoId);
}
public static ShipmentDeclarationId ofRepoIdOrNull(@Nullable final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
int repoId;
private ShipmentDeclarationId(final int repoId) | {
this.repoId = Check.assumeGreaterThanZero(repoId, "M_Shipment_Declaration_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static int toRepoId(final ShipmentDeclarationId id)
{
return id != null ? id.getRepoId() : -1;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipment\ShipmentDeclarationId.java | 2 |
请完成以下Java代码 | public Map<Class<?>, String> getBulkDeleteStatements() {
return bulkDeleteStatements;
}
public void setBulkDeleteStatements(Map<Class<?>, String> bulkDeleteStatements) {
this.bulkDeleteStatements = bulkDeleteStatements;
}
public Map<Class<?>, String> getSelectStatements() {
return selectStatements;
}
public void setSelectStatements(Map<Class<?>, String> selectStatements) {
this.selectStatements = selectStatements;
}
public boolean isDbHistoryUsed() {
return isDbHistoryUsed;
}
public void setDbHistoryUsed(boolean isDbHistoryUsed) {
this.isDbHistoryUsed = isDbHistoryUsed;
}
public void setDatabaseTablePrefix(String databaseTablePrefix) {
this.databaseTablePrefix = databaseTablePrefix;
}
public String getDatabaseTablePrefix() {
return databaseTablePrefix;
} | public String getDatabaseCatalog() {
return databaseCatalog;
}
public void setDatabaseCatalog(String databaseCatalog) {
this.databaseCatalog = databaseCatalog;
}
public String getDatabaseSchema() {
return databaseSchema;
}
public void setDatabaseSchema(String databaseSchema) {
this.databaseSchema = databaseSchema;
}
public void setTablePrefixIsSchema(boolean tablePrefixIsSchema) {
this.tablePrefixIsSchema = tablePrefixIsSchema;
}
public boolean isTablePrefixIsSchema() {
return tablePrefixIsSchema;
}
public int getMaxNrOfStatementsInBulkInsert() {
return maxNrOfStatementsInBulkInsert;
}
public void setMaxNrOfStatementsInBulkInsert(int maxNrOfStatementsInBulkInsert) {
this.maxNrOfStatementsInBulkInsert = maxNrOfStatementsInBulkInsert;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\DbSqlSessionFactory.java | 1 |
请完成以下Java代码 | public void setSendEMail (final boolean SendEMail)
{
set_Value (COLUMNNAME_SendEMail, SendEMail);
}
@Override
public boolean isSendEMail()
{
return get_ValueAsBoolean(COLUMNNAME_SendEMail);
}
@Override
public org.compiere.model.I_C_ElementValue getUser1()
{
return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser1(final org.compiere.model.I_C_ElementValue User1)
{
set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1);
}
@Override
public void setUser1_ID (final int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, User1_ID);
}
@Override
public int getUser1_ID()
{
return get_ValueAsInt(COLUMNNAME_User1_ID);
}
@Override
public org.compiere.model.I_C_ElementValue getUser2()
{
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser2(final org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
@Override
public void setUser2_ID (final int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, User2_ID);
}
@Override
public int getUser2_ID()
{
return get_ValueAsInt(COLUMNNAME_User2_ID);
}
@Override
public void setVolume (final @Nullable BigDecimal Volume)
{ | set_Value (COLUMNNAME_Volume, Volume);
}
@Override
public BigDecimal getVolume()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Volume);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWeight (final @Nullable BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
@Override
public BigDecimal getWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOut.java | 1 |
请完成以下Java代码 | public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Exam other = (Exam) obj;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id)) | return false;
if (shortText == null) {
if (other.shortText != null)
return false;
} else if (!shortText.equals(other.shortText))
return false;
if (text == null) {
if (other.text != null)
return false;
} else if (!text.equals(other.text))
return false;
return true;
}
} | repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\text\Exam.java | 1 |
请完成以下Java代码 | public static final class VarBuilder extends Builder<VarBuilder> {
private VarBuilder(String name) {
super(name, false);
}
/**
* Sets no value.
* @return the property declaration
*/
public KotlinPropertyDeclaration empty() {
return new KotlinPropertyDeclaration(this);
}
@Override
protected VarBuilder self() {
return this;
}
}
/**
* Builder for a property accessor.
*
* @param <T> the type of builder
*/
public static final class AccessorBuilder<T extends Builder<T>> {
private final AnnotationContainer annotations = new AnnotationContainer();
private CodeBlock code;
private final T parent;
private final Consumer<Accessor> accessorFunction;
private AccessorBuilder(T parent, Consumer<Accessor> accessorFunction) {
this.parent = parent;
this.accessorFunction = accessorFunction;
}
/**
* Adds an annotation.
* @param className the class name of the annotation
* @return this for method chaining
*/
public AccessorBuilder<?> withAnnotation(ClassName className) {
return withAnnotation(className, null);
}
/**
* Adds an annotation.
* @param className the class name of the annotation
* @param annotation configurer for the annotation
* @return this for method chaining
*/
public AccessorBuilder<?> withAnnotation(ClassName className, Consumer<Annotation.Builder> annotation) {
this.annotations.addSingle(className, annotation);
return this;
}
/**
* Sets the body.
* @param code the code for the body
* @return this for method chaining
*/
public AccessorBuilder<?> withBody(CodeBlock code) {
this.code = code; | return this;
}
/**
* Builds the accessor.
* @return the parent getter / setter
*/
public T buildAccessor() {
this.accessorFunction.accept(new Accessor(this));
return this.parent;
}
}
static final class Accessor implements Annotatable {
private final AnnotationContainer annotations;
private final CodeBlock code;
Accessor(AccessorBuilder<?> builder) {
this.annotations = builder.annotations.deepCopy();
this.code = builder.code;
}
CodeBlock getCode() {
return this.code;
}
@Override
public AnnotationContainer annotations() {
return this.annotations;
}
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\kotlin\KotlinPropertyDeclaration.java | 1 |
请完成以下Java代码 | public boolean isAutoInvoice(@NonNull final JsonOLCandCreateRequest request, @NonNull final BPartnerId bpartnerId)
{
if (request.getIsAutoInvoice() != null)
{
return request.getIsAutoInvoice();
}
return bPartnerEffectiveBL.getById(bpartnerId).isAutoInvoice(SOTrx.SALES);
}
@Nullable
public Incoterms getIncoterms(@NonNull final JsonOLCandCreateRequest request,
@NonNull final OrgId orgId,
@NonNull final BPartnerId bPartnerId)
{
final Incoterms incoterms;
if(request.getIncotermsValue() != null) | {
incoterms = incotermsRepository.getByValue(request.getIncotermsValue(), orgId);
}
else
{
incoterms = bPartnerEffectiveBL.getById(bPartnerId).getIncoterms(SOTrx.SALES);
}
if(incoterms == null)
{
return null;
}
return StringUtils.trimBlankToNull(request.getIncotermsLocation()) == null ? incoterms
: incoterms.withLocationEffective(request.getIncotermsLocation());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\bpartner\BPartnerMasterdataProvider.java | 1 |
请完成以下Java代码 | public void setExternalSystem(final de.metas.externalsystem.model.I_ExternalSystem ExternalSystem)
{
set_ValueFromPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class, ExternalSystem);
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
@Override
public void setName (final java.lang.String Name)
{ | set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setWriteAudit (final boolean WriteAudit)
{
set_Value (COLUMNNAME_WriteAudit, WriteAudit);
}
@Override
public boolean isWriteAudit()
{
return get_ValueAsBoolean(COLUMNNAME_WriteAudit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EntityViewDataValidator extends DataValidator<EntityView> {
private final EntityViewDao entityViewDao;
private final TenantService tenantService;
private final CustomerDao customerDao;
@Override
protected void validateCreate(TenantId tenantId, EntityView entityView) {
entityViewDao.findEntityViewByTenantIdAndName(entityView.getTenantId().getId(), entityView.getName())
.ifPresent(e -> {
throw new DataValidationException("Entity view with such name already exists!");
});
}
@Override
protected EntityView validateUpdate(TenantId tenantId, EntityView entityView) {
var opt = entityViewDao.findEntityViewByTenantIdAndName(entityView.getTenantId().getId(), entityView.getName());
opt.ifPresent(e -> {
if (!e.getUuidId().equals(entityView.getUuidId())) {
throw new DataValidationException("Entity view with such name already exists!");
}
});
return opt.orElse(null);
}
@Override | protected void validateDataImpl(TenantId tenantId, EntityView entityView) {
validateString("Entity view name", entityView.getName());
validateString("Entity view type", entityView.getType());
if (entityView.getTenantId() == null) {
throw new DataValidationException("Entity view should be assigned to tenant!");
} else {
if (!tenantService.tenantExists(entityView.getTenantId())) {
throw new DataValidationException("Entity view is referencing to non-existent tenant!");
}
}
if (entityView.getCustomerId() == null) {
entityView.setCustomerId(new CustomerId(NULL_UUID));
} else if (!entityView.getCustomerId().getId().equals(NULL_UUID)) {
Customer customer = customerDao.findById(tenantId, entityView.getCustomerId().getId());
if (customer == null) {
throw new DataValidationException("Can't assign entity view to non-existent customer!");
}
if (!customer.getTenantId().getId().equals(entityView.getTenantId().getId())) {
throw new DataValidationException("Can't assign entity view to customer from different tenant!");
}
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\EntityViewDataValidator.java | 2 |
请完成以下Java代码 | public AdElementId getADElementIdByColumnNameOrNull(@NonNull final String columnName)
{
return queryADElementByColumnName(columnName)
.create()
.firstIdOnly(AdElementId::ofRepoIdOrNull);
}
private IQueryBuilder<I_AD_Element> queryADElementByColumnName(@NonNull final String columnName)
{
return Services.get(IQueryBL.class).createQueryBuilder(I_AD_Element.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_Element.COLUMNNAME_ColumnName, columnName, UpperCaseQueryFilterModifier.instance);
}
@Override
public void makeElementMandatoryInApplicationDictionaryTables()
{
make_AD_Element_Mandatory_In_AD_Tab();
make_AD_Element_Mandatory_In_AD_Window();
make_AD_Element_Mandatory_In_AD_Menu();
}
private void make_AD_Element_Mandatory_In_AD_Menu()
{
final I_AD_Column elementIdColumn = Services.get(IADTableDAO.class).retrieveColumn(I_AD_Menu.Table_Name, I_AD_Menu.COLUMNNAME_AD_Element_ID);
makeElementColumnMandatory(elementIdColumn);
}
private void make_AD_Element_Mandatory_In_AD_Window()
{
final I_AD_Column elementIdColumn = Services.get(IADTableDAO.class).retrieveColumn(I_AD_Window.Table_Name, I_AD_Window.COLUMNNAME_AD_Element_ID);
makeElementColumnMandatory(elementIdColumn);
} | private void make_AD_Element_Mandatory_In_AD_Tab()
{
final I_AD_Column elementIdColumn = Services.get(IADTableDAO.class).retrieveColumn(I_AD_Tab.Table_Name, I_AD_Tab.COLUMNNAME_AD_Element_ID);
makeElementColumnMandatory(elementIdColumn);
}
private void makeElementColumnMandatory(final I_AD_Column elementIdColumn)
{
elementIdColumn.setIsMandatory(true);
save(elementIdColumn);
final TableDDLSyncService syncService = SpringContextHolder.instance.getBean(TableDDLSyncService.class);
syncService.syncToDatabase(AdColumnId.ofRepoId(elementIdColumn.getAD_Column_ID()));
}
@Override
public I_AD_Element getById(final int elementId)
{
return loadOutOfTrx(elementId, I_AD_Element.class);
}
@Override
public AdElementId createNewElement(@NonNull final CreateADElementRequest request)
{
final I_AD_Element record = newInstance(I_AD_Element.class);
record.setName(request.getName());
record.setPrintName(request.getPrintName());
record.setDescription(request.getDescription());
record.setHelp(request.getHelp());
record.setCommitWarning(request.getTabCommitWarning());
saveRecord(record);
return AdElementId.ofRepoId(record.getAD_Element_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\element\api\impl\ADElementDAO.java | 1 |
请完成以下Java代码 | public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return !(user.getId() == null || getId() == null) && Objects.equals(getId(), user.getId());
} | @Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\domain\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/logout").permitAll()
.antMatchers("/images/**").permitAll()
.antMatchers("/js/**").permitAll()
.antMatchers("/css/**").permitAll()
.antMatchers("/fonts/**").permitAll()
.antMatchers("/favicon.ico").permitAll()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry)
.and()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(urlUserService).passwordEncoder(new PasswordEncoder() {
@Override | public String encode(CharSequence rawPassword) {
return MD5Util.encode((String) rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encodedPassword.equals(MD5Util.encode((String) rawPassword));
}
});
}
@Bean
public SessionRegistry getSessionRegistry(){
SessionRegistry sessionRegistry=new SessionRegistryImpl();
return sessionRegistry;
}
} | repos\springBoot-master\springboot-springSecurity4\src\main\java\com\yy\example\config\WebSecurityConfig.java | 2 |
请完成以下Java代码 | public void valueChanged (ListSelectionEvent e)
{
if (e.getValueIsAdjusting())
return;
ListItem selected = null;
try
{ // throws a ArrayIndexOutOfBoundsException if root is selected
selected = (ListItem)centerList.getSelectedValue();
}
catch (Exception ex)
{
}
log.info("Selected=" + selected);
if (selected != null) // allow add if not in tree
bAdd.setEnabled(!centerTree.setTreeSelectionPath(selected.id));
} // valueChanged
/**
* VTreePanel Changed
* @param e event
*/
@Override
public void propertyChange (PropertyChangeEvent e)
{
MTreeNode tn = (MTreeNode)e.getNewValue();
log.info(tn.toString());
if (tn == null)
return;
ListModel model = centerList.getModel();
int size = model.getSize();
int index = -1;
for (index = 0; index < size; index++)
{
ListItem item = (ListItem)model.getElementAt(index);
if (item.id == tn.getNode_ID())
break;
}
centerList.setSelectedIndex(index);
} // propertyChange
/**
* Action: Add Node to Tree
* @param item item
*/
private void action_treeAdd(ListItem item)
{
log.info("Item=" + item);
if (item != null)
{
MTreeNode info = new MTreeNode(item.id, 0, item.name, item.description, -1,
item.isSummary, item.imageIndicator, false, null);
centerTree.nodeChanged(true, info);
// May cause Error if in tree
addNode(item);
}
} // action_treeAdd
/**
* Action: Delete Node from Tree
* @param item item
*/
private void action_treeDelete(ListItem item)
{
log.info("Item=" + item);
if (item != null)
{
MTreeNode info = new MTreeNode(item.id, 0, item.name, item.description, -1,
item.isSummary, item.imageIndicator, false, null);
centerTree.nodeChanged(false, info);
deleteNode(item); | }
} // action_treeDelete
/**
* Action: Add All Nodes to Tree
*/
private void action_treeAddAll()
{
log.info("");
ListModel model = centerList.getModel();
int size = model.getSize();
int index = -1;
for (index = 0; index < size; index++)
{
ListItem item = (ListItem)model.getElementAt(index);
action_treeAdd(item);
}
} // action_treeAddAll
/**
* Action: Delete All Nodes from Tree
*/
private void action_treeDeleteAll()
{
log.info("");
ListModel model = centerList.getModel();
int size = model.getSize();
int index = -1;
for (index = 0; index < size; index++)
{
ListItem item = (ListItem)model.getElementAt(index);
action_treeDelete(item);
}
} // action_treeDeleteAll
} // VTreeMaintenance | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\VTreeMaintenance.java | 1 |
请完成以下Spring Boot application配置 | spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource | .password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver | repos\spring-boot-leaning-master\2.x_42_courses\第 3-1 课: Spring Boot 使用 JDBC 操作数据库\spring-boot-jdbc\src\main\resources\application.properties | 2 |
请完成以下Java代码 | private static String timeToString(@Nullable final LocalTime time)
{
if (time == null)
{
return "";
}
return time.format(TIME_FORMATTER);
}
private static String intToString(@NonNull final Optional<Integer> integer)
{
if (integer.isPresent())
{
return Integer.toString(integer.get());
}
return "";
}
private static String intToString(@Nullable final Integer integer)
{
if (integer == null)
{
return "";
}
return Integer.toString(integer); | }
private static String bigDecimalToString(@Nullable final BigDecimal bigDecimal)
{
if (bigDecimal == null)
{
return "";
}
return bigDecimal.toString();
}
private static String stringToString(@NonNull final Optional<String> string)
{
if (string.isPresent())
{
return string.get();
}
return "";
}
private String truncateCheckDigitFromParcelNo(@NonNull final String parcelNumber)
{
return StringUtils.trunc(parcelNumber, 11, TruncateAt.STRING_END);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\misc\Converters.java | 1 |
请完成以下Java代码 | public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getText() {
return this.text;
}
public void setText(String text) {
this.text = text; | }
public String getSummary() {
return this.summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
@Override
public String toString() {
return "Message{" +
"id=" + id +
", text='" + text + '\'' +
", summary='" + summary + '\'' +
", createDate=" + createDate +
'}';
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-9 课:Spring Boot 中使用 Swagger2 构建 RESTful APIs\spring-boot-swagger\src\main\java\com\neo\model\Message.java | 1 |
请完成以下Java代码 | private static HUQRCodePackingInfo fromJson(@NonNull final JsonHUQRCodePackingInfoV1 json)
{
return HUQRCodePackingInfo.builder()
.huUnitType(json.getHuUnitType())
.packingInstructionsId(json.getPackingInstructionsId())
.caption(json.getCaption())
.build();
}
private static JsonHUQRCodeProductInfoV1 toJson(@NonNull final HUQRCodeProductInfo product)
{
return JsonHUQRCodeProductInfoV1.builder()
.id(product.getId())
.code(product.getCode())
.name(product.getName())
.build();
}
private static HUQRCodeProductInfo fromJson(@Nullable final JsonHUQRCodeProductInfoV1 json)
{
if (json == null)
{
return null;
}
return HUQRCodeProductInfo.builder()
.id(json.getId())
.code(json.getCode())
.name(json.getName())
.build();
}
private static JsonHUQRCodeAttributeV1 toJson(@NonNull final HUQRCodeAttribute attribute)
{
return JsonHUQRCodeAttributeV1.builder()
.code(attribute.getCode()) | .displayName(attribute.getDisplayName())
.value(attribute.getValue())
// NOTE: in order to make the generated JSON shorter,
// we will set valueRendered only if it's different from value.
.valueRendered(
!Objects.equals(attribute.getValue(), attribute.getValueRendered())
? attribute.getValueRendered()
: null)
.build();
}
private static HUQRCodeAttribute fromJson(@NonNull final JsonHUQRCodeAttributeV1 json)
{
return HUQRCodeAttribute.builder()
.code(json.getCode())
.displayName(json.getDisplayName())
.value(json.getValue())
.valueRendered(json.getValueRendered())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\json\v1\JsonConverterV1.java | 1 |
请完成以下Java代码 | public static void connectBeforeSubscribe() throws InterruptedException {
ConnectableObservable obs = getObservable().doOnNext(x -> LOGGER.info("saving " + x)).publish();
LOGGER.info("connecting:");
Subscription s = obs.connect();
Thread.sleep(1000);
LOGGER.info("subscribing #1");
obs.subscribe((i) -> LOGGER.info("subscriber#1 is printing x-coordinate " + i));
Thread.sleep(1000);
LOGGER.info("subscribing #2");
obs.subscribe((i) -> LOGGER.info("subscriber#2 is printing x-coordinate " + i));
Thread.sleep(1000);
s.unsubscribe();
}
public static void autoConnectAndSubscribe() throws InterruptedException {
Observable obs = getObservable().doOnNext(x -> LOGGER.info("saving " + x)).publish().autoConnect();
LOGGER.info("autoconnect()");
Thread.sleep(1000);
LOGGER.info("subscribing #1");
Subscription s1 = obs.subscribe((i) -> LOGGER.info("subscriber#1 is printing x-coordinate " + i));
Thread.sleep(1000);
LOGGER.info("subscribing #2");
Subscription s2 = obs.subscribe((i) -> LOGGER.info("subscriber#2 is printing x-coordinate " + i));
Thread.sleep(1000);
LOGGER.info("unsubscribe 1");
s1.unsubscribe();
Thread.sleep(1000);
LOGGER.info("unsubscribe 2");
s2.unsubscribe();
}
public static void refCountAndSubscribe() throws InterruptedException {
Observable obs = getObservable().doOnNext(x -> LOGGER.info("saving " + x)).publish().refCount();
LOGGER.info("refcount()");
Thread.sleep(1000);
LOGGER.info("subscribing #1");
Subscription subscription1 = obs.subscribe((i) -> LOGGER.info("subscriber#1 is printing x-coordinate " + i));
Thread.sleep(1000);
LOGGER.info("subscribing #2");
Subscription subscription2 = obs.subscribe((i) -> LOGGER.info("subscriber#2 is printing x-coordinate " + i));
Thread.sleep(1000); | LOGGER.info("unsubscribe#1");
subscription1.unsubscribe();
Thread.sleep(1000);
LOGGER.info("unsubscribe#2");
subscription2.unsubscribe();
}
private static Observable getObservable() {
return Observable.create(subscriber -> {
frame.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
subscriber.onNext(e.getX());
}
});
subscriber.add(Subscriptions.create(() -> {
LOGGER.info("Clear resources");
for (MouseListener listener : frame.getListeners(MouseListener.class)) {
frame.removeMouseListener(listener);
}
}));
});
}
} | repos\tutorials-master\rxjava-modules\rxjava-observables\src\main\java\com\baeldung\rxjava\MultipleSubscribersHotObs.java | 1 |
请完成以下Java代码 | public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
} | public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "Address [id=" + id + ", addressLine1=" + addressLine1 + ", addressLine2=" + addressLine2 + ", city=" + city + "]";
}
} | repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\ebean\model\Address.java | 1 |
请完成以下Java代码 | public String getPrvcOfBirth() {
return prvcOfBirth;
}
/**
* Sets the value of the prvcOfBirth property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPrvcOfBirth(String value) {
this.prvcOfBirth = value;
}
/**
* Gets the value of the cityOfBirth property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCityOfBirth() {
return cityOfBirth;
}
/**
* Sets the value of the cityOfBirth property.
*
* @param value
* allowed object is
* {@link String } | *
*/
public void setCityOfBirth(String value) {
this.cityOfBirth = value;
}
/**
* Gets the value of the ctryOfBirth property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCtryOfBirth() {
return ctryOfBirth;
}
/**
* Sets the value of the ctryOfBirth property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCtryOfBirth(String value) {
this.ctryOfBirth = 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\DateAndPlaceOfBirth.java | 1 |
请完成以下Java代码 | public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() { | return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<Address> getAddressList() {
return addressList;
}
public void setAddressList(List<Address> addressList) {
this.addressList = addressList;
}
} | repos\tutorials-master\persistence-modules\hibernate-jpa\src\main\java\com\baeldung\hibernate\pessimisticlocking\Customer.java | 1 |
请完成以下Java代码 | public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand)
{
set_ValueNoCheck (COLUMNNAME_QtyOnHand, QtyOnHand);
}
@Override
public BigDecimal getQtyOnHand()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOrdered (final @Nullable BigDecimal QtyOrdered)
{
set_ValueNoCheck (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO; | }
@Override
public void setQtyReserved (final @Nullable BigDecimal QtyReserved)
{
set_ValueNoCheck (COLUMNNAME_QtyReserved, QtyReserved);
}
@Override
public BigDecimal getQtyReserved()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_RV_M_HU_Storage_InvoiceHistory.java | 1 |
请完成以下Java代码 | public void abort(final WFProcessId wfProcessId, final UserId callerId)
{
jobService.abort(wfProcessId, callerId);
}
@Override
public void abortAll(final UserId callerId)
{
jobService.abortAll(callerId);
}
@Override
public void logout(final @NonNull UserId userId)
{
abortAll(userId);
}
@Override
public WFProcess getWFProcessById(final WFProcessId wfProcessId)
{
final Inventory inventory = jobService.getById(toInventoryId(wfProcessId));
return toWFProcess(inventory);
}
@Override
public WFProcessHeaderProperties getHeaderProperties(final @NonNull WFProcess wfProcess)
{
final WarehousesLoadingCache warehouses = warehouseService.newLoadingCache();
final Inventory inventory = getInventory(wfProcess);
return WFProcessHeaderProperties.builder()
.entry(WFProcessHeaderProperty.builder()
.caption(TranslatableStrings.adElementOrMessage("DocumentNo"))
.value(inventory.getDocumentNo())
.build())
.entry(WFProcessHeaderProperty.builder()
.caption(TranslatableStrings.adElementOrMessage("MovementDate"))
.value(TranslatableStrings.date(inventory.getMovementDate().toLocalDate()))
.build())
.entry(WFProcessHeaderProperty.builder()
.caption(TranslatableStrings.adElementOrMessage("M_Warehouse_ID"))
.value(inventory.getWarehouseId() != null | ? warehouses.getById(inventory.getWarehouseId()).getWarehouseName()
: "")
.build())
.build();
}
@NonNull
public static Inventory getInventory(final @NonNull WFProcess wfProcess)
{
return wfProcess.getDocumentAs(Inventory.class);
}
public static WFProcess mapJob(@NonNull final WFProcess wfProcess, @NonNull final UnaryOperator<Inventory> mapper)
{
final Inventory inventory = getInventory(wfProcess);
final Inventory inventoryChanged = mapper.apply(inventory);
return !Objects.equals(inventory, inventoryChanged) ? toWFProcess(inventoryChanged) : wfProcess;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\InventoryMobileApplication.java | 1 |
请完成以下Java代码 | private Object normalizeValue(final Object value, final ModelType model, final AggregationItem aggregationItem)
{
final int displayType = aggregationItem.getDisplayType();
if (DisplayType.isID(displayType))
{
final Integer valueInt = (Integer)value;
if (valueInt == null)
{
return 0;
}
else if (valueInt <= 0)
{
return 0;
}
else
{
return valueInt;
}
}
else if (displayType == DisplayType.Date)
{
return value == null ? null : dateFormat.format(value);
}
else if (displayType == DisplayType.Time)
{
return value == null ? null : timeFormat.format(value);
}
else if (displayType == DisplayType.DateTime)
{
return value == null ? null : dateTimeFormat.format(value); | }
else if (DisplayType.isText(displayType))
{
return value == null ? 0 : toHashcode(value.toString());
}
else if (displayType == DisplayType.YesNo)
{
return DisplayType.toBooleanNonNull(value, false);
}
else
{
return value;
}
}
private static int toHashcode(final String s)
{
if (Check.isEmpty(s, true))
{
return 0;
}
return s.hashCode();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\api\impl\GenericAggregationKeyBuilder.java | 1 |
请完成以下Java代码 | public Capacity getCapacity(
@NonNull final I_M_HU_Item huItem,
final I_M_Product product,
final I_C_UOM uom,
final ZonedDateTime date)
{
final ProductId productId = ProductId.ofRepoIdOrNull(product != null ? product.getM_Product_ID() : -1);
return getCapacity(huItem, productId, uom, date);
}
@Override
public boolean isInfiniteCapacity(final I_M_HU_PI_Item_Product itemDefProduct)
{
return itemDefProduct.isInfiniteCapacity();
}
@Override
public boolean isValidItemProduct(final I_M_HU_PI_Item_Product itemDefProduct)
{ | Check.assumeNotNull(itemDefProduct, "Error: Null record");
// item which allows any product should have infinite capacity and no product assigned
if (itemDefProduct.isAllowAnyProduct() && (itemDefProduct.getM_Product_ID() > 0 || !isInfiniteCapacity(itemDefProduct)))
{
return false;
}
if (isInfiniteCapacity(itemDefProduct))
{
// Infinite capacity item product -> valid
return true;
}
// If it's not infinite capacity, quantity must be > 0
return itemDefProduct.getQty().signum() > 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUCapacityBL.java | 1 |
请完成以下Java代码 | public int getC_LicenseFeeSettings_ID()
{
return get_ValueAsInt(COLUMNNAME_C_LicenseFeeSettings_ID);
}
@Override
public void setCommission_Product_ID (final int Commission_Product_ID)
{
if (Commission_Product_ID < 1)
set_Value (COLUMNNAME_Commission_Product_ID, null);
else
set_Value (COLUMNNAME_Commission_Product_ID, Commission_Product_ID);
}
@Override
public int getCommission_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_Commission_Product_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setName (final java.lang.String Name) | {
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPointsPrecision (final int PointsPrecision)
{
set_Value (COLUMNNAME_PointsPrecision, PointsPrecision);
}
@Override
public int getPointsPrecision()
{
return get_ValueAsInt(COLUMNNAME_PointsPrecision);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_LicenseFeeSettings.java | 1 |
请完成以下Java代码 | public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public void setIsCreateWarningOnTarget (final boolean IsCreateWarningOnTarget)
{
set_Value (COLUMNNAME_IsCreateWarningOnTarget, IsCreateWarningOnTarget);
}
@Override
public boolean isCreateWarningOnTarget()
{
return get_ValueAsBoolean(COLUMNNAME_IsCreateWarningOnTarget);
}
@Override
public void setIsDebug (final boolean IsDebug)
{
set_Value (COLUMNNAME_IsDebug, IsDebug);
}
@Override
public boolean isDebug()
{
return get_ValueAsBoolean(COLUMNNAME_IsDebug);
}
@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);
}
/**
* Severity AD_Reference_ID=541949
* Reference name: Severity
*/
public static final int SEVERITY_AD_Reference_ID=541949;
/** Notice = N */
public static final String SEVERITY_Notice = "N";
/** Error = E */
public static final String SEVERITY_Error = "E";
@Override
public void setSeverity (final java.lang.String Severity)
{
set_Value (COLUMNNAME_Severity, Severity);
}
@Override
public java.lang.String getSeverity()
{
return get_ValueAsString(COLUMNNAME_Severity);
}
@Override
public org.compiere.model.I_AD_Val_Rule getValidation_Rule()
{
return get_ValueAsPO(COLUMNNAME_Validation_Rule_ID, org.compiere.model.I_AD_Val_Rule.class);
} | @Override
public void setValidation_Rule(final org.compiere.model.I_AD_Val_Rule Validation_Rule)
{
set_ValueFromPO(COLUMNNAME_Validation_Rule_ID, org.compiere.model.I_AD_Val_Rule.class, Validation_Rule);
}
@Override
public void setValidation_Rule_ID (final int Validation_Rule_ID)
{
if (Validation_Rule_ID < 1)
set_Value (COLUMNNAME_Validation_Rule_ID, null);
else
set_Value (COLUMNNAME_Validation_Rule_ID, Validation_Rule_ID);
}
@Override
public int getValidation_Rule_ID()
{
return get_ValueAsInt(COLUMNNAME_Validation_Rule_ID);
}
@Override
public void setWarning_Message_ID (final int Warning_Message_ID)
{
if (Warning_Message_ID < 1)
set_Value (COLUMNNAME_Warning_Message_ID, null);
else
set_Value (COLUMNNAME_Warning_Message_ID, Warning_Message_ID);
}
@Override
public int getWarning_Message_ID()
{
return get_ValueAsInt(COLUMNNAME_Warning_Message_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule.java | 1 |
请完成以下Java代码 | public void setBeanResolver(BeanResolver beanResolver) {
this.beanResolver = beanResolver;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
/**
* Configure AuthenticationPrincipal template resolution
* <p>
* By default, this value is <code>null</code>, which indicates that templates should
* not be resolved.
* @param templateDefaults - whether to resolve AuthenticationPrincipal templates
* parameters
* @since 6.4
*/
public void setTemplateDefaults(AnnotationTemplateExpressionDefaults templateDefaults) {
this.scanner = SecurityAnnotationScanners.requireUnique(AuthenticationPrincipal.class, templateDefaults);
this.useAnnotationTemplate = templateDefaults != null;
} | /**
* Obtains the specified {@link Annotation} on the specified {@link MethodParameter}.
* {@link MethodParameter}
* @param parameter the {@link MethodParameter} to search for an {@link Annotation}
* @return the {@link Annotation} that was found or null.
*/
@SuppressWarnings("unchecked")
private @Nullable AuthenticationPrincipal findMethodAnnotation(MethodParameter parameter) {
if (this.useAnnotationTemplate) {
return this.scanner.scan(parameter.getParameter());
}
AuthenticationPrincipal annotation = parameter.getParameterAnnotation(this.annotationType);
if (annotation != null) {
return annotation;
}
Annotation[] annotationsToSearch = parameter.getParameterAnnotations();
for (Annotation toSearch : annotationsToSearch) {
annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), this.annotationType);
if (annotation != null) {
return MergedAnnotations.from(toSearch).get(this.annotationType).synthesize();
}
}
return null;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\method\annotation\AuthenticationPrincipalArgumentResolver.java | 1 |
请完成以下Java代码 | public int getC_Location_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Location_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name); | }
/** Set Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_C_Allotment.java | 1 |
请完成以下Java代码 | final class CostCollectorCandidateFinishedGoodsHUProducer extends AbstractPPOrderReceiptHUProducer
{
private final transient IHUPPOrderBL huPPOrderBL = Services.get(IHUPPOrderBL.class);
private final I_PP_Order ppOrder;
private final ProductId productId;
public CostCollectorCandidateFinishedGoodsHUProducer(final org.eevolution.model.I_PP_Order ppOrder)
{
super(PPOrderId.ofRepoId(ppOrder.getPP_Order_ID()));
// TODO: validate:
// * if is a completed PP_Order
this.ppOrder = InterfaceWrapperHelper.create(ppOrder, I_PP_Order.class);
productId = ProductId.ofRepoId(ppOrder.getM_Product_ID());
}
private I_PP_Order getPP_Order()
{
return ppOrder;
}
@Override
protected ProductId getProductId()
{
return productId;
}
@Override
protected Object getAllocationRequestReferencedModel()
{
return getPP_Order();
}
@Override
protected IAllocationSource createAllocationSource()
{
final I_PP_Order ppOrder = getPP_Order();
return huPPOrderBL.createAllocationSourceForPPOrder(ppOrder);
}
@Override
protected IDocumentLUTUConfigurationManager createReceiptLUTUConfigurationManager()
{
final I_PP_Order ppOrder = getPP_Order();
return huPPOrderBL.createReceiptLUTUConfigurationManager(ppOrder);
}
@Override
protected ReceiptCandidateRequestProducer newReceiptCandidateRequestProducer() | {
final I_PP_Order order = getPP_Order();
final PPOrderId orderId = PPOrderId.ofRepoId(order.getPP_Order_ID());
final OrgId orgId = OrgId.ofRepoId(order.getAD_Org_ID());
return ReceiptCandidateRequestProducer.builder()
.orderId(orderId)
.orgId(orgId)
.date(getMovementDate())
.locatorId(getLocatorId())
.pickingCandidateId(getPickingCandidateId())
.build();
}
@Override
protected void addAssignedHUs(final Collection<I_M_HU> hus)
{
final I_PP_Order ppOrder = getPP_Order();
huPPOrderBL.addAssignedHandlingUnits(ppOrder, hus);
}
@Override
public IPPOrderReceiptHUProducer withPPOrderLocatorId()
{
return locatorId(LocatorId.ofRepoId(ppOrder.getM_Warehouse_ID(), ppOrder.getM_Locator_ID()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\CostCollectorCandidateFinishedGoodsHUProducer.java | 1 |
请完成以下Java代码 | public void setWeight (final @Nullable BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
@Override
public BigDecimal getWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWeight_UOM_ID (final int Weight_UOM_ID)
{
if (Weight_UOM_ID < 1)
set_Value (COLUMNNAME_Weight_UOM_ID, null);
else
set_Value (COLUMNNAME_Weight_UOM_ID, Weight_UOM_ID);
} | @Override
public int getWeight_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_Weight_UOM_ID);
}
@Override
public void setWidthInCm (final int WidthInCm)
{
set_Value (COLUMNNAME_WidthInCm, WidthInCm);
}
@Override
public int getWidthInCm()
{
return get_ValueAsInt(COLUMNNAME_WidthInCm);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product.java | 1 |
请完成以下Java代码 | public static void main(String[] args) throws IOException
{
if (args.length < 1) usage();
new Distance(args[0]).execute();
}
protected Result getTargetVector()
{
final int words = vectorsReader.getNumWords();
final int size = vectorsReader.getSize();
String[] input = null;
while ((input = nextWords(1, "Enter a word")) != null)
{
// linear search the input word in vocabulary
float[] vec = null;
int bi = -1;
double len = 0;
for (int i = 0; i < words; i++)
{
if (input[0].equals(vectorsReader.getWord(i)))
{
bi = i;
System.out.printf("\nWord: %s Position in vocabulary: %d\n", input[0], bi);
vec = new float[size];
for (int j = 0; j < size; j++)
{
vec[j] = vectorsReader.getMatrixElement(bi, j);
len += vec[j] * vec[j];
}
}
}
if (vec == null)
{
System.out.printf("%s : Out of dictionary word!\n", input[0]); | continue;
}
len = Math.sqrt(len);
for (int i = 0; i < size; i++)
{
vec[i] /= len;
}
return new Result(vec, new int[]{bi});
}
return null;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Distance.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8761 # 设置 Eureka-Server 的端口
spring:
application:
name: eureka-server
eureka:
client:
register-with-eureka: false # 不注册到 Eureka-Serve | r,默认为 true
fetch-registry: false # 不从 Eureka-Server 获取注册表,默认为 true | repos\SpringBoot-Labs-master\labx-22\labx-22-scn-eureka-server-standalone\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public OrderLineBuilder manualDiscount(final BigDecimal manualDiscount)
{
assertNotBuilt();
this.manualDiscount = manualDiscount;
return this;
}
public OrderLineBuilder setDimension(final Dimension dimension)
{
assertNotBuilt();
this.dimension = dimension;
return this;
}
public boolean isProductAndUomMatching(@Nullable final ProductId productId, @Nullable final UomId uomId)
{
return ProductId.equals(getProductId(), productId)
&& UomId.equals(getUomId(), uomId);
}
public OrderLineBuilder description(@Nullable final String description)
{
this.description = description;
return this;
}
public OrderLineBuilder hideWhenPrinting(final boolean hideWhenPrinting)
{
this.hideWhenPrinting = hideWhenPrinting;
return this; | }
public OrderLineBuilder details(@NonNull final Collection<OrderLineDetailCreateRequest> details)
{
assertNotBuilt();
detailCreateRequests.addAll(details);
return this;
}
public OrderLineBuilder detail(@NonNull final OrderLineDetailCreateRequest detail)
{
assertNotBuilt();
detailCreateRequests.add(detail);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderLineBuilder.java | 1 |
请完成以下Java代码 | public int[] getBrownClusterFullString()
{
return brownClusterFullString;
}
@Override
public boolean equals(Object obj)
{
if (obj instanceof Sentence)
{
Sentence sentence = (Sentence) obj;
if (sentence.words.length != words.length)
return false;
for (int i = 0; i < sentence.words.length; i++)
{
if (sentence.words[i] != words[i])
return false;
if (sentence.tags[i] != tags[i])
return false;
}
return true;
}
return false;
}
@Override
public int compareTo(Object o)
{ | if (equals(o))
return 0;
return hashCode() - o.hashCode();
}
@Override
public int hashCode()
{
int hash = 0;
for (int tokenId = 0; tokenId < words.length; tokenId++)
{
hash ^= (words[tokenId] * tags[tokenId]);
}
return hash;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\structures\Sentence.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static Element getElementByTag(@NonNull final Node node, @NonNull final String tagName)
{
final Element element = node instanceof Document
? ((Document)node).getDocumentElement()
: (Element)node;
final NodeList nodeList = element.getElementsByTagName(tagName);
if (nodeList.getLength() == 0)
{
return null;
}
final Node childNode = nodeList.item(0);
return (Element)childNode;
} | @NonNull
public static String addXMLDeclarationIfNeeded(@NonNull final String payload)
{
if (payload.trim().startsWith("<?xml")) {
// Payload already contains XML declaration
return payload;
}
final String xmlDeclaration = String.format(
"<?xml version=\"1.0\" encoding=\"%s\" standalone=\"%s\"?>\n",
XML_PROPERTY_FILE_ENCODING_VALUE,
XML_PROPERTY_VALUE_YES
);
return xmlDeclaration + payload;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\util\XMLUtil.java | 2 |
请完成以下Java代码 | public void setIsPostalValidated (final boolean IsPostalValidated)
{
set_ValueNoCheck (COLUMNNAME_IsPostalValidated, IsPostalValidated);
}
@Override
public boolean isPostalValidated()
{
return get_ValueAsBoolean(COLUMNNAME_IsPostalValidated);
}
@Override
public void setLatitude (final @Nullable BigDecimal Latitude)
{
set_Value (COLUMNNAME_Latitude, Latitude);
}
@Override
public BigDecimal getLatitude()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Latitude);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setLongitude (final @Nullable BigDecimal Longitude)
{
set_Value (COLUMNNAME_Longitude, Longitude);
}
@Override
public BigDecimal getLongitude()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Longitude);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPOBox (final @Nullable java.lang.String POBox)
{
set_ValueNoCheck (COLUMNNAME_POBox, POBox);
}
@Override
public java.lang.String getPOBox()
{
return get_ValueAsString(COLUMNNAME_POBox);
}
@Override
public void setPostal (final @Nullable java.lang.String Postal)
{
set_ValueNoCheck (COLUMNNAME_Postal, Postal); | }
@Override
public java.lang.String getPostal()
{
return get_ValueAsString(COLUMNNAME_Postal);
}
@Override
public void setPostal_Add (final @Nullable java.lang.String Postal_Add)
{
set_ValueNoCheck (COLUMNNAME_Postal_Add, Postal_Add);
}
@Override
public java.lang.String getPostal_Add()
{
return get_ValueAsString(COLUMNNAME_Postal_Add);
}
@Override
public void setRegionName (final @Nullable java.lang.String RegionName)
{
set_ValueNoCheck (COLUMNNAME_RegionName, RegionName);
}
@Override
public java.lang.String getRegionName()
{
return get_ValueAsString(COLUMNNAME_RegionName);
}
@Override
public void setStreet (final @Nullable java.lang.String Street)
{
set_Value (COLUMNNAME_Street, Street);
}
@Override
public java.lang.String getStreet()
{
return get_ValueAsString(COLUMNNAME_Street);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Location.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected Properties loadFrom(Resource location, String prefix, Charset encoding) throws IOException {
prefix = prefix.endsWith(".") ? prefix : prefix + ".";
Properties source = loadSource(location, encoding);
Properties target = new Properties();
for (String key : source.stringPropertyNames()) {
if (key.startsWith(prefix)) {
target.put(key.substring(prefix.length()), source.get(key));
}
}
return target;
}
private Properties loadSource(Resource location, @Nullable Charset encoding) throws IOException {
if (encoding != null) {
return PropertiesLoaderUtils.loadProperties(new EncodedResource(location, encoding));
}
return PropertiesLoaderUtils.loadProperties(location);
}
static class GitResourceAvailableCondition extends SpringBootCondition { | @Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ResourceLoader loader = context.getResourceLoader();
Environment environment = context.getEnvironment();
String location = environment.getProperty("spring.info.git.location");
if (location == null) {
location = "classpath:git.properties";
}
ConditionMessage.Builder message = ConditionMessage.forCondition("GitResource");
if (loader.getResource(location).exists()) {
return ConditionOutcome.match(message.found("git info at").items(location));
}
return ConditionOutcome.noMatch(message.didNotFind("git info at").items(location));
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\info\ProjectInfoAutoConfiguration.java | 2 |
请完成以下Java代码 | public de.metas.marketing.base.model.I_MKTG_Platform getMKTG_Platform() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_MKTG_Platform_ID, de.metas.marketing.base.model.I_MKTG_Platform.class);
}
@Override
public void setMKTG_Platform(de.metas.marketing.base.model.I_MKTG_Platform MKTG_Platform)
{
set_ValueFromPO(COLUMNNAME_MKTG_Platform_ID, de.metas.marketing.base.model.I_MKTG_Platform.class, MKTG_Platform);
}
/** Set MKTG_Platform.
@param MKTG_Platform_ID MKTG_Platform */
@Override
public void setMKTG_Platform_ID (int MKTG_Platform_ID)
{
if (MKTG_Platform_ID < 1)
set_Value (COLUMNNAME_MKTG_Platform_ID, null);
else
set_Value (COLUMNNAME_MKTG_Platform_ID, Integer.valueOf(MKTG_Platform_ID));
}
/** Get MKTG_Platform.
@return MKTG_Platform */
@Override
public int getMKTG_Platform_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Platform_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Externe Datensatz-ID.
@param RemoteRecordId Externe Datensatz-ID */ | @Override
public void setRemoteRecordId (java.lang.String RemoteRecordId)
{
set_Value (COLUMNNAME_RemoteRecordId, RemoteRecordId);
}
/** Get Externe Datensatz-ID.
@return Externe Datensatz-ID */
@Override
public java.lang.String getRemoteRecordId ()
{
return (java.lang.String)get_Value(COLUMNNAME_RemoteRecordId);
}
/** Set Anfangsdatum.
@param StartDate
First effective day (inclusive)
*/
@Override
public void setStartDate (java.sql.Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Anfangsdatum.
@return First effective day (inclusive)
*/
@Override
public java.sql.Timestamp getStartDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_Campaign.java | 1 |
请完成以下Java代码 | public byte[] getBase64() {
return base64;
}
/**
* Sets the value of the base64 property.
*
* @param value
* allowed object is
* byte[]
*/
public void setBase64(byte[] value) {
this.base64 = value;
}
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
/**
* Gets the value of the filename property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFilename() {
return filename;
}
/**
* Sets the value of the filename property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFilename(String value) { | this.filename = value;
}
/**
* Gets the value of the mimeType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMimeType() {
return mimeType;
}
/**
* Sets the value of the mimeType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMimeType(String value) {
this.mimeType = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\response\DocumentType.java | 1 |
请完成以下Java代码 | public KeyValues getLowCardinalityKeyValues(GatewayContext context) {
KeyValues keyValues = KeyValues.empty();
if (context.getCarrier() == null) {
return keyValues;
}
Route route = context.getServerWebExchange().getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
if (route != null) {
keyValues = keyValues
.and(ROUTE_URI.withValue(route.getUri().toString()),
METHOD.withValue(context.getRequest().getMethod().name()))
.and(ROUTE_ID.withValue(route.getId()));
}
ServerHttpResponse response = context.getResponse();
if (response != null && response.getStatusCode() != null) {
keyValues = keyValues.and(STATUS.withValue(String.valueOf(response.getStatusCode().value())));
}
else {
keyValues = keyValues.and(STATUS.withValue("UNKNOWN"));
}
return keyValues;
}
@Override | public KeyValues getHighCardinalityKeyValues(GatewayContext context) {
return KeyValues.of(URI.withValue(context.getRequest().getURI().toString()));
}
@Override
public String getName() {
return "http.client.requests";
}
@Override
public @Nullable String getContextualName(GatewayContext context) {
if (context.getRequest() == null) {
return null;
}
return "HTTP " + context.getRequest().getMethod();
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\observation\DefaultGatewayObservationConvention.java | 1 |
请完成以下Java代码 | public void setM_FixChangeNotice_ID (int M_FixChangeNotice_ID)
{
if (M_FixChangeNotice_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_FixChangeNotice_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_FixChangeNotice_ID, Integer.valueOf(M_FixChangeNotice_ID));
}
/** Get Fixed in.
@return Fixed in Change Notice
*/
public int getM_FixChangeNotice_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_FixChangeNotice_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
public org.eevolution.model.I_PP_Product_BOM getPP_Product_BOM() throws RuntimeException
{
return (org.eevolution.model.I_PP_Product_BOM)MTable.get(getCtx(), org.eevolution.model.I_PP_Product_BOM.Table_Name)
.getPO(getPP_Product_BOM_ID(), get_TrxName()); }
/** Set BOM & Formula.
@param PP_Product_BOM_ID
BOM & Formula
*/
public void setPP_Product_BOM_ID (int PP_Product_BOM_ID)
{
if (PP_Product_BOM_ID < 1) | set_ValueNoCheck (COLUMNNAME_PP_Product_BOM_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Product_BOM_ID, Integer.valueOf(PP_Product_BOM_ID));
}
/** Get BOM & Formula.
@return BOM & Formula
*/
public int getPP_Product_BOM_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Product_BOM_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ChangeRequest.java | 1 |
请完成以下Java代码 | public ShortValue createValue(Object value, Map<String, Object> valueInfo) {
return Variables.shortValue((Short) value, isTransient(valueInfo));
}
@Override
public ValueType getParent() {
return ValueType.NUMBER;
}
@Override
public ShortValue convertFromTypedValue(TypedValue typedValue) {
if (typedValue.getType() != ValueType.NUMBER) {
throw unsupportedConversion(typedValue.getType());
}
ShortValueImpl shortValue = null;
NumberValue numberValue = (NumberValue) typedValue;
if (numberValue.getValue() != null) {
shortValue = (ShortValueImpl) Variables.shortValue(numberValue.getValue().shortValue());
} else {
shortValue = (ShortValueImpl) Variables.shortValue(null);
}
shortValue.setTransient(numberValue.isTransient());
return shortValue;
}
@Override
public boolean canConvertFromTypedValue(TypedValue typedValue) {
if (typedValue.getType() != ValueType.NUMBER) {
return false;
}
if (typedValue.getValue() != null) {
NumberValue numberValue = (NumberValue) typedValue;
double doubleValue = numberValue.getValue().doubleValue();
// returns false if the value changes due to conversion (e.g. by overflows
// or by loss in precision)
if (numberValue.getValue().shortValue() != doubleValue) {
return false;
}
} | return true;
}
}
public static class StringTypeImpl extends PrimitiveValueTypeImpl {
private static final long serialVersionUID = 1L;
public StringTypeImpl() {
super(String.class);
}
public StringValue createValue(Object value, Map<String, Object> valueInfo) {
return Variables.stringValue((String) value, isTransient(valueInfo));
}
}
public static class NumberTypeImpl extends PrimitiveValueTypeImpl {
private static final long serialVersionUID = 1L;
public NumberTypeImpl() {
super(Number.class);
}
public NumberValue createValue(Object value, Map<String, Object> valueInfo) {
return Variables.numberValue((Number) value, isTransient(valueInfo));
}
@Override
public boolean isAbstract() {
return true;
}
}
} | repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\type\PrimitiveValueTypeImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public URL getResourceURLOrNull(
@Nullable final PrintFormatId printFormatId,
@Nullable final String resourceName)
{
// Skip if it's not about our hooked image attachment resources
if (!isAttachmentImageResourceName(resourceName))
{
return null;
}
if (printFormatId == null)
{
return null;
}
//
// Get the local image file
final File imageFile = geImageFile(printFormatId);
if (imageFile == null)
{
return null;
}
//
// Convert the attachment file to URL
try
{
return imageFile.toURI().toURL();
}
catch (MalformedURLException e)
{
logger.warn("Failed converting the image file to URL: {}", imageFile, e);
}
return null;
}
private File geImageFile(@NonNull final PrintFormatId printFormatId)
{
final AttachmentEntryId attachmentEntryId = getFirstAttachmentEntryIdByPrintFormatId(printFormatId);
if(attachmentEntryId == null)
{
logger.warn("Cannot find image for {}, please add a file to the Print format. Returning empty PNG file", this);
return ImageUtils.getEmptyPNGFile();
}
else
{
final byte[] data = attachmentEntryService.retrieveData(attachmentEntryId);
return ImageUtils.createTempPNGFile("attachmentEntry", data);
}
}
/**
* get one attachment entry; does not matter if are several
*/
@Nullable
private AttachmentEntryId getFirstAttachmentEntryIdByPrintFormatId(@NonNull final PrintFormatId printFormatId)
{ | final List<AttachmentEntry> entries = attachmentEntryService.getByReferencedRecord(TableRecordReference.of(I_AD_PrintFormat.Table_Name, printFormatId));
if (!entries.isEmpty())
{
final AttachmentEntry entry = entries.get(0);
return entry.getId();
}
else
{
return null;
}
}
/**
* @return true if given resourceName is an attachment image
*/
private boolean isAttachmentImageResourceName(final String resourceName)
{
// Skip if no resourceName
if (resourceName == null || resourceName.isEmpty())
{
return false;
}
// Check if our resource name ends with one of our predefined matchers
for (final String resourceNameEndsWithMatcher : resourceNameEndsWithMatchers)
{
if (resourceName.endsWith(resourceNameEndsWithMatcher))
{
return true;
}
}
// Fallback: not a attachment resource
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\class_loader\images\attachment\AttachmentImageFileClassLoaderHook.java | 2 |
请完成以下Java代码 | public class CdiResolver extends ELResolver {
protected jakarta.el.ELContext context;
public CdiResolver() {
context = new jakarta.el.ELContext() {
@Override
public VariableMapper getVariableMapper() {
return null;
}
@Override
public FunctionMapper getFunctionMapper() {
return null;
}
@Override
public jakarta.el.ELResolver getELResolver() {
return getWrappedResolver();
}
};
}
protected BeanManager getBeanManager() {
return BeanManagerLookup.getBeanManager();
}
protected jakarta.el.ELResolver getWrappedResolver() {
BeanManager beanManager = getBeanManager();
jakarta.el.ELResolver resolver = beanManager.getELResolver();
return resolver;
}
@Override
public Class<?> getCommonPropertyType(ELContext context, Object base) {
return getWrappedResolver().getCommonPropertyType(this.context, base);
}
@Override
public Class<?> getType(ELContext context, Object base, Object property) {
return getWrappedResolver().getType(this.context, base, property);
}
@Override
public Object getValue(ELContext context, Object base, Object property) {
try {
Object result = getWrappedResolver().getValue(this.context, base, property);
context.setPropertyResolved(result != null);
return result;
} catch (IllegalStateException e) {
// dependent scoped / EJBs
Object result = ProgrammaticBeanLookup.lookup(property.toString(), getBeanManager()); | context.setPropertyResolved(result != null);
return result;
}
}
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
return getWrappedResolver().isReadOnly(this.context, base, property);
}
@Override
public void setValue(ELContext context, Object base, Object property, Object value) {
getWrappedResolver().setValue(this.context, base, property, value);
}
@Override
public Object invoke(ELContext context, Object base, Object method, java.lang.Class<?>[] paramTypes, Object[] params) {
Object result = getWrappedResolver().invoke(this.context, base, method, paramTypes, params);
context.setPropertyResolved(result != null);
return result;
}
} | repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\el\CdiResolver.java | 1 |
请完成以下Java代码 | public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Calendar getCreated() {
return this.created;
}
public void setCreated(Calendar created) {
this.created = created;
}
public String getText() {
return this.text; | }
public void setText(String text) {
this.text = text;
}
public String getSummary() {
return this.summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-8 课: Spring Boot 构建一个 RESTful Web 服务\spring-boot-web-restful\src\main\java\com\neo\model\Message.java | 1 |
请完成以下Java代码 | public void setOperation (String Operation)
{
set_Value (COLUMNNAME_Operation, Operation);
}
/** Get Arbeitsvorgang .
@return Compare Operation
*/
public String getOperation ()
{
return (String)get_Value(COLUMNNAME_Operation);
}
/** Type AD_Reference_ID=540202 */
public static final int TYPE_AD_Reference_ID=540202;
/** Field Value = FV */
public static final String TYPE_FieldValue = "FV";
/** Context Value = CV */ | public static final String TYPE_ContextValue = "CV";
/** Set Art.
@param Type
Type of Validation (SQL, Java Script, Java Language)
*/
public void setType (String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Type of Validation (SQL, Java Script, Java Language)
*/
public String getType ()
{
return (String)get_Value(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_AD_TriggerUI_Criteria.java | 1 |
请完成以下Java代码 | public class JavaTypeDeclaration extends TypeDeclaration {
private int modifiers;
private final List<JavaFieldDeclaration> fieldDeclarations = new ArrayList<>();
private final List<JavaMethodDeclaration> methodDeclarations = new ArrayList<>();
JavaTypeDeclaration(String name) {
super(name);
}
/**
* Sets the modifiers.
* @param modifiers the modifiers
*/
public void modifiers(int modifiers) {
this.modifiers = modifiers;
}
/**
* Return the modifiers.
* @return the modifiers
*/
public int getModifiers() {
return this.modifiers;
}
/**
* Adds the given field declaration.
* @param fieldDeclaration the field declaration
*/
public void addFieldDeclaration(JavaFieldDeclaration fieldDeclaration) {
this.fieldDeclarations.add(fieldDeclaration);
}
/**
* Returns the field declarations.
* @return the field declarations
*/
public List<JavaFieldDeclaration> getFieldDeclarations() {
return this.fieldDeclarations; | }
/**
* Adds the given method declaration.
* @param methodDeclaration the method declaration
*/
public void addMethodDeclaration(JavaMethodDeclaration methodDeclaration) {
this.methodDeclarations.add(methodDeclaration);
}
/**
* Returns the method declarations.
* @return the method declarations
*/
public List<JavaMethodDeclaration> getMethodDeclarations() {
return this.methodDeclarations;
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\java\JavaTypeDeclaration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<PMESU1> getPMESU1() {
if (pmesu1 == null) {
pmesu1 = new ArrayList<PMESU1>();
}
return this.pmesu1;
}
/**
* Gets the value of the phand1 property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the phand1 property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPHAND1().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PHAND1 }
*
*
*/
public List<PHAND1> getPHAND1() {
if (phand1 == null) {
phand1 = new ArrayList<PHAND1>();
}
return this.phand1;
}
/** | * Gets the value of the detail property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the detail property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDETAIL().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DETAILXlief }
*
*
*/
public List<DETAILXlief> getDETAIL() {
if (detail == null) {
detail = new ArrayList<DETAILXlief>();
}
return this.detail;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\PPACK1.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode()
{
return Objects.hash(name, value);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class EbayTaxReference {\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" value: ").append(toIndentedString(value)).append("\n");
sb.append("}");
return sb.toString();
} | /**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\EbayTaxReference.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.