instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public String URL(Map<String, String> variables)
{
String url = this.URL;
// go through variables and replace placeholders
for (Map.Entry<String, ServerVariable> variable : this.variables.entrySet())
{
String name = variable.getKey();
ServerVariable serverVariable = variable.getValue();
String value = serverVariable.defaultValue;
if (variables != null && variables.containsKey(name))
{
value = variables.get(name);
if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value))
{
throw new RuntimeException("The variable " + name + " in the server URL has invalid value " + value + "."); | }
}
url = url.replaceAll("\\{" + name + "\\}", value);
}
return url;
}
/**
* Format URL template using default server variables.
*
* @return Formatted URL.
*/
public String URL()
{
return URL(null);
}
} | 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\invoker\ServerConfiguration.java | 2 |
请完成以下Java代码 | public void forEach(@NonNull final BiConsumer<String, Object> keyAndValueConsumer)
{
for (final String keyColumnName : keyColumnNames)
{
final Object value = getValue(keyColumnName);
keyAndValueConsumer.accept(keyColumnName, value);
}
}
public SqlAndParams getSqlValuesCommaSeparated()
{
final SqlAndParams.Builder sqlBuilder = SqlAndParams.builder();
for (final String keyColumnName : keyColumnNames)
{
final Object value = getValue(keyColumnName);
if (!sqlBuilder.isEmpty())
{
sqlBuilder.append(", ");
}
sqlBuilder.append("?", value);
}
return sqlBuilder.build();
}
public String getSqlWhereClauseById(@NonNull final String tableAlias)
{
final StringBuilder sql = new StringBuilder();
for (final String keyFieldName : keyColumnNames)
{
final Object idPart = getValue(keyFieldName);
if (sql.length() > 0) | {
sql.append(" AND ");
}
sql.append(tableAlias).append(".").append(keyFieldName);
if (!JSONNullValue.isNull(idPart))
{
sql.append("=").append(DB.TO_SQL(idPart));
}
else
{
sql.append(" IS NULL");
}
}
return sql.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlComposedKey.java | 1 |
请完成以下Java代码 | public boolean isTopLevel()
{
return huId != null && topLevelHUId == null && storageProductId == null;
}
public boolean isHU()
{
return storageProductId == null;
}
public HuId getHuId()
{
return huId;
}
public HUEditorRowId toTopLevelRowId()
{
if (isTopLevel())
{
return this;
}
final HuId huId = getTopLevelHUId();
final ProductId storageProductId = null;
final HuId topLevelHUId = null;
final String json = null; | final DocumentId documentId = null;
return new HUEditorRowId(huId, storageProductId, topLevelHUId, json, documentId);
}
public HuId getTopLevelHUId()
{
if (topLevelHUId != null)
{
return topLevelHUId;
}
return huId;
}
public ProductId getStorageProductId()
{
return storageProductId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRowId.java | 1 |
请完成以下Java代码 | public String startNewArticle(Model model, @CurrentUser CurrentUserToken loggedInUserDtl) {
model.addAttribute("article", new Article()); //new article box at top
return "article/new-article";
}
@PostMapping("/add")
public String finishAddArticle(ArticleCreateDto articleDto, RedirectAttributes redirectAttrs) {
//TODO:validate and return to GET:/add on errors
Article article = articleService.createArticle(articleDto);
redirectAttrs.addFlashAttribute("success", "Article with title " + article.getTitle() + " is received and being analyzed");
return "redirect:/";
}
@GetMapping("/delete/{id}")
@PreAuthorize("@permEvaluator.hasAccess(#id, 'Article' )")
public String deleteArticle(@PathVariable Long id, RedirectAttributes redirectAttrs) {
articleService.delete(id);
redirectAttrs.addFlashAttribute("success", "Article with id " + id + " is deleted");
return "redirect:/article/";
}
@GetMapping("/edit/{id}")
@PreAuthorize("@permEvaluator.hasAccess(#id, 'Article' )")
public String startEditArticle(Model model, @PathVariable Long id) {
model.addAttribute("msg", "Add a new article");
model.addAttribute("article", articleService.read(id));
return "article/edit-article";
}
@PostMapping("/edit")
@PreAuthorize("@permEvaluator.hasAccess(#articleDto.id, 'Article' )")
public String finishEditArticle(Model model, ArticleEditDto articleDto, RedirectAttributes redirectAttrs) {
model.addAttribute("msg", "Add a new article");
//TODO:validate and return to GET:/edit/{id} on errors | articleService.update(articleDto);
redirectAttrs.addFlashAttribute("success", "Article with title " + articleDto.getTitle() + " is updated");
return "redirect:/article/";
}
@PostMapping("/addComment")
public String addComment(NewCommentDto dto, RedirectAttributes redirectAttrs) {
//TODO:validate and return to GET:/add on errors
commentService.save(dto);
redirectAttrs.addFlashAttribute("success", "Comment saved. Its currently under review.");
return "redirect:/article/read/" + dto.getArticleId();
}
@GetMapping("/read/{id}")
public String read(@PathVariable Long id, Model model) {
ArticleReadDto dto = articleService.read(id);
//TODO: fix ordering -- ordering is not consistent
model.addAttribute("article", dto);
return "article/read-article";
}
} | repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\java\gt\app\web\mvc\ArticleController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class H2ConsoleLogger {
H2ConsoleLogger(ObjectProvider<DataSource> dataSources, String path) {
if (logger.isInfoEnabled()) {
ClassLoader classLoader = getClass().getClassLoader();
withThreadContextClassLoader(classLoader, () -> log(getConnectionUrls(dataSources), path));
}
}
private void withThreadContextClassLoader(ClassLoader classLoader, Runnable action) {
ClassLoader previous = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(classLoader);
action.run();
}
finally {
Thread.currentThread().setContextClassLoader(previous);
}
}
private List<String> getConnectionUrls(ObjectProvider<DataSource> dataSources) {
return dataSources.orderedStream(ObjectProvider.UNFILTERED)
.map(this::getConnectionUrl)
.filter(Objects::nonNull)
.toList();
} | private @Nullable String getConnectionUrl(DataSource dataSource) {
try (Connection connection = dataSource.getConnection()) {
return "'" + connection.getMetaData().getURL() + "'";
}
catch (Exception ex) {
return null;
}
}
private void log(List<String> urls, String path) {
if (!urls.isEmpty()) {
logger.info(LogMessage.format("H2 console available at '%s'. %s available at %s", path,
(urls.size() > 1) ? "Databases" : "Database", String.join(", ", urls)));
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-h2console\src\main\java\org\springframework\boot\h2console\autoconfigure\H2ConsoleAutoConfiguration.java | 2 |
请完成以下Java代码 | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Red.
@param Red
RGB value
*/
public void setRed (int Red)
{
set_Value (COLUMNNAME_Red, Integer.valueOf(Red));
}
/** Get Red.
@return RGB value
*/
public int getRed ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Red);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set 2nd Red.
@param Red_1
RGB value for second color
*/
public void setRed_1 (int Red_1)
{
set_Value (COLUMNNAME_Red_1, Integer.valueOf(Red_1));
}
/** Get 2nd Red.
@return RGB value for second color
*/
public int getRed_1 ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Red_1);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Repeat Distance.
@param RepeatDistance
Distance in points to repeat gradient color - or zero
*/
public void setRepeatDistance (int RepeatDistance)
{
set_Value (COLUMNNAME_RepeatDistance, Integer.valueOf(RepeatDistance));
}
/** Get Repeat Distance. | @return Distance in points to repeat gradient color - or zero
*/
public int getRepeatDistance ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_RepeatDistance);
if (ii == null)
return 0;
return ii.intValue();
}
/** StartPoint AD_Reference_ID=248 */
public static final int STARTPOINT_AD_Reference_ID=248;
/** North = 1 */
public static final String STARTPOINT_North = "1";
/** North East = 2 */
public static final String STARTPOINT_NorthEast = "2";
/** East = 3 */
public static final String STARTPOINT_East = "3";
/** South East = 4 */
public static final String STARTPOINT_SouthEast = "4";
/** South = 5 */
public static final String STARTPOINT_South = "5";
/** South West = 6 */
public static final String STARTPOINT_SouthWest = "6";
/** West = 7 */
public static final String STARTPOINT_West = "7";
/** North West = 8 */
public static final String STARTPOINT_NorthWest = "8";
/** Set Start Point.
@param StartPoint
Start point of the gradient colors
*/
public void setStartPoint (String StartPoint)
{
set_Value (COLUMNNAME_StartPoint, StartPoint);
}
/** Get Start Point.
@return Start point of the gradient colors
*/
public String getStartPoint ()
{
return (String)get_Value(COLUMNNAME_StartPoint);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Color.java | 1 |
请完成以下Java代码 | public String getKeyByKeyId(String keyId) {
return dictionaryParsed.get(keyId);
}
private boolean isBlockFinished(String line) {
return StringUtils.isBlank(line) || line.equals("\\.");
}
private boolean isBlockStarted(String line) {
return line.startsWith("COPY public.key_dictionary (");
}
private void parseDictionaryDump(LineIterator iterator) throws IOException {
try {
String tempLine;
while (iterator.hasNext()) {
tempLine = iterator.nextLine();
if (isBlockStarted(tempLine)) {
processBlock(iterator);
}
} | } finally {
iterator.close();
}
}
private void processBlock(LineIterator lineIterator) {
String tempLine;
String[] lineSplited;
while(lineIterator.hasNext()) {
tempLine = lineIterator.nextLine();
if(isBlockFinished(tempLine)) {
return;
}
lineSplited = tempLine.split("\t");
dictionaryParsed.put(lineSplited[1], lineSplited[0]);
}
}
} | repos\thingsboard-master\tools\src\main\java\org\thingsboard\client\tools\migrator\DictionaryParser.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class QuarantineAttributeStorageListener implements IAttributeStorageListener
{
private final transient HULotNumberQuarantineService lotNumberQuarantineService;
public QuarantineAttributeStorageListener(@NonNull final HULotNumberQuarantineService lotNumberQuarantineService)
{
this.lotNumberQuarantineService = lotNumberQuarantineService;
Services.get(IAttributeStorageFactoryService.class).addAttributeStorageListener(this);
}
@Override
public void onAttributeValueChanged(
@NonNull final IAttributeValueContext attributeValueContext,
@NonNull final IAttributeStorage storage,
IAttributeValue attributeValue,
Object valueOld)
{
final AbstractHUAttributeStorage huAttributeStorage = AbstractHUAttributeStorage.castOrNull(storage);
final boolean storageIsAboutHUs = huAttributeStorage != null;
if (!storageIsAboutHUs)
{
return;
}
if (!storage.hasAttribute(HUAttributeConstants.ATTR_Quarantine))
{
return;
}
final AttributeCode attributeCode = attributeValue.getAttributeCode();
final boolean relevantAttributeHasChanged = AttributeConstants.ATTR_LotNumber.equals(attributeCode); | if (!relevantAttributeHasChanged)
{
return;
}
if (lotNumberQuarantineService.isQuarantineLotNumber(huAttributeStorage))
{
storage.setValue(HUAttributeConstants.ATTR_Quarantine, HUAttributeConstants.ATTR_Quarantine_Value_Quarantine);
}
else
{
storage.setValue(HUAttributeConstants.ATTR_Quarantine, null);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\quarantine\QuarantineAttributeStorageListener.java | 2 |
请完成以下Java代码 | public class Profiles
{
private static final Logger logger = LogManager.getLogger(Profiles.class);
public static final String PROFILE_Test = "test";
public static final String PROFILE_NotTest = "!" + PROFILE_Test;
public static final String PROFILE_Webui = "metasfresh-webui-api";
/**
* metasfresh-app a.k.a. the app-server.
*/
public static final String PROFILE_App = "metasfresh-app";
public static final String PROFILE_SwingUI = "metasfresh-swingui";
/** Profile activate when running from IDE */
public static final String PROFILE_Development = "development";
public static final String PROFILE_MaterialDispo = "material-dispo";
public static final String PROFILE_ReportService = "metasfresh-jasper-service";
public static final String PROFILE_ReportService_Standalone = PROFILE_ReportService + "-standalone";
public static final String PROFILE_NOT_ReportService_Standalone = "!" + PROFILE_ReportService_Standalone;
public static final String PROFILE_PrintService = "metasfresh-printing-service";
public static final String PROFILE_AccountingService = "metasfresh-accounting-service"; | /** @return true if {@link #PROFILE_Development} is active (i.e. we are running from IDE) */
public boolean isDevelopmentProfileActive()
{
return isProfileActive(Profiles.PROFILE_Development);
}
/** @return true if given profile is active */
public boolean isProfileActive(final String profile)
{
final ApplicationContext context = SpringContextHolder.instance.getApplicationContext();
if (context == null)
{
logger.warn("No application context found to determine if '{}' profile is active", profile);
return true;
}
return context.getEnvironment().acceptsProfiles(profile);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\Profiles.java | 1 |
请完成以下Java代码 | public String getUserId() {
return userId;
}
@Override
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public String getKey() {
return key;
}
@Override
public void setKey(String key) {
this.key = key;
}
@Override
public String getValue() {
return value;
}
@Override
public void setValue(String value) {
this.value = value;
}
@Override
public byte[] getPasswordBytes() {
return passwordBytes;
}
@Override
public void setPasswordBytes(byte[] passwordBytes) {
this.passwordBytes = passwordBytes;
}
@Override
public String getPassword() {
return password;
} | @Override
public void setPassword(String password) {
this.password = password;
}
@Override
public String getName() {
return key;
}
@Override
public String getUsername() {
return value;
}
@Override
public String getParentId() {
return parentId;
}
@Override
public void setParentId(String parentId) {
this.parentId = parentId;
}
@Override
public Map<String, String> getDetails() {
return details;
}
@Override
public void setDetails(Map<String, String> details) {
this.details = details;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\IdentityInfoEntityImpl.java | 1 |
请完成以下Java代码 | public applet addElement (String hashcode, String element)
{
addElementToRegistry (hashcode, element);
return (this);
}
/**
* Add an element to the element
*
* @param element
* a string representation of the element
*/
public applet addElement (String element)
{
addElementToRegistry (element);
return (this);
}
/**
* Add an element to the element
*
* @param element
* an element to add | */
public applet addElement (Element element)
{
addElementToRegistry (element);
return (this);
}
/**
* Removes an Element from the element.
*
* @param hashcode
* the name of the element to be removed.
*/
public applet removeElement (String hashcode)
{
removeElementFromRegistry (hashcode);
return (this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\applet.java | 1 |
请完成以下Java代码 | public int getPP_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_ID);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setRevision (final @Nullable java.lang.String Revision)
{
set_Value (COLUMNNAME_Revision, Revision);
}
@Override
public java.lang.String getRevision()
{
return get_ValueAsString(COLUMNNAME_Revision);
}
@Override
public org.compiere.model.I_AD_Sequence getSerialNo_Sequence()
{
return get_ValueAsPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class);
}
@Override
public void setSerialNo_Sequence(final org.compiere.model.I_AD_Sequence SerialNo_Sequence)
{
set_ValueFromPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class, SerialNo_Sequence);
}
@Override
public void setSerialNo_Sequence_ID (final int SerialNo_Sequence_ID)
{
if (SerialNo_Sequence_ID < 1)
set_Value (COLUMNNAME_SerialNo_Sequence_ID, null);
else
set_Value (COLUMNNAME_SerialNo_Sequence_ID, SerialNo_Sequence_ID);
}
@Override | public int getSerialNo_Sequence_ID()
{
return get_ValueAsInt(COLUMNNAME_SerialNo_Sequence_ID);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_BOM.java | 1 |
请完成以下Java代码 | public EMail sendEMail(@NonNull final EMailRequest request)
{
final ILoggable debugLoggable = request.getDebugLoggable();
if (debugLoggable != null)
{
debugLoggable.addLog("Request: {}", request);
}
if (debugLoggable != null)
{
debugLoggable.addLog("Mailbox: {}", request.getMailbox());
}
final EMail email = createEMail(request);
if (request.getDebugLoggable() != null)
{
email.setDebugMode(true);
email.setDebugLoggable(debugLoggable);
}
if(request.isForceRealEmailRecipients())
{
email.forceRealEmailRecipients();
}
request.getToList().forEach(email::addTo);
final EMailAddress cc = request.getCc();
if (cc !=null && !request.getToList().contains(cc))
{
email.addCc(request.getCc());
}
request.getAttachments().forEach(email::addAttachment);
final EMailSentStatus sentStatus = email.send();
if (request.isFailIfNotSent())
{
sentStatus.throwIfNotOK((exception) -> exception.setParameter("email", email));
}
return email;
}
private MailSender getMailSender(@NonNull final MailboxType type)
{
final MailSender mailSender = mailSenders.get(type);
if (mailSender == null)
{
throw new AdempiereException("Unsupported type: " + type);
}
return mailSender;
}
private boolean isDebugModeEnabled()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_DEBUG, false);
}
/**
* Gets the EMail TO address to be used when sending mails.
* If present, this address will be used to send all emails to a particular address instead of actual email addresses.
*
* @return email address or null
*/
@Nullable | private InternetAddress getDebugMailToAddressOrNull()
{
final Properties ctx = Env.getCtx();
final String emailStr = StringUtils.trimBlankToNull(
sysConfigBL.getValue(SYSCONFIG_DebugMailTo,
null, // defaultValue
Env.getAD_Client_ID(ctx),
Env.getAD_Org_ID(ctx))
);
if (Check.isEmpty(emailStr, true) || emailStr.equals("-"))
{
return null;
}
try
{
return new InternetAddress(emailStr, true);
}
catch (final Exception ex)
{
logger.warn("Invalid debug email address provided by sysconfig {}: {}. Returning null.", SYSCONFIG_DebugMailTo, emailStr, ex);
return null;
}
}
public void send(final EMail email)
{
final EMailSentStatus sentStatus = email.send();
sentStatus.throwIfNotOK();
}
public MailTextBuilder newMailTextBuilder(@NonNull final MailTemplate mailTemplate)
{
return MailTextBuilder.newInstance(mailTemplate);
}
public MailTextBuilder newMailTextBuilder(final MailTemplateId mailTemplateId)
{
final MailTemplate mailTemplate = mailTemplatesRepo.getById(mailTemplateId);
return newMailTextBuilder(mailTemplate);
}
public void test(@NonNull final TestMailRequest request)
{
TestMailCommand.builder()
.mailService(this)
.request(request)
.build()
.execute();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\MailService.java | 1 |
请完成以下Java代码 | public void setIsBalancing (final boolean IsBalancing)
{
set_Value (COLUMNNAME_IsBalancing, IsBalancing);
}
@Override
public boolean isBalancing()
{
return get_ValueAsBoolean(COLUMNNAME_IsBalancing);
}
@Override
public void setIsNaturalAccount (final boolean IsNaturalAccount)
{
set_Value (COLUMNNAME_IsNaturalAccount, IsNaturalAccount);
}
@Override
public boolean isNaturalAccount()
{
return get_ValueAsBoolean(COLUMNNAME_IsNaturalAccount);
}
@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 setVFormat (final @Nullable java.lang.String VFormat)
{
set_Value (COLUMNNAME_VFormat, VFormat);
}
@Override
public java.lang.String getVFormat()
{
return get_ValueAsString(COLUMNNAME_VFormat);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Element.java | 1 |
请完成以下Java代码 | public synchronized void addRtAndSuccessQps(double avgRt, Long successQps) {
this.rt += avgRt * successQps;
this.successQps += successQps;
}
/**
* {@link #rt} = {@code avgRt * successQps}
*
* @param avgRt average rt of {@code successQps}
* @param successQps
*/
public synchronized void setRtAndSuccessQps(double avgRt, Long successQps) {
this.rt = avgRt * successQps;
this.successQps = successQps;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtModified() {
return gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
this.resourceCode = resource.hashCode();
}
public Long getPassQps() {
return passQps;
} | public void setPassQps(Long passQps) {
this.passQps = passQps;
}
public Long getBlockQps() {
return blockQps;
}
public void setBlockQps(Long blockQps) {
this.blockQps = blockQps;
}
public Long getExceptionQps() {
return exceptionQps;
}
public void setExceptionQps(Long exceptionQps) {
this.exceptionQps = exceptionQps;
}
public double getRt() {
return rt;
}
public void setRt(double rt) {
this.rt = rt;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getResourceCode() {
return resourceCode;
}
public Long getSuccessQps() {
return successQps;
}
public void setSuccessQps(Long successQps) {
this.successQps = successQps;
}
@Override
public String toString() {
return "MetricEntity{" +
"id=" + id +
", gmtCreate=" + gmtCreate +
", gmtModified=" + gmtModified +
", app='" + app + '\'' +
", timestamp=" + timestamp +
", resource='" + resource + '\'' +
", passQps=" + passQps +
", blockQps=" + blockQps +
", successQps=" + successQps +
", exceptionQps=" + exceptionQps +
", rt=" + rt +
", count=" + count +
", resourceCode=" + resourceCode +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\MetricEntity.java | 1 |
请完成以下Java代码 | public String toString()
{
return "DunningCandidateQuery ["
+ "AD_Table_ID=" + AD_Table_ID + ", Record_ID=" + Record_ID
+ ", C_DunningLevels=" + C_DunningLevels
+ ", active=" + active
+ ", applyClientSecurity=" + applyClientSecurity
+ ", applyAccessFilter=" + applyAccessFilter
+ ", processed=" + processed
+ ", writeOff=" + writeOff
+ "]";
}
@Override
public int hashCode()
{
return new HashcodeBuilder()
.append(AD_Table_ID)
.append(Record_ID)
.append(C_DunningLevels)
.append(active)
.append(applyClientSecurity)
.append(processed)
.append(writeOff)
.toHashcode();
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
final DunningCandidateQuery other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return new EqualsBuilder()
.append(AD_Table_ID, other.AD_Table_ID)
.append(Record_ID, other.Record_ID)
.append(C_DunningLevels, other.C_DunningLevels)
.append(active, other.active)
.append(applyClientSecurity, other.applyClientSecurity)
.append(processed, this.processed)
.append(writeOff, this.writeOff)
.isEqual();
}
@Override
public int getAD_Table_ID()
{
return AD_Table_ID;
}
public void setAD_Table_ID(int aD_Table_ID)
{
AD_Table_ID = aD_Table_ID;
}
@Override
public int getRecord_ID()
{
return Record_ID;
}
public void setRecord_ID(int record_ID)
{
Record_ID = record_ID;
}
@Override | public List<I_C_DunningLevel> getC_DunningLevels()
{
return C_DunningLevels;
}
public void setC_DunningLevels(List<I_C_DunningLevel> c_DunningLevels)
{
C_DunningLevels = c_DunningLevels;
}
@Override
public boolean isActive()
{
return active;
}
public void setActive(boolean active)
{
this.active = active;
}
@Override
public boolean isApplyClientSecurity()
{
return applyClientSecurity;
}
public void setApplyClientSecurity(boolean applyClientSecurity)
{
this.applyClientSecurity = applyClientSecurity;
}
@Override
public Boolean getProcessed()
{
return processed;
}
public void setProcessed(Boolean processed)
{
this.processed = processed;
}
@Override
public Boolean getWriteOff()
{
return writeOff;
}
public void setWriteOff(Boolean writeOff)
{
this.writeOff = writeOff;
}
@Override
public String getAdditionalWhere()
{
return additionalWhere;
}
public void setAdditionalWhere(String additionalWhere)
{
this.additionalWhere = additionalWhere;
}
@Override
public ApplyAccessFilter getApplyAccessFilter()
{
return applyAccessFilter;
}
public void setApplyAccessFilter(ApplyAccessFilter applyAccessFilter)
{
this.applyAccessFilter = applyAccessFilter;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningCandidateQuery.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getFiscalNumber() {
return fiscalNumber;
}
/**
* Sets the value of the fiscalNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFiscalNumber(String value) {
this.fiscalNumber = value;
}
/**
* Registered office of the company.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRegisteredOfficeOfCompany() {
return registeredOfficeOfCompany;
}
/**
* Sets the value of the registeredOfficeOfCompany property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRegisteredOfficeOfCompany(String value) {
this.registeredOfficeOfCompany = value;
}
/**
* Legal form of the company.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLegalFormOfCompany() {
return legalFormOfCompany; | }
/**
* Sets the value of the legalFormOfCompany property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLegalFormOfCompany(String value) {
this.legalFormOfCompany = value;
}
/**
* Place of the commercial register entry of the company.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTribnalPlaceRegistrationLocation() {
return tribnalPlaceRegistrationLocation;
}
/**
* Sets the value of the tribnalPlaceRegistrationLocation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTribnalPlaceRegistrationLocation(String value) {
this.tribnalPlaceRegistrationLocation = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\SupplierExtensionType.java | 2 |
请完成以下Java代码 | public static ShipmentScheduleAndJobSchedules of(@NonNull final I_M_ShipmentSchedule shipmentSchedule, @Nullable Collection<PickingJobSchedule> jobSchedules)
{
return new ShipmentScheduleAndJobSchedules(shipmentSchedule, jobSchedules);
}
public static ShipmentScheduleAndJobSchedules ofShipmentSchedule(@NonNull final de.metas.inoutcandidate.model.I_M_ShipmentSchedule shipmentSchedule)
{
return new ShipmentScheduleAndJobSchedules(InterfaceWrapperHelper.create(shipmentSchedule, I_M_ShipmentSchedule.class), null);
}
public ShipmentScheduleAndJobScheduleIdSet toScheduleIds()
{
return jobSchedules.isEmpty()
? ShipmentScheduleAndJobScheduleIdSet.of(getShipmentScheduleId())
: jobSchedules.toShipmentScheduleAndJobScheduleIdSet(); | }
public boolean isProcessed()
{
return shipmentSchedule.isProcessed();
}
public boolean hasJobSchedules()
{
return !jobSchedules.isEmpty();
}
public Set<PickingJobScheduleId> getJobScheduleIds() {return jobSchedules.getJobScheduleIds();}
public String getHeaderAggregationKey() {return StringUtils.trimBlankToNull(shipmentSchedule.getHeaderAggregationKey());}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\ShipmentScheduleAndJobSchedules.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ReferenceType getOrderReference() {
return orderReference;
}
/**
* Sets the value of the orderReference property.
*
* @param value
* allowed object is
* {@link ReferenceType }
*
*/
public void setOrderReference(ReferenceType value) {
this.orderReference = value;
}
/**
* DEPRICATED: please use DocumentExtension/MessageFunction instead.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMessageFunction() {
return messageFunction;
}
/**
* Sets the value of the messageFunction property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessageFunction(String value) {
this.messageFunction = value;
}
/**
* Reference to the consignment.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConsignmentReference() {
return consignmentReference;
}
/** | * Sets the value of the consignmentReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConsignmentReference(String value) {
this.consignmentReference = value;
}
/**
* Free text information.Gets the value of the freeText 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 freeText property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getFreeText().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FreeTextType }
*
*
*/
public List<FreeTextType> getFreeText() {
if (freeText == null) {
freeText = new ArrayList<FreeTextType>();
}
return this.freeText;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ORDRSPExtensionType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getTotalIncome() {
return totalIncome;
}
public void setTotalIncome(BigDecimal totalIncome) {
this.totalIncome = totalIncome;
}
public BigDecimal getTotalExpend() {
return totalExpend;
}
public void setTotalExpend(BigDecimal totalExpend) {
this.totalExpend = totalExpend;
}
public BigDecimal getTodayIncome() {
return todayIncome;
}
public void setTodayIncome(BigDecimal todayIncome) {
this.todayIncome = todayIncome;
}
public BigDecimal getTodayExpend() {
return todayExpend;
}
public void setTodayExpend(BigDecimal todayExpend) {
this.todayExpend = todayExpend;
} | public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType == null ? null : accountType.trim();
}
public BigDecimal getSettAmount() {
return settAmount;
}
public void setSettAmount(BigDecimal settAmount) {
this.settAmount = settAmount;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpAccount.java | 2 |
请完成以下Java代码 | public void setAD_PrinterHW_ID (int AD_PrinterHW_ID)
{
if (AD_PrinterHW_ID < 1)
set_Value (COLUMNNAME_AD_PrinterHW_ID, null);
else
set_Value (COLUMNNAME_AD_PrinterHW_ID, Integer.valueOf(AD_PrinterHW_ID));
}
@Override
public int getAD_PrinterHW_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_PrinterHW_ID);
}
@Override
public void setAD_Printer_ID (int AD_Printer_ID)
{
if (AD_Printer_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Printer_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Printer_ID, Integer.valueOf(AD_Printer_ID));
}
@Override
public int getAD_Printer_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Printer_ID);
}
@Override
public void setAD_Printer_Matching_ID (int AD_Printer_Matching_ID)
{
if (AD_Printer_Matching_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Printer_Matching_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Printer_Matching_ID, Integer.valueOf(AD_Printer_Matching_ID));
}
@Override
public int getAD_Printer_Matching_ID()
{ | return get_ValueAsInt(COLUMNNAME_AD_Printer_Matching_ID);
}
@Override
public void setAD_Tray_Matching_IncludedTab (java.lang.String AD_Tray_Matching_IncludedTab)
{
set_Value (COLUMNNAME_AD_Tray_Matching_IncludedTab, AD_Tray_Matching_IncludedTab);
}
@Override
public java.lang.String getAD_Tray_Matching_IncludedTab()
{
return (java.lang.String)get_Value(COLUMNNAME_AD_Tray_Matching_IncludedTab);
}
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_Printer_Matching.java | 1 |
请完成以下Java代码 | public <T> T execute(CommandConfig config, Command<T> command) {
CommandContext context = Context.getCommandContext();
boolean contextReused = false;
// We need to check the exception, because the transaction can be in a
// rollback state, and some other command is being fired to compensate (eg. decrementing job retries)
if (!config.isContextReusePossible() || context == null || context.getException() != null) {
context = commandContextFactory.createCommandContext(command);
} else {
log.debug(
"Valid context found. Reusing it for the current command '{}'",
command.getClass().getCanonicalName()
);
contextReused = true;
context.setReused(true);
}
try {
// Push on stack
Context.setCommandContext(context);
Context.setProcessEngineConfiguration(processEngineConfiguration);
return next.execute(config, command);
} catch (Throwable e) {
context.exception(e);
} finally {
try {
if (!contextReused) {
context.close(); | }
} finally {
// Pop from stack
Context.removeCommandContext();
Context.removeProcessEngineConfiguration();
Context.removeBpmnOverrideContext();
}
}
return null;
}
public CommandContextFactory getCommandContextFactory() {
return commandContextFactory;
}
public void setCommandContextFactory(CommandContextFactory commandContextFactory) {
this.commandContextFactory = commandContextFactory;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public void setProcessEngineContext(ProcessEngineConfigurationImpl processEngineContext) {
this.processEngineConfiguration = processEngineContext;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContextInterceptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setPackagingIdentification(PackagingIdentificationType value) {
this.packagingIdentification = value;
}
/**
* Planning Quantity Gets the value of the planningQuantity 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 planningQuantity property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPlanningQuantity().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PlanningQuantityType }
*
*
*/
public List<PlanningQuantityType> getPlanningQuantity() {
if (planningQuantity == null) {
planningQuantity = new ArrayList<PlanningQuantityType>();
}
return this.planningQuantity;
}
/**
* Gets the value of the forecastListLineItemExtension property.
* | * @return
* possible object is
* {@link ForecastListLineItemExtensionType }
*
*/
public ForecastListLineItemExtensionType getForecastListLineItemExtension() {
return forecastListLineItemExtension;
}
/**
* Sets the value of the forecastListLineItemExtension property.
*
* @param value
* allowed object is
* {@link ForecastListLineItemExtensionType }
*
*/
public void setForecastListLineItemExtension(ForecastListLineItemExtensionType value) {
this.forecastListLineItemExtension = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ForecastListLineItemType.java | 2 |
请完成以下Java代码 | public void setIsPrintoutForOtherUser (final boolean IsPrintoutForOtherUser)
{
set_Value (COLUMNNAME_IsPrintoutForOtherUser, IsPrintoutForOtherUser);
}
@Override
public boolean isPrintoutForOtherUser()
{
return get_ValueAsBoolean(COLUMNNAME_IsPrintoutForOtherUser);
}
/**
* ItemName AD_Reference_ID=540735
* Reference name: ItemName
*/
public static final int ITEMNAME_AD_Reference_ID=540735;
/** Rechnung = Rechnung */
public static final String ITEMNAME_Rechnung = "Rechnung";
/** Mahnung = Mahnung */
public static final String ITEMNAME_Mahnung = "Mahnung";
/** Mitgliedsausweis = Mitgliedsausweis */
public static final String ITEMNAME_Mitgliedsausweis = "Mitgliedsausweis";
/** Brief = Brief */
public static final String ITEMNAME_Brief = "Brief";
/** Sofort-Druck PDF = Sofort-Druck PDF */
public static final String ITEMNAME_Sofort_DruckPDF = "Sofort-Druck PDF";
/** PDF = PDF */
public static final String ITEMNAME_PDF = "PDF";
/** Versand/Wareneingang = Versand/Wareneingang */
public static final String ITEMNAME_VersandWareneingang = "Versand/Wareneingang";
@Override
public void setItemName (final @Nullable java.lang.String ItemName)
{
set_Value (COLUMNNAME_ItemName, ItemName);
}
@Override
public java.lang.String getItemName()
{ | return get_ValueAsString(COLUMNNAME_ItemName);
}
@Override
public void setPrintingQueueAggregationKey (final @Nullable java.lang.String PrintingQueueAggregationKey)
{
set_Value (COLUMNNAME_PrintingQueueAggregationKey, PrintingQueueAggregationKey);
}
@Override
public java.lang.String getPrintingQueueAggregationKey()
{
return get_ValueAsString(COLUMNNAME_PrintingQueueAggregationKey);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Printing_Queue.java | 1 |
请完成以下Java代码 | protected boolean isRedirectable(String method) {
return true;
}
});
try (CloseableHttpClient client = httpClientBuilder.build()) {
HttpPut put = new HttpPut(loadUrl);
StringEntity entity = new StringEntity(content, "UTF-8");
put.setHeader(HttpHeaders.EXPECT, "100-continue");
put.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader(STARROCKS_USER, STARROCKS_PASSWORD));
// the label header is optional, not necessary
// use label header can ensure at most once semantics
put.setHeader("label", "39c25a5c-7000-496e-a98e-348a264c81de1");
put.setEntity(entity);
try (CloseableHttpResponse response = client.execute(put)) {
String loadResult = "";
if (response.getEntity() != null) {
loadResult = EntityUtils.toString(response.getEntity());
}
final int statusCode = response.getStatusLine().getStatusCode();
// statusCode 200 just indicates that starrocks be service is ok, not stream load
// you should see the output content to find whether stream load is success
if (statusCode != 200) {
throw new IOException(
String.format("Stream load failed, statusCode=%s load result=%s", statusCode, loadResult));
}
System.out.println(loadResult);
}
} | }
private String basicAuthHeader(String username, String password) {
final String tobeEncode = username + ":" + password;
byte[] encoded = Base64.encodeBase64(tobeEncode.getBytes(StandardCharsets.UTF_8));
return "Basic " + new String(encoded);
}
public static void main(String[] args) throws Exception {
int id1 = 1;
int id2 = 10;
String id3 = "Simon";
int rowNumber = 10;
String oneRow = id1 + "\t" + id2 + "\t" + id3 + "\n";
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < rowNumber; i++) {
stringBuilder.append(oneRow);
}
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
String loadData = stringBuilder.toString();
StarRocksStreamLoad starrocksStreamLoad = new StarRocksStreamLoad();
starrocksStreamLoad.sendData(loadData);
}
} | repos\springboot-demo-master\starrocks\src\main\java\com\et\starrocks\streamload\StarRocksStreamLoad.java | 1 |
请完成以下Java代码 | public void updateDeliveryDayWhenAllocationChanged(
final de.metas.tourplanning.model.I_M_DeliveryDay deliveryDay,
final de.metas.tourplanning.model.I_M_DeliveryDay_Alloc deliveryDayAlloc,
final de.metas.tourplanning.model.I_M_DeliveryDay_Alloc deliveryDayAllocOld)
{
final I_M_DeliveryDay huDeliveryDay = InterfaceWrapperHelper.create(deliveryDay, I_M_DeliveryDay.class);
//
// Get Old Qtys from M_DeliveryDay_Alloc
I_M_DeliveryDay_Alloc qtysToRemove = InterfaceWrapperHelper.create(deliveryDayAllocOld, I_M_DeliveryDay_Alloc.class);
if (qtysToRemove != null && !qtysToRemove.isActive())
{
qtysToRemove = null;
}
//
// Get New Qtys from M_DeliveryDay_Alloc
I_M_DeliveryDay_Alloc qtysToAdd = InterfaceWrapperHelper.create(deliveryDayAlloc, I_M_DeliveryDay_Alloc.class);
if (qtysToAdd != null && !qtysToAdd.isActive())
{
qtysToAdd = null;
}
// Adjust Delivery Day's quantities
HUDeliveryQuantitiesHelper.adjust(huDeliveryDay, qtysToRemove, qtysToAdd);
}
@Override
public void updateTourInstanceWhenDeliveryDayChanged(
final de.metas.tourplanning.model.I_M_Tour_Instance tourInstance,
final de.metas.tourplanning.model.I_M_DeliveryDay deliveryDay,
final de.metas.tourplanning.model.I_M_DeliveryDay deliveryDayOld)
{
final I_M_Tour_Instance huTourInstance = InterfaceWrapperHelper.create(tourInstance, I_M_Tour_Instance.class); | //
// Get Old Qtys from M_DeliveryDay
I_M_DeliveryDay qtysToRemove = InterfaceWrapperHelper.create(deliveryDayOld, I_M_DeliveryDay.class);
if (qtysToRemove != null && !qtysToRemove.isActive())
{
qtysToRemove = null;
}
//
// Get New Qtys from M_DeliveryDay_Alloc
I_M_DeliveryDay qtysToAdd = InterfaceWrapperHelper.create(deliveryDay, I_M_DeliveryDay.class);
if (qtysToAdd != null && !qtysToAdd.isActive())
{
qtysToAdd = null;
}
// Adjust Tour Instance's quantities
HUDeliveryQuantitiesHelper.adjust(huTourInstance, qtysToRemove, qtysToAdd);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\tourplanning\spi\impl\HUShipmentScheduleDeliveryDayHandler.java | 1 |
请完成以下Java代码 | public String getDisplayName()
{
return displayName;
}
/**
* @return true if this action is currently running
*/
public final boolean isRunning()
{
return running;
}
@Override
public void execute()
{
running = true;
try
{
execute0();
}
finally
{
running = false;
}
}
private void execute0()
{
final int countEnqueued = PMM_GenerateOrders.prepareEnqueuing()
.filter(gridTab.createCurrentRecordsQueryFilter(I_PMM_PurchaseCandidate.class))
.confirmRecordsToProcess(this::confirmRecordsToProcess) | .enqueue();
//
// Refresh rows, because they were updated
if (countEnqueued > 0)
{
gridTab.dataRefreshAll();
}
//
// Inform the user
clientUI.info(windowNo, "Updated", "#" + countEnqueued);
}
private final boolean confirmRecordsToProcess(final int countToProcess)
{
return clientUI.ask()
.setParentWindowNo(windowNo)
.setAdditionalMessage(msgBL.getMsg(Env.getCtx(), MSG_DoYouWantToUpdate_1P, new Object[] { countToProcess }))
.setDefaultAnswer(false)
.getAnswer();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\callout\PMM_CreatePurchaseOrders_Action.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<User> getUserList() {
return new ArrayList<>(users.values());
}
@ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "query"),
@ApiImplicitParam(name = "name", value = "用户名", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "age", value = "年龄", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "ipAddr", value = "ip哟", required = false, dataType = "String", paramType = "query")
})
@RequestMapping(value = "", method = RequestMethod.POST)
public BaseResult<User> postUser(@ApiIgnore User user) {
users.put(user.getId(), user);
return BaseResult.successWithData(user);
}
@ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable Long id) {
return users.get(id);
}
@ApiOperation(value = "更新用户信息", notes = "根据用户ID更新信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "query"),
@ApiImplicitParam(name = "name", value = "用户名", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "age", value = "年龄", required = true, dataType = "String", paramType = "query")
}) | @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public BaseResult<User> putUser(@PathVariable Long id, @ApiIgnore User user) {
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
return BaseResult.successWithData(u);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
users.remove(id);
return "success";
}
@RequestMapping(value = "/ignoreMe/{id}", method = RequestMethod.DELETE)
public String ignoreMe(@PathVariable Long id) {
users.remove(id);
return "success";
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-9 课:Spring Boot 中使用 Swagger2 构建 RESTful APIs\spring-boot-swagger\src\main\java\com\neo\controller\UserController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public DirectExchange eventsExchange()
{
return new DirectExchange(EXCHANGE_NAME_PREFIX);
}
@Bean
public Binding eventsBinding()
{
return BindingBuilder.bind(eventsQueue())
.to(eventsExchange()).with(EXCHANGE_NAME_PREFIX);
}
@Override
public String getQueueName()
{ | return eventsQueue().getName();
}
@Override
public Optional<String> getTopicName()
{
return Optional.empty();
}
@Override
public String getExchangeName()
{
return eventsExchange().getName();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\remote\rabbitmq\queues\default_queue\DefaultQueueConfiguration.java | 2 |
请完成以下Java代码 | public boolean isOrganizationOnly()
{
return this == Organization;
}
/**
* @return user friendly AD_Message of this access level.
*/
public String getAD_Message()
{
return adMessage;
}
/**
* Gets user friendly description of enabled flags.
*
* e.g. "3 - Client - Org"
*
* @return user friendly description of enabled flags
*/
public String getDescription()
{
final StringBuilder accessLevelInfo = new StringBuilder();
accessLevelInfo.append(getAccessLevelString());
if (isSystem())
{
accessLevelInfo.append(" - System");
}
if (isClient())
{
accessLevelInfo.append(" - Client");
}
if (isOrganization()) | {
accessLevelInfo.append(" - Org");
}
return accessLevelInfo.toString();
}
// --------------------------------------
// Pre-indexed values for optimization
private static ImmutableMap<Integer, TableAccessLevel> accessLevelInt2accessLevel;
static
{
final ImmutableMap.Builder<Integer, TableAccessLevel> builder = new ImmutableMap.Builder<Integer, TableAccessLevel>();
for (final TableAccessLevel l : values())
{
builder.put(l.getAccessLevelInt(), l);
}
accessLevelInt2accessLevel = builder.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\TableAccessLevel.java | 1 |
请完成以下Java代码 | public class OrgLawType {
@XmlAttribute(name = "insured_id")
protected String insuredId;
@XmlAttribute(name = "case_id")
protected String caseId;
@XmlAttribute(name = "case_date")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar caseDate;
/**
* Gets the value of the insuredId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInsuredId() {
return insuredId;
}
/**
* Sets the value of the insuredId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInsuredId(String value) {
this.insuredId = value;
}
/**
* Gets the value of the caseId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCaseId() {
return caseId;
}
/**
* Sets the value of the caseId property.
*
* @param value
* allowed object is
* {@link String }
*
*/ | public void setCaseId(String value) {
this.caseId = value;
}
/**
* Gets the value of the caseDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getCaseDate() {
return caseDate;
}
/**
* Sets the value of the caseDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setCaseDate(XMLGregorianCalendar value) {
this.caseDate = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\OrgLawType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static final class H2ConsoleRequestMatcher extends ApplicationContextRequestMatcher<ApplicationContext> {
private volatile @Nullable RequestMatcher delegate;
private H2ConsoleRequestMatcher() {
super(ApplicationContext.class);
}
@Override
protected boolean ignoreApplicationContext(WebApplicationContext applicationContext) {
return hasServerNamespace(applicationContext, "management");
}
@Override
protected void initialized(Supplier<ApplicationContext> context) { | String path = context.get().getBean(H2ConsoleProperties.class).getPath();
Assert.hasText(path, "'path' in H2ConsoleProperties must not be empty");
this.delegate = PathPatternRequestMatcher.withDefaults().matcher(path + "/**");
}
@Override
protected boolean matches(HttpServletRequest request, Supplier<ApplicationContext> context) {
RequestMatcher delegate = this.delegate;
Assert.state(delegate != null, "'delegate' must not be null");
return delegate.matches(request);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\autoconfigure\web\servlet\PathRequest.java | 2 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() { | return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public ContactPerson getContactPerson() {
return contactPerson;
}
public void setContactPerson(ContactPerson contactPerson) {
this.contactPerson = contactPerson;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-annotations\src\main\java\com\baeldung\embeddable\model\Company.java | 1 |
请完成以下Java代码 | public class Author {
@Id
private Long id;
private String firstName;
private String lastName;
@Indexed
private int age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName; | }
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return this.firstName + " " + this.lastName + ", " + this.age + " years old";
}
} | repos\tutorials-master\persistence-modules\spring-data-geode\src\main\java\com\baeldung\springdatageode\domain\Author.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EmployeeController {
@Autowired
private EmployeeService employeeService;
// display list of employee
@GetMapping("/")
public String viewHomePage(Model model){
return findPaginated(1, "firstName", "asc", model);
}
@GetMapping("/showNewEmployeeForm")
public String showNewEmployeeForm(Model model) {
// create model attribute to bind from data
Employee employee = new Employee();
model.addAttribute("employee", employee);
return "new_employee";
}
@PostMapping("/saveEmployee")
public String saveEmployee(@ModelAttribute ("employee") Employee employee){
// save employee to database
employeeService.saveEmployee(employee);
return "redirect:/";
}
@GetMapping("/showFormForUpdate/{id}")
public String showFormForUpdate(@PathVariable(value = "id") long id, Model model){
// get employee from the service
Employee employee = employeeService.getEmployeeById(id);
//set employee a model attribute to pre-population the form | model.addAttribute("employee", employee);
return "update_employee";
}
@GetMapping("/deleteEmployee/{id}")
public String deleteEmployee(@PathVariable (value = "id") long id) {
// call delete employee method
this.employeeService.deleteEmployeeById(id);
return "redirect:/";
}
@GetMapping("/page/{pageNo}")
public String findPaginated(@PathVariable (value = "pageNo") int pageNo,
@RequestParam("sortField") String sortField,
@RequestParam("sortDir") String sortDir,
Model model) {
int pageSize = 5;
Page<Employee> page = employeeService.findPaginated(pageNo, pageSize, sortField, sortDir);
List<Employee> listEmployees = page.getContent();
model.addAttribute("currentPage", pageNo);
model.addAttribute("totalPages", page.getTotalPages());
model.addAttribute("totalItems", page.getTotalElements());
model.addAttribute("sortField", sortField);
model.addAttribute("sortDir", sortDir);
model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc");
model.addAttribute("listEmployees", listEmployees);
return "index";
}
} | repos\Spring-Boot-Advanced-Projects-main\Registration-FullStack-Springboot\src\main\java\pagination\sort\controller\EmployeeController.java | 2 |
请完成以下Java代码 | public IAttributeSet getAttributesFrom()
{
return attributeStorageFrom;
}
@Override
public IAttributeStorage getAttributesTo()
{
return attributeStorageTo;
}
@Override
public IHUStorage getHUStorageFrom()
{
return huStorageFrom;
}
@Override
public IHUStorage getHUStorageTo() | {
return huStorageTo;
}
@Override
public BigDecimal getQtyUnloaded()
{
return qtyUnloaded;
}
@Override
public boolean isVHUTransfer()
{
return vhuTransfer;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\strategy\impl\HUAttributeTransferRequest.java | 1 |
请完成以下Java代码 | public String getTaskId() {
return taskId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getOperationType() {
return operationType;
}
public String getAssignerId() {
return assignerId;
}
public String getTenantId() {
return tenantId;
}
public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public static HistoricIdentityLinkLogDto fromHistoricIdentityLink(HistoricIdentityLinkLog historicIdentityLink) {
HistoricIdentityLinkLogDto dto = new HistoricIdentityLinkLogDto();
fromHistoricIdentityLink(dto, historicIdentityLink); | return dto;
}
public static void fromHistoricIdentityLink(HistoricIdentityLinkLogDto dto,
HistoricIdentityLinkLog historicIdentityLink) {
dto.id = historicIdentityLink.getId();
dto.assignerId = historicIdentityLink.getAssignerId();
dto.groupId = historicIdentityLink.getGroupId();
dto.operationType = historicIdentityLink.getOperationType();
dto.taskId = historicIdentityLink.getTaskId();
dto.time = historicIdentityLink.getTime();
dto.type = historicIdentityLink.getType();
dto.processDefinitionId = historicIdentityLink.getProcessDefinitionId();
dto.processDefinitionKey = historicIdentityLink.getProcessDefinitionKey();
dto.userId = historicIdentityLink.getUserId();
dto.tenantId = historicIdentityLink.getTenantId();
dto.removalTime = historicIdentityLink.getRemovalTime();
dto.rootProcessInstanceId = historicIdentityLink.getRootProcessInstanceId();
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIdentityLinkLogDto.java | 1 |
请完成以下Java代码 | public class GenreTypeConverter implements AttributeConverter<GenreType, Integer> {
@Override
public Integer convertToDatabaseColumn(GenreType attr) {
if (attr == null) {
return null;
}
switch (attr) {
case HORROR:
return 10;
case ANTHOLOGY:
return 20;
case HISTORY:
return 30;
default:
throw new IllegalArgumentException("The " + attr + " not supported.");
}
} | @Override
public GenreType convertToEntityAttribute(Integer dbData) {
if (dbData == null) {
return null;
}
switch (dbData) {
case 10:
return HORROR;
case 20:
return ANTHOLOGY;
case 30:
return HISTORY;
default:
throw new IllegalArgumentException("The " + dbData + " not supported.");
}
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootEnumAttributeConverter\src\main\java\com\bookstore\converter\GenreTypeConverter.java | 1 |
请完成以下Java代码 | public int getAD_PrinterHW_MediaTray_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_PrinterHW_MediaTray_ID);
}
@Override
public void setCalX (int CalX)
{
set_Value (COLUMNNAME_CalX, Integer.valueOf(CalX));
}
@Override
public int getCalX()
{
return get_ValueAsInt(COLUMNNAME_CalX);
}
@Override
public void setCalY (int CalY)
{
set_Value (COLUMNNAME_CalY, Integer.valueOf(CalY));
}
@Override
public int getCalY()
{
return get_ValueAsInt(COLUMNNAME_CalY);
}
@Override
public void setHostKey (java.lang.String HostKey)
{
throw new IllegalArgumentException ("HostKey is virtual column"); }
@Override
public java.lang.String getHostKey()
{
return (java.lang.String)get_Value(COLUMNNAME_HostKey);
}
@Override
public void setIsManualCalibration (boolean IsManualCalibration)
{
set_Value (COLUMNNAME_IsManualCalibration, Boolean.valueOf(IsManualCalibration));
}
@Override | public boolean isManualCalibration()
{
return get_ValueAsBoolean(COLUMNNAME_IsManualCalibration);
}
@Override
public void setMeasurementX (java.math.BigDecimal MeasurementX)
{
set_Value (COLUMNNAME_MeasurementX, MeasurementX);
}
@Override
public java.math.BigDecimal getMeasurementX()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MeasurementX);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setMeasurementY (java.math.BigDecimal MeasurementY)
{
set_Value (COLUMNNAME_MeasurementY, MeasurementY);
}
@Override
public java.math.BigDecimal getMeasurementY()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MeasurementY);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterHW_Calibration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void bulkDeleteHistoricVariableInstancesByProcessInstanceIds(Collection<String> processInstanceIds) {
dataManager.bulkDeleteHistoricVariableInstancesByProcessInstanceIds(processInstanceIds);
}
@Override
public void bulkDeleteHistoricVariableInstancesByTaskIds(Collection<String> taskIds) {
dataManager.bulkDeleteHistoricVariableInstancesByTaskIds(taskIds);
}
@Override
public void bulkDeleteHistoricVariableInstancesByScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType) {
dataManager.bulkDeleteHistoricVariableInstancesByScopeIdsAndScopeType(scopeIds, scopeType);
}
@Override
public void deleteHistoricVariableInstancesForNonExistingProcessInstances() {
dataManager.deleteHistoricVariableInstancesForNonExistingProcessInstances();
} | @Override
public void deleteHistoricVariableInstancesForNonExistingCaseInstances() {
dataManager.deleteHistoricVariableInstancesForNonExistingCaseInstances();
}
@Override
public List<HistoricVariableInstance> findHistoricVariableInstancesByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricVariableInstancesByNativeQuery(parameterMap);
}
@Override
public long findHistoricVariableInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricVariableInstanceCountByNativeQuery(parameterMap);
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\HistoricVariableInstanceEntityManagerImpl.java | 2 |
请完成以下Java代码 | public BigDecimal getQtyCUsPerLU()
{
return ediDesadvPackItems.stream()
.map(EDIDesadvPackItem::getQtyCUsPerLU)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
@Value
@Builder
public static class EDIDesadvPackItem
{
@NonNull
EDIDesadvPackItemId ediDesadvPackItemId;
@NonNull
EDIDesadvPackId ediDesadvPackId;
@NonNull
EDIDesadvLineId ediDesadvLineId;
int line;
@NonNull
BigDecimal movementQty;
@Nullable
InOutId inOutId;
@Nullable
InOutLineId inOutLineId;
@Nullable
BigDecimal qtyItemCapacity;
@Nullable
Integer qtyTu;
@Nullable
BigDecimal qtyCUsPerTU; | @Nullable
BigDecimal qtyCUPerTUinInvoiceUOM;
@Nullable
BigDecimal qtyCUsPerLU;
@Nullable
BigDecimal qtyCUsPerLUinInvoiceUOM;
@Nullable
Timestamp bestBeforeDate;
@Nullable
String lotNumber;
@Nullable
PackagingCodeId huPackagingCodeTuId;
@Nullable
String gtinTuPackingMaterial;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\pack\EDIDesadvPack.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class VoidOrderHandler implements VoidOrderAndRelatedDocsHandler
{
@Override
public RecordsToHandleKey getRecordsToHandleKey()
{
return RecordsToHandleKey.of(I_C_Order.Table_Name);
}
@Override
public void handleOrderVoided(@NonNull final VoidOrderAndRelatedDocsRequest request)
{
final IDocumentBL documentBL = Services.get(IDocumentBL.class);
final IPair<RecordsToHandleKey, List<ITableRecordReference>> recordsToHandle = request.getRecordsToHandle();
final List<I_C_Order> orderRecordsToHandle = TableRecordReference.getModels(recordsToHandle.getRight(), I_C_Order.class);
for (final I_C_Order orderRecord : orderRecordsToHandle)
{
// update the old orders' documentno
final String documentNo = setVoidedOrderNewDocumenTNo(request.getVoidedOrderDocumentNoPrefix(), orderRecord, 1);
final I_C_Order copiedOrderRecord = newInstance(I_C_Order.class);
InterfaceWrapperHelper.copyValues(orderRecord, copiedOrderRecord);
copiedOrderRecord.setDocumentNo(documentNo);
saveRecord(copiedOrderRecord);
// copy-with-details, set orderRecord's previous DocumentNo
CopyRecordFactory.getCopyRecordSupport(I_C_Order.Table_Name)
.copyChildren(
LegacyAdapters.convertToPO(copiedOrderRecord),
LegacyAdapters.convertToPO(orderRecord));
documentBL.processEx(orderRecord, IDocument.ACTION_Void);
saveRecord(orderRecord);
}
}
private String setVoidedOrderNewDocumenTNo(
@NonNull final String voidedOrderDocumentNoPrefix,
@NonNull final I_C_Order orderRecord,
int attemptCount) | {
final String prefixToUse;
if (attemptCount <= 1)
{
prefixToUse = String.format("%s-", voidedOrderDocumentNoPrefix);
}
else
{
prefixToUse = String.format("%s(%s)-", voidedOrderDocumentNoPrefix, attemptCount);
}
final String documentNo = orderRecord.getDocumentNo();
// try to update; retry on exception, with a different docNo;
// Rationale: duplicate documentNos are OK if the doc has different docTypes or bPartners(!).
// I don't want to make assumptions on the exact unique constraint
// Also, I hope that a voided order's copy is voided again is rare enough.
try
{
orderRecord.setDocumentNo(prefixToUse + documentNo);
saveRecord(orderRecord);
}
catch (final DBUniqueConstraintException e)
{
orderRecord.setDocumentNo(documentNo); // go back to the original documentno for the next try, to avoid <prefix>(2)-<prefix>-document
setVoidedOrderNewDocumenTNo(voidedOrderDocumentNoPrefix, orderRecord, attemptCount + 1);
}
return documentNo;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\voidorderandrelateddocs\VoidOrderHandler.java | 2 |
请完成以下Java代码 | public class EncryptUtils {
private static final String STR_PARAM = "Passw0rd";
private static final IvParameterSpec IV = new IvParameterSpec(STR_PARAM.getBytes(StandardCharsets.UTF_8));
private static DESKeySpec getDesKeySpec(String source) throws Exception {
if (source == null || source.isEmpty()) {
return null;
}
String strKey = "Passw0rd";
return new DESKeySpec(strKey.getBytes(StandardCharsets.UTF_8));
}
/**
* 对称加密
*/
public static String desEncrypt(String source) throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = getDesKeySpec(source);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, IV);
return byte2hex(cipher.doFinal(source.getBytes(StandardCharsets.UTF_8))).toUpperCase();
}
/**
* 对称解密
*/
public static String desDecrypt(String source) throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
byte[] src = hex2byte(source.getBytes(StandardCharsets.UTF_8));
DESKeySpec desKeySpec = getDesKeySpec(source);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
cipher.init(Cipher.DECRYPT_MODE, secretKey, IV); | byte[] retByte = cipher.doFinal(src);
return new String(retByte);
}
private static String byte2hex(byte[] inStr) {
String stmp;
StringBuilder out = new StringBuilder(inStr.length * 2);
for (byte b : inStr) {
stmp = Integer.toHexString(b & 0xFF);
if (stmp.length() == 1) {
out.append("0").append(stmp);
} else {
out.append(stmp);
}
}
return out.toString();
}
private static byte[] hex2byte(byte[] b) {
int size = 2;
if ((b.length % size) != 0) {
throw new IllegalArgumentException("长度不是偶数");
}
byte[] b2 = new byte[b.length / 2];
for (int n = 0; n < b.length; n += size) {
String item = new String(b, n, 2);
b2[n / 2] = (byte) Integer.parseInt(item, 16);
}
return b2;
}
} | repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\EncryptUtils.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8079
management:
server:
port: 8078 # 自定义端口,避免 Nginx 暴露出去
endpoint:
health:
show-details: always # 配置展示明细,这样自定义的 ServerHealthIndicator 才可以被访问
web:
| exposure:
include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 | repos\SpringBoot-Labs-master\lab-41\lab-41-demo02\src\main\resources\application-dev.yaml | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getField4() {
return field4;
}
public void setField4(String field4) {
this.field4 = field4 == null ? null : field4.trim();
}
public String getField5() {
return field5;
}
public void setField5(String field5) {
this.field5 = field5 == null ? null : field5.trim();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(super.getId());
sb.append(", version=").append(super.getVersion());
sb.append(", createTime=").append(super.getCreateTime());
sb.append(", editor=").append(super.getEditor());
sb.append(", creater=").append(super.getCreater());
sb.append(", editTime=").append(super.getEditTime());
sb.append(", status=").append(super.getStatus());
sb.append(", productName=").append(productName);
sb.append(", merchantOrderNo=").append(merchantOrderNo);
sb.append(", orderAmount=").append(orderAmount);
sb.append(", orderFrom=").append(orderFrom);
sb.append(", merchantName=").append(merchantName);
sb.append(", merchantNo=").append(merchantNo);
sb.append(", orderTime=").append(orderTime);
sb.append(", orderDate=").append(orderDate); | sb.append(", orderIp=").append(orderIp);
sb.append(", orderRefererUrl=").append(orderRefererUrl);
sb.append(", returnUrl=").append(returnUrl);
sb.append(", notifyUrl=").append(notifyUrl);
sb.append(", cancelReason=").append(cancelReason);
sb.append(", orderPeriod=").append(orderPeriod);
sb.append(", expireTime=").append(expireTime);
sb.append(", payWayCode=").append(payWayCode);
sb.append(", payWayName=").append(payWayName);
sb.append(", remark=").append(remark);
sb.append(", trxType=").append(trxType);
sb.append(", payTypeCode=").append(payTypeCode);
sb.append(", payTypeName=").append(payTypeName);
sb.append(", fundIntoType=").append(fundIntoType);
sb.append(", isRefund=").append(isRefund);
sb.append(", refundTimes=").append(refundTimes);
sb.append(", successRefundAmount=").append(successRefundAmount);
sb.append(", trxNo=").append(trxNo);
sb.append(", field1=").append(field1);
sb.append(", field2=").append(field2);
sb.append(", field3=").append(field3);
sb.append(", field4=").append(field4);
sb.append(", field5=").append(field5);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\RpTradePaymentOrder.java | 2 |
请完成以下Java代码 | protected void onCreate(ActivitiEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an entity initialized event is received.
*/
protected void onInitialized(ActivitiEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an entity delete event is received.
*/
protected void onDelete(ActivitiEvent event) {
// Default implementation is a NO-OP | }
/**
* Called when an entity update event is received.
*/
protected void onUpdate(ActivitiEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an event is received, which is not a create, an update or delete.
*/
protected void onEntityEvent(ActivitiEvent event) {
// Default implementation is a NO-OP
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\BaseEntityEventListener.java | 1 |
请完成以下Java代码 | public Collection<Role> retrieveAllRolesWithUserAccess()
{
final Set<RoleId> roleIds = Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_AD_Role.class)
.addEqualsFilter(I_AD_Role.COLUMNNAME_IsManual, false)
.addOnlyActiveRecordsFilter()
.create()
.setRequiredAccess(Access.READ)
.idsAsSet(RoleId::ofRepoId);
return getByIds(roleIds);
}
@Override
public String getRoleName(final RoleId adRoleId)
{
if (adRoleId == null)
{
return "?";
}
final Role role = getById(adRoleId);
return role.getName();
}
@Override
// @Cached(cacheName = I_AD_User_Roles.Table_Name + "#by#AD_Role_ID", expireMinutes = 0) // not sure if caching is needed...
public Set<UserId> retrieveUserIdsForRoleId(final RoleId adRoleId)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_User_Roles.class)
.addEqualsFilter(I_AD_User_Roles.COLUMN_AD_Role_ID, adRoleId)
.addOnlyActiveRecordsFilter()
.create()
.listDistinct(I_AD_User_Roles.COLUMNNAME_AD_User_ID, Integer.class)
.stream()
.map(UserId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
}
@Override
public RoleId retrieveFirstRoleIdForUserId(final UserId userId)
{
final Integer firstRoleId = Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_User_Roles.class) | .addEqualsFilter(I_AD_User_Roles.COLUMN_AD_User_ID, userId)
.addOnlyActiveRecordsFilter()
.create()
.first(I_AD_User_Roles.COLUMNNAME_AD_Role_ID, Integer.class);
return firstRoleId == null ? null : RoleId.ofRepoIdOrNull(firstRoleId);
}
@Override
public void createUserRoleAssignmentIfMissing(final UserId adUserId, final RoleId adRoleId)
{
if (hasUserRoleAssignment(adUserId, adRoleId))
{
return;
}
final I_AD_User_Roles userRole = InterfaceWrapperHelper.newInstance(I_AD_User_Roles.class);
userRole.setAD_User_ID(adUserId.getRepoId());
userRole.setAD_Role_ID(adRoleId.getRepoId());
InterfaceWrapperHelper.save(userRole);
Services.get(IUserRolePermissionsDAO.class).resetCacheAfterTrxCommit();
}
private boolean hasUserRoleAssignment(final UserId adUserId, final RoleId adRoleId)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_User_Roles.class)
.addEqualsFilter(I_AD_User_Roles.COLUMNNAME_AD_User_ID, adUserId)
.addEqualsFilter(I_AD_User_Roles.COLUMN_AD_Role_ID, adRoleId)
.addOnlyActiveRecordsFilter()
.create()
.anyMatch();
}
public void deleteUserRolesByUserId(final UserId userId)
{
Services.get(IQueryBL.class).createQueryBuilder(I_AD_User_Roles.class)
.addEqualsFilter(I_AD_User_Roles.COLUMNNAME_AD_User_ID, userId)
.create()
.delete();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\RoleDAO.java | 1 |
请完成以下Java代码 | private ImmutableSet<HuId> resolveHuIdsByParentHUQr(@NonNull final HUQRCode parentHUQrCode, @NonNull final HUQRCodeAssignment targetQrCodeAssignment)
{
final HUQRCodeAssignment parentQrCodeAssignment = huQRCodeService
.getHUAssignmentByQRCode(parentHUQrCode)
.orElseThrow(() -> new AdempiereException("No HU found for parent QR Code!")
.appendParametersToMessage()
.setParameter("parentHUQrCode", parentHUQrCode));
if (!parentQrCodeAssignment.isSingleHUAssigned())
{
throw new AdempiereException("More than one HU assigned to parentHUQRCode!")
.appendParametersToMessage()
.setParameter("parentHUQrCode", parentHUQrCode)
.setParameter("assignedHUs", parentQrCodeAssignment
.getHuIds()
.stream()
.map(HuId::getRepoId)
.map(String::valueOf)
.collect(Collectors.joining(",", "[", "]")));
}
return handlingUnitsDAO.retrieveIncludedHUs(parentQrCodeAssignment.getSingleHUId())
.stream()
.map(I_M_HU::getM_HU_ID)
.map(HuId::ofRepoId)
.filter(targetQrCodeAssignment::isAssignedToHuId)
.collect(ImmutableSet.toImmutableSet());
}
@Nullable
private String getEffectivePIName(@NonNull final I_M_HU hu)
{
return Optional.ofNullable(handlingUnitsBL.getEffectivePI(hu))
.map(I_M_HU_PI::getName)
.orElse(null);
}
@Nullable
private String extractTopLevelParentHUIdValue(@NonNull final I_M_HU hu)
{
return Optional.ofNullable(handlingUnitsBL.getTopLevelParent(hu))
.map(I_M_HU::getM_HU_ID)
.filter(parentHUId -> parentHUId != hu.getM_HU_ID())
.map(String::valueOf)
.orElse(null);
} | private static @NonNull ResponseEntity<JsonGetSingleHUResponse> toBadRequestResponseEntity(final Exception e)
{
final String adLanguage = Env.getADLanguageOrBaseLanguage();
return ResponseEntity.badRequest()
.body(JsonGetSingleHUResponse.builder()
.error(JsonErrors.ofThrowable(e, adLanguage))
.multipleHUsFound(wereMultipleHUsFound(e))
.build());
}
private static boolean wereMultipleHUsFound(final Exception e)
{
return Optional.of(e)
.filter(error -> error instanceof AdempiereException)
.map(error -> (AdempiereException)error)
.map(adempiereEx -> adempiereEx.getParameter(MORE_THAN_ONE_HU_FOUND_ERROR_PARAM_NAME))
.filter(moreThanOneHUFoundParam -> moreThanOneHUFoundParam instanceof Boolean)
.map(moreThanOneHUFoundParam -> (Boolean)moreThanOneHUFoundParam)
.orElse(false);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\rest_api\HandlingUnitsService.java | 1 |
请完成以下Java代码 | public void init()
{
final IProgramaticCalloutProvider programmaticCalloutProvider = Services.get(IProgramaticCalloutProvider.class);
programmaticCalloutProvider.registerAnnotatedCallout(this);
}
@CalloutMethod(columnNames = I_AD_Window.COLUMNNAME_AD_Element_ID)
public void calloutOnElementIdChanged(final I_AD_Window window)
{
updateWindowFromElement(window);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_AD_Tab.COLUMNNAME_AD_Element_ID)
public void onBeforeWindowSave_WhenElementIdChanged(final I_AD_Window window)
{
updateWindowFromElement(window);
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = I_AD_Window.COLUMNNAME_AD_Element_ID)
public void onAfterWindowSave_WhenElementIdChanged(final I_AD_Window window)
{
updateTranslationsForElement(window);
recreateElementLinkForWindow(window);
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE })
public void onAfterWindowSave_AssertNoCyclesInWindowCustomizationsChain(@NonNull final I_AD_Window window)
{
customizedWindowInfoMapRepository.assertNoCycles(AdWindowId.ofRepoId(window.getAD_Window_ID()));
}
private void updateWindowFromElement(final I_AD_Window window)
{
// do not copy translations from element to window
if (!IElementTranslationBL.DYNATTR_AD_Window_UpdateTranslations.getValue(window, true))
{
return;
}
final I_AD_Element windowElement = adElementDAO.getById(window.getAD_Element_ID());
if (windowElement == null)
{
// nothing to do. It was not yet set
return;
}
window.setName(windowElement.getName());
window.setDescription(windowElement.getDescription());
window.setHelp(windowElement.getHelp());
}
private void updateTranslationsForElement(final I_AD_Window window)
{
final AdElementId windowElementId = AdElementId.ofRepoIdOrNull(window.getAD_Element_ID());
if (windowElementId == null)
{
// nothing to do. It was not yet set | return;
}
elementTranslationBL.updateWindowTranslationsFromElement(windowElementId);
}
private void recreateElementLinkForWindow(final I_AD_Window window)
{
final AdWindowId adWindowId = AdWindowId.ofRepoIdOrNull(window.getAD_Window_ID());
if (adWindowId != null)
{
final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class);
elementLinksService.recreateADElementLinkForWindowId(adWindowId);
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE })
public void onBeforeWindowDelete(final I_AD_Window window)
{
final AdWindowId adWindowId = AdWindowId.ofRepoId(window.getAD_Window_ID());
final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class);
elementLinksService.deleteExistingADElementLinkForWindowId(adWindowId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\window\model\interceptor\AD_Window.java | 1 |
请完成以下Java代码 | public ImmutableShipmentScheduleSegment build()
{
return ImmutableShipmentScheduleSegment.builder()
.productIds(productIds)
.locatorIds(locatorIds)
.bpartnerIds(bpartnerIds)
.attributes(attributeSegments)
.build();
}
public ShipmentScheduleSegmentBuilder productId(final int productId)
{
productIds.add(productId);
return this;
}
public ShipmentScheduleSegmentBuilder bpartnerId(final int bpartnerId)
{
bpartnerIds.add(bpartnerId);
return this;
}
public ShipmentScheduleSegmentBuilder locatorId(final int locatorId)
{
locatorIds.add(locatorId);
return this;
}
public ShipmentScheduleSegmentBuilder locator(final I_M_Locator locator)
{
if (locator == null)
{
return this;
}
locatorIds.add(locator.getM_Locator_ID());
return this;
}
public ShipmentScheduleSegmentBuilder warehouseId(@NonNull final WarehouseId warehouseId)
{
final IWarehouseDAO warehouseDAO = Services.get(IWarehouseDAO.class);
final List<LocatorId> locatorIds = warehouseDAO.getLocatorIds(warehouseId);
for (final LocatorId locatorId : locatorIds)
{ | locatorId(locatorId.getRepoId());
}
return this;
}
public ShipmentScheduleSegmentBuilder warehouseIdIfNotNull(final @Nullable WarehouseId warehouseId)
{
if (warehouseId == null)
{
return this;
}
return warehouseId(warehouseId);
}
public ShipmentScheduleSegmentBuilder attributeSetInstanceId(final int M_AttributeSetInstance_ID)
{
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(M_AttributeSetInstance_ID);
return attributeSetInstanceId(asiId);
}
private ShipmentScheduleSegmentBuilder attributeSetInstanceId(@NonNull final AttributeSetInstanceId asiId)
{
final ShipmentScheduleAttributeSegment attributeSegment = ShipmentScheduleAttributeSegment.ofAttributeSetInstanceId(asiId);
attributeSegments.add(attributeSegment);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\invalidation\segments\ShipmentScheduleSegmentBuilder.java | 1 |
请完成以下Java代码 | public static JMXRegistry get()
{
return instance;
}
/**
* What to do when the JMX we want to register already exists
*/
public static enum OnJMXAlreadyExistsPolicy
{
/**
* Fail by throwning an {@link JMXException}.
*/
Fail,
/**
* Skip registration.
*/
Ignore,
/**
* Replace already existing JMX bean with our bean.
*/
Replace,
}
private JMXRegistry()
{
super();
}
/**
* Register given JMX Bean.
*
* @param jmxBean JMX bean to be registered
* @param onJMXAlreadyExistsPolicy what to do if a bean with same JMX Name already exists
* @return JMX's {@link ObjectName} which was registered
* @throws JMXException if registration failed
*/
public <T extends IJMXNameAware> ObjectName registerJMX(final T jmxBean, final OnJMXAlreadyExistsPolicy onJMXAlreadyExistsPolicy)
{
Check.assumeNotNull(jmxBean, "jmxBean not null");
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
//
// Create JMX ObjectName
final String jmxName = jmxBean.getJMXName();
final ObjectName jmxObjectName;
try
{
jmxObjectName = new ObjectName(jmxName);
}
catch (MalformedObjectNameException e)
{
throw new JMXException("Unable to create JMX ObjectName for JMX Name '" + jmxName + "'", e);
}
try
{
synchronized (mbs)
{
//
// Check if JMX Bean was already registered
if (mbs.isRegistered(jmxObjectName))
{
switch (onJMXAlreadyExistsPolicy)
{
case Ignore:
return null;
case Replace:
mbs.unregisterMBean(jmxObjectName);
break;
case Fail:
default:
throw new JMXException("A JMX bean was already registed for " + jmxName);
}
}
//
// Try registering or JMX bean
mbs.registerMBean(jmxBean, jmxObjectName);
}
}
catch (JMXException e)
{
throw e;
}
catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException | InstanceNotFoundException e)
{
throw new JMXException("Unable to register mbean for JMX Name'" + jmxName + "'", e);
}
return jmxObjectName; | }
/**
* Unregister JMX Bean for given <code>jmxObjectName</code>
*
* @param jmxObjectName
* @param failOnError
* @return true if successfully unregistered
* @throws JMXException if unregistration failed and <code>failOnError</code> is <code>true</code>.
*/
public boolean unregisterJMX(final ObjectName jmxObjectName, final boolean failOnError)
{
if (jmxObjectName == null)
{
if (failOnError)
{
throw new JMXException("Invalid JMX ObjectName: " + jmxObjectName);
}
return false;
}
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
boolean success = false;
try
{
mbs.unregisterMBean(jmxObjectName);
success = true;
}
catch (Exception e)
{
if (failOnError)
{
throw new JMXException("Cannot unregister " + jmxObjectName, e);
}
success = false;
}
return success;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\jmx\JMXRegistry.java | 1 |
请完成以下Java代码 | public class RestInterceptor implements WriterInterceptor, ReaderInterceptor {
/** logger */
private static final Logger logger = LoggerFactory.getLogger(RestInterceptor.class);
@Override
public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {
byte[] buffer = IOUtils.toByteArray(context.getInputStream());
logger.info("The contents of request body is: \n" + new String(buffer, "UTF-8") + "\n");
context.setInputStream(new ByteArrayInputStream(buffer));
return context.proceed();
}
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
RestInterceptor.OutputStreamWrapper wrapper =
new RestInterceptor.OutputStreamWrapper(context.getOutputStream());
context.setOutputStream(wrapper);
context.proceed();
logger.info("The contents of response body is: \n" + new String(wrapper.getBytes(), "UTF-8") + "\n");
}
protected static class OutputStreamWrapper extends OutputStream {
private final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
private final OutputStream output;
private OutputStreamWrapper(OutputStream output) {
this.output = output;
}
@Override
public void write(int i) throws IOException { | buffer.write(i);
output.write(i);
}
@Override
public void write(byte[] b) throws IOException {
buffer.write(b);
output.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
buffer.write(b, off, len);
output.write(b, off, len);
}
@Override
public void flush() throws IOException {
output.flush();
}
@Override
public void close() throws IOException {
output.close();
}
public byte[] getBytes() {
return buffer.toByteArray();
}
}
} | repos\springBoot-master\springboot-dubbo\abel-user-provider\src\main\java\cn\abel\user\filter\RestInterceptor.java | 1 |
请完成以下Java代码 | public Builder setResource(final TableColumnResource resource)
{
this.resource = resource;
return this;
}
public final Builder addAccess(final Access access)
{
accesses.add(access);
return this;
}
public final Builder removeAccess(final Access access)
{
accesses.remove(access);
return this;
}
public final Builder setAccesses(final Set<Access> acceses)
{
accesses.clear();
accesses.addAll(acceses); | return this;
}
public final Builder addAccesses(final Set<Access> acceses)
{
accesses.addAll(acceses);
return this;
}
public final Builder removeAllAccesses()
{
accesses.clear();
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TableColumnPermission.java | 1 |
请完成以下Java代码 | public RegisteredClient getRegisteredClient() {
return this.registeredClient;
}
/**
* Returns the {@link OAuth2AccessToken access token}.
* @return the {@link OAuth2AccessToken}
*/
public OAuth2AccessToken getAccessToken() {
return this.accessToken;
}
/**
* Returns the {@link OAuth2RefreshToken refresh token}.
* @return the {@link OAuth2RefreshToken} or {@code null} if not available | */
@Nullable
public OAuth2RefreshToken getRefreshToken() {
return this.refreshToken;
}
/**
* Returns the additional parameters.
* @return a {@code Map} of the additional parameters, may be empty
*/
public Map<String, Object> getAdditionalParameters() {
return this.additionalParameters;
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AccessTokenAuthenticationToken.java | 1 |
请完成以下Java代码 | public static boolean isSameWeekWithToday(Date date) {
if (date == null) {
return false;
}
// 0.先把Date类型的对象转换Calendar类型的对象
Calendar todayCal = Calendar.getInstance();
Calendar dateCal = Calendar.getInstance();
todayCal.setTime(new Date());
dateCal.setTime(date);
int subYear = todayCal.get(Calendar.YEAR) - dateCal.get(Calendar.YEAR);
// subYear==0,说明是同一年
if (subYear == 0) {
if (todayCal.get(Calendar.WEEK_OF_YEAR) == dateCal.get(Calendar.WEEK_OF_YEAR))
return true;
} else if (subYear == 1 && dateCal.get(Calendar.MONTH) == 11 && todayCal.get(Calendar.MONTH) == 0) {
if (todayCal.get(Calendar.WEEK_OF_YEAR) == dateCal.get(Calendar.WEEK_OF_YEAR))
return true;
} else if (subYear == -1 && todayCal.get(Calendar.MONTH) == 11 && dateCal.get(Calendar.MONTH) == 0) {
if (todayCal.get(Calendar.WEEK_OF_YEAR) == dateCal.get(Calendar.WEEK_OF_YEAR))
return true;
}
return false;
}
/**
* getStrFormTime: <br/>
*
* @param form
* 格式时间
* @param date
* 时间
* @return
*/
public static String getStrFormTime(String form, Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(form);
return sdf.format(date);
}
/**
* 获取几天内日期 return 2014-5-4、2014-5-3
*/
public static List<String> getLastDays(int countDay) {
List<String> listDate = new ArrayList<String>();
for (int i = 0; i < countDay; i++) {
listDate.add(DateUtils.getReqDateyyyyMMdd(DateUtils.getDate(-i)));
}
return listDate;
}
/**
* 对时间进行格式化
*
* @param date
* @return
*/
public static Date dateFormat(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date value = new Date();
try {
value = sdf.parse(sdf.format(date)); | } catch (ParseException e) {
e.printStackTrace();
}
return value;
}
public static boolean isSameDayWithToday(Date date) {
if (date == null) {
return false;
}
Calendar todayCal = Calendar.getInstance();
Calendar dateCal = Calendar.getInstance();
todayCal.setTime(new Date());
dateCal.setTime(date);
int subYear = todayCal.get(Calendar.YEAR) - dateCal.get(Calendar.YEAR);
int subMouth = todayCal.get(Calendar.MONTH) - dateCal.get(Calendar.MONTH);
int subDay = todayCal.get(Calendar.DAY_OF_MONTH) - dateCal.get(Calendar.DAY_OF_MONTH);
if (subYear == 0 && subMouth == 0 && subDay == 0) {
return true;
}
return false;
}
} | repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\utils\DateUtils.java | 1 |
请完成以下Java代码 | public PickingJobStep reduceWithPickedEvent(
@NonNull PickingJobStepPickFromKey key,
@NonNull PickingJobStepPickedTo pickedTo)
{
return withChangedPickFroms(pickFroms -> pickFroms.reduceWithPickedEvent(key, pickedTo));
}
public PickingJobStep reduceWithUnpickEvent(
@NonNull PickingJobStepPickFromKey key,
@NonNull PickingJobStepUnpickInfo unpicked)
{
return withChangedPickFroms(pickFroms -> pickFroms.reduceWithUnpickEvent(key, unpicked));
}
private PickingJobStep withChangedPickFroms(@NonNull final UnaryOperator<PickingJobStepPickFromMap> mapper)
{
final PickingJobStepPickFromMap newPickFroms = mapper.apply(this.pickFroms);
return !Objects.equals(this.pickFroms, newPickFroms)
? toBuilder().pickFroms(newPickFroms).build()
: this;
}
public ImmutableSet<PickingJobStepPickFromKey> getPickFromKeys()
{
return pickFroms.getKeys();
}
public PickingJobStepPickFrom getPickFrom(@NonNull final PickingJobStepPickFromKey key)
{
return pickFroms.getPickFrom(key);
}
public PickingJobStepPickFrom getPickFromByHUQRCode(@NonNull final HUQRCode qrCode)
{ | return pickFroms.getPickFromByHUQRCode(qrCode);
}
@NonNull
public List<HuId> getPickedHUIds()
{
return pickFroms.getPickedHUIds();
}
@NonNull
public Optional<PickingJobStepPickedToHU> getLastPickedHU()
{
return pickFroms.getLastPickedHU();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobStep.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Address getInvoiceAddress() {
return invoiceAddress;
}
/**
* Sets the value of the invoiceAddress property.
*
* @param value
* allowed object is
* {@link Address }
*
*/
public void setInvoiceAddress(Address value) {
this.invoiceAddress = value;
}
/**
* Gets the value of the countrySpecificService property.
*
* @return
* possible object is
* {@link String }
* | */
public String getCountrySpecificService() {
return countrySpecificService;
}
/**
* Sets the value of the countrySpecificService property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCountrySpecificService(String value) {
this.countrySpecificService = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\ProductAndServiceData.java | 2 |
请完成以下Java代码 | public void init(final IModelValidationEngine engine)
{
CopyRecordFactory.enableForTableName(I_M_ProductPrice.Table_Name);
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE })
public void assertMainProductPriceIsNotDuplicate(@NonNull final I_M_ProductPrice productPrice)
{
ProductPrices.assertMainProductPriceIsNotDuplicate(productPrice);
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_M_ProductPrice.COLUMNNAME_C_UOM_ID, I_M_ProductPrice.COLUMNNAME_IsInvalidPrice, I_M_ProductPrice.COLUMNNAME_IsActive })
public void assertUomConversionExists(@NonNull final I_M_ProductPrice productPrice)
{
ProductPrices.assertUomConversionExists(productPrice);
} | @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_AFTER_CHANGE },
ifColumnsChanged = { I_M_ProductPrice.COLUMNNAME_C_TaxCategory_ID })
public void assertProductTaxCategoryExists(@NonNull final I_M_ProductPrice productPrice)
{
if (productPrice.getC_TaxCategory_ID() <= 0)
{
final Optional<TaxCategoryId> taxCategoryId = productTaxCategoryService.getTaxCategoryIdOptional(productPrice);
if (!taxCategoryId.isPresent())
{
final ITranslatableString message = msgBL.getTranslatableMsgText(MSG_NO_C_TAX_CATEGORY_FOR_PRODUCT_PRICE);
throw new AdempiereException(message).markAsUserValidationError();
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\interceptor\M_ProductPrice.java | 1 |
请完成以下Java代码 | static boolean saveDat(String path, TreeMap<String, String> map)
{
Collection<String> dependencyList = map.values();
// 缓存值文件
try
{
DataOutputStream out = new DataOutputStream(IOUtil.newOutputStream(path + ".bi" + Predefine.BIN_EXT));
out.writeInt(dependencyList.size());
for (String dependency : dependencyList)
{
out.writeUTF(dependency);
}
if (!trie.save(out)) return false;
out.close();
}
catch (Exception e)
{
Predefine.logger.warning("保存失败" + e);
return false;
}
return true;
}
public static String get(String key)
{
return trie.get(key);
}
/**
* 获取一个词和另一个词最可能的依存关系 | * @param fromWord
* @param fromPos
* @param toWord
* @param toPos
* @return
*/
public static String get(String fromWord, String fromPos, String toWord, String toPos)
{
String dependency = get(fromWord + "@" + toWord);
if (dependency == null) dependency = get(fromWord + "@" + WordNatureWeightModelMaker.wrapTag(toPos));
if (dependency == null) dependency = get(WordNatureWeightModelMaker.wrapTag(fromPos) + "@" + toWord);
if (dependency == null) dependency = get(WordNatureWeightModelMaker.wrapTag(fromPos) + "@" + WordNatureWeightModelMaker.wrapTag(toPos));
if (dependency == null) dependency = "未知";
return dependency;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\bigram\BigramDependencyModel.java | 1 |
请完成以下Java代码 | public class ImportImpl extends BpmnModelElementInstanceImpl implements Import {
protected static Attribute<String> namespaceAttribute;
protected static Attribute<String> locationAttribute;
protected static Attribute<String> importTypeAttribute;
public static void registerType(ModelBuilder bpmnModelBuilder) {
ModelElementTypeBuilder typeBuilder = bpmnModelBuilder.defineType(Import.class, BPMN_ELEMENT_IMPORT)
.namespaceUri(BPMN20_NS)
.instanceProvider(new ModelTypeInstanceProvider<Import>() {
public Import newInstance(ModelTypeInstanceContext instanceContext) {
return new ImportImpl(instanceContext);
}
});
namespaceAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAMESPACE)
.required()
.build();
locationAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_LOCATION)
.required()
.build();
importTypeAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_IMPORT_TYPE)
.required()
.build();
typeBuilder.build();
} | public ImportImpl(ModelTypeInstanceContext context) {
super(context);
}
public String getNamespace() {
return namespaceAttribute.getValue(this);
}
public void setNamespace(String namespace) {
namespaceAttribute.setValue(this, namespace);
}
public String getLocation() {
return locationAttribute.getValue(this);
}
public void setLocation(String location) {
locationAttribute.setValue(this, location);
}
public String getImportType() {
return importTypeAttribute.getValue(this);
}
public void setImportType(String importType) {
importTypeAttribute.setValue(this, importType);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ImportImpl.java | 1 |
请完成以下Java代码 | public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
} | public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title
+ ", isbn=" + isbn + ", genre=" + genre + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootAvoidEntityInDtoViaConstructor\src\main\java\com\bookstore\entity\Book.java | 1 |
请完成以下Java代码 | public IPreliminaryDocumentNoBuilder createPreliminaryDocumentNoBuilder()
{
return new PreliminaryDocumentNoBuilder();
}
@Override
public IDocumentNoBuilder forTableName(@NonNull final String tableName, final int adClientId, final int adOrgId)
{
Check.assumeNotEmpty(tableName, "Given tableName parameter may not not ne empty");
return createDocumentNoBuilder()
.setDocumentSequenceInfo(computeDocumentSequenceInfoByTableName(tableName, adClientId, adOrgId))
.setClientId(ClientId.ofRepoId(adClientId))
.setFailOnError(false);
}
private DocumentSequenceInfo computeDocumentSequenceInfoByTableName(final String tableName, final int adClientId, final int adOrgId)
{
Check.assumeNotEmpty(tableName, DocumentNoBuilderException.class, "tableName not empty");
final IDocumentSequenceDAO documentSequenceDAO = Services.get(IDocumentSequenceDAO.class);
final String sequenceName = IDocumentNoBuilder.PREFIX_DOCSEQ + tableName;
return documentSequenceDAO.retriveDocumentSequenceInfo(sequenceName, adClientId, adOrgId);
}
@Override
public IDocumentNoBuilder forDocType(final int C_DocType_ID, final boolean useDefiniteSequence)
{
return createDocumentNoBuilder()
.setDocumentSequenceByDocTypeId(C_DocType_ID, useDefiniteSequence);
}
@Override
public IDocumentNoBuilder forSequenceId(final DocSequenceId sequenceId)
{
return createDocumentNoBuilder()
.setDocumentSequenceInfoBySequenceId(sequenceId);
}
@Override
public DocumentNoBuilder createDocumentNoBuilder()
{
return new DocumentNoBuilder();
}
@Override
public IDocumentNoBuilder createValueBuilderFor(@NonNull final Object modelRecord)
{
final IClientOrgAware clientOrg = create(modelRecord, IClientOrgAware.class);
final ClientId clientId = ClientId.ofRepoId(clientOrg.getAD_Client_ID()); | final ProviderResult providerResult = getDocumentSequenceInfo(modelRecord);
return createDocumentNoBuilder()
.setDocumentSequenceInfo(providerResult.getInfoOrNull())
.setClientId(clientId)
.setDocumentModel(modelRecord)
.setFailOnError(false);
}
private ProviderResult getDocumentSequenceInfo(@NonNull final Object modelRecord)
{
for (final ValueSequenceInfoProvider provider : additionalProviders)
{
final ProviderResult result = provider.computeValueInfo(modelRecord);
if (result.hasInfo())
{
return result;
}
}
return tableNameBasedProvider.computeValueInfo(modelRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\DocumentNoBuilderFactory.java | 1 |
请完成以下Java代码 | private RegisteredClient create() {
RegisteredClient registeredClient = new RegisteredClient();
registeredClient.id = this.id;
registeredClient.clientId = this.clientId;
registeredClient.clientIdIssuedAt = this.clientIdIssuedAt;
registeredClient.clientSecret = this.clientSecret;
registeredClient.clientSecretExpiresAt = this.clientSecretExpiresAt;
registeredClient.clientName = this.clientName;
registeredClient.clientAuthenticationMethods = Collections
.unmodifiableSet(new HashSet<>(this.clientAuthenticationMethods));
registeredClient.authorizationGrantTypes = Collections
.unmodifiableSet(new HashSet<>(this.authorizationGrantTypes));
registeredClient.redirectUris = Collections.unmodifiableSet(new HashSet<>(this.redirectUris));
registeredClient.postLogoutRedirectUris = Collections
.unmodifiableSet(new HashSet<>(this.postLogoutRedirectUris));
registeredClient.scopes = Collections.unmodifiableSet(new HashSet<>(this.scopes));
registeredClient.clientSettings = this.clientSettings;
registeredClient.tokenSettings = this.tokenSettings;
return registeredClient;
}
private void validateScopes() {
if (CollectionUtils.isEmpty(this.scopes)) {
return;
}
for (String scope : this.scopes) {
Assert.isTrue(validateScope(scope), "scope \"" + scope + "\" contains invalid characters");
}
}
private static boolean validateScope(String scope) {
return scope == null || scope.chars()
.allMatch((c) -> withinTheRangeOf(c, 0x21, 0x21) || withinTheRangeOf(c, 0x23, 0x5B)
|| withinTheRangeOf(c, 0x5D, 0x7E));
}
private static boolean withinTheRangeOf(int c, int min, int max) {
return c >= min && c <= max;
}
private void validateRedirectUris() {
if (CollectionUtils.isEmpty(this.redirectUris)) {
return;
}
for (String redirectUri : this.redirectUris) {
Assert.isTrue(validateRedirectUri(redirectUri),
"redirect_uri \"" + redirectUri + "\" is not a valid redirect URI or contains fragment");
} | }
private void validatePostLogoutRedirectUris() {
if (CollectionUtils.isEmpty(this.postLogoutRedirectUris)) {
return;
}
for (String postLogoutRedirectUri : this.postLogoutRedirectUris) {
Assert.isTrue(validateRedirectUri(postLogoutRedirectUri), "post_logout_redirect_uri \""
+ postLogoutRedirectUri + "\" is not a valid post logout redirect URI or contains fragment");
}
}
private static boolean validateRedirectUri(String redirectUri) {
try {
URI validRedirectUri = new URI(redirectUri);
return validRedirectUri.getFragment() == null;
}
catch (URISyntaxException ex) {
return false;
}
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\client\RegisteredClient.java | 1 |
请完成以下Java代码 | public @Nullable String getSubject() {
return this.subject;
}
/**
* See {@link com.rabbitmq.stream.MessageBuilder.PropertiesBuilder#subject(String)}.
* @param subject the subject.
*/
public void setSubject(String subject) {
this.subject = subject;
}
/**
* See {@link com.rabbitmq.stream.Properties#getCreationTime()}.
* @return the creation time.
*/
public long getCreationTime() {
return this.creationTime;
}
/**
* See
* {@link com.rabbitmq.stream.MessageBuilder.PropertiesBuilder#creationTime(long)}.
* @param creationTime the creation time.
*/
public void setCreationTime(long creationTime) {
this.creationTime = creationTime;
}
/**
* See {@link com.rabbitmq.stream.Properties#getGroupId()}.
* @return the group id.
*/
public @Nullable String getGroupId() {
return this.groupId;
}
/**
* See {@link com.rabbitmq.stream.MessageBuilder.PropertiesBuilder#groupId(String)}.
* @param groupId the group id.
*/
public void setGroupId(String groupId) {
this.groupId = groupId;
}
/**
* See {@link com.rabbitmq.stream.Properties#getGroupSequence()}.
* @return the group sequence.
*/
public long getGroupSequence() {
return this.groupSequence;
}
/**
* See
* {@link com.rabbitmq.stream.MessageBuilder.PropertiesBuilder#groupSequence(long)}.
* @param groupSequence the group sequence.
*/
public void setGroupSequence(long groupSequence) {
this.groupSequence = groupSequence;
}
/**
* See {@link com.rabbitmq.stream.Properties#getReplyToGroupId()}.
* @return the reply to group id.
*/
public @Nullable String getReplyToGroupId() {
return this.replyToGroupId;
}
/** | * See
* {@link com.rabbitmq.stream.MessageBuilder.PropertiesBuilder#replyToGroupId(String)}.
* @param replyToGroupId the reply to group id.
*/
public void setReplyToGroupId(String replyToGroupId) {
this.replyToGroupId = replyToGroupId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + Objects.hash(this.creationTime, this.groupId, this.groupSequence, this.replyToGroupId,
this.subject, this.to);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
StreamMessageProperties other = (StreamMessageProperties) obj;
return this.creationTime == other.creationTime && Objects.equals(this.groupId, other.groupId)
&& this.groupSequence == other.groupSequence
&& Objects.equals(this.replyToGroupId, other.replyToGroupId)
&& Objects.equals(this.subject, other.subject) && Objects.equals(this.to, other.to);
}
} | repos\spring-amqp-main\spring-rabbit-stream\src\main\java\org\springframework\rabbit\stream\support\StreamMessageProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AopConfiguration {
@Pointcut("execution(public String com.baeldung.performancemonitor.PersonService.getFullName(..))")
public void monitor() { }
@Pointcut("execution(public int com.baeldung.performancemonitor.PersonService.getAge(..))")
public void myMonitor() { }
@Bean
public PerformanceMonitorInterceptor performanceMonitorInterceptor() {
return new PerformanceMonitorInterceptor(true);
}
@Bean
public Advisor performanceMonitorAdvisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("com.baeldung.performancemonitor.AopConfiguration.monitor()");
return new DefaultPointcutAdvisor(pointcut, performanceMonitorInterceptor());
}
@Bean | public Person person(){
return new Person("John","Smith", LocalDate.of(1980, Month.JANUARY, 12));
}
@Bean
public PersonService personService(){
return new PersonService();
}
@Bean
public MyPerformanceMonitorInterceptor myPerformanceMonitorInterceptor() {
return new MyPerformanceMonitorInterceptor(true);
}
@Bean
public Advisor myPerformanceMonitorAdvisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("com.baeldung.performancemonitor.AopConfiguration.myMonitor()");
return new DefaultPointcutAdvisor(pointcut, myPerformanceMonitorInterceptor());
}
} | repos\tutorials-master\spring-aop-2\src\main\java\com\baeldung\performancemonitor\AopConfiguration.java | 2 |
请完成以下Java代码 | public class UnaryTestsImpl extends DmnElementImpl implements UnaryTests {
protected static Attribute<String> expressionLanguageAttribute;
protected static ChildElement<Text> textChild;
public UnaryTestsImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getExpressionLanguage() {
return expressionLanguageAttribute.getValue(this);
}
public void setExpressionLanguage(String expressionLanguage) {
expressionLanguageAttribute.setValue(this, expressionLanguage);
}
public Text getText() {
return textChild.getChild(this);
}
public void setText(Text text) {
textChild.setChild(this, text);
}
public static void registerType(ModelBuilder modelBuilder) { | ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(UnaryTests.class, DMN_ELEMENT_UNARY_TESTS)
.namespaceUri(LATEST_DMN_NS)
.extendsType(DmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<UnaryTests>() {
public UnaryTests newInstance(ModelTypeInstanceContext instanceContext) {
return new UnaryTestsImpl(instanceContext);
}
});
expressionLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPRESSION_LANGUAGE)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
textChild = sequenceBuilder.element(Text.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\UnaryTestsImpl.java | 1 |
请完成以下Java代码 | public Builder orderByAliasFieldNames(@NonNull final String fieldName, @NonNull final String... aliasFieldNames)
{
Check.assumeNotEmpty(aliasFieldNames, "aliasFieldNames is not empty");
orderByFieldNameAliasMap.orderByAliasFieldName(fieldName, ImmutableList.copyOf(aliasFieldNames));
return this;
}
public Builder filterDescriptors(@NonNull final DocumentFilterDescriptorsProvider filterDescriptors)
{
this.filterDescriptors = filterDescriptors;
return this;
}
private DocumentFilterDescriptorsProvider getViewFilterDescriptors()
{
return filterDescriptors;
}
private SqlDocumentFilterConvertersList buildViewFilterConverters()
{
return filterConverters.build();
}
public Builder filterConverter(@NonNull final SqlDocumentFilterConverter converter)
{
filterConverters.converter(converter);
return this;
}
public Builder filterConverters(@NonNull final List<SqlDocumentFilterConverter> converters)
{
filterConverters.converters(converters);
return this;
}
public Builder rowIdsConverter(@NonNull final SqlViewRowIdsConverter rowIdsConverter)
{
this.rowIdsConverter = rowIdsConverter;
return this;
}
private SqlViewRowIdsConverter getRowIdsConverter()
{
if (rowIdsConverter != null)
{
return rowIdsConverter;
}
if (groupingBinding != null)
{
return groupingBinding.getRowIdsConverter();
}
return SqlViewRowIdsConverters.TO_INT_STRICT;
}
public Builder groupingBinding(final SqlViewGroupingBinding groupingBinding)
{
this.groupingBinding = groupingBinding;
return this;
}
public Builder filterConverterDecorator(@NonNull final SqlDocumentFilterConverterDecorator sqlDocumentFilterConverterDecorator)
{
this.sqlDocumentFilterConverterDecorator = sqlDocumentFilterConverterDecorator;
return this;
}
public Builder rowCustomizer(final ViewRowCustomizer rowCustomizer)
{ | this.rowCustomizer = rowCustomizer;
return this;
}
private ViewRowCustomizer getRowCustomizer()
{
return rowCustomizer;
}
public Builder viewInvalidationAdvisor(@NonNull final IViewInvalidationAdvisor viewInvalidationAdvisor)
{
this.viewInvalidationAdvisor = viewInvalidationAdvisor;
return this;
}
private IViewInvalidationAdvisor getViewInvalidationAdvisor()
{
return viewInvalidationAdvisor;
}
public Builder refreshViewOnChangeEvents(final boolean refreshViewOnChangeEvents)
{
this.refreshViewOnChangeEvents = refreshViewOnChangeEvents;
return this;
}
public Builder queryIfNoFilters(final boolean queryIfNoFilters)
{
this.queryIfNoFilters = queryIfNoFilters;
return this;
}
public Builder includedEntitiesDescriptors(final Map<DetailId, SqlDocumentEntityDataBindingDescriptor> includedEntitiesDescriptors)
{
this.includedEntitiesDescriptors = includedEntitiesDescriptors;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlViewBinding.java | 1 |
请完成以下Java代码 | public class Person {
@Id
private String id;
private String name;
@DBRef
private List<Pet> pets;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<Pet> getPets() {
return pets;
} | public void setPets(List<Pet> pets) {
this.pets = pets;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", pets=" + pets + "]";
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-4\src\main\java\com\baeldung\mongodb\dbref\model\Person.java | 1 |
请完成以下Java代码 | public TokenizedStringBuilder append(final Object obj)
{
if (autoAppendSeparator)
{
appendSeparatorIfNeeded();
}
sb.append(obj);
lastAppendedIsSeparator = false;
return this;
}
public TokenizedStringBuilder appendSeparatorIfNeeded()
{ | if (lastAppendedIsSeparator)
{
return this;
}
if (sb.length() <= 0)
{
return this;
}
sb.append(separator);
lastAppendedIsSeparator = true;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\text\TokenizedStringBuilder.java | 1 |
请完成以下Java代码 | public String getFamilyname() {
return familyname;
}
/**
* Sets the value of the familyname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFamilyname(String value) {
this.familyname = value;
}
/**
* Gets the value of the givenname property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGivenname() {
return givenname;
}
/**
* Sets the value of the givenname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGivenname(String value) {
this.givenname = value;
}
/**
* Gets the value of the telecom property.
*
* @return
* possible object is
* {@link TelecomAddressType }
*
*/
public TelecomAddressType getTelecom() {
return telecom;
}
/**
* Sets the value of the telecom property.
*
* @param value
* allowed object is
* {@link TelecomAddressType }
*
*/
public void setTelecom(TelecomAddressType value) {
this.telecom = value;
}
/**
* Gets the value of the online property.
*
* @return
* possible object is
* {@link OnlineAddressType }
*
*/
public OnlineAddressType getOnline() {
return online;
}
/**
* Sets the value of the online property.
*
* @param value
* allowed object is
* {@link OnlineAddressType } | *
*/
public void setOnline(OnlineAddressType value) {
this.online = value;
}
/**
* Gets the value of the salutation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSalutation() {
return salutation;
}
/**
* Sets the value of the salutation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSalutation(String value) {
this.salutation = 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;
}
} | 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\EmployeeType.java | 1 |
请完成以下Java代码 | public static LastSyncStatus ofCode(@NonNull String code) {return index.ofCode(code);}
public static LastSyncStatus ofNullableCode(@Nullable String code) {return index.ofNullableCode(code);}
}
//
//
//
//
//
//
@Value
@Builder
@Jacksonized
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE)
public static class LastSync
{
@NonNull LastSyncStatus status;
@Nullable Instant timestamp; | @Nullable AdIssueId errorId;
public static LastSync ok()
{
return builder()
.status(LastSyncStatus.OK)
.timestamp(SystemTime.asInstant())
.build();
}
public static LastSync error(@NonNull final AdIssueId errorId)
{
return builder()
.status(LastSyncStatus.Error)
.timestamp(SystemTime.asInstant())
.errorId(errorId)
.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpTransaction.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DistributionJobStep
{
@NonNull DistributionJobStepId id;
@NonNull Quantity qtyToMoveTarget;
//
// Pick From
@NonNull HUInfo pickFromHU;
@NonNull Quantity qtyPicked;
@Nullable QtyRejectedReasonCode qtyNotPickedReasonCode;
boolean isPickedFromLocator;
@Nullable LocatorId inTransitLocatorId;
//
// Drop To
boolean isDroppedToLocator;
@NonNull WFActivityStatus status;
@Builder
private DistributionJobStep(
@NonNull final DistributionJobStepId id,
@NonNull final Quantity qtyToMoveTarget,
//
@NonNull final HUInfo pickFromHU,
@NonNull final Quantity qtyPicked,
@Nullable final QtyRejectedReasonCode qtyNotPickedReasonCode,
final boolean isPickedFromLocator,
@Nullable final LocatorId inTransitLocatorId,
//
final boolean isDroppedToLocator)
{
Quantity.assertSameUOM(qtyToMoveTarget, qtyPicked);
this.id = id;
this.qtyToMoveTarget = qtyToMoveTarget;
this.pickFromHU = pickFromHU;
this.qtyPicked = qtyPicked;
this.qtyNotPickedReasonCode = qtyNotPickedReasonCode;
this.isPickedFromLocator = isPickedFromLocator;
this.inTransitLocatorId = inTransitLocatorId;
this.isDroppedToLocator = isDroppedToLocator;
this.status = computeStatus(this.isPickedFromLocator, this.isDroppedToLocator);
}
private static WFActivityStatus computeStatus(final boolean isPickedFromLocator, final boolean isDroppedToLocator)
{ | if (isPickedFromLocator)
{
return isDroppedToLocator ? WFActivityStatus.COMPLETED : WFActivityStatus.IN_PROGRESS;
}
else
{
return WFActivityStatus.NOT_STARTED;
}
}
@NonNull
public DDOrderMoveScheduleId getScheduleId() {return getId().toScheduleId();}
public boolean isInTransit() {return isPickedFromLocator && !isDroppedToLocator;}
public Quantity getQtyInTransit()
{
return isInTransit()
? qtyPicked
: qtyPicked.toZero();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\model\DistributionJobStep.java | 2 |
请完成以下Java代码 | public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public String getCallbackId() {
return callbackId;
}
@Override
public void setCallbackId(String callbackId) {
this.callbackId = callbackId;
}
@Override
public String getCallbackType() {
return callbackType;
}
@Override
public void setCallbackType(String callbackType) {
this.callbackType = callbackType;
}
@Override
public String getReferenceId() {
return referenceId;
}
@Override
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
@Override
public String getReferenceType() {
return referenceType;
}
@Override
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
@Override
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
@Override
public void setPropagatedStageInstanceId(String propagatedStageInstanceId) {
this.propagatedStageInstanceId = propagatedStageInstanceId;
}
@Override
public Map<String, Object> getProcessVariables() {
Map<String, Object> variables = new HashMap<>();
if (queryVariables != null) {
for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() == null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
@Override
public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) { | queryVariables = new HistoricVariableInitializingList();
}
return queryVariables;
}
@Override
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricProcessInstanceEntity[id=").append(getId())
.append(", definition=").append(getProcessDefinitionId());
if (superProcessInstanceId != null) {
sb.append(", superProcessInstanceId=").append(superProcessInstanceId);
}
if (referenceId != null) {
sb.append(", referenceId=").append(referenceId)
.append(", referenceType=").append(referenceType);
}
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricProcessInstanceEntityImpl.java | 1 |
请完成以下Java代码 | public void addQtyToIssue(@NonNull final ProductId productId, @NonNull final Quantity qtyToIssueToAdd, @NonNull final I_M_HU huToAssign)
{
// Validate
if (!ProductId.equals(productId, this.productId))
{
throw new HUException("Invalid product to issue."
+ "\nExpected: " + this.productId
+ "\nGot: " + productId
+ "\n@PP_Order_BOMLine_ID@: " + orderBOMLine);
}
final UOMConversionContext uomConversionCtx = UOMConversionContext.of(productId);
final Quantity qtyToIssueToAddConv = uomConversionBL.convertQuantityTo(qtyToIssueToAdd, uomConversionCtx, qtyToIssue.getUOM());
qtyToIssue = qtyToIssue.add(qtyToIssueToAddConv);
husToAssign.add(huToAssign);
} | private void addMaterialTracking(
@NonNull final I_M_Material_Tracking materialTracking,
@NonNull final Quantity quantity)
{
MaterialTrackingWithQuantity materialTrackingWithQuantity = this.id2materialTracking.get(materialTracking.getM_Material_Tracking_ID());
if (materialTrackingWithQuantity == null)
{
materialTrackingWithQuantity = new MaterialTrackingWithQuantity(materialTracking);
this.id2materialTracking.put(materialTracking.getM_Material_Tracking_ID(), materialTrackingWithQuantity);
}
materialTrackingWithQuantity.addQuantity(quantity);
}
public boolean isZeroQty()
{
return getQtyToIssue().isZero();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\HUPPOrderIssueReceiptCandidatesProcessor.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_M_PromotionGroup[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Promotion Group.
@param M_PromotionGroup_ID Promotion Group */
public void setM_PromotionGroup_ID (int M_PromotionGroup_ID)
{
if (M_PromotionGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, Integer.valueOf(M_PromotionGroup_ID));
} | /** Get Promotion Group.
@return Promotion Group */
public int getM_PromotionGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionGroup.java | 1 |
请完成以下Java代码 | public static void main(String... args) throws Exception {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(subscribeUrl);
try (final SseEventSource eventSource = SseEventSource.target(target)
.reconnectingEvery(5, TimeUnit.SECONDS)
.build()) {
eventSource.register(onEvent, onError, onComplete);
eventSource.open();
System.out.println("Wainting for incoming event ...");
//Consuming events for one hour
Thread.sleep(60 * 60 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
client.close();
System.out.println("End");
} | // A new event is received
private static Consumer<InboundSseEvent> onEvent = (inboundSseEvent) -> {
String data = inboundSseEvent.readData();
System.out.println(data);
};
//Error
private static Consumer<Throwable> onError = (throwable) -> {
throwable.printStackTrace();
};
//Connection close and there is nothing to receive
private static Runnable onComplete = () -> {
System.out.println("Done!");
};
} | repos\tutorials-master\apache-cxf-modules\sse-jaxrs\sse-jaxrs-client\src\main\java\com\baeldung\sse\jaxrs\client\SseClientBroadcastApp.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getMessageEventSubscriptionName() {
return messageEventSubscriptionName;
}
public void setMessageEventSubscriptionName(String messageEventSubscriptionName) {
this.messageEventSubscriptionName = messageEventSubscriptionName;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
} | public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Set<String> getProcessInstanceIds() {
return processInstanceIds;
}
public void setProcessInstanceIds(Set<String> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ExecutionQueryRequest.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class TableAndColumnName
{
@NonNull TableName tableName;
@NonNull ColumnName columnName;
public static TableAndColumnName ofTableAndColumnStrings(@NonNull final String tableName, @NonNull final String columnName)
{
return ofTableAndColumn(TableName.ofString(tableName), ColumnName.ofString(columnName));
}
@Override
@Deprecated
public String toString()
{
return getAsString();
}
public String getAsString() | {
return tableName.getAsString() + "." + columnName.getAsString();
}
public String getTableNameAsString()
{
return tableName.getAsString();
}
public String getColumnNameAsString()
{
return columnName.getAsString();
}
public boolean equalsByColumnName(final String otherColumnName)
{
return Objects.equals(columnName.getAsString(), otherColumnName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\TableAndColumnName.java | 2 |
请完成以下Java代码 | public IHUAttributeTransferRequest create()
{
return new HUAttributeTransferRequest(huContext,
productId, qty, uom,
attributeStorageFrom, attributeStorageTo,
huStorageFrom, huStorageTo,
qtyUnloaded,
vhuTransfer);
}
@Override
public IHUAttributeTransferRequestBuilder setProductId(final ProductId productId)
{
this.productId = productId;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setQty(final BigDecimal qty)
{
this.qty = qty;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setUOM(final I_C_UOM uom)
{
this.uom = uom;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setQuantity(final Quantity quantity)
{
qty = quantity.toBigDecimal();
uom = quantity.getUOM();
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setAttributeStorageFrom(final IAttributeSet attributeStorageFrom)
{
this.attributeStorageFrom = attributeStorageFrom;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setAttributeStorageTo(final IAttributeStorage attributeStorageTo) | {
this.attributeStorageTo = attributeStorageTo;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setHUStorageFrom(final IHUStorage huStorageFrom)
{
this.huStorageFrom = huStorageFrom;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setHUStorageTo(final IHUStorage huStorageTo)
{
this.huStorageTo = huStorageTo;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setQtyUnloaded(final BigDecimal qtyUnloaded)
{
this.qtyUnloaded = qtyUnloaded;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setVHUTransfer(final boolean vhuTransfer)
{
this.vhuTransfer = vhuTransfer;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\strategy\impl\HUAttributeTransferRequestBuilder.java | 1 |
请完成以下Java代码 | private boolean isWhiteList(String ip) {
List<String> whiteList = requestProperties.getWhiteList();
String[] defaultWhiteIps = defaultWhiteList.toArray(new String[0]);
String[] whiteIps = whiteList.toArray(new String[0]);
return PatternMatchUtils.simpleMatch(defaultWhiteIps, ip) || PatternMatchUtils.simpleMatch(whiteIps, ip);
}
/**
* 是否黑名单
*
* @param ip ip地址
* @return boolean
*/
private boolean isBlackList(String ip) {
List<String> blackList = requestProperties.getBlackList();
String[] blackIps = blackList.toArray(new String[0]);
return PatternMatchUtils.simpleMatch(blackIps, ip);
}
/**
* 是否禁用请求访问
*
* @param path 请求路径
* @return boolean
*/
private boolean isRequestBlock(String path) {
List<String> blockUrl = requestProperties.getBlockUrl();
return defaultBlockUrl.stream().anyMatch(pattern -> antPathMatcher.match(pattern, path)) ||
blockUrl.stream().anyMatch(pattern -> antPathMatcher.match(pattern, path));
}
/** | * 是否拦截请求
*
* @param path 请求路径
* @param ip ip地址
* @return boolean
*/
private boolean isRequestBlock(String path, String ip) {
return (isRequestBlock(path) && !isWhiteList(ip)) || isBlackList(ip);
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
} | repos\SpringBlade-master\blade-gateway\src\main\java\org\springblade\gateway\filter\GatewayFilter.java | 1 |
请完成以下Java代码 | public class ConvertBPartnerMemo extends JavaProcess {
@Override
protected String doIt() throws Exception {
final String whereClause = "";
final List<MBPartner> bPartners = new Query(getCtx(),
I_C_BPartner.Table_Name, whereClause, get_TrxName())
.setOnlyActiveRecords(true).setClient_ID().list(MBPartner.class);
final Timestamp startDate = SystemTime.asTimestamp();
int counter = 0;
for (final MBPartner bPartner : bPartners) {
final String memoInput = (String) bPartner.get_Value(I_C_BPartner.COLUMNNAME_Memo);
if (memoInput == null) {
continue;
}
if (memoInput.toUpperCase().startsWith("<HTML")) {
// string is already converted
continue;
}
final InputStream r = new ByteArrayInputStream(memoInput.getBytes(StandardCharsets.UTF_8));
final DefaultStyledDocument doc = new DefaultStyledDocument();
final EditorKit inputEditorKit;
if (memoInput.startsWith("{\\rtf")) {
inputEditorKit = new RTFEditorKit();
} else {
inputEditorKit = new DefaultEditorKit();
}
inputEditorKit.read(r, doc, 0);
final HTMLEditorKit outputEditorKit = new HTMLEditorKit();
final ByteArrayOutputStream outpOutputStream = new ByteArrayOutputStream();
outputEditorKit.write(outpOutputStream, doc, 0, doc.getLength());
final String memoHtml = outpOutputStream.toString().replace(
"font-size: 8pt", "font-size: 16pt"); | bPartner.set_ValueOfColumn(I_C_BPartner.COLUMNNAME_Memo, memoHtml);
bPartner.saveEx();
counter++;
if (counter % 1000 == 0) {
commitEx();
}
}
addLog("Updated " + counter + " bpartners in "
+ TimeUtil.formatElapsed(startDate));
return "@Success@";
}
@Override
protected void prepare() {
// nothing to do
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\process\ConvertBPartnerMemo.java | 1 |
请完成以下Java代码 | private IPricingResult getPricingResult(@NonNull final I_C_OLCand olCand)
{
try
{
final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(olCand.getAD_Org_ID()));
final BigDecimal qtyOverride = null;
final LocalDate datePromisedEffective = TimeUtil.asLocalDate(olCandEffectiveValuesBL.getDatePromised_Effective(olCand), timeZone);
return olCandBL.computePriceActual(olCand, qtyOverride, PricingSystemId.NULL, datePromisedEffective);
}
catch (final AdempiereException e)
{
// Warn developer that something went wrong.
// In this way he/she can early see the issue and where it happened.
if (developerModeBL.isEnabled())
{
logger.warn(e.getLocalizedMessage(), e);
}
throw e;
}
}
public static IPricingResult getPreviouslyCalculatedPricingResultOrNull(@NonNull final I_C_OLCand olCand)
{
return DYNATTR_OLCAND_PRICEVALIDATOR_PRICING_RESULT.getValue(olCand);
}
/**
* Validates the UOM conversion; we will need convertToProductUOM in order to get the QtyOrdered in the order line.
*/ | private void validateUOM(@NonNull final I_C_OLCand olCand)
{
final ProductId productId = olCandEffectiveValuesBL.getM_Product_Effective_ID(olCand);
final I_C_UOM targetUOMRecord = olCandEffectiveValuesBL.getC_UOM_Effective(olCand);
if (uomsDAO.isUOMForTUs(UomId.ofRepoId(targetUOMRecord.getC_UOM_ID())))
{
if (olCandEffectiveValuesBL.getQtyItemCapacity_Effective(olCand).signum() <= 0)
{
throw new AdempiereException(ERR_ITEM_CAPACITY_NOT_FOUND);
}
return;
}
final BigDecimal convertedQty = uomConversionBL.convertToProductUOM(
productId,
targetUOMRecord,
olCandEffectiveValuesBL.getEffectiveQtyEntered(olCand));
if (convertedQty == null)
{
final String productName = productBL.getProductName(productId);
final String productValue = productBL.getProductValue(productId);
final String productX12de355 = productBL.getStockUOM(productId).getX12DE355();
final String targetX12de355 = targetUOMRecord.getX12DE355();
throw new AdempiereException(MSG_NO_UOM_CONVERSION, productValue + "_" + productName, productX12de355, targetX12de355).markAsUserValidationError();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\spi\impl\DefaultOLCandValidator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonPriceListResponse
{
@NonNull
@JsonProperty("metasfreshId")
JsonMetasfreshId metasfreshId;
@NonNull
@JsonProperty("name")
String name;
@NonNull
@JsonProperty("pricePrecision")
Integer pricePrecision;
@NonNull | @JsonProperty("isSOTrx")
JsonSOTrx isSOTrx;
@NonNull
@JsonProperty("currencyCode")
String currencyCode;
@Nullable
@JsonProperty("countryCode")
String countryCode;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonProperty("priceListVersions")
@Singular
List<JsonPriceListVersionResponse> priceListVersions;
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-pricing\src\main\java\de\metas\common\pricing\v2\productprice\JsonPriceListResponse.java | 2 |
请在Spring Boot框架中完成以下Java代码 | KotlinGradleBuildCustomizer kotlinBuildCustomizerKotlinDsl(KotlinProjectSettings kotlinProjectSettings) {
return new KotlinGradleBuildCustomizer(kotlinProjectSettings, '\"');
}
@Bean
@ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_GROOVY)
KotlinGradleBuildCustomizer kotlinBuildCustomizerGroovyDsl(KotlinProjectSettings kotlinProjectSettings) {
return new KotlinGradleBuildCustomizer(kotlinProjectSettings, '\'');
}
/**
* Configuration for Kotlin projects using Spring Boot 2.0 and later.
*/
@Configuration
@ConditionalOnPlatformVersion("2.0.0.M1")
static class SpringBoot2AndLaterKotlinProjectGenerationConfiguration {
@Bean
@ConditionalOnBuildSystem(MavenBuildSystem.ID)
KotlinMavenBuildCustomizer kotlinBuildCustomizer(KotlinProjectSettings kotlinProjectSettings) {
return new KotlinMavenBuildCustomizer(kotlinProjectSettings);
}
@Bean
MainCompilationUnitCustomizer<KotlinTypeDeclaration, KotlinCompilationUnit> mainFunctionContributor(
ProjectDescription description) {
return (compilationUnit) -> compilationUnit.addTopLevelFunction(KotlinFunctionDeclaration.function("main")
.parameters(Parameter.of("args", "Array<String>"))
.body(CodeBlock.ofStatement("$T<$L>(*args)", "org.springframework.boot.runApplication",
description.getApplicationName()))); | }
}
/**
* Kotlin source code contributions for projects using war packaging.
*/
@Configuration
@ConditionalOnPackaging(WarPackaging.ID)
static class WarPackagingConfiguration {
@Bean
ServletInitializerCustomizer<KotlinTypeDeclaration> javaServletInitializerCustomizer(
ProjectDescription description) {
return (typeDeclaration) -> {
KotlinFunctionDeclaration configure = KotlinFunctionDeclaration.function("configure")
.modifiers(KotlinModifier.OVERRIDE)
.returning("org.springframework.boot.builder.SpringApplicationBuilder")
.parameters(
Parameter.of("application", "org.springframework.boot.builder.SpringApplicationBuilder"))
.body(CodeBlock.ofStatement("return application.sources($L::class.java)",
description.getApplicationName()));
typeDeclaration.addFunctionDeclaration(configure);
};
}
}
} | repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\kotlin\KotlinProjectGenerationDefaultContributorsConfiguration.java | 2 |
请完成以下Java代码 | public ReferenceId getAD_Reference_Value_ID()
{
return AD_Reference_Value_ID;
}
/**
* Get Column Name or SQL .. with/without AS
*
* @param withAS include AS ColumnName for virtual columns in select statements
* @return column name
*/
public String getColumnSQL(final boolean withAS)
{
// metas
if (ColumnClass != null)
{
return "NULL";
}
// metas end
if (ColumnSQL != null && !ColumnSQL.isEmpty())
{
if (withAS)
{
return ColumnSQL + " AS " + ColumnName;
}
else
{
return ColumnSQL;
}
}
return ColumnName;
} // getColumnSQL
public ColumnSql getColumnSql(@NonNull final String ctxTableName)
{
return ColumnSql.ofSql(getColumnSQL(false), ctxTableName);
}
/**
* Is Virtual Column
*
* @return column is virtual
*/
public boolean isVirtualColumn()
{
return (ColumnSQL != null && !ColumnSQL.isEmpty())
|| (ColumnClass != null && !ColumnClass.isEmpty());
} // isColumnVirtual
public boolean isReadOnly()
{
return IsReadOnly; | }
public boolean isUpdateable()
{
return IsUpdateable;
}
public boolean isAlwaysUpdateable()
{
return IsAlwaysUpdateable;
}
public boolean isKey()
{
return IsKey;
}
public boolean isEncryptedField()
{
return IsEncryptedField;
}
public boolean isEncryptedColumn()
{
return IsEncryptedColumn;
}
public boolean isSelectionColumn()
{
return defaultFilterDescriptor != null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridFieldVO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class C_Location
{
public static final Topic EVENTS_TOPIC = Topic.distributed("de.metas.location.geocoding.events");
@NonNull private final ITrxManager trxManager = Services.get(ITrxManager.class);
@NonNull private final IEventBusFactory eventBusFactory;
@NonNull private final GeocodingService geocodingService;
@ModelChange(timings = ModelValidator.TYPE_AFTER_NEW)
public void onNewLocation(final I_C_Location locationRecord)
{
if (geocodingService.isProviderConfigured())
{
trxManager.accumulateAndProcessAfterCommit(
"LocationGeocodeEventRequest",
ImmutableList.of(LocationGeocodeEventRequest.of(LocationId.ofRepoId(locationRecord.getC_Location_ID()))),
this::fireLocationGeocodeRequests
);
}
} | @ModelChange(
timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = I_C_Location.COLUMNNAME_Postal)
public void trimPostal(@NonNull final I_C_Location locationRecord)
{
final String untrimmedPostal = locationRecord.getPostal();
locationRecord.setPostal(StringUtils.trim(untrimmedPostal));
}
private void fireLocationGeocodeRequests(final List<LocationGeocodeEventRequest> requests)
{
eventBusFactory.getEventBus(EVENTS_TOPIC).enqueueObjectsCollection(requests);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\geocoding\interceptor\C_Location.java | 2 |
请完成以下Java代码 | private void sortEntries()
{
List<BBANStructureEntry> listEntries = _BBANStructure.getEntries();
// if there is no entry , than we have BBAN structure
if (listEntries.isEmpty())
{
_BBANStructure = null;
return;
}
// order list by seqNo
Collections.sort(listEntries, (entry1, entry2) -> {
String seqNo1 = entry1.getSeqNo();
if (Check.isEmpty(seqNo1, true))
{
seqNo1 = "10";
}
String seqNo2 = entry2.getSeqNo();
if (Check.isEmpty(seqNo2, true))
{
seqNo2 = "20";
} | final int no1 = Integer.valueOf(seqNo1);
final int no2 = Integer.valueOf(seqNo2);
// order
if (no1 > no2)
{
return 1;
}
else if (no1 < no2)
{
return -1;
}
else
{
return 0;
}
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\BBANStructureBuilder.java | 1 |
请完成以下Java代码 | public void deleteNode(ListItem item)
{
if (item != null)
{
if (m_tree.isProduct())
{
MTree_NodePR node = MTree_NodePR.get (m_tree, item.id);
if (node != null)
node.delete(true);
}
else if (m_tree.isBPartner())
{
MTree_NodeBP node = MTree_NodeBP.get (m_tree, item.id);
if (node != null)
node.delete(true);
}
else if (m_tree.isMenu())
{
MTree_NodeMM node = MTree_NodeMM.get (m_tree, item.id);
if (node != null)
node.delete(true);
}
else
{
MTree_Node node = MTree_Node.get (m_tree, item.id);
if (node != null)
node.delete(true);
}
}
} // action_treeDelete
/**************************************************************************
* Tree Maintenance List Item
*/
public class ListItem
{
/**
* ListItem
* @param ID
* @param Name
* @param Description
* @param summary
* @param ImageIndicator
*/
public ListItem (int ID, String Name, String Description,
boolean summary, String ImageIndicator)
{
id = ID;
name = Name;
description = Description;
isSummary = summary; | imageIndicator = ImageIndicator;
} // ListItem
/** ID */
public int id;
/** Name */
public String name;
/** Description */
public String description;
/** Summary */
public boolean isSummary;
/** Indicator */
public String imageIndicator; // Menu - Action
/**
* To String
* @return String Representation
*/
@Override
public String toString ()
{
String retValue = name;
if (description != null && description.length() > 0)
retValue += " (" + description + ")";
return retValue;
} // toString
} // ListItem
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\TreeMaintenance.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class ProjectQuotationPriceCalculator
{
private final IPricingBL pricingBL;
private final ProjectQuotationPricingInfo pricingInfo;
@Builder
private ProjectQuotationPriceCalculator(
@NonNull final IPricingBL pricingBL,
@NonNull final ProjectQuotationPricingInfo pricingInfo)
{
this.pricingBL = pricingBL;
this.pricingInfo = pricingInfo;
}
public CurrencyId getCurrencyId()
{
return pricingInfo.getCurrencyId();
}
public OrderLineDetailCreateRequest computeOrderLineDetailCreateRequest(final ServiceRepairProjectCostCollector costCollector)
{
final Quantity qty = costCollector.getQtyReservedOrConsumed();
//
// Price & Amount precision
final Money price;
final CurrencyPrecision amountPrecision;
if (costCollector.getType().isZeroPrice())
{
price = Money.zero(getCurrencyId());
amountPrecision = CurrencyPrecision.TWO;
}
else
{
final IPricingResult pricingResult = calculatePrice(costCollector);
price = pricingResult.getPriceStdAsMoney();
amountPrecision = pricingResult.getPrecision();
}
return OrderLineDetailCreateRequest.builder()
.productId(costCollector.getProductId())
.qty(qty)
.price(price)
.amount(price.multiply(qty.toBigDecimal()).round(amountPrecision))
.build();
}
public IPricingResult calculatePrice(@NonNull final ServiceRepairProjectCostCollector costCollector)
{
final IEditablePricingContext pricingCtx = createPricingContext(costCollector)
.setFailIfNotCalculated(); | try
{
return pricingBL.calculatePrice(pricingCtx);
}
catch (final Exception ex)
{
throw AdempiereException.wrapIfNeeded(ex)
.setParameter("pricingInfo", pricingInfo)
.setParameter("pricingContext", pricingCtx)
.setParameter("costCollector", costCollector);
}
}
private IEditablePricingContext createPricingContext(
@NonNull final ServiceRepairProjectCostCollector costCollector)
{
return pricingBL.createPricingContext()
.setFailIfNotCalculated()
.setOrgId(pricingInfo.getOrgId())
.setProductId(costCollector.getProductId())
.setBPartnerId(pricingInfo.getShipBPartnerId())
.setQty(costCollector.getQtyReservedOrConsumed())
.setConvertPriceToContextUOM(true)
.setSOTrx(SOTrx.SALES)
.setPriceDate(pricingInfo.getDatePromised().toLocalDate())
.setPricingSystemId(pricingInfo.getPricingSystemId())
.setPriceListId(pricingInfo.getPriceListId())
.setPriceListVersionId(pricingInfo.getPriceListVersionId())
.setCountryId(pricingInfo.getCountryId())
.setCurrencyId(pricingInfo.getCurrencyId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\commands\createQuotationFromProjectCommand\ProjectQuotationPriceCalculator.java | 2 |
请完成以下Java代码 | public class BenchmarkRunner {
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
@State(Scope.Benchmark)
public static class MyState {
final Stream<Integer> getIntegers() {
return IntStream.range(1, 1000000)
.boxed();
}
final Predicate<Integer> PREDICATE = i -> i == 751879;
}
@Benchmark
public void evaluateFindUniqueElementMatchingPredicate_WithReduction(Blackhole blackhole, MyState state) {
blackhole.consume(FilterUtils.findUniqueElementMatchingPredicate_WithReduction(state.getIntegers(), state.PREDICATE));
}
@Benchmark
public void evaluateFindUniqueElementMatchingPredicate_WithCollectingAndThen(Blackhole blackhole, MyState state) {
blackhole.consume(FilterUtils.findUniqueElementMatchingPredicate_WithCollectingAndThen(state.getIntegers(), state.PREDICATE));
} | @Benchmark
public void evaluateGetUniqueElementMatchingPredicate_WithReduction(Blackhole blackhole, MyState state) {
try {
FilterUtils.getUniqueElementMatchingPredicate_WithReduction(state.getIntegers(), state.PREDICATE);
} catch (IllegalStateException exception) {
blackhole.consume(exception);
}
}
@Benchmark
public void evaluateGetUniqueElementMatchingPredicate_WithCollectingAndThen(Blackhole blackhole, MyState state) {
try {
FilterUtils.getUniqueElementMatchingPredicate_WithCollectingAndThen(state.getIntegers(), state.PREDICATE);
} catch (IllegalStateException exception) {
blackhole.consume(exception);
}
}
} | repos\tutorials-master\core-java-modules\core-java-streams-4\src\main\java\com\baeldung\streams\filteronlyoneelement\BenchmarkRunner.java | 1 |
请完成以下Java代码 | public boolean isMatching(@NonNull final LocalDate date)
{
if (!isInRange(date))
{
return false;
}
if (frequency == RecurrentNonBusinessDayFrequency.WEEKLY)
{
final DayOfWeek dayOfWeek = this.startDate.getDayOfWeek();
return date.getDayOfWeek().equals(dayOfWeek);
}
else if (frequency == RecurrentNonBusinessDayFrequency.YEARLY)
{
LocalDate currentDate = startDate;
while (isInRange(currentDate) && currentDate.compareTo(date) <= 0)
{
if (currentDate.equals(date))
{
return true;
}
currentDate = currentDate.plusYears(1);
}
return false;
}
else
{
throw new AdempiereException("Unknown frequency type: " + frequency); | }
}
private boolean isInRange(@NonNull final LocalDate date)
{
// Before start date
if (date.compareTo(startDate) < 0)
{
return false;
}
// After end date
if (endDate != null && date.compareTo(endDate) > 0)
{
return false;
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\calendar\RecurrentNonBusinessDay.java | 1 |
请完成以下Java代码 | public class RouteDefinition {
private @Nullable String id;
@NotEmpty
@Valid
private List<PredicateDefinition> predicates = new ArrayList<>();
@Valid
private List<FilterDefinition> filters = new ArrayList<>();
private @Nullable URI uri;
private Map<String, Object> metadata = new HashMap<>();
private int order = 0;
private boolean enabled = true;
public RouteDefinition() {
}
public RouteDefinition(String text) {
int eqIdx = text.indexOf('=');
if (eqIdx <= 0) {
throw new ValidationException(
"Unable to parse RouteDefinition text '" + text + "'" + ", must be of the form name=value");
}
setId(text.substring(0, eqIdx));
String[] args = tokenizeToStringArray(text.substring(eqIdx + 1), ",");
setUri(URI.create(args[0]));
for (int i = 1; i < args.length; i++) {
this.predicates.add(new PredicateDefinition(args[i]));
}
}
public @Nullable String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<PredicateDefinition> getPredicates() {
return predicates;
}
public void setPredicates(List<PredicateDefinition> predicates) {
this.predicates = predicates;
}
public List<FilterDefinition> getFilters() {
return filters;
}
public void setFilters(List<FilterDefinition> filters) {
this.filters = filters;
}
public @Nullable URI getUri() {
return uri; | }
public void setUri(URI uri) {
this.uri = uri;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public Map<String, Object> getMetadata() {
return metadata;
}
public void setMetadata(Map<String, Object> metadata) {
this.metadata = metadata;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RouteDefinition that = (RouteDefinition) o;
return this.order == that.order && Objects.equals(this.id, that.id)
&& Objects.equals(this.predicates, that.predicates) && Objects.equals(this.filters, that.filters)
&& Objects.equals(this.uri, that.uri) && Objects.equals(this.metadata, that.metadata)
&& Objects.equals(this.enabled, that.enabled);
}
@Override
public int hashCode() {
return Objects.hash(this.id, this.predicates, this.filters, this.uri, this.metadata, this.order, this.enabled);
}
@Override
public String toString() {
return "RouteDefinition{" + "id='" + id + '\'' + ", predicates=" + predicates + ", filters=" + filters
+ ", uri=" + uri + ", order=" + order + ", metadata=" + metadata + ", enabled=" + enabled + '}';
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\route\RouteDefinition.java | 1 |
请完成以下Java代码 | public String getAD_Message()
{
return adMessage;
}
/**
* Gets user friendly description of enabled flags.
*
* e.g. "3 - Client - Org"
*
* @return user friendly description of enabled flags
*/
public String getDescription()
{
final StringBuilder accessLevelInfo = new StringBuilder();
accessLevelInfo.append(getAccessLevelString());
if (isSystem())
{
accessLevelInfo.append(" - System");
}
if (isClient())
{
accessLevelInfo.append(" - Client");
}
if (isOrganization())
{ | accessLevelInfo.append(" - Org");
}
return accessLevelInfo.toString();
}
// --------------------------------------
// Pre-indexed values for optimization
private static ImmutableMap<Integer, TableAccessLevel> accessLevelInt2accessLevel;
static
{
final ImmutableMap.Builder<Integer, TableAccessLevel> builder = new ImmutableMap.Builder<Integer, TableAccessLevel>();
for (final TableAccessLevel l : values())
{
builder.put(l.getAccessLevelInt(), l);
}
accessLevelInt2accessLevel = builder.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\TableAccessLevel.java | 1 |
请完成以下Java代码 | public void setIsClosed (final boolean IsClosed)
{
set_Value (COLUMNNAME_IsClosed, IsClosed);
}
@Override
public boolean isClosed()
{
return get_ValueAsBoolean(COLUMNNAME_IsClosed);
}
@Override
public void setisQtyLUByMaxLoadWeight (final boolean isQtyLUByMaxLoadWeight)
{
set_Value (COLUMNNAME_isQtyLUByMaxLoadWeight, isQtyLUByMaxLoadWeight);
}
@Override
public boolean isQtyLUByMaxLoadWeight()
{
return get_ValueAsBoolean(COLUMNNAME_isQtyLUByMaxLoadWeight);
}
@Override
public void setIsInvoiceable (final boolean IsInvoiceable)
{
set_Value (COLUMNNAME_IsInvoiceable, IsInvoiceable);
}
@Override
public boolean isInvoiceable()
{
return get_ValueAsBoolean(COLUMNNAME_IsInvoiceable);
}
@Override
public void setLength (final @Nullable BigDecimal Length)
{
set_Value (COLUMNNAME_Length, Length);
}
@Override
public BigDecimal getLength()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Length);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setMaxLoadWeight (final @Nullable BigDecimal MaxLoadWeight)
{
set_Value (COLUMNNAME_MaxLoadWeight, MaxLoadWeight);
}
@Override
public BigDecimal getMaxLoadWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxLoadWeight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_HU_PackingMaterial_ID (final int M_HU_PackingMaterial_ID)
{
if (M_HU_PackingMaterial_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PackingMaterial_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PackingMaterial_ID, M_HU_PackingMaterial_ID);
}
@Override
public int getM_HU_PackingMaterial_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PackingMaterial_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID); | }
@Override
public void 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 setStackabilityFactor (final int StackabilityFactor)
{
set_Value (COLUMNNAME_StackabilityFactor, StackabilityFactor);
}
@Override
public int getStackabilityFactor()
{
return get_ValueAsInt(COLUMNNAME_StackabilityFactor);
}
@Override
public void setWidth (final @Nullable BigDecimal Width)
{
set_Value (COLUMNNAME_Width, Width);
}
@Override
public BigDecimal getWidth()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width);
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_M_HU_PackingMaterial.java | 1 |
请完成以下Java代码 | public void setQtyInternalUse (final @Nullable BigDecimal QtyInternalUse)
{
set_Value (COLUMNNAME_QtyInternalUse, QtyInternalUse);
}
@Override
public BigDecimal getQtyInternalUse()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInternalUse);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setRenderedQRCode (final @Nullable java.lang.String RenderedQRCode)
{
set_Value (COLUMNNAME_RenderedQRCode, RenderedQRCode);
}
@Override
public java.lang.String getRenderedQRCode()
{
return get_ValueAsString(COLUMNNAME_RenderedQRCode);
}
@Override
public org.compiere.model.I_M_InventoryLine getReversalLine()
{
return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_M_InventoryLine.class);
}
@Override
public void setReversalLine(final org.compiere.model.I_M_InventoryLine ReversalLine)
{
set_ValueFromPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_M_InventoryLine.class, ReversalLine);
}
@Override
public void setReversalLine_ID (final int ReversalLine_ID)
{
if (ReversalLine_ID < 1)
set_Value (COLUMNNAME_ReversalLine_ID, null); | else
set_Value (COLUMNNAME_ReversalLine_ID, ReversalLine_ID);
}
@Override
public int getReversalLine_ID()
{
return get_ValueAsInt(COLUMNNAME_ReversalLine_ID);
}
@Override
public void setUPC (final @Nullable java.lang.String UPC)
{
throw new IllegalArgumentException ("UPC is virtual column"); }
@Override
public java.lang.String getUPC()
{
return get_ValueAsString(COLUMNNAME_UPC);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
throw new IllegalArgumentException ("Value is virtual column"); }
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InventoryLine.java | 1 |
请完成以下Java代码 | public final class AuthorizeReturnObjectMethodInterceptor implements AuthorizationAdvisor {
@SuppressWarnings("NullAway.Init")
private @Nullable AuthorizationProxyFactory authorizationProxyFactory;
private Pointcut pointcut = Pointcuts.intersection(
new MethodReturnTypePointcut(Predicate.not(ClassUtils::isVoidType)),
AuthorizationMethodPointcuts.forAnnotations(AuthorizeReturnObject.class));
private int order = AuthorizationInterceptorsOrder.SECURE_RESULT.getOrder();
/**
* Construct the interceptor
*
* <p>
* Using this constructor requires you to specify
* {@link #setAuthorizationProxyFactory}
* </p>
* @since 6.5
*/
public AuthorizeReturnObjectMethodInterceptor() {
}
public AuthorizeReturnObjectMethodInterceptor(AuthorizationProxyFactory authorizationProxyFactory) {
Assert.notNull(authorizationProxyFactory, "authorizationProxyFactory cannot be null");
this.authorizationProxyFactory = authorizationProxyFactory;
}
@Override
public @Nullable Object invoke(MethodInvocation mi) throws Throwable {
Object result = mi.proceed();
if (result == null) {
return null;
}
Assert.notNull(this.authorizationProxyFactory, "authorizationProxyFactory cannot be null");
return this.authorizationProxyFactory.proxy(result);
}
/**
* Use this {@link AuthorizationProxyFactory}
* @param authorizationProxyFactory the proxy factory to use
* @since 6.5
*/
public void setAuthorizationProxyFactory(AuthorizationProxyFactory authorizationProxyFactory) {
Assert.notNull(authorizationProxyFactory, "authorizationProxyFactory cannot be null");
this.authorizationProxyFactory = authorizationProxyFactory;
}
@Override
public int getOrder() {
return this.order;
} | public void setOrder(int order) {
this.order = order;
}
/**
* {@inheritDoc}
*/
@Override
public Pointcut getPointcut() {
return this.pointcut;
}
public void setPointcut(Pointcut pointcut) {
this.pointcut = pointcut;
}
@Override
public Advice getAdvice() {
return this;
}
@Override
public boolean isPerInstance() {
return true;
}
static final class MethodReturnTypePointcut extends StaticMethodMatcherPointcut {
private final Predicate<Class<?>> returnTypeMatches;
MethodReturnTypePointcut(Predicate<Class<?>> returnTypeMatches) {
this.returnTypeMatches = returnTypeMatches;
}
@Override
public boolean matches(Method method, Class<?> targetClass) {
return this.returnTypeMatches.test(method.getReturnType());
}
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\AuthorizeReturnObjectMethodInterceptor.java | 1 |
请完成以下Java代码 | public int getPP_Order_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{ | set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP_Alternative.java | 1 |
请完成以下Java代码 | public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public Long getMilliseconds() {
return milliseconds;
}
public void setMilliseconds(Long milliseconds) {
this.milliseconds = milliseconds;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getValue() {
return value;
}
public void setValue(long value) {
this.value = value;
}
public String getReporter() {
return reporter;
} | public void setReporter(String reporter) {
this.reporter = reporter;
}
public Object getPersistentState() {
// immutable
return MeterLogEntity.class;
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<String>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<String, Class>();
return referenceIdAndClass;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MeterLogEntity.java | 1 |
请完成以下Java代码 | public class ComplexGatewayXMLConverter extends BaseBpmnXMLConverter {
@Override
public Class<? extends BaseElement> getBpmnElementType() {
// complex gateway is not supported so transform it to exclusive gateway
return ComplexGateway.class;
}
@Override
protected String getXMLElementName() {
return ELEMENT_GATEWAY_COMPLEX;
}
@Override
@SuppressWarnings("unchecked")
protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception {
ExclusiveGateway gateway = new ExclusiveGateway();
BpmnXMLUtil.addXMLLocation(gateway, xtr); | BpmnXMLUtil.addCustomAttributes(xtr, gateway, defaultElementAttributes, defaultActivityAttributes);
parseChildElements(getXMLElementName(), gateway, model, xtr);
return gateway;
}
@Override
protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception {
}
@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception {
}
} | repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\ComplexGatewayXMLConverter.java | 1 |
请完成以下Java代码 | public class EmptyUtil
{
/**
* @return {@code true} if the given value is either {@code null} or
* <li>an empty collection</li>
* <li>an empty array</li>
* <li>a blank string</li>
*/
@Contract("null -> true")
public boolean isEmpty(@Nullable final Object value)
{
if (value == null)
{
return true;
}
else if (value instanceof String)
{
return isBlank((String)value);
}
else if (value instanceof Object[])
{
return isEmpty((Object[])value);
}
else if (value instanceof Collection<?>)
{
return isEmpty((Collection<?>)value);
}
else if (value instanceof Iterable<?>)
{
return !((Iterable<?>)value).iterator().hasNext();
}
else
{
return false;
}
}
@Contract("null -> true")
public boolean isEmpty(@Nullable final String str)
{
return isEmpty(str, false);
}
/**
* @return return true if the string is null, has length 0, or contains only whitespace.
*/
@Contract("null -> true")
public boolean isBlank(@Nullable final String str)
{
return isEmpty(str, true);
}
/**
* @return return true if the string is not null, has length > 0, and does not contain only whitespace.
*/
@Contract("null -> false")
public boolean isNotBlank(@Nullable final String str)
{
return !isEmpty(str, true);
}
/**
* Is String Empty
*
* @param str string
* @param trimWhitespaces trim whitespaces
* @return true if >= 1 char
*/
@Contract("null, _ -> true")
public boolean isEmpty(@Nullable final String str, final boolean trimWhitespaces)
{ | if (str == null)
{
return true;
}
if (trimWhitespaces)
{
return str.trim().isEmpty();
}
else
{
return str.isEmpty();
}
} // isEmpty
/**
* @return true if the array is null or it's length is zero.
*/
@Contract("null -> true")
public <T> boolean isEmpty(@Nullable final T[] arr)
{
return arr == null || arr.length == 0;
}
/**
* @return true if given collection is <code>null</code> or it has no elements
*/
@Contract("null -> true")
public boolean isEmpty(@Nullable final Collection<?> collection)
{
return collection == null || collection.isEmpty();
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\EmptyUtil.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.