instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
private static class PrinterQueuesMap
{
private final LinkedHashMap<HardwarePrinterId, PrinterQueue> queuesMap = new LinkedHashMap<>();
public void add(@NonNull PrintingData printingData)
{
printingData.getSegments().forEach(segment -> add(printingData, segment));
}
private void add(
@NonNull PrintingData printingData,
@NonNull PrintingSegment segment)
{
final HardwarePrinter printer = segment.getPrinter();
getOrCreateQueue(printer).add(printingData, segment);
}
private PrinterQueue getOrCreateQueue(final HardwarePrinter printer)
{
return queuesMap.computeIfAbsent(printer.getId(), k -> new PrinterQueue(printer));
}
public void clear()
{
queuesMap.clear();
}
public FrontendPrinterData toFrontendPrinterData()
{
return queuesMap.values()
.stream()
.map(PrinterQueue::toFrontendPrinterData)
.collect(GuavaCollectors.collectUsingListAccumulator(FrontendPrinterData::of));
}
}
@RequiredArgsConstructor
private static class PrinterQueue
{
@NonNull private final HardwarePrinter printer;
@NonNull private final ArrayList<PrintingDataAndSegment> segments = new ArrayList<>();
public void add(
@NonNull PrintingData printingData,
@NonNull PrintingSegment segment)
{
Check.assumeEquals(this.printer, segment.getPrinter(), "Expected segment printer to match: {}, expected={}", segment, printer);
|
segments.add(PrintingDataAndSegment.of(printingData, segment));
}
public FrontendPrinterDataItem toFrontendPrinterData()
{
return FrontendPrinterDataItem.builder()
.printer(printer)
.filename(suggestFilename())
.data(toByteArray())
.build();
}
private byte[] toByteArray()
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (final PrintingDataToPDFWriter pdfWriter = new PrintingDataToPDFWriter(baos))
{
for (PrintingDataAndSegment printingDataAndSegment : segments)
{
pdfWriter.addArchivePartToPDF(printingDataAndSegment.getPrintingData(), printingDataAndSegment.getSegment());
}
}
return baos.toByteArray();
}
private String suggestFilename()
{
final ImmutableSet<String> filenames = segments.stream()
.map(PrintingDataAndSegment::getDocumentFileName)
.collect(ImmutableSet.toImmutableSet());
return filenames.size() == 1 ? filenames.iterator().next() : "report.pdf";
}
}
@Value(staticConstructor = "of")
private static class PrintingDataAndSegment
{
@NonNull PrintingData printingData;
@NonNull PrintingSegment segment;
public String getDocumentFileName()
{
return printingData.getDocumentFileName();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\frontend\FrontendPrinter.java
| 1
|
请完成以下Java代码
|
public java.lang.String getReplacement()
{
return get_ValueAsString(COLUMNNAME_Replacement);
}
/**
* ReplacementSource AD_Reference_ID=541598
* Reference name: ReplacementSourceList
*/
public static final int REPLACEMENTSOURCE_AD_Reference_ID=541598;
/** Product = P */
public static final String REPLACEMENTSOURCE_Product = "P";
/** PPOrder = PP */
public static final String REPLACEMENTSOURCE_PPOrder = "PP";
/** CustomProcessResult = CP */
public static final String REPLACEMENTSOURCE_CustomProcessResult = "CP";
@Override
public void setReplacementSource (final java.lang.String ReplacementSource)
{
set_Value (COLUMNNAME_ReplacementSource, ReplacementSource);
}
@Override
public java.lang.String getReplacementSource()
{
return get_ValueAsString(COLUMNNAME_ReplacementSource);
}
@Override
public void setReplaceRegExp (final @Nullable java.lang.String ReplaceRegExp)
{
set_Value (COLUMNNAME_ReplaceRegExp, ReplaceRegExp);
}
@Override
public java.lang.String getReplaceRegExp()
{
return get_ValueAsString(COLUMNNAME_ReplaceRegExp);
}
@Override
public void setTargetFieldName (final java.lang.String TargetFieldName)
{
set_Value (COLUMNNAME_TargetFieldName, TargetFieldName);
}
@Override
|
public java.lang.String getTargetFieldName()
{
return get_ValueAsString(COLUMNNAME_TargetFieldName);
}
/**
* TargetFieldType AD_Reference_ID=541611
* Reference name: AttributeTypeList
*/
public static final int TARGETFIELDTYPE_AD_Reference_ID=541611;
/** textArea = textArea */
public static final String TARGETFIELDTYPE_TextArea = "textArea";
/** EAN13 = EAN13 */
public static final String TARGETFIELDTYPE_EAN13 = "EAN13";
/** EAN128 = EAN128 */
public static final String TARGETFIELDTYPE_EAN128 = "EAN128";
/** numberField = numberField */
public static final String TARGETFIELDTYPE_NumberField = "numberField";
/** date = date */
public static final String TARGETFIELDTYPE_Date = "date";
/** unitChar = unitChar */
public static final String TARGETFIELDTYPE_UnitChar = "unitChar";
/** graphic = graphic */
public static final String TARGETFIELDTYPE_Graphic = "graphic";
@Override
public void setTargetFieldType (final java.lang.String TargetFieldType)
{
set_Value (COLUMNNAME_TargetFieldType, TargetFieldType);
}
@Override
public java.lang.String getTargetFieldType()
{
return get_ValueAsString(COLUMNNAME_TargetFieldType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_LeichMehl_PluFile_Config.java
| 1
|
请完成以下Java代码
|
public String getEmailAdr() {
return emailAdr;
}
/**
* Sets the value of the emailAdr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEmailAdr(String value) {
this.emailAdr = value;
}
/**
* Gets the value of the othr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOthr() {
|
return othr;
}
/**
* Sets the value of the othr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOthr(String value) {
this.othr = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ContactDetails2.java
| 1
|
请完成以下Java代码
|
public static BigDecimal toBigDecimal(@NonNull final Duration duration, @NonNull final TemporalUnit unit)
{
return BigDecimal.valueOf(toLong(duration, unit));
}
public static Duration fromBigDecimal(@NonNull final BigDecimal duration, @NonNull final TemporalUnit unit)
{
return Duration.of(duration.longValue(), unit);
}
public static int toInt(@NonNull final Duration duration, @NonNull final TemporalUnit unit)
{
return (int)toLong(duration, unit);
}
public static long toLong(@NonNull final Duration duration, @NonNull final TemporalUnit unit)
{
if (unit == ChronoUnit.SECONDS)
{
return duration.getSeconds();
}
else if (unit == ChronoUnit.MINUTES)
{
return duration.toMinutes();
}
else if (unit == ChronoUnit.HOURS)
{
return duration.toHours();
}
else if (unit == ChronoUnit.DAYS)
{
return duration.toDays();
}
else
{
throw Check.newException("Cannot convert " + duration + " to " + unit);
}
}
|
private static BigDecimal getEquivalentInSmallerTemporalUnit(@NonNull final BigDecimal durationBD, @NonNull final TemporalUnit unit)
{
if (unit == ChronoUnit.DAYS)
{
return durationBD.multiply(BigDecimal.valueOf(WORK_HOURS_PER_DAY));// This refers to work hours, not calendar hours
}
if (unit == ChronoUnit.HOURS)
{
return durationBD.multiply(BigDecimal.valueOf(60));
}
if (unit == ChronoUnit.MINUTES)
{
return durationBD.multiply(BigDecimal.valueOf(60));
}
if (unit == ChronoUnit.SECONDS)
{
return durationBD.multiply(BigDecimal.valueOf(1000));
}
throw Check.newException("No smaller temporal unit defined for {}", unit);
}
public static boolean isCompleteDays(@NonNull final Duration duration)
{
if (duration.isZero())
{
return true;
}
final Duration daysAsDuration = Duration.ofDays(duration.toDays());
return daysAsDuration.equals(duration);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\DurationUtils.java
| 1
|
请完成以下Java代码
|
public void setBinaryFormat (java.lang.String BinaryFormat)
{
set_Value (COLUMNNAME_BinaryFormat, BinaryFormat);
}
@Override
public java.lang.String getBinaryFormat()
{
return (java.lang.String)get_Value(COLUMNNAME_BinaryFormat);
}
@Override
public void setCopies (int Copies)
{
set_Value (COLUMNNAME_Copies, Integer.valueOf(Copies));
}
@Override
public int getCopies()
{
return get_ValueAsInt(COLUMNNAME_Copies);
}
@Override
public de.metas.printing.model.I_C_Print_Job_Instructions getC_Print_Job_Instructions()
{
return get_ValueAsPO(COLUMNNAME_C_Print_Job_Instructions_ID, de.metas.printing.model.I_C_Print_Job_Instructions.class);
}
@Override
public void setC_Print_Job_Instructions(de.metas.printing.model.I_C_Print_Job_Instructions C_Print_Job_Instructions)
{
set_ValueFromPO(COLUMNNAME_C_Print_Job_Instructions_ID, de.metas.printing.model.I_C_Print_Job_Instructions.class, C_Print_Job_Instructions);
}
@Override
public void setC_Print_Job_Instructions_ID (int C_Print_Job_Instructions_ID)
{
if (C_Print_Job_Instructions_ID < 1)
set_Value (COLUMNNAME_C_Print_Job_Instructions_ID, null);
else
set_Value (COLUMNNAME_C_Print_Job_Instructions_ID, Integer.valueOf(C_Print_Job_Instructions_ID));
}
@Override
public int getC_Print_Job_Instructions_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Job_Instructions_ID);
}
@Override
public void setC_Print_Package_ID (int C_Print_Package_ID)
{
if (C_Print_Package_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Print_Package_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Print_Package_ID, Integer.valueOf(C_Print_Package_ID));
}
@Override
public int getC_Print_Package_ID()
|
{
return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID);
}
@Override
public void setPackageInfoCount (int PackageInfoCount)
{
throw new IllegalArgumentException ("PackageInfoCount is virtual column"); }
@Override
public int getPackageInfoCount()
{
return get_ValueAsInt(COLUMNNAME_PackageInfoCount);
}
@Override
public void setPageCount (int PageCount)
{
set_Value (COLUMNNAME_PageCount, Integer.valueOf(PageCount));
}
@Override
public int getPageCount()
{
return get_ValueAsInt(COLUMNNAME_PageCount);
}
@Override
public void setTransactionID (java.lang.String TransactionID)
{
set_Value (COLUMNNAME_TransactionID, TransactionID);
}
@Override
public java.lang.String getTransactionID()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Package.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void init(FilterConfig filterConfig) throws ServletException {
LOG.info("initializing ...");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest)request;
String sessionId = httpServletRequest.getSession(true).getId();
Optional<UserData> userData = userAccessService.isAuthenticated(sessionId);
if (userData.isPresent()) {
String user = userData.get().getUserName();
String method = httpServletRequest.getMethod();
String path = httpServletRequest.getRequestURI();
if (enforcer.enforce(user, path, method)) {
LOG.info("session is authorized: {} {} {} {}", sessionId, user, method, path);
List<String> rolesForUser = enforcer.getRolesForUser(user);
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(new AuthenticationImpl(userData.get().getUserName(), rolesForUser));
HttpSession session = httpServletRequest.getSession();
|
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
chain.doFilter(request, response);
} else {
LOG.error("session is not authorized: {} {} {} {}", sessionId, user, method, path);
HttpServletResponse httpServletResponse = (HttpServletResponse)response;
httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
}
} else {
LOG.error("session is not authenticated: {}", sessionId);
HttpServletResponse httpServletResponse = (HttpServletResponse)response;
httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
}
}
@Override
public void destroy() {
LOG.info("destroy.");
}
}
|
repos\spring-examples-java-17\spring-jcasbin\src\main\java\itx\examples\springboot\security\config\JCasBinFilter.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private @Nullable ModelAndView resolve(String viewName, Map<String, Object> model) {
String errorViewName = "error/" + viewName;
TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName,
this.applicationContext);
if (provider != null) {
return new ModelAndView(errorViewName, model);
}
return resolveResource(errorViewName, model);
}
private @Nullable ModelAndView resolveResource(String viewName, Map<String, Object> model) {
for (String location : this.resources.getStaticLocations()) {
try {
Resource resource = this.applicationContext.getResource(location);
resource = resource.createRelative(viewName + ".html");
if (resource.exists()) {
return new ModelAndView(new HtmlResourceView(resource), model);
}
}
catch (Exception ex) {
// Ignore
}
}
return null;
}
@Override
public int getOrder() {
return this.order;
}
|
public void setOrder(int order) {
this.order = order;
}
/**
* {@link View} backed by an HTML resource.
*/
private static class HtmlResourceView implements View {
private final Resource resource;
HtmlResourceView(Resource resource) {
this.resource = resource;
}
@Override
public String getContentType() {
return MediaType.TEXT_HTML_VALUE;
}
@Override
public void render(@Nullable Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.setContentType(getContentType());
FileCopyUtils.copy(this.resource.getInputStream(), response.getOutputStream());
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\error\DefaultErrorViewResolver.java
| 2
|
请完成以下Java代码
|
public void execute(InterpretableExecution execution) {
ScopeImpl scope = getScope(execution);
List<ExecutionListener> executionListeners = scope.getExecutionListeners(getEventName());
int executionListenerIndex = execution.getExecutionListenerIndex();
if (executionListeners.size() > executionListenerIndex) {
execution.setEventName(getEventName());
execution.setEventSource(scope);
ExecutionListener listener = executionListeners.get(executionListenerIndex);
try {
listener.notify(execution);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new PvmException("couldn't execute event listener : " + e.getMessage(), e);
}
execution.setExecutionListenerIndex(executionListenerIndex + 1);
|
execution.performOperation(this);
} else {
execution.setExecutionListenerIndex(0);
execution.setEventName(null);
execution.setEventSource(null);
eventNotificationsCompleted(execution);
}
}
protected abstract ScopeImpl getScope(InterpretableExecution execution);
protected abstract String getEventName();
protected abstract void eventNotificationsCompleted(InterpretableExecution execution);
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\runtime\AbstractEventAtomicOperation.java
| 1
|
请完成以下Java代码
|
public void deleteGroupMember(String userId) {
ensureNotReadOnly();
userId = PathUtil.decodePathParam(userId);
identityService.deleteMembership(userId, resourceId);
}
public ResourceOptionsDto availableOperations(UriInfo context) {
ResourceOptionsDto dto = new ResourceOptionsDto();
URI uri = context.getBaseUriBuilder()
.path(relativeRootResourcePath)
.path(GroupRestService.PATH)
.path(resourceId)
|
.path(PATH)
.build();
if (!identityService.isReadOnly() && isAuthorized(DELETE)) {
dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete");
}
if (!identityService.isReadOnly() && isAuthorized(CREATE)) {
dto.addReflexiveLink(uri, HttpMethod.PUT, "create");
}
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\identity\impl\GroupMembersResourceImpl.java
| 1
|
请完成以下Java代码
|
public boolean accept(@Nullable final Object model)
{
if (model == null)
{
return false;
}
// Check tableName match
final String modelTableName = InterfaceWrapperHelper.getModelTableName(model);
if (!tableName.equals(modelTableName))
{
return false;
}
if (isDocument)
{
return acceptDocument(model);
}
return true;
}
protected boolean acceptDocument(final Object model)
{
return docOutboundConfigService.retrieveConfigForModel(model) != null;
}
@Override
public void createDocOutbound(@NonNull final Object model)
{
enqueueModelForWorkpackageProcessor(model, DocOutboundWorkpackageProcessor.class);
}
@Override
|
public void voidDocOutbound(@NonNull final Object model)
{
enqueueModelForWorkpackageProcessor(model, ProcessPrintingQueueWorkpackageProcessor.class);
}
private void enqueueModelForWorkpackageProcessor(
@NonNull final Object model,
@NonNull final Class<? extends IWorkpackageProcessor> packageProcessorClass)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(model);
final I_C_Async_Batch asyncBatch = asyncBatchBL.getAsyncBatchId(model)
.map(asyncBatchBL::getAsyncBatchById)
.orElse(null);
workPackageQueueFactory
.getQueueForEnqueuing(ctx, packageProcessorClass)
.newWorkPackage()
.bindToThreadInheritedTrx()
.addElement(model)
.setC_Async_Batch(asyncBatch)
.setUserInChargeId(Env.getLoggedUserIdIfExists().orElse(null))
.buildAndEnqueue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\spi\impl\AbstractDocOutboundProducer.java
| 1
|
请完成以下Spring Boot application配置
|
#application
spring.application.name=springboot-neo4j
application.main=cn.abel.Application
server.port=9657
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8
server.tomcat.max-threads=200
server.session-timeout=60
log4j.logger.java.sql.Connection=DEBUG
logging.file=./logs/springboot-neo4j/springboot-neo4j.log
|
spring.data.neo4j.url=bolt://localhost:7687
spring.data.neo4j.username=neo4j
spring.data.neo4j.password=admin
neo4j.url=bolt://localhost:7687
neo4j.username=neo4j
neo4j.password=admin
|
repos\springBoot-master\springboot-neo4j\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public LUQtysBuilder setQtyTUsPerLU(final int qtyTUs)
{
return setQtyTUsPerLU(BigDecimal.valueOf(qtyTUs));
}
private BigDecimal getQtyCUsPerTU()
{
Check.assumeNotNull(qtyCUsPerTU, "qtyCUsPerTU not null");
return qtyCUsPerTU;
}
public LUQtysBuilder setQtyCUsPerTU(final BigDecimal qtyCUsPerTU)
{
this.qtyCUsPerTU = NumberUtils.stripTrailingDecimalZeros(qtyCUsPerTU);
return this;
}
public LUQtysBuilder setQtyCUsPerTU(final int qtyCUsPerTU)
{
return setQtyCUsPerTU(BigDecimal.valueOf(qtyCUsPerTU));
}
/**
* Sets quantity CUs/LU.
*
* Use it only if you have incomplete TUs, else it would be calculated as QtyCUsPerLU = QtyCUsPerTU * QtyTUs.
*
* @param qtyCUsPerLU
*/
public LUQtysBuilder setQtyCUsPerLU_IfGreaterThanZero(BigDecimal qtyCUsPerLU)
{
if (qtyCUsPerLU == null || qtyCUsPerLU.signum() <= 0)
{
return this;
}
this.qtyCUsPerLU = NumberUtils.stripTrailingDecimalZeros(qtyCUsPerLU);
return this;
}
private BigDecimal getQtyCUsPerLU()
{
if (qtyCUsPerLU == null)
{
return getQtyCUsPerTU().multiply(getQtyTUsPerLU());
}
return qtyCUsPerLU;
}
}
}
/** {@link TotalQtyCUBreakdownCalculator} builder */
public static final class Builder
{
private BigDecimal qtyCUsTotal;
private BigDecimal qtyTUsTotal;
private BigDecimal qtyCUsPerTU;
private BigDecimal qtyTUsPerLU;
private Builder()
{
super();
}
public TotalQtyCUBreakdownCalculator build()
{
return new TotalQtyCUBreakdownCalculator(this);
}
public Builder setQtyCUsTotal(final BigDecimal qtyCUsTotal)
{
this.qtyCUsTotal = qtyCUsTotal;
return this;
}
public BigDecimal getQtyCUsTotal()
{
Check.assumeNotNull(qtyCUsTotal, "qtyCUsTotal not null");
return qtyCUsTotal;
}
public Builder setQtyTUsTotal(final BigDecimal qtyTUsTotal)
|
{
this.qtyTUsTotal = qtyTUsTotal;
return this;
}
public BigDecimal getQtyTUsTotal()
{
if (qtyTUsTotal == null)
{
return Quantity.QTY_INFINITE;
}
return qtyTUsTotal;
}
public Builder setStandardQtyCUsPerTU(final BigDecimal qtyCUsPerTU)
{
this.qtyCUsPerTU = qtyCUsPerTU;
return this;
}
public BigDecimal getStandardQtyCUsPerTU()
{
return qtyCUsPerTU;
}
public Builder setStandardQtyTUsPerLU(final BigDecimal qtyTUsPerLU)
{
this.qtyTUsPerLU = qtyTUsPerLU;
return this;
}
public Builder setStandardQtyTUsPerLU(final int qtyTUsPerLU)
{
return setStandardQtyTUsPerLU(BigDecimal.valueOf(qtyTUsPerLU));
}
public BigDecimal getStandardQtyTUsPerLU()
{
return qtyTUsPerLU;
}
public Builder setStandardQtysAsInfinite()
{
setStandardQtyCUsPerTU(BigDecimal.ZERO);
setStandardQtyTUsPerLU(BigDecimal.ZERO);
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\TotalQtyCUBreakdownCalculator.java
| 1
|
请完成以下Java代码
|
public boolean isDefault() {
return isDefault;
}
@Schema(description = "Complex JSON object that includes addition device profile configuration (transport, alarm rules, etc).")
public DeviceProfileData getProfileData() {
if (profileData != null) {
return profileData;
} else {
if (profileDataBytes != null) {
try {
profileData = mapper.readValue(new ByteArrayInputStream(profileDataBytes), DeviceProfileData.class);
} catch (IOException e) {
log.warn("Can't deserialize device profile data: ", e);
return null;
}
return profileData;
} else {
|
return null;
}
}
}
public void setProfileData(DeviceProfileData data) {
this.profileData = data;
try {
this.profileDataBytes = data != null ? mapper.writeValueAsBytes(data) : null;
} catch (JsonProcessingException e) {
log.warn("Can't serialize device profile data: ", e);
}
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\DeviceProfile.java
| 1
|
请完成以下Java代码
|
public MTreeNode loadNodeInfo(final MTree tree, final ResultSet rs) throws SQLException
{
final int nodeId = rs.getInt("Node_ID");
final String name = rs.getString("Name");
final String description = rs.getString("Description");
final boolean isAllowChildren = "Y".equals(rs.getString("IsSummary"));
final Color color = loadPrintColor(tree, rs);
final int seqNo = 0;
final String imageIndicator = null;
final boolean onBar = false;
final int parent_ID = 0;
final MTreeNode node = new MTreeNode(
nodeId,
seqNo,
name,
description,
parent_ID,
isAllowChildren,
imageIndicator,
onBar,
color);
node.setAD_Tree_ID(tree.getAD_Tree_ID());
node.setAD_Table_ID(tree.getAD_Table_ID());
return node;
}
/**
* Code cut&pasted (and cleaned up) from {@link org.compiere.model.MTree#getDefaultAD_Tree_ID(int, String)}
*/
@Override
public String getTreeType()
{
final String keyColumnName = tableName + "_ID";
final String treeType;
if (keyColumnName.equals("AD_Menu_ID"))
{
treeType = X_AD_Tree.TREETYPE_Menu;
}
else if (keyColumnName.equals("C_ElementValue_ID"))
{
treeType = X_AD_Tree.TREETYPE_ElementValue;
}
else if (keyColumnName.equals("M_Product_ID"))
{
treeType = X_AD_Tree.TREETYPE_Product;
}
else if (keyColumnName.equals("C_BPartner_ID"))
{
treeType = X_AD_Tree.TREETYPE_BPartner;
}
else if (keyColumnName.equals("AD_Org_ID"))
{
treeType = X_AD_Tree.TREETYPE_Organization;
}
else if (keyColumnName.equals("C_Project_ID"))
{
treeType = X_AD_Tree.TREETYPE_Project;
}
else if (keyColumnName.equals("M_ProductCategory_ID"))
{
treeType = X_AD_Tree.TREETYPE_ProductCategory;
}
else if (keyColumnName.equals("M_BOM_ID"))
{
treeType = X_AD_Tree.TREETYPE_BoM;
}
else if (keyColumnName.equals("C_SalesRegion_ID"))
|
{
treeType = X_AD_Tree.TREETYPE_SalesRegion;
}
else if (keyColumnName.equals("C_Campaign_ID"))
{
treeType = X_AD_Tree.TREETYPE_Campaign;
}
else if (keyColumnName.equals("C_Activity_ID"))
{
treeType = X_AD_Tree.TREETYPE_Activity;
}
else if (keyColumnName.equals("CM_CStage_ID"))
{
treeType = X_AD_Tree.TREETYPE_CMContainerStage;
}
else if (keyColumnName.equals("CM_Container_ID"))
{
treeType = X_AD_Tree.TREETYPE_CMContainer;
}
else if (keyColumnName.equals("CM_Media_ID"))
{
treeType = X_AD_Tree.TREETYPE_CMMedia;
}
else if (keyColumnName.equals("CM_Template_ID"))
{
treeType = X_AD_Tree.TREETYPE_CMTemplate;
}
else
{
treeType = null;
}
return treeType;
}
@Override
public void setTableName(final String tableName)
{
this.tableName = tableName;
}
protected String getTableName()
{
return tableName;
}
@Override
public final void disableRoleAccessCheckWhileLoading()
{
this.checkRoleAccessWhileLoading = false;
}
protected final boolean isCheckRoleAccessWhileLoading()
{
return checkRoleAccessWhileLoading;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\tree\spi\impl\DefaultPOTreeSupport.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) {
PropertyMapper map = PropertyMapper.get();
JmsTemplate template = new JmsTemplate(connectionFactory);
template.setPubSubDomain(this.properties.isPubSubDomain());
map.from(this.destinationResolver::getIfUnique).to(template::setDestinationResolver);
map.from(this.messageConverter::getIfUnique).to(template::setMessageConverter);
map.from(this.observationRegistry::getIfUnique).to(template::setObservationRegistry);
mapTemplateProperties(this.properties.getTemplate(), template);
return template;
}
private void mapTemplateProperties(Template properties, JmsTemplate template) {
PropertyMapper map = PropertyMapper.get();
map.from(properties.getSession().getAcknowledgeMode()::getMode).to(template::setSessionAcknowledgeMode);
map.from(properties.getSession()::isTransacted).to(template::setSessionTransacted);
map.from(properties::getDefaultDestination).to(template::setDefaultDestinationName);
map.from(properties::getDeliveryDelay).as(Duration::toMillis).to(template::setDeliveryDelay);
map.from(properties::determineQosEnabled).to(template::setExplicitQosEnabled);
map.from(properties::getDeliveryMode).as(DeliveryMode::getValue).to(template::setDeliveryMode);
map.from(properties::getPriority).to(template::setPriority);
map.from(properties::getTimeToLive).as(Duration::toMillis).to(template::setTimeToLive);
map.from(properties::getReceiveTimeout).as(Duration::toMillis).to(template::setReceiveTimeout);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(JmsMessagingTemplate.class)
static class MessagingTemplateConfiguration {
@Bean
@ConditionalOnMissingBean(JmsMessageOperations.class)
@ConditionalOnSingleCandidate(JmsTemplate.class)
JmsMessagingTemplate jmsMessagingTemplate(JmsProperties properties, JmsTemplate jmsTemplate) {
JmsMessagingTemplate messagingTemplate = new JmsMessagingTemplate(jmsTemplate);
mapTemplateProperties(properties.getTemplate(), messagingTemplate);
return messagingTemplate;
}
private void mapTemplateProperties(Template properties, JmsMessagingTemplate messagingTemplate) {
|
PropertyMapper map = PropertyMapper.get();
map.from(properties::getDefaultDestination).to(messagingTemplate::setDefaultDestinationName);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(JmsClient.class)
static class JmsClientConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnSingleCandidate(JmsTemplate.class)
JmsClient jmsClient(JmsTemplate jmsTemplate) {
return JmsClient.create(jmsTemplate);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JmsClientConfigurations.java
| 2
|
请完成以下Java代码
|
public class OmsOrderReturnReason implements Serializable {
private Long id;
@ApiModelProperty(value = "退货类型")
private String name;
private Integer sort;
@ApiModelProperty(value = "状态:0->不启用;1->启用")
private Integer status;
@ApiModelProperty(value = "添加时间")
private Date createTime;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Integer getStatus() {
return status;
|
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", sort=").append(sort);
sb.append(", status=").append(status);
sb.append(", createTime=").append(createTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderReturnReason.java
| 1
|
请完成以下Java代码
|
public BigDecimal getBankRate() {
return bankRate;
}
/** 银行费率 **/
public void setBankRate(BigDecimal bankRate) {
this.bankRate = bankRate;
}
/** 订单金额 **/
public BigDecimal getTotalFee() {
return totalFee;
}
/** 订单金额 **/
public void setTotalFee(BigDecimal totalFee) {
this.totalFee = totalFee;
}
/** 银行流水 **/
public String getTradeNo() {
return tradeNo;
}
/** 银行流水 **/
public void setTradeNo(String tradeNo) {
this.tradeNo = tradeNo;
}
/** 交易类型 **/
public String getTransType() {
return transType;
}
/** 交易类型 **/
public void setTransType(String transType) {
this.transType = transType;
}
|
/** 交易时间 **/
public Date getTransDate() {
return transDate;
}
/** 交易时间 **/
public void setTransDate(Date transDate) {
this.transDate = transDate;
}
/** 银行(支付宝)该笔订单收取的手续费 **/
public BigDecimal getBankFee() {
return bankFee;
}
/** 银行(支付宝)该笔订单收取的手续费 **/
public void setBankFee(BigDecimal bankFee) {
this.bankFee = bankFee;
}
}
|
repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\java\com\roncoo\pay\app\reconciliation\vo\AlipayAccountLogVO.java
| 1
|
请完成以下Java代码
|
private UserId getNotificationRecipientUserId(final I_M_InOut inout)
{
//
// In case of reversal i think we shall notify the current user too
final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(inout.getDocStatus());
if (docStatus.isReversedOrVoided())
{
final int currentUserId = Env.getAD_User_ID(Env.getCtx()); // current/triggering user
if (currentUserId > 0)
{
return UserId.ofRepoId(currentUserId);
}
return UserId.ofRepoId(inout.getUpdatedBy()); // last updated
}
//
// Fallback: notify only the creator
else
{
return UserId.ofRepoId(inout.getCreatedBy());
}
}
public InOutUserNotificationsProducer notifyShipmentError(
@NonNull final String sourceInfo,
@NonNull final String errorMessage)
{
// don't send after commit, because the trx will very probably be rolled back if an error happened
|
notificationBL.send(newUserNotificationRequest()
.recipientUserId(Env.getLoggedUserId())
.contentADMessage(MSG_Event_ShipmentError)
.contentADMessageParam(sourceInfo)
.contentADMessageParam(errorMessage)
.build());
return this;
}
private void postNotifications(final List<UserNotificationRequest> notifications)
{
notificationBL.sendAfterCommit(notifications);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\event\InOutUserNotificationsProducer.java
| 1
|
请完成以下Java代码
|
public ResponseEntity<?> revertInvoice(
@PathVariable("invoiceId") @ApiParam(required = true, value = "metasfreshId of the invoice to revert") final int invoiceRecordId)
{
final InvoiceId invoiceId = InvoiceId.ofRepoIdOrNull(invoiceRecordId);
if (invoiceId == null)
{
return ResponseEntity.notFound().build();
}
try
{
final Optional<JsonReverseInvoiceResponse> response = jsonInvoiceService.reverseInvoice(invoiceId);
return response.isPresent()
? ResponseEntity.ok(response.get())
: ResponseEntity.notFound().build();
}
catch (final Exception ex)
{
final JsonError error = JsonError.ofSingleItem(JsonErrors.ofThrowable(ex, Env.getADLanguageOrBaseLanguage()));
return ResponseEntity.unprocessableEntity().body(error);
}
}
@ApiOperation("Create new invoice payment")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully created new invoice payment"),
@ApiResponse(code = 401, message = "You are not authorized to create a new invoice payment"),
@ApiResponse(code = 403, message = "Accessing a related resource is forbidden"),
@ApiResponse(code = 422, message = "The request body could not be processed")
})
@PostMapping("/payment")
public ResponseEntity<?> createInvoicePayment(@NonNull @RequestBody final JsonInvoicePaymentCreateRequest request)
{
|
try
{
jsonInvoiceService.createInboundPaymentFromJson(request);
return ResponseEntity.ok().build();
}
catch (final Exception ex)
{
logger.error(ex.getMessage(), ex);
final String adLanguage = Env.getADLanguageOrBaseLanguage();
return ResponseEntity.unprocessableEntity()
.body(JsonErrors.ofThrowable(ex, adLanguage));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\invoice\InvoicesRestController.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PickingJobStepPickedTo
{
@Nullable QtyRejectedWithReason qtyRejected;
@NonNull ImmutableList<PickingJobStepPickedToHU> actualPickedHUs;
@NonNull Quantity qtyPicked;
@Nullable Quantity catchWeight;
@Builder(toBuilder = true)
@Jacksonized
private PickingJobStepPickedTo(
@NonNull final ImmutableList<PickingJobStepPickedToHU> actualPickedHUs,
@Nullable final QtyRejectedWithReason qtyRejected)
{
// NOTE: empty actualPickedHUs is also OK for the case when the whole HU was rejected
//Check.assumeNotEmpty(actualPickedHUs, "actualPickedHUs not empty");
Maps.uniqueIndex(actualPickedHUs, PickingJobStepPickedToHU::getActualPickedHU); // make sure there are no duplicates
this.qtyRejected = qtyRejected;
this.actualPickedHUs = actualPickedHUs;
final Quantity qtyPicked = actualPickedHUs.stream()
.map(PickingJobStepPickedToHU::getQtyPicked)
.reduce(Quantity::add)
.orElse(null);
if (qtyPicked == null)
{
if (qtyRejected == null)
{
throw new AdempiereException("qtyPicked and qtyRejected cannot be both null");
}
this.qtyPicked = qtyRejected.toQuantity().toZero();
}
else
{
this.qtyPicked = qtyPicked;
}
this.catchWeight = actualPickedHUs.stream()
.map(PickingJobStepPickedToHU::getCatchWeight)
.filter(Objects::nonNull)
.reduce(Quantity::add)
.orElse(null);
Quantity.assertSameUOM(this.qtyPicked, this.qtyRejected != null ? this.qtyRejected.toQuantity() : null);
}
public Stream<PickingJobStepPickedToHU> stream() {return actualPickedHUs.stream();}
@Nullable
|
public PickingJobStepPickedTo removing(final List<PickingJobStepPickedToHU> toRemove)
{
if (toRemove.isEmpty())
{
return this;
}
final ImmutableList<PickingJobStepPickedToHU> actualPickedHUsNew = this.actualPickedHUs.stream()
.filter(pickedHU -> !toRemove.contains(pickedHU))
.collect(ImmutableList.toImmutableList());
if (actualPickedHUsNew.size() == actualPickedHUs.size())
{
return this;
}
if (actualPickedHUsNew.isEmpty() && this.qtyRejected == null)
{
return null;
}
return toBuilder().actualPickedHUs(actualPickedHUsNew).build();
}
@NonNull
public List<HuId> getPickedHuIds()
{
return actualPickedHUs.stream()
.map(PickingJobStepPickedToHU::getActualPickedHU)
.map(HUInfo::getId)
.collect(ImmutableList.toImmutableList());
}
@NonNull
public Optional<PickingJobStepPickedToHU> getLastPickedHu()
{
return actualPickedHUs.stream()
.max(Comparator.comparing(PickingJobStepPickedToHU::getCreatedAt));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobStepPickedTo.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isAutoIndex() {
return this.autoIndex;
}
public void setAutoIndex(boolean autoIndex) {
this.autoIndex = autoIndex;
}
public @Nullable String getBucketName() {
return this.bucketName;
}
public void setBucketName(@Nullable String bucketName) {
this.bucketName = bucketName;
}
public @Nullable String getScopeName() {
return this.scopeName;
}
public void setScopeName(@Nullable String scopeName) {
this.scopeName = scopeName;
}
public @Nullable Class<?> getFieldNamingStrategy() {
return this.fieldNamingStrategy;
|
}
public void setFieldNamingStrategy(@Nullable Class<?> fieldNamingStrategy) {
this.fieldNamingStrategy = fieldNamingStrategy;
}
public String getTypeKey() {
return this.typeKey;
}
public void setTypeKey(String typeKey) {
this.typeKey = typeKey;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-data-couchbase\src\main\java\org\springframework\boot\data\couchbase\autoconfigure\DataCouchbaseProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public ModelResponse updateModel(@ApiParam(name = "modelId") @PathVariable String modelId, @RequestBody ModelRequest modelRequest) {
Model model = getModelFromRequest(modelId);
if (modelRequest.isCategoryChanged()) {
model.setCategory(modelRequest.getCategory());
}
if (modelRequest.isDeploymentChanged()) {
model.setDeploymentId(modelRequest.getDeploymentId());
}
if (modelRequest.isKeyChanged()) {
model.setKey(modelRequest.getKey());
}
if (modelRequest.isMetaInfoChanged()) {
model.setMetaInfo(modelRequest.getMetaInfo());
}
if (modelRequest.isNameChanged()) {
model.setName(modelRequest.getName());
}
if (modelRequest.isVersionChanged()) {
model.setVersion(modelRequest.getVersion());
}
if (modelRequest.isTenantIdChanged()) {
model.setTenantId(modelRequest.getTenantId());
}
|
repositoryService.saveModel(model);
return restResponseFactory.createModelResponse(model);
}
@ApiOperation(value = "Delete a model", tags = { "Models" }, code = 204)
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Indicates the model was found and has been deleted. Response-body is intentionally empty."),
@ApiResponse(code = 404, message = "Indicates the requested model was not found.")
})
@DeleteMapping("/repository/models/{modelId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteModel(@ApiParam(name = "modelId") @PathVariable String modelId) {
Model model = getModelFromRequest(modelId);
repositoryService.deleteModel(model.getId());
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ModelResource.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Optional<JsonRequestProductTaxCategoryUpsert> getProductTaxCategoryUpsertRequest(@NonNull final ProductRow productRow)
{
if (productRow.getTaxRate() == null)
{
return Optional.empty();
}
final JsonRequestProductTaxCategoryUpsert request = new JsonRequestProductTaxCategoryUpsert();
request.setTaxCategory(getTaxCategory(productRow.getTaxRate()));
request.setCountryCode(DEFAULT_COUNTRY_CODE);
request.setValidFrom(Instant.now().minus(365, ChronoUnit.DAYS));
request.setActive(true);
return Optional.of(request);
}
@NonNull
public Optional<JsonRequestUOMConversionUpsert> getUOMConversionUpsertRequest(@NonNull final ProductRow productRow)
{
if (productRow.getQty() == null)
{
return Optional.empty();
}
final String toUomCode = UOMCodeEnum.getX12DE355CodeByPCMCode(productRow.getUomCode())
.orElse(productRow.getUomCode());
if (DEFAULT_UOM_X12DE355_CODE.equals(toUomCode))
{
return Optional.empty();
}
final JsonRequestUOMConversionUpsert request = new JsonRequestUOMConversionUpsert();
request.setFromUomCode(DEFAULT_UOM_X12DE355_CODE);
request.setToUomCode(toUomCode);
request.setFromToMultiplier(productRow.getQty());
return Optional.of(request);
}
@NonNull
private String getTaxCategory(@NonNull final BigDecimal taxRate)
{
return taxCategory2TaxRates
.entrySet()
|
.stream()
.filter(entry -> entry.getValue().stream().anyMatch(rate -> rate.compareTo(taxRate) == 0))
.map(Map.Entry::getKey)
.findFirst()
.orElseThrow(() -> new RuntimeException("No Tax Category found for Tax Rate = " + taxRate));
}
@NonNull
private static ImmutableMap<String, List<BigDecimal>> getTaxCategoryMappingRules(@NonNull final JsonExternalSystemRequest externalSystemRequest)
{
final String taxCategoryMappings = externalSystemRequest.getParameters().get(ExternalSystemConstants.PARAM_TAX_CATEGORY_MAPPINGS);
if (Check.isBlank(taxCategoryMappings))
{
return ImmutableMap.of();
}
final ObjectMapper mapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
try
{
return mapper.readValue(taxCategoryMappings, JsonTaxCategoryMappings.class)
.getJsonTaxCategoryMappingList()
.stream()
.collect(ImmutableMap.toImmutableMap(JsonTaxCategoryMapping::getTaxCategory, JsonTaxCategoryMapping::getTaxRates));
}
catch (final JsonProcessingException e)
{
throw new RuntimeException(e);
}
}
private static boolean hasMissingFields(@NonNull final ProductRow productRow)
{
return Check.isBlank(productRow.getProductIdentifier())
|| Check.isBlank(productRow.getName())
|| Check.isBlank(productRow.getValue());
}
@NonNull
private static JsonRequestProductUpsert wrapUpsertItem(@NonNull final JsonRequestProductUpsertItem upsertItem)
{
return JsonRequestProductUpsert.builder()
.syncAdvise(SyncAdvise.CREATE_OR_MERGE)
.requestItems(ImmutableList.of(upsertItem))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\product\ProductUpsertProcessor.java
| 2
|
请完成以下Java代码
|
public String getRegnId() {
return regnId;
}
/**
* Sets the value of the regnId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRegnId(String value) {
this.regnId = value;
}
/**
* Gets the value of the taxTp property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTaxTp() {
return taxTp;
}
/**
* Sets the value of the taxTp property.
*
* @param value
* allowed object is
* {@link String }
|
*
*/
public void setTaxTp(String value) {
this.taxTp = value;
}
/**
* Gets the value of the authstn property.
*
* @return
* possible object is
* {@link TaxAuthorisation1 }
*
*/
public TaxAuthorisation1 getAuthstn() {
return authstn;
}
/**
* Sets the value of the authstn property.
*
* @param value
* allowed object is
* {@link TaxAuthorisation1 }
*
*/
public void setAuthstn(TaxAuthorisation1 value) {
this.authstn = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TaxParty2.java
| 1
|
请完成以下Java代码
|
protected long calculateIdleTime() {
if (idleLevel <= 0) {
return 0;
} else if (idleLevel >= maxIdleLevel) {
return maxIdleWaitTime;
}
else {
return (long) (baseIdleWaitTime * Math.pow(idleIncreaseFactor, idleLevel - 1));
}
}
protected long calculateBackoffTime() {
long backoffTime = 0;
if (backoffLevel <= 0) {
backoffTime = 0;
} else if (backoffLevel >= maxBackoffLevel) {
backoffTime = maxBackoffWaitTime;
}
else {
backoffTime = (long) (baseBackoffWaitTime * Math.pow(backoffIncreaseFactor, backoffLevel - 1));
}
if (applyJitter) {
// add a bounded random jitter to avoid multiple job acquisitions getting exactly the same
// polling interval
backoffTime += Math.random() * (backoffTime / 2);
}
|
return backoffTime;
}
@Override
public int getNumJobsToAcquire(String processEngine) {
Integer numJobsToAcquire = jobsToAcquire.get(processEngine);
if (numJobsToAcquire != null) {
return numJobsToAcquire;
}
else {
return baseNumJobsToAcquire;
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\BackoffJobAcquisitionStrategy.java
| 1
|
请完成以下Java代码
|
public class SetDecisionTableCategoryCmd implements Command<Void> {
protected String decisionTableId;
protected String category;
public SetDecisionTableCategoryCmd(String decisionTableId, String category) {
this.decisionTableId = decisionTableId;
this.category = category;
}
@Override
public Void execute(CommandContext commandContext) {
if (decisionTableId == null) {
throw new FlowableIllegalArgumentException("Decision table id is null");
}
DecisionEntity decisionTable = CommandContextUtil.getDecisionEntityManager(commandContext).findById(decisionTableId);
if (decisionTable == null) {
throw new FlowableObjectNotFoundException("No decision table found for id = '" + decisionTableId + "'");
}
// Update category
decisionTable.setCategory(category);
// Remove process definition from cache, it will be refetch later
DeploymentCache<DecisionCacheEntry> decisionTableCache = CommandContextUtil.getDmnEngineConfiguration().getDefinitionCache();
if (decisionTableCache != null) {
decisionTableCache.remove(decisionTableId);
}
CommandContextUtil.getDecisionEntityManager(commandContext).update(decisionTable);
return null;
}
|
public String getDecisionTableId() {
return decisionTableId;
}
public void setDecisionTableId(String decisionTableId) {
this.decisionTableId = decisionTableId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\cmd\SetDecisionTableCategoryCmd.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SpringbootMongodbApplication implements CommandLineRunner {
@Autowired
private CustomerRepository repository;
public static void main(String[] args) {
SpringApplication.run(SpringbootMongodbApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
repository.deleteAll();
// save a couple of customers
repository.save(new Customer("Alice", "Smith"));
repository.save(new Customer("Bob", "Smith"));
// fetch all customers
System.out.println("Customers found with findAll():");
System.out.println("-------------------------------");
for (Customer customer : repository.findAll()) {
System.out.println(customer);
}
System.out.println();
|
// fetch an individual customer
System.out.println("Customer found with findByFirstName('Alice'):");
System.out.println("--------------------------------");
System.out.println(repository.findByFirstName("Alice"));
System.out.println("Customers found with findByLastName('Smith'):");
System.out.println("--------------------------------");
for (Customer customer : repository.findByLastName("Smith")) {
System.out.println(customer);
}
}
/**
* Customers found with findAll():
-------------------------------
Customer[id=58f880f589ffb696b8a6077e, firstName='Alice', lastName='Smith']
Customer[id=58f880f589ffb696b8a6077f, firstName='Bob', lastName='Smith']
Customer found with findByFirstName('Alice'):
--------------------------------
Customer[id=58f880f589ffb696b8a6077e, firstName='Alice', lastName='Smith']
Customers found with findByLastName('Smith'):
--------------------------------
Customer[id=58f880f589ffb696b8a6077e, firstName='Alice', lastName='Smith']
Customer[id=58f880f589ffb696b8a6077f, firstName='Bob', lastName='Smith']
*/
}
|
repos\SpringBootLearning-master\springboot-mongodb\src\main\java\com\forezp\SpringbootMongodbApplication.java
| 2
|
请完成以下Java代码
|
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Remote Client.
@param Remote_Client_ID
Remote Client to be used to replicate / synchronize data with.
*/
public void setRemote_Client_ID (int Remote_Client_ID)
{
if (Remote_Client_ID < 1)
set_ValueNoCheck (COLUMNNAME_Remote_Client_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Remote_Client_ID, Integer.valueOf(Remote_Client_ID));
}
/** Get Remote Client.
@return Remote Client to be used to replicate / synchronize data with.
*/
public int getRemote_Client_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Remote_Client_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Remote Organization.
@param Remote_Org_ID
Remote Organization to be used to replicate / synchronize data with.
*/
public void setRemote_Org_ID (int Remote_Org_ID)
|
{
if (Remote_Org_ID < 1)
set_ValueNoCheck (COLUMNNAME_Remote_Org_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Remote_Org_ID, Integer.valueOf(Remote_Org_ID));
}
/** Get Remote Organization.
@return Remote Organization to be used to replicate / synchronize data with.
*/
public int getRemote_Org_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Remote_Org_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Suffix.
@param Suffix
Suffix after the number
*/
public void setSuffix (String Suffix)
{
set_Value (COLUMNNAME_Suffix, Suffix);
}
/** Get Suffix.
@return Suffix after the number
*/
public String getSuffix ()
{
return (String)get_Value(COLUMNNAME_Suffix);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication.java
| 1
|
请完成以下Java代码
|
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/**
* RuleType AD_Reference_ID=53235
* Reference name: AD_Rule_RuleType
*/
public static final int RULETYPE_AD_Reference_ID=53235;
/** AspectOrientProgram = A */
public static final String RULETYPE_AspectOrientProgram = "A";
/** JSR223ScriptingAPIs = S */
public static final String RULETYPE_JSR223ScriptingAPIs = "S";
/** JSR94RuleEngineAPI = R */
public static final String RULETYPE_JSR94RuleEngineAPI = "R";
/** SQL = Q */
public static final String RULETYPE_SQL = "Q";
/** Set Rule Type.
@param RuleType Rule Type */
@Override
public void setRuleType (java.lang.String RuleType)
{
set_Value (COLUMNNAME_RuleType, RuleType);
}
/** Get Rule Type.
@return Rule Type */
@Override
public java.lang.String getRuleType ()
{
return (java.lang.String)get_Value(COLUMNNAME_RuleType);
}
/** Set Skript.
@param Script
Dynamic Java Language Script to calculate result
|
*/
@Override
public void setScript (java.lang.String Script)
{
set_Value (COLUMNNAME_Script, Script);
}
/** Get Skript.
@return Dynamic Java Language Script to calculate result
*/
@Override
public java.lang.String getScript ()
{
return (java.lang.String)get_Value(COLUMNNAME_Script);
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Rule.java
| 1
|
请完成以下Java代码
|
public class TypSondertag {
@XmlElement(name = "Bestellfenster")
protected List<SondertagBestellfenster> bestellfenster;
@XmlAttribute(name = "Datum", required = true)
@XmlSchemaType(name = "date")
protected XMLGregorianCalendar datum;
/**
* Gets the value of the bestellfenster 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 bestellfenster property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getBestellfenster().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SondertagBestellfenster }
*
*
*/
public List<SondertagBestellfenster> getBestellfenster() {
if (bestellfenster == null) {
bestellfenster = new ArrayList<SondertagBestellfenster>();
}
return this.bestellfenster;
|
}
/**
* Gets the value of the datum property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDatum() {
return datum;
}
/**
* Sets the value of the datum property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDatum(XMLGregorianCalendar value) {
this.datum = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\TypSondertag.java
| 1
|
请完成以下Java代码
|
public class ChildCaseInstanceStateChangeCallback implements RuntimeInstanceStateChangeCallback {
@Override
public void stateChanged(CallbackData callbackData) {
/*
* The child case instance has the plan item instance id as callback id stored.
* When the child case instance is finished, the plan item of the parent case
* needs to be triggered.
*/
if (CaseInstanceState.COMPLETED.equals(callbackData.getNewState())
|| CaseInstanceState.TERMINATED.equals(callbackData.getNewState())) {
CommandContext commandContext = CommandContextUtil.getCommandContext();
PlanItemInstanceEntity planItemInstanceEntity = CommandContextUtil.getPlanItemInstanceEntityManager(commandContext)
.findById(callbackData.getCallbackId());
if (planItemInstanceEntity != null) {
if (CaseInstanceState.COMPLETED.equals(callbackData.getNewState())) {
CommandContextUtil.getAgenda(commandContext).planTriggerPlanItemInstanceOperation(planItemInstanceEntity);
} else if (CaseInstanceState.TERMINATED.equals(callbackData.getNewState())) {
if (callbackData.getAdditionalData() != null && callbackData.getAdditionalData().containsKey(CallbackConstants.MANUAL_TERMINATION)) {
boolean manualTermination = (Boolean) callbackData.getAdditionalData().get(CallbackConstants.MANUAL_TERMINATION);
if (manualTermination) {
// For a manual termination, the state is simply changed and no additional logic (e.g. out parameter mapping) needs to be done.
CommandContextUtil.getAgenda(commandContext).planTerminatePlanItemInstanceOperation(planItemInstanceEntity,
(String) callbackData.getAdditionalData().get(CallbackConstants.EXIT_TYPE),
(String) callbackData.getAdditionalData().get(CallbackConstants.EXIT_EVENT_TYPE));
} else {
// a termination through an exit sentry needs to go beyond than just change the state
|
CommandContextUtil.getAgenda(commandContext).planExitPlanItemInstanceOperation(planItemInstanceEntity,
(String) callbackData.getAdditionalData().get(CallbackConstants.EXIT_CRITERION_ID),
(String) callbackData.getAdditionalData().get(CallbackConstants.EXIT_TYPE),
(String) callbackData.getAdditionalData().get(CallbackConstants.EXIT_EVENT_TYPE));
}
}
}
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\callback\ChildCaseInstanceStateChangeCallback.java
| 1
|
请完成以下Java代码
|
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(this.authenticationManager);
endpoints.tokenStore(tokenStore());
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')");
oauthServer.checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("normal-app")
.authorizedGrantTypes("authorization_code", "implicit")
.authorities("ROLE_CLIENT")
.scopes("read", "write")
.resourceIds(resourceId)
.accessTokenValiditySeconds(accessTokenValiditySeconds)
.and()
.withClient("trusted-app")
.authorizedGrantTypes("client_credentials", "password")
.authorities("ROLE_TRUSTED_CLIENT")
|
.scopes("read", "write")
.resourceIds(resourceId)
.accessTokenValiditySeconds(accessTokenValiditySeconds)
.secret("secret");
}
/**
* token store
*
* @return
*/
@Bean
public TokenStore tokenStore() {
return new RedisTokenStore(redisConnectionFactory);
}
}
|
repos\spring-boot-quick-master\quick-oauth2\quick-oauth2-server\src\main\java\com\quick\auth\server\security\AuthorizationServerConfiguration.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return "MJournal["
+ get_ID() + "," + getDescription()
+ ",DR=" + getTotalDr()
+ ",CR=" + getTotalCr()
+ "]";
} // toString
/**
* Get Document Info
*
* @return document info (untranslated)
*/
@Override
public String getDocumentInfo()
{
MDocType dt = MDocType.get(getCtx(), getC_DocType_ID());
return dt.getName() + " " + getDocumentNo();
} // getDocumentInfo
/**
* Create PDF
*
* @return File or null
*/
@Override
public File createPDF()
{
return null;
}
/**
* Get Process Message
*
* @return clear text error message
*/
@Override
public String getProcessMsg()
{
return m_processMsg;
} // getProcessMsg
/**
* Get Document Owner (Responsible)
*
* @return AD_User_ID (Created)
*/
@Override
public int getDoc_User_ID()
{
return getCreatedBy();
} // getDoc_User_ID
/**
* Get Document Approval Amount
*
* @return DR amount
*/
@Override
public BigDecimal getApprovalAmt()
{
return getTotalDr();
} // getApprovalAmt
|
/**
* Document Status is Complete or Closed
*
* @return true if CO, CL or RE
*/
@Deprecated
public boolean isComplete()
{
return Services.get(IGLJournalBL.class).isComplete(this);
} // isComplete
// metas: cg: 02476
private static void setAmtPrecision(final I_GL_Journal journal)
{
final AcctSchemaId acctSchemaId = AcctSchemaId.ofRepoIdOrNull(journal.getC_AcctSchema_ID());
if (acctSchemaId == null)
{
return;
}
final AcctSchema as = Services.get(IAcctSchemaDAO.class).getById(acctSchemaId);
final CurrencyPrecision precision = as.getStandardPrecision();
final BigDecimal controlAmt = precision.roundIfNeeded(journal.getControlAmt());
journal.setControlAmt(controlAmt);
}
} // MJournal
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\model\MJournal.java
| 1
|
请完成以下Java代码
|
public static IdmEngine getDefaultIdmEngine() {
return getIdmEngine(NAME_DEFAULT);
}
/**
* obtain a idm engine by name.
*
* @param idmEngineName is the name of the idm engine or null for the default idm engine.
*/
public static IdmEngine getIdmEngine(String idmEngineName) {
if (!isInitialized()) {
init();
}
return idmEngines.get(idmEngineName);
}
/**
* retries to initialize a idm engine that previously failed.
*/
public static EngineInfo retry(String resourceUrl) {
LOGGER.debug("retying initializing of resource {}", resourceUrl);
try {
return initIdmEngineFromResource(new URL(resourceUrl));
} catch (MalformedURLException e) {
throw new FlowableException("invalid url: " + resourceUrl, e);
}
}
/**
* provides access to idm engine to application clients in a managed server environment.
*/
public static Map<String, IdmEngine> getIdmEngines() {
return idmEngines;
}
/**
* closes all idm engines. This method should be called when the server shuts down.
*/
public static synchronized void destroy() {
if (isInitialized()) {
|
Map<String, IdmEngine> engines = new HashMap<>(idmEngines);
idmEngines = new HashMap<>();
for (String idmEngineName : engines.keySet()) {
IdmEngine idmEngine = engines.get(idmEngineName);
try {
idmEngine.close();
} catch (Exception e) {
LOGGER.error("exception while closing {}", (idmEngineName == null ? "the default idm engine" : "idm engine " + idmEngineName), e);
}
}
idmEngineInfosByName.clear();
idmEngineInfosByResourceUrl.clear();
idmEngineInfos.clear();
setInitialized(false);
}
}
public static boolean isInitialized() {
return isInitialized;
}
public static void setInitialized(boolean isInitialized) {
IdmEngines.isInitialized = isInitialized;
}
}
|
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\IdmEngines.java
| 1
|
请完成以下Java代码
|
public void performanceMonitoringServiceSaveEx(@NonNull final Runnable runnable)
{
final PerformanceMonitoringService performanceMonitoringService = performanceMonitoringService();
performanceMonitoringService.monitor(runnable, PM_METADATA_SAVE_EX);
}
public boolean performanceMonitoringServiceLoad(@NonNull final Callable<Boolean> callable)
{
final PerformanceMonitoringService performanceMonitoringService = performanceMonitoringService();
return performanceMonitoringService.monitor(callable, PM_METADATA_LOAD);
}
private PerformanceMonitoringService performanceMonitoringService()
{
PerformanceMonitoringService performanceMonitoringService = _performanceMonitoringService;
if (performanceMonitoringService == null || performanceMonitoringService instanceof NoopPerformanceMonitoringService)
{
performanceMonitoringService = _performanceMonitoringService = SpringContextHolder.instance.getBeanOr(
PerformanceMonitoringService.class,
NoopPerformanceMonitoringService.INSTANCE);
}
return performanceMonitoringService;
}
//
//
//
public boolean isDeveloperMode()
{
return developerModeBL().isEnabled();
}
public boolean getSysConfigBooleanValue(final String sysConfigName, final boolean defaultValue, final int ad_client_id, final int ad_org_id)
{
return sysConfigBL().getBooleanValue(sysConfigName, defaultValue, ad_client_id, ad_org_id);
}
public boolean getSysConfigBooleanValue(final String sysConfigName, final boolean defaultValue)
{
return sysConfigBL().getBooleanValue(sysConfigName, defaultValue);
}
public boolean isChangeLogEnabled()
{
return sessionBL().isChangeLogEnabled();
}
public String getInsertChangeLogType(final int adClientId)
|
{
return sysConfigBL().getValue("SYSTEM_INSERT_CHANGELOG", "N", adClientId);
}
public void saveChangeLogs(final List<ChangeLogRecord> changeLogRecords)
{
sessionDAO().saveChangeLogs(changeLogRecords);
}
public void logMigration(final MFSession session, final PO po, final POInfo poInfo, final String actionType)
{
migrationLogger().logMigration(session, po, poInfo, actionType);
}
public void fireDocumentNoChange(final PO po, final String value)
{
documentNoBL().fireDocumentNoChange(po, value); // task 09776
}
public ADRefList getRefListById(@NonNull final ReferenceId referenceId)
{
return adReferenceService().getRefListById(referenceId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\POServicesFacade.java
| 1
|
请完成以下Java代码
|
public static TableRecordReference createTableRecordReferenceFromShipmentScheduleId(final ShipmentScheduleId shipmentScheduleId)
{
return TableRecordReference.of(I_M_Packageable_V.Table_Name, shipmentScheduleId);
}
@Builder
private PackageableRow(
@NonNull final ShipmentScheduleId shipmentScheduleId,
@NonNull final Optional<OrderLineId> salesOrderLineId,
@NonNull final ViewId viewId,
final LookupValue order,
final LookupValue product,
@NonNull final Quantity qtyOrdered,
final Quantity qtyPicked,
final LookupValue bpartner,
final ZonedDateTime preparationDate)
{
this.viewId = viewId;
this.id = createRowIdFromShipmentScheduleId(shipmentScheduleId);
this.documentPath = DocumentPath.rootDocumentPath(PickingConstants.WINDOWID_PickingView, id);
this.order = order;
this.product = product;
this.qtyOrdered = qtyOrdered;
this.qtyPicked = qtyPicked;
this.picked = qtyPicked != null && qtyPicked.compareTo(qtyOrdered) >= 0;
this.bpartner = bpartner;
this.preparationDate = preparationDate;
this.shipmentScheduleId = shipmentScheduleId;
this.salesOrderLineId = salesOrderLineId;
// create the included view's ID
// note that despite all our packageable-rows have the same picking slots, the IDs still need to be individual per-row,
// because we need to notify the picking slot view of this packageable-rows is selected at a given point in time
this.includedViewId = PickingSlotViewsIndexStorage.createViewId(viewId, id);
}
@Override
public DocumentId getId()
{
return id;
}
@Override
public IViewRowType getType()
{
return DefaultRowType.Row;
}
@Override
public boolean isProcessed()
{
return false;
}
@Override
public DocumentPath getDocumentPath()
{
return documentPath;
}
public TableRecordReference getTableRecordReference()
{
return createTableRecordReferenceFromShipmentScheduleId(getShipmentScheduleId());
}
@Override
public ImmutableSet<String> getFieldNames()
{
return values.getFieldNames();
|
}
@Override
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues()
{
return values.get(this);
}
@Override
public List<? extends IViewRow> getIncludedRows()
{
return ImmutableList.of();
}
@Override
public boolean hasAttributes()
{
return false;
}
@Override
public IViewRowAttributes getAttributes() throws EntityNotFoundException
{
throw new EntityNotFoundException("Row does not support attributes");
}
@Override
public ViewId getIncludedViewId()
{
return includedViewId;
}
public ShipmentScheduleId getShipmentScheduleId()
{
return shipmentScheduleId;
}
public Optional<OrderLineId> getSalesOrderLineId()
{
return salesOrderLineId;
}
public ProductId getProductId()
{
return product != null ? ProductId.ofRepoIdOrNull(product.getIdAsInt()) : null;
}
public Quantity getQtyOrderedWithoutPicked()
{
return qtyOrdered.subtract(qtyPicked).toZeroIfNegative();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\PackageableRow.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static PPOrderCandidateId extractPPOrderCandidateId(final I_PP_OrderCandidate_PP_Order record)
{
return PPOrderCandidateId.ofRepoId(record.getPP_Order_Candidate_ID());
}
@NotNull
private static PPOrderCandidateId extractPPOrderCandidateId(final I_PP_Order_Candidate record)
{
return PPOrderCandidateId.ofRepoId(record.getPP_Order_Candidate_ID());
}
private static Quantity extractQtyEntered(@NonNull final I_PP_OrderCandidate_PP_Order record)
{
return Quantitys.of(record.getQtyEntered(), UomId.ofRepoId(record.getC_UOM_ID()));
}
private static Quantity extractQtyEntered(@NonNull final I_PP_Order_Candidate record)
{
return Quantitys.of(record.getQtyEntered(), UomId.ofRepoId(record.getC_UOM_ID()));
|
}
//
//
//
@Value
@Builder
public static class PPOrderCandidateUpdateFlagsRequest
{
@NonNull PPOrderCandidateId ppOrderCandidateId;
boolean forceMarkProcessed;
boolean forceClose;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\service\PPOrderCandidateService.java
| 2
|
请完成以下Java代码
|
public String getImportType() {
return importType;
}
public void setImportType(String importType) {
this.importType = importType;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getNamespace() {
return namespace;
|
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public Import clone() {
Import clone = new Import();
clone.setValues(this);
return clone;
}
public void setValues(Import otherElement) {
super.setValues(otherElement);
setImportType(otherElement.getImportType());
setLocation(otherElement.getLocation());
setNamespace(otherElement.getNamespace());
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Import.java
| 1
|
请完成以下Java代码
|
public List<EventDefinition> getEventDefinitions() {
return eventDefinitions;
}
public void setEventDefinitions(List<EventDefinition> eventDefinitions) {
this.eventDefinitions = eventDefinitions;
}
public void addEventDefinition(EventDefinition eventDefinition) {
eventDefinitions.add(eventDefinition);
}
public void setValues(Event otherEvent) {
super.setValues(otherEvent);
|
eventDefinitions = new ArrayList<EventDefinition>();
if (otherEvent.getEventDefinitions() != null && !otherEvent.getEventDefinitions().isEmpty()) {
for (EventDefinition eventDef : otherEvent.getEventDefinitions()) {
eventDefinitions.add(eventDef.clone());
}
}
}
public boolean isLinkEvent() {
if (this.getEventDefinitions().size() == 1) {
return this.getEventDefinitions().getFirst() instanceof LinkEventDefinition;
}
return false;
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Event.java
| 1
|
请完成以下Java代码
|
public void parseParams() {
String disabled = initParams.get(DISABLED_PARAM);
if (ServletFilterUtil.isEmpty(disabled)) {
setDisabled(false);
} else {
setDisabled(Boolean.parseBoolean(disabled));
}
String value = initParams.get(VALUE_PARAM);
if (!ServletFilterUtil.isEmpty(value)) {
value = normalizeString(value);
setValue(value);
} else {
setValue(HEADER_DEFAULT_VALUE);
}
}
protected String normalizeString(String value) {
|
return value
.trim()
.replaceAll("\\s+", " "); // replaces [\t\n\x0B\f\r]
}
@Override
public String getHeaderName() {
return HEADER_NAME;
}
@Override
public String getHeaderValue(final ServletContext servletContext) {
final String nonce = generateNonce();
servletContext.setAttribute(ATTR_CSP_FILTER_NONCE, nonce);
return value.replaceAll("\\" + HEADER_NONCE_PLACEHOLDER, String.format("'nonce-%s'", nonce));
}
protected String generateNonce() {
final byte[] bytes = new byte[20];
ThreadLocalRandom.current().nextBytes(bytes);
return ENCODER.encodeToString(bytes);
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\headersec\provider\impl\ContentSecurityPolicyProvider.java
| 1
|
请完成以下Java代码
|
public Salary deepCopy(Salary value) {
if (Objects.isNull(value))
return null;
Salary newSal = new Salary();
newSal.setAmount(value.getAmount());
newSal.setCurrency(value.getCurrency());
return newSal;
}
@Override
public boolean isMutable() {
return true;
}
@Override
public Serializable disassemble(Salary value) {
return deepCopy(value);
|
}
@Override
public Salary assemble(Serializable cached, Object owner) {
return deepCopy((Salary) cached);
}
@Override
public Salary replace(Salary detached, Salary managed, Object owner) {
return detached;
}
@Override
public void setParameterValues(Properties parameters) {
this.localCurrency = parameters.getProperty("currency");
}
}
|
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\SalaryType.java
| 1
|
请完成以下Java代码
|
public CostAmount getCreateCosts(@NonNull final AcctSchema as)
{
final CostSegmentAndElement costSegmentAndElement = costRevaluationLine.getCostSegmentAndElement();
if (!AcctSchemaId.equals(costSegmentAndElement.getAcctSchemaId(), as.getId()))
{
throw new AdempiereException("Accounting schema not matching: " + costRevaluationLine + ", " + as);
}
if (isReversalLine())
{
throw new UnsupportedOperationException(); // TODO impl
// return services.createReversalCostDetails(CostDetailReverseRequest.builder()
// .acctSchemaId(as.getId())
// .reversalDocumentRef(CostingDocumentRef.ofCostRevaluationLineId(get_ID()))
// .initialDocumentRef(CostingDocumentRef.ofCostRevaluationLineId(getReversalLine_ID()))
// .date(getDateAcctAsInstant())
// .build())
// .getTotalAmountToPost(as);
}
|
else
{
return services.createCostDetail(
CostDetailCreateRequest.builder()
.acctSchemaId(costSegmentAndElement.getAcctSchemaId())
.clientId(costSegmentAndElement.getClientId())
.orgId(costSegmentAndElement.getOrgId())
.productId(costSegmentAndElement.getProductId())
.attributeSetInstanceId(costSegmentAndElement.getAttributeSetInstanceId())
.documentRef(CostingDocumentRef.ofCostRevaluationLineId(costRevaluationLine.getId()))
.qty(costRevaluationLine.getCurrentQty().toZero())
.amt(costRevaluationLine.getDeltaAmountToBook())
.explicitCostPrice(costRevaluationLine.getNewCostPrice())
.date(getDateAcctAsInstant())
.build())
.getMainAmountToPost(as);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine_CostRevaluation.java
| 1
|
请完成以下Java代码
|
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代码
|
class DocumentAttachmentEntry implements IDocumentAttachmentEntry
{
/* package */
static DocumentAttachmentEntry of(@NonNull final DocumentId id, @NonNull final AttachmentEntry entry)
{
return new DocumentAttachmentEntry(id, entry);
}
private final DocumentId id;
private final AttachmentEntry entry;
private DocumentAttachmentEntry(
@NonNull final DocumentId id,
@NonNull final AttachmentEntry entry)
{
this.id = id;
this.entry = entry;
}
@Override
public DocumentId getId()
{
return id;
}
@Override
public AttachmentEntryType getType()
{
return entry.getType();
}
@Override
public String getFilename()
{
return entry.getFilename();
}
@Override
public byte[] getData()
|
{
final AttachmentEntryService attachmentEntryService = Adempiere.getBean(AttachmentEntryService.class);
return attachmentEntryService.retrieveData(entry.getId());
}
@Override
public String getContentType()
{
return entry.getMimeType();
}
@Override
public URI getUrl()
{
return entry.getUrl();
}
@Override
public Instant getCreated()
{
return entry.getCreatedUpdatedInfo().getCreated().toInstant();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attachments\DocumentAttachmentEntry.java
| 1
|
请完成以下Java代码
|
static void setZeroesInRows(int[][] matrix, int rows, int cols) {
for (int i = 1; i < rows; i++) {
if (matrix[i][0] == 0) {
for (int j = 1; j < cols; j++) {
matrix[i][j] = 0;
}
}
}
}
static void setZeroesInCols(int[][] matrix, int rows, int cols) {
for (int j = 1; j < cols; j++) {
if (matrix[0][j] == 0) {
for (int i = 1; i < rows; i++) {
matrix[i][j] = 0;
}
}
}
}
static void setZeroesInFirstRow(int[][] matrix, int cols) {
for (int j = 0; j < cols; j++) {
matrix[0][j] = 0;
}
}
static void setZeroesInFirstCol(int[][] matrix, int rows) {
for (int i = 0; i < rows; i++) {
matrix[i][0] = 0;
}
}
static void setZeroesByOptimalApproach(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
boolean firstRowZero = hasZeroInFirstRow(matrix, cols);
|
boolean firstColZero = hasZeroInFirstCol(matrix, rows);
markZeroesInMatrix(matrix, rows, cols);
setZeroesInRows(matrix, rows, cols);
setZeroesInCols(matrix, rows, cols);
if (firstRowZero) {
setZeroesInFirstRow(matrix, cols);
}
if (firstColZero) {
setZeroesInFirstCol(matrix, rows);
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\matrixtozero\SetMatrixToZero.java
| 1
|
请完成以下Java代码
|
protected Cache getCache() {
return Hal.getInstance().getHalRelationCache(getHalResourceClass());
}
/**
* Returns a list with all resources which are cached.
*
* @param linkedIds the ids to resolve
* @param cache the cache to use
* @param notCachedLinkedIds a list with ids which are not found in the cache
* @return the cached resources
*/
protected List<HalResource<?>> resolveCachedLinks(String[] linkedIds, Cache cache, List<String> notCachedLinkedIds) {
ArrayList<HalResource<?>> resolvedResources = new ArrayList<HalResource<?>>();
for (String linkedId : linkedIds) {
HalResource<?> resource = (HalResource<?>) cache.get(linkedId);
if (resource != null) {
resolvedResources.add(resource);
}
else {
notCachedLinkedIds.add(linkedId);
}
}
return resolvedResources;
}
/**
* Put a resource into the cache.
*/
protected void putIntoCache(List<HalResource<?>> notCachedResources) {
Cache cache = getCache();
|
for (HalResource<?> notCachedResource : notCachedResources) {
cache.put(getResourceId(notCachedResource), notCachedResource);
}
}
/**
* @return the class of the entity which is resolved
*/
protected abstract Class<?> getHalResourceClass();
/**
* @return a comparator for this HAL resource if not overridden sorting is skipped
*/
protected Comparator<HalResource<?>> getResourceComparator() {
return null;
}
/**
* @return the resolved resources which are currently not cached
*/
protected abstract List<HalResource<?>> resolveNotCachedLinks(String[] linkedIds, ProcessEngine processEngine);
/**
* @return the id which identifies a resource in the cache
*/
protected abstract String getResourceId(HalResource<?> resource);
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\cache\HalCachingLinkResolver.java
| 1
|
请完成以下Java代码
|
public Constraints build()
{
return new Constraints(this);
}
private ImmutableMap<Class<? extends Constraint>, Constraint> getConstraints()
{
return ImmutableMap.copyOf(constraints);
}
public Builder addConstraint(final Constraint constraint)
{
Check.assumeNotNull(constraint, "constraint not null");
constraints.put(constraint.getClass(), constraint);
return this;
}
|
public Builder addConstraintIfNotEquals(final Constraint constraint, final Constraint constraintToExclude)
{
Check.assumeNotNull(constraint, "constraint not null");
Check.assumeNotNull(constraintToExclude, "constraintToExclude not null");
if (constraint.equals(constraintToExclude))
{
return this;
}
constraints.put(constraint.getClass(), constraint);
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\Constraints.java
| 1
|
请完成以下Java代码
|
class ArrayFilterer<T> implements Filterer<T> {
protected static final Log logger = LogFactory.getLog(ArrayFilterer.class);
private final Set<T> removeList;
private final T[] list;
ArrayFilterer(T[] list) {
this.list = list;
// Collect the removed objects to a HashSet so that
// it is fast to lookup them when a filtered array
// is constructed.
this.removeList = new HashSet<>();
}
@Override
@SuppressWarnings("unchecked")
public T[] getFilteredObject() {
// Recreate an array of same type and filter the removed objects.
int originalSize = this.list.length;
int sizeOfResultingList = originalSize - this.removeList.size();
T[] filtered = (T[]) Array.newInstance(this.list.getClass().getComponentType(), sizeOfResultingList);
for (int i = 0, j = 0; i < this.list.length; i++) {
T object = this.list[i];
if (!this.removeList.contains(object)) {
filtered[j] = object;
j++;
}
}
logger.debug(LogMessage.of(() -> "Original array contained " + originalSize + " elements; now contains "
+ sizeOfResultingList + " elements"));
return filtered;
}
@Override
public Iterator<T> iterator() {
|
return new ArrayFiltererIterator();
}
@Override
public void remove(T object) {
this.removeList.add(object);
}
/**
* Iterator for {@link ArrayFilterer} elements.
*/
private class ArrayFiltererIterator implements Iterator<T> {
private int index = 0;
@Override
public boolean hasNext() {
return this.index < ArrayFilterer.this.list.length;
}
@Override
public T next() {
if (hasNext()) {
return ArrayFilterer.this.list[this.index++];
}
throw new NoSuchElementException();
}
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\acls\afterinvocation\ArrayFilterer.java
| 1
|
请完成以下Java代码
|
public Set<String> getVariableNames() {
return getVariableNamesLocal();
}
public Set<String> getVariableNamesLocal() {
return wrappedScope.getVariableNamesLocal();
}
public void setVariable(String variableName, Object value) {
setVariableLocal(variableName, value);
}
public void setVariableLocal(String variableName, Object value) {
wrappedScope.setVariableLocal(variableName, value);
}
public void setVariables(Map<String, ? extends Object> variables) {
setVariablesLocal(variables);
}
public void setVariablesLocal(Map<String, ? extends Object> variables) {
wrappedScope.setVariablesLocal(variables);
}
public boolean hasVariables() {
return hasVariablesLocal();
}
public boolean hasVariablesLocal() {
return wrappedScope.hasVariablesLocal();
}
public boolean hasVariable(String variableName) {
return hasVariableLocal(variableName);
}
public boolean hasVariableLocal(String variableName) {
return wrappedScope.hasVariableLocal(variableName);
}
public void removeVariable(String variableName) {
removeVariableLocal(variableName);
|
}
public void removeVariableLocal(String variableName) {
wrappedScope.removeVariableLocal(variableName);
}
public void removeVariables(Collection<String> variableNames) {
removeVariablesLocal(variableNames);
}
public void removeVariablesLocal(Collection<String> variableNames) {
wrappedScope.removeVariablesLocal(variableNames);
}
public void removeVariables() {
removeVariablesLocal();
}
public void removeVariablesLocal() {
wrappedScope.removeVariablesLocal();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\VariableScopeLocalAdapter.java
| 1
|
请完成以下Java代码
|
public void setIsSameLine (String IsSameLine)
{
set_Value (COLUMNNAME_IsSameLine, IsSameLine);
}
/** Get Same Line.
@return Displayed on same line as previous field
*/
public String getIsSameLine ()
{
return (String)get_Value(COLUMNNAME_IsSameLine);
}
/** IsUpdateable AD_Reference_ID=319 */
public static final int ISUPDATEABLE_AD_Reference_ID=319;
/** Yes = Y */
public static final String ISUPDATEABLE_Yes = "Y";
/** No = N */
public static final String ISUPDATEABLE_No = "N";
/** Set Updateable.
@param IsUpdateable
Determines, if the field can be updated
*/
public void setIsUpdateable (String IsUpdateable)
{
set_Value (COLUMNNAME_IsUpdateable, IsUpdateable);
}
/** Get Updateable.
@return Determines, if the field can be updated
*/
public String getIsUpdateable ()
{
return (String)get_Value(COLUMNNAME_IsUpdateable);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
|
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Record Sort No.
@param SortNo
Determines in what order the records are displayed
*/
public void setSortNo (int SortNo)
{
set_Value (COLUMNNAME_SortNo, Integer.valueOf(SortNo));
}
/** Get Record Sort No.
@return Determines in what order the records are displayed
*/
public int getSortNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SortNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserDef_Field.java
| 1
|
请完成以下Java代码
|
public @Nullable ConsumerRecords<K, V> intercept(ConsumerRecords<K, V> records, Consumer<K, V> consumer) {
ConsumerRecords<K, V> recordsToIntercept = records;
for (BatchInterceptor<K, V> delegate : this.delegates) {
recordsToIntercept = delegate.intercept(recordsToIntercept, consumer);
if (recordsToIntercept == null) {
break;
}
}
return recordsToIntercept;
}
@Override
public void success(ConsumerRecords<K, V> records, Consumer<K, V> consumer) {
this.delegates.forEach(del -> del.success(records, consumer));
}
@Override
public void failure(ConsumerRecords<K, V> records, Exception exception, Consumer<K, V> consumer) {
this.delegates.forEach(del -> del.failure(records, exception, consumer));
}
@Override
public void setupThreadState(Consumer<?, ?> consumer) {
|
this.delegates.forEach(del -> del.setupThreadState(consumer));
}
@Override
public void clearThreadState(Consumer<?, ?> consumer) {
this.delegates.forEach(del -> del.clearThreadState(consumer));
}
/**
* Add an {@link BatchInterceptor} to delegates.
* @param batchInterceptor the interceptor.
* @since 4.0
*/
public void addBatchInterceptor(BatchInterceptor<K, V> batchInterceptor) {
this.delegates.add(batchInterceptor);
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\CompositeBatchInterceptor.java
| 1
|
请完成以下Java代码
|
public SessionCookieProperties getSessionCookie() {
return sessionCookie;
}
public void setSessionCookie(SessionCookieProperties sessionCookie) {
this.sessionCookie = sessionCookie;
}
public HeaderSecurityProperties getHeaderSecurity() {
return headerSecurity;
}
public void setHeaderSecurity(HeaderSecurityProperties headerSecurity) {
this.headerSecurity = headerSecurity;
}
public AuthenticationProperties getAuth() {
return auth;
}
|
public void setAuth(AuthenticationProperties authentication) {
this.auth = authentication;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("indexRedirectEnabled=" + indexRedirectEnabled)
.add("webjarClasspath='" + webjarClasspath + '\'')
.add("securityConfigFile='" + securityConfigFile + '\'')
.add("webappPath='" + applicationPath + '\'')
.add("csrf='" + csrf + '\'')
.add("headerSecurityProperties='" + headerSecurity + '\'')
.add("sessionCookie='" + sessionCookie + '\'')
.add("auth='" + auth + '\'')
.toString();
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\WebappProperty.java
| 1
|
请完成以下Java代码
|
public void setQtyOrdered (BigDecimal QtyOrdered)
{
set_ValueNoCheck (COLUMNNAME_QtyOrdered, QtyOrdered);
}
/** Get Ordered Quantity.
@return Ordered Quantity
*/
public BigDecimal getQtyOrdered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Reserved Quantity.
@param QtyReserved
Reserved Quantity
*/
public void setQtyReserved (BigDecimal QtyReserved)
{
set_ValueNoCheck (COLUMNNAME_QtyReserved, QtyReserved);
}
/** Get Reserved Quantity.
@return Reserved Quantity
*/
public BigDecimal getQtyReserved ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReserved);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set SKU.
@param SKU
Stock Keeping Unit
*/
public void setSKU (String SKU)
{
set_ValueNoCheck (COLUMNNAME_SKU, SKU);
}
/** Get SKU.
@return Stock Keeping Unit
*/
public String getSKU ()
{
return (String)get_Value(COLUMNNAME_SKU);
}
/** Set Symbol.
@param UOMSymbol
Symbol for a Unit of Measure
*/
public void setUOMSymbol (String UOMSymbol)
{
set_ValueNoCheck (COLUMNNAME_UOMSymbol, UOMSymbol);
}
|
/** Get Symbol.
@return Symbol for a Unit of Measure
*/
public String getUOMSymbol ()
{
return (String)get_Value(COLUMNNAME_UOMSymbol);
}
/** Set UPC/EAN.
@param UPC
Bar Code (Universal Product Code or its superset European Article Number)
*/
public void setUPC (String UPC)
{
set_ValueNoCheck (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
@return Bar Code (Universal Product Code or its superset European Article Number)
*/
public String getUPC ()
{
return (String)get_Value(COLUMNNAME_UPC);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Set Warehouse.
@param WarehouseName
Warehouse Name
*/
public void setWarehouseName (String WarehouseName)
{
set_ValueNoCheck (COLUMNNAME_WarehouseName, WarehouseName);
}
/** Get Warehouse.
@return Warehouse Name
*/
public String getWarehouseName ()
{
return (String)get_Value(COLUMNNAME_WarehouseName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_RV_WarehousePrice.java
| 1
|
请完成以下Java代码
|
private static List<Store> readStores() throws Exception {
var resource = new ClassPathResource("starbucks.csv");
var scanner = new Scanner(resource.getInputStream());
var line = scanner.nextLine();
scanner.close();
// DelimitedLineTokenizer defaults to comma as its delimiter
var tokenizer = new DelimitedLineTokenizer();
tokenizer.setNames(line.split(","));
tokenizer.setStrict(false);
var lineMapper = new DefaultLineMapper<Store>();
lineMapper.setFieldSetMapper(fields -> {
var location = new Point(fields.readDouble("Longitude"), fields.readDouble("Latitude"));
var address = new Address(fields.readString("Street Address"), fields.readString("City"),
fields.readString("Zip"), location);
return new Store(UUID.randomUUID(), fields.readString("Name"), address);
});
var itemReader = new FlatFileItemReader<>(lineMapper);
itemReader.setResource(resource);
|
lineMapper.setLineTokenizer(tokenizer);
itemReader.setLineMapper(lineMapper);
itemReader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy());
itemReader.setLinesToSkip(1);
itemReader.open(new ExecutionContext());
List<Store> stores = new ArrayList<>();
Store store = null;
do {
store = itemReader.read();
if (store != null) {
stores.add(store);
}
} while (store != null);
return stores;
}
}
|
repos\spring-data-examples-main\rest\starbucks\src\main\java\example\springdata\rest\stores\StoreInitializer.java
| 1
|
请完成以下Java代码
|
public class ExecuteSchemaOperationCommand implements Command<Void> {
protected String schemaOperation;
protected TenantInfoHolder tenantInfoHolder;
public ExecuteSchemaOperationCommand(String schemaOperation) {
this.schemaOperation = schemaOperation;
}
public Void execute(CommandContext commandContext) {
if (ProcessEngineConfigurationImpl.DB_SCHEMA_UPDATE_DROP_CREATE.equals(schemaOperation)) {
try {
commandContext.getDbSqlSession().dbSchemaDrop();
} catch (RuntimeException e) {
// ignore
}
}
|
if (
org.activiti.engine.ProcessEngineConfiguration.DB_SCHEMA_UPDATE_CREATE_DROP.equals(schemaOperation) ||
ProcessEngineConfigurationImpl.DB_SCHEMA_UPDATE_DROP_CREATE.equals(schemaOperation) ||
ProcessEngineConfigurationImpl.DB_SCHEMA_UPDATE_CREATE.equals(schemaOperation)
) {
commandContext.getDbSqlSession().dbSchemaCreate();
} else if (org.activiti.engine.ProcessEngineConfiguration.DB_SCHEMA_UPDATE_FALSE.equals(schemaOperation)) {
commandContext.getDbSqlSession().dbSchemaCheckVersion();
} else if (ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE.equals(schemaOperation)) {
commandContext.getDbSqlSession().dbSchemaUpdate();
}
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\multitenant\ExecuteSchemaOperationCommand.java
| 1
|
请完成以下Java代码
|
public final void addAttributeStorageListener(final IAttributeStorageListener listener)
{
Check.assumeNotNull(listener, "listener not null");
if (attributeStorageListeners.contains(listener))
{
// already added
return;
}
attributeStorageListeners.add(listener);
//
// Add listener to current existing storages
for (final IAttributeStorage storage : getExistingAttributeStorages())
{
storage.addListener(listener);
}
}
@Override
public final void removeAttributeStorageListener(final IAttributeStorageListener listener)
{
// guard against null
if (listener == null)
{
return;
}
attributeStorageListeners.remove(listener);
//
// Add listener to current existing storages
for (final IAttributeStorage storage : getExistingAttributeStorages())
{
storage.removeListener(listener);
}
}
/**
* Gets current existing {@link IAttributeStorage}s from cache (if any)
*
* @return cached {@link IAttributeStorage}s
*/
protected abstract Collection<? extends IAttributeStorage> getExistingAttributeStorages();
/**
* Adds current listeners to given {@link IAttributeStorage}.
*
* Use this method after you instantiate a new storage.
*
* @param attributeStorage
*/
protected final void addListenersToAttributeStorage(final IAttributeStorage attributeStorage)
{
//
// Add listeners to our storage
for (final IAttributeStorageListener listener : attributeStorageListeners)
{
attributeStorage.addListener(listener);
}
}
/**
* Removes current listeners from given {@link IAttributeStorage}.
*
|
* @param attributeStorage
*/
protected final void removeListenersFromAttributeStorage(final IAttributeStorage attributeStorage)
{
for (final IAttributeStorageListener listener : attributeStorageListeners)
{
attributeStorage.removeListener(listener);
}
}
@Override
public final IHUAttributesDAO getHUAttributesDAO()
{
Check.assumeNotNull(huAttributesDAO, "huAttributesDAO not null");
return huAttributesDAO;
}
@Override
public final void setHUAttributesDAO(final IHUAttributesDAO huAttributesDAO)
{
this.huAttributesDAO = huAttributesDAO;
}
@Override
public IHUStorageDAO getHUStorageDAO()
{
return getHUStorageFactory().getHUStorageDAO();
}
@Override
public IHUStorageFactory getHUStorageFactory()
{
Check.assumeNotNull(huStorageFactory, "IHUStorageFactory member of AbstractAttributeStorageFactory {} is not null", this);
return huStorageFactory;
}
@Override
public void setHUStorageFactory(final IHUStorageFactory huStorageFactory)
{
this.huStorageFactory = huStorageFactory;
}
@Override
public String toString()
{
final ToStringHelper stringHelper = MoreObjects.toStringHelper(this);
toString(stringHelper);
return stringHelper.toString();
}
protected void toString(final ToStringHelper stringHelper)
{
// nothing on this level
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AbstractAttributeStorageFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Refresh getRefresh() {
return this.refresh;
}
public static class Refresh {
/**
* Whether to discover and query all cluster nodes for obtaining the
* cluster topology. When set to false, only the initial seed nodes are
* used as sources for topology discovery.
*/
private boolean dynamicRefreshSources = true;
/**
* Cluster topology refresh period.
*/
private @Nullable Duration period;
/**
* Whether adaptive topology refreshing using all available refresh
* triggers should be used.
*/
private boolean adaptive;
public boolean isDynamicRefreshSources() {
return this.dynamicRefreshSources;
}
public void setDynamicRefreshSources(boolean dynamicRefreshSources) {
|
this.dynamicRefreshSources = dynamicRefreshSources;
}
public @Nullable Duration getPeriod() {
return this.period;
}
public void setPeriod(@Nullable Duration period) {
this.period = period;
}
public boolean isAdaptive() {
return this.adaptive;
}
public void setAdaptive(boolean adaptive) {
this.adaptive = adaptive;
}
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\DataRedisProperties.java
| 2
|
请完成以下Java代码
|
public String getIsDelivered ()
{
return (String)get_Value(COLUMNNAME_IsDelivered);
}
/** Set Mail Text.
@param MailText
Text used for Mail message
*/
public void setMailText (String MailText)
{
set_Value (COLUMNNAME_MailText, MailText);
}
/** Get Mail Text.
@return Text used for Mail message
*/
public String getMailText ()
{
return (String)get_Value(COLUMNNAME_MailText);
}
/** Set Message ID.
@param MessageID
EMail Message ID
*/
public void setMessageID (String MessageID)
{
set_ValueNoCheck (COLUMNNAME_MessageID, MessageID);
}
/** Get Message ID.
@return EMail Message ID
*/
public String getMessageID ()
{
return (String)get_Value(COLUMNNAME_MessageID);
}
public I_R_MailText getR_MailText() throws RuntimeException
{
return (I_R_MailText)MTable.get(getCtx(), I_R_MailText.Table_Name)
.getPO(getR_MailText_ID(), get_TrxName()); }
/** Set Mail Template.
@param R_MailText_ID
Text templates for mailings
*/
public void setR_MailText_ID (int R_MailText_ID)
{
if (R_MailText_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_MailText_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_MailText_ID, Integer.valueOf(R_MailText_ID));
}
/** Get Mail Template.
@return Text templates for mailings
*/
public int getR_MailText_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_MailText_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Subject.
@param Subject
|
Email Message Subject
*/
public void setSubject (String Subject)
{
set_Value (COLUMNNAME_Subject, Subject);
}
/** Get Subject.
@return Email Message Subject
*/
public String getSubject ()
{
return (String)get_Value(COLUMNNAME_Subject);
}
public I_W_MailMsg getW_MailMsg() throws RuntimeException
{
return (I_W_MailMsg)MTable.get(getCtx(), I_W_MailMsg.Table_Name)
.getPO(getW_MailMsg_ID(), get_TrxName()); }
/** Set Mail Message.
@param W_MailMsg_ID
Web Store Mail Message Template
*/
public void setW_MailMsg_ID (int W_MailMsg_ID)
{
if (W_MailMsg_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_MailMsg_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_MailMsg_ID, Integer.valueOf(W_MailMsg_ID));
}
/** Get Mail Message.
@return Web Store Mail Message Template
*/
public int getW_MailMsg_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_MailMsg_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserMail.java
| 1
|
请完成以下Java代码
|
public Flux<InstanceEvent> findAll() {
return Flux.defer(() -> Flux.fromIterable(eventLog.values())
.flatMapIterable(Function.identity())
.sort(byTimestampAndIdAndVersion));
}
@Override
public Flux<InstanceEvent> find(InstanceId id) {
return Flux.defer(() -> Flux.fromIterable(eventLog.getOrDefault(id, Collections.emptyList())));
}
@Override
public Mono<Void> append(List<InstanceEvent> events) {
return Mono.fromRunnable(() -> {
while (true) {
if (doAppend(events)) {
return;
}
}
});
}
protected boolean doAppend(List<InstanceEvent> events) {
if (events.isEmpty()) {
return true;
}
InstanceId id = events.get(0).getInstance();
if (!events.stream().allMatch((event) -> event.getInstance().equals(id))) {
throw new IllegalArgumentException("'events' must only refer to the same instance.");
}
List<InstanceEvent> oldEvents = eventLog.computeIfAbsent(id,
(key) -> new ArrayList<>(maxLogSizePerAggregate + 1));
long lastVersion = getLastVersion(oldEvents);
if (lastVersion >= events.get(0).getVersion()) {
throw createOptimisticLockException(events.get(0), lastVersion);
}
List<InstanceEvent> newEvents = new ArrayList<>(oldEvents);
newEvents.addAll(events);
|
if (newEvents.size() > maxLogSizePerAggregate) {
log.debug("Threshold for {} reached. Compacting events", id);
compact(newEvents);
}
if (eventLog.replace(id, oldEvents, newEvents)) {
log.debug("Events appended to log {}", events);
return true;
}
log.debug("Unsuccessful attempt append the events {} ", events);
return false;
}
private void compact(List<InstanceEvent> events) {
BinaryOperator<InstanceEvent> latestEvent = (e1, e2) -> (e1.getVersion() > e2.getVersion()) ? e1 : e2;
Map<Class<?>, Optional<InstanceEvent>> latestPerType = events.stream()
.collect(groupingBy(InstanceEvent::getClass, reducing(latestEvent)));
events.removeIf((e) -> !Objects.equals(e, latestPerType.get(e.getClass()).orElse(null)));
}
private OptimisticLockingException createOptimisticLockException(InstanceEvent event, long lastVersion) {
return new OptimisticLockingException(
"Version " + event.getVersion() + " was overtaken by " + lastVersion + " for " + event.getInstance());
}
protected static long getLastVersion(List<InstanceEvent> events) {
return events.isEmpty() ? -1 : events.get(events.size() - 1).getVersion();
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\eventstore\ConcurrentMapEventStore.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ShiroRealm shiroRealm(){
ShiroRealm shiroRealm = new ShiroRealm();
return shiroRealm;
}
public SimpleCookie rememberMeCookie() {
SimpleCookie cookie = new SimpleCookie("rememberMe");
cookie.setMaxAge(86400);
return cookie;
}
public CookieRememberMeManager rememberMeManager() {
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie());
cookieRememberMeManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag=="));
return cookieRememberMeManager;
}
@Bean
@DependsOn({"lifecycleBeanPostProcessor"})
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
|
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
public RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
return redisManager;
}
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
return redisCacheManager;
}
}
|
repos\SpringAll-master\14.Spring-Boot-Shiro-Redis\src\main\java\com\springboot\config\ShiroConfig.java
| 2
|
请完成以下Java代码
|
public class InitOnDemandSingleton {
/**
* Holder for a singleton instance.
*
* @author Donato Rimenti
*
*/
private static class InstanceHolder {
/**
* Current instance of the singleton.
*/
private static final InitOnDemandSingleton INSTANCE = new InitOnDemandSingleton();
}
|
/**
* Private constructor to avoid instantiation.
*/
private InitOnDemandSingleton() {
}
/**
* Returns the current instance of the singleton.
*
* @return the current instance of the singleton
*/
public static InitOnDemandSingleton getInstance() {
return InstanceHolder.INSTANCE;
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-creational\src\main\java\com\baeldung\singleton\synchronization\InitOnDemandSingleton.java
| 1
|
请完成以下Java代码
|
private static WFProcessStatus computeStatusFromActivities(@NonNull final ImmutableList<WFActivity> activities)
{
final ImmutableSet<WFActivityStatus> activityStatuses = activities
.stream()
.map(WFActivity::getStatus)
.collect(ImmutableSet.toImmutableSet());
return WFProcessStatus.computeFromActivityStatuses(activityStatuses);
}
private static boolean computeIsAllowAbort(@Nullable final Boolean isAllowAbort, @NonNull final WFProcessStatus status)
{
if (isAllowAbort != null)
{
return isAllowAbort;
}
else
{
return status.isNotStarted();
}
}
public void assertHasAccess(@NonNull final UserId userId)
{
if (!hasAccess(userId))
{
throw new AdempiereException(NO_ACCESS_ERROR_MSG);
}
}
public boolean hasAccess(@NonNull final UserId userId)
{
return UserId.equals(getResponsibleId(), userId);
}
public <T> T getDocumentAs(@NonNull final Class<T> type)
{
return type.cast(document);
}
public WFActivity getActivityById(@NonNull final WFActivityId id)
{
return getActivityByIdOptional(id)
.orElseThrow(() -> new AdempiereException(NO_ACTIVITY_ERROR_MSG)
.appendParametersToMessage()
.setParameter("ID", id)
.setParameter("WFProcess", this));
}
|
@NonNull
public Optional<WFActivity> getActivityByIdOptional(@NonNull final WFActivityId id)
{
return Optional.ofNullable(activitiesById.get(id));
}
public WFProcess withChangedActivityStatus(
@NonNull final WFActivityId wfActivityId,
@NonNull final WFActivityStatus newActivityStatus)
{
return withChangedActivityById(wfActivityId, wfActivity -> wfActivity.withStatus(newActivityStatus));
}
private WFProcess withChangedActivityById(@NonNull final WFActivityId wfActivityId, @NonNull final UnaryOperator<WFActivity> remappingFunction)
{
return withChangedActivities(wfActivity -> wfActivity.getId().equals(wfActivityId)
? remappingFunction.apply(wfActivity)
: wfActivity);
}
private WFProcess withChangedActivities(@NonNull final UnaryOperator<WFActivity> remappingFunction)
{
final ImmutableList<WFActivity> activitiesNew = CollectionUtils.map(this.activities, remappingFunction);
return !Objects.equals(this.activities, activitiesNew)
? toBuilder().activities(activitiesNew).build()
: this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WFProcess.java
| 1
|
请完成以下Java代码
|
public DataType getType() {
return DataType.LONG;
}
@Override
public long getLong() {
return value;
}
@Override
public double getDouble() {
return value;
}
@Override
|
public String valueToString() {
return Long.toString(value);
}
@Override
public int compareTo(DataPoint dataPoint) {
if (dataPoint.getType() == DataType.DOUBLE) {
return Double.compare(getDouble(), dataPoint.getDouble());
} else if (dataPoint.getType() == DataType.LONG) {
return Long.compare(value, dataPoint.getLong());
} else {
return super.compareTo(dataPoint);
}
}
}
|
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\data\dp\LongDataPoint.java
| 1
|
请完成以下Java代码
|
public int retrieveLastLineNo()
{
final DocumentQuery query = build();
final DocumentsRepository documentsRepository = getDocumentsRepository();
return documentsRepository.retrieveLastLineNo(query);
}
private DocumentsRepository getDocumentsRepository()
{
return entityDescriptor.getDataBinding().getDocumentsRepository();
}
public Builder setRecordId(@Nullable final DocumentId documentId)
{
recordIds = documentId != null
? ImmutableSet.of(documentId)
: ImmutableSet.of();
return this;
}
public Builder setRecordIds(@Nullable final Collection<DocumentId> documentIds)
{
recordIds = documentIds != null
? ImmutableSet.copyOf(documentIds)
: ImmutableSet.of();
return this;
}
public Builder setParentDocument(final Document parentDocument)
{
this.parentDocument = parentDocument;
return this;
}
public Builder noSorting()
{
_noSorting = true;
_orderBys = null;
return this;
}
public boolean isNoSorting()
{
return _noSorting;
}
public Builder addOrderBy(@NonNull final DocumentQueryOrderBy orderBy)
{
Check.assume(!_noSorting, "sorting not disabled for {}", this);
if (_orderBys == null)
{
_orderBys = new ArrayList<>();
}
_orderBys.add(orderBy);
return this;
}
public Builder setOrderBys(final DocumentQueryOrderByList orderBys)
{
if (orderBys == null || orderBys.isEmpty())
{
_orderBys = null;
}
else
{
_orderBys = new ArrayList<>(orderBys.toList());
}
|
return this;
}
private DocumentQueryOrderByList getOrderBysEffective()
{
return _noSorting
? DocumentQueryOrderByList.EMPTY
: DocumentQueryOrderByList.ofList(_orderBys);
}
public Builder setFirstRow(final int firstRow)
{
this.firstRow = firstRow;
return this;
}
public Builder setPageLength(final int pageLength)
{
this.pageLength = pageLength;
return this;
}
public Builder setExistingDocumentsSupplier(final Function<DocumentId, Document> existingDocumentsSupplier)
{
this.existingDocumentsSupplier = existingDocumentsSupplier;
return this;
}
public Builder setChangesCollector(IDocumentChangesCollector changesCollector)
{
this.changesCollector = changesCollector;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentQuery.java
| 1
|
请完成以下Java代码
|
public File dumpHeap(@Nullable Boolean live) throws IOException, InterruptedException {
Assert.state(live == null, "OpenJ9DiagnosticsMXBean does not support live parameter when dumping the heap");
String file = (String) ReflectionUtils.invokeMethod(this.dumpHeapMethod, this.diagnosticMXBean, "heap",
null);
Assert.state(file != null, "'file' must not be null");
return new File(file);
}
}
/**
* Exception to be thrown if the {@link HeapDumper} cannot be created.
*/
protected static class HeapDumperUnavailableException extends RuntimeException {
public HeapDumperUnavailableException(String message, Throwable cause) {
super(message, cause);
}
}
private static final class TemporaryFileSystemResource extends FileSystemResource {
private final Log logger = LogFactory.getLog(getClass());
private TemporaryFileSystemResource(File file) {
super(file);
}
@Override
public ReadableByteChannel readableChannel() throws IOException {
ReadableByteChannel readableChannel = super.readableChannel();
return new ReadableByteChannel() {
@Override
public boolean isOpen() {
return readableChannel.isOpen();
}
@Override
public void close() throws IOException {
closeThenDeleteFile(readableChannel);
}
@Override
public int read(ByteBuffer dst) throws IOException {
return readableChannel.read(dst);
}
};
}
|
@Override
public InputStream getInputStream() throws IOException {
return new FilterInputStream(super.getInputStream()) {
@Override
public void close() throws IOException {
closeThenDeleteFile(this.in);
}
};
}
private void closeThenDeleteFile(Closeable closeable) throws IOException {
try {
closeable.close();
}
finally {
deleteFile();
}
}
private void deleteFile() {
try {
Files.delete(getFile().toPath());
}
catch (IOException ex) {
TemporaryFileSystemResource.this.logger
.warn("Failed to delete temporary heap dump file '" + getFile() + "'", ex);
}
}
@Override
public boolean isFile() {
// Prevent zero-copy so we can delete the file on close
return false;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\management\HeapDumpWebEndpoint.java
| 1
|
请完成以下Java代码
|
public boolean isTriggeredByEvent() {
Boolean isTriggeredByEvent = getProperties().get(BpmnProperties.TRIGGERED_BY_EVENT);
return Boolean.TRUE.equals(isTriggeredByEvent);
}
//============================================================================
//===============================DELEGATES====================================
//============================================================================
/**
* The delegate for the async before attribute update.
*/
protected AsyncBeforeUpdate delegateAsyncBeforeUpdate;
/**
* The delegate for the async after attribute update.
*/
protected AsyncAfterUpdate delegateAsyncAfterUpdate;
public AsyncBeforeUpdate getDelegateAsyncBeforeUpdate() {
return delegateAsyncBeforeUpdate;
}
public void setDelegateAsyncBeforeUpdate(AsyncBeforeUpdate delegateAsyncBeforeUpdate) {
this.delegateAsyncBeforeUpdate = delegateAsyncBeforeUpdate;
}
public AsyncAfterUpdate getDelegateAsyncAfterUpdate() {
return delegateAsyncAfterUpdate;
}
public void setDelegateAsyncAfterUpdate(AsyncAfterUpdate delegateAsyncAfterUpdate) {
this.delegateAsyncAfterUpdate = delegateAsyncAfterUpdate;
|
}
/**
* Delegate interface for the asyncBefore property update.
*/
public interface AsyncBeforeUpdate {
/**
* Method which is called if the asyncBefore property should be updated.
*
* @param asyncBefore the new value for the asyncBefore flag
* @param exclusive the exclusive flag
*/
public void updateAsyncBefore(boolean asyncBefore, boolean exclusive);
}
/**
* Delegate interface for the asyncAfter property update
*/
public interface AsyncAfterUpdate {
/**
* Method which is called if the asyncAfter property should be updated.
*
* @param asyncAfter the new value for the asyncBefore flag
* @param exclusive the exclusive flag
*/
public void updateAsyncAfter(boolean asyncAfter, boolean exclusive);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\ActivityImpl.java
| 1
|
请完成以下Java代码
|
public String getCode()
{
return code;
}
@Nullable
public static InvoiceLineAllocType ofCodeNullable(@Nullable final String code)
{
if (Check.isBlank(code))
{
return null;
}
return ofCode(code);
}
@JsonCreator
|
public static InvoiceLineAllocType ofCode(@NonNull final String code)
{
final InvoiceLineAllocType type = typesByCode.get(code);
if (type == null)
{
throw new AdempiereException("No " + InvoiceLineAllocType.class + " found for code: " + code);
}
return type;
}
private static final ImmutableMap<String, InvoiceLineAllocType> typesByCode = Maps.uniqueIndex(Arrays.asList(values()), InvoiceLineAllocType::getCode);
public boolean isCreditMemoReinvoiceable()
{
return this == CreditMemoReinvoiceable;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineAllocType.java
| 1
|
请完成以下Java代码
|
public class MMailMsg extends X_W_MailMsg
{
/**
*
*/
private static final long serialVersionUID = 6181691633960939054L;
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param W_MailMsg_ID id
* @param trxName trx
*/
public MMailMsg (Properties ctx, int W_MailMsg_ID, String trxName)
{
super (ctx, W_MailMsg_ID, trxName);
if (W_MailMsg_ID == 0)
{
// setW_Store_ID (0);
// setMailMsgType (null);
// setName (null);
// setSubject (null);
// setMessage (null);
}
} // MMailMsg
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName trx
*/
|
public MMailMsg (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MMailMsg
/**
* Full Constructor
* @param parent store
* @param MailMsgType msg type
* @param Name name
* @param Subject subject
* @param Message message
* @param Message2 message
* @param Message3 message
*/
public MMailMsg (MStore parent, String MailMsgType,
String Name, String Subject, String Message, String Message2, String Message3)
{
this (parent.getCtx(), 0, parent.get_TrxName());
setClientOrg(parent);
setW_Store_ID(parent.getW_Store_ID());
setMailMsgType (MailMsgType);
setName (Name);
setSubject (Subject);
setMessage (Message);
setMessage2 (Message2);
setMessage3 (Message3);
} // MMailMsg
} // MMailMsg
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MMailMsg.java
| 1
|
请完成以下Java代码
|
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_UOM_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setM_PriceList_ID (final int M_PriceList_ID)
{
if (M_PriceList_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, M_PriceList_ID);
}
@Override
public int getM_PriceList_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_ID);
}
@Override
public void setM_PriceList_Version_ID (final int M_PriceList_Version_ID)
{
if (M_PriceList_Version_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PriceList_Version_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PriceList_Version_ID, M_PriceList_Version_ID);
}
@Override
public int getM_PriceList_Version_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_Version_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setProductPriceInStockUOM (final BigDecimal ProductPriceInStockUOM)
{
set_ValueNoCheck (COLUMNNAME_ProductPriceInStockUOM, ProductPriceInStockUOM);
}
|
@Override
public BigDecimal getProductPriceInStockUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ProductPriceInStockUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_ValueNoCheck (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final java.sql.Timestamp ValidTo)
{
set_ValueNoCheck (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_purchase_prices_in_stock_uom_plv_v.java
| 1
|
请完成以下Java代码
|
public int getC_Flatrate_Transition_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Flatrate_Transition_ID);
}
@Override
public void setM_PricingSystem_ID (final int M_PricingSystem_ID)
{
if (M_PricingSystem_ID < 1)
set_Value (COLUMNNAME_M_PricingSystem_ID, null);
else
set_Value (COLUMNNAME_M_PricingSystem_ID, M_PricingSystem_ID);
}
@Override
public int getM_PricingSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PricingSystem_ID);
}
@Override
public void setM_Product_Category_Matching_ID (final int M_Product_Category_Matching_ID)
{
if (M_Product_Category_Matching_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_Matching_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_Matching_ID, M_Product_Category_Matching_ID);
}
@Override
public int getM_Product_Category_Matching_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_Matching_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 setQtyPerDelivery (final BigDecimal QtyPerDelivery)
{
set_Value (COLUMNNAME_QtyPerDelivery, QtyPerDelivery);
}
@Override
public BigDecimal getQtyPerDelivery()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPerDelivery);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Matching.java
| 1
|
请完成以下Java代码
|
public void setResourceFactory(@Nullable JettyResourceFactory resourceFactory) {
this.resourceFactory = resourceFactory;
}
protected @Nullable JettyResourceFactory getResourceFactory() {
return this.resourceFactory;
}
protected Server createJettyServer(ServletHttpHandlerAdapter servlet) {
int port = Math.max(getPort(), 0);
InetSocketAddress address = new InetSocketAddress(getAddress(), port);
Server server = new Server(getThreadPool());
if (this.resourceFactory == null) {
server.addConnector(createConnector(address, server));
}
else {
server.addConnector(createConnector(address, server, this.resourceFactory.getExecutor(),
this.resourceFactory.getScheduler(), this.resourceFactory.getByteBufferPool()));
}
server.setStopTimeout(0);
ServletHolder servletHolder = new ServletHolder(servlet);
servletHolder.setAsyncSupported(true);
ServletContextHandler contextHandler = new ServletContextHandler("/", false, false);
contextHandler.addServlet(servletHolder, "/");
server.setHandler(addHandlerWrappers(contextHandler));
logger.info("Server initialized with port: " + port);
if (this.getMaxConnections() > -1) {
server.addBean(new NetworkConnectionLimit(this.getMaxConnections(), server));
}
|
if (Ssl.isEnabled(getSsl())) {
customizeSsl(server, address);
}
for (JettyServerCustomizer customizer : getServerCustomizers()) {
customizer.customize(server);
}
if (this.isUseForwardHeaders()) {
new ForwardHeadersCustomizer().customize(server);
}
if (getShutdown() == Shutdown.GRACEFUL) {
StatisticsHandler statisticsHandler = new StatisticsHandler();
statisticsHandler.setHandler(server.getHandler());
server.setHandler(statisticsHandler);
}
return server;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\reactive\JettyReactiveWebServerFactory.java
| 1
|
请完成以下Java代码
|
final class DurationToNumberConverter implements GenericConverter {
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Duration.class, Number.class));
}
@Override
public @Nullable Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
return convert((Duration) source, getDurationUnit(sourceType), targetType.getObjectType());
}
private @Nullable ChronoUnit getDurationUnit(TypeDescriptor sourceType) {
|
DurationUnit annotation = sourceType.getAnnotation(DurationUnit.class);
return (annotation != null) ? annotation.value() : null;
}
private Object convert(Duration source, @Nullable ChronoUnit unit, Class<?> type) {
try {
return type.getConstructor(String.class)
.newInstance(String.valueOf(DurationStyle.Unit.fromChronoUnit(unit).longValue(source)));
}
catch (Exception ex) {
ReflectionUtils.rethrowRuntimeException(ex);
throw new IllegalStateException(ex);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\convert\DurationToNumberConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private String getUserName(Principal principal) {
if (principal == null) {
return "anonymous";
} else {
final UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal();
Collection<? extends GrantedAuthority> authorities = currentUser.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
System.out.println(grantedAuthority.getAuthority());
}
return principal.getName();
}
}
private Collection<String> getUserRoles(Principal principal) {
|
if (principal == null) {
return Arrays.asList("none");
} else {
Set<String> roles = new HashSet<String>();
final UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal();
Collection<? extends GrantedAuthority> authorities = currentUser.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
roles.add(grantedAuthority.getAuthority());
}
return roles;
}
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-ldap\src\main\java\com\baeldung\controller\MyController.java
| 2
|
请完成以下Java代码
|
private final EmptiesInOutLinePackingMaterialDocumentLine toImpl(final IPackingMaterialDocumentLine pmLine)
{
return (EmptiesInOutLinePackingMaterialDocumentLine)pmLine;
}
@Override
protected void removeDocumentLine(@NonNull final IPackingMaterialDocumentLine pmLine)
{
final EmptiesInOutLinePackingMaterialDocumentLine inoutLinePMLine = toImpl(pmLine);
final I_M_InOutLine inoutLine = inoutLinePMLine.getM_InOutLine();
if (!InterfaceWrapperHelper.isNew(inoutLine))
{
InterfaceWrapperHelper.delete(inoutLine);
}
}
@Override
protected void createDocumentLine(@NonNull final IPackingMaterialDocumentLine pmLine)
{
final EmptiesInOutLinePackingMaterialDocumentLine inoutLinePMLine = toImpl(pmLine);
final I_M_InOut inout = getM_InOut();
InterfaceWrapperHelper.save(inout); // make sure inout header is saved
final I_M_InOutLine inoutLine = inoutLinePMLine.getM_InOutLine();
inoutLine.setM_InOut(inout); // make sure inout line is linked to our M_InOut_ID (in case it was just saved)
inoutLine.setIsActive(true); // just to be sure
// task FRESH-273
inoutLine.setIsPackagingMaterial(true);
|
final boolean wasNew = InterfaceWrapperHelper.isNew(inoutLine);
InterfaceWrapperHelper.save(inoutLine);
if (wasNew)
{
affectedInOutLinesId.add(inoutLine.getM_InOutLine_ID());
}
}
@Override
protected void linkSourceToDocumentLine(final IPackingMaterialDocumentLineSource source, final IPackingMaterialDocumentLine pmLine)
{
// nothing
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\empties\EmptiesInOutLinesProducer.java
| 1
|
请完成以下Java代码
|
public static Predicate<PricingConditionsRow> isEditableRowOrMatching(final DocumentFilterList filters)
{
if (filters.isEmpty())
{
return Predicates.alwaysTrue();
}
final boolean showCustomers = filters.getParamValueAsBoolean(FILTERID_IsCustomer, PARAM_IsCustomer, false);
final boolean showVendors = filters.getParamValueAsBoolean(FILTERID_IsVendor, PARAM_IsVendor, false);
final boolean showAll = !showCustomers && !showVendors;
if (showAll)
{
return Predicates.alwaysTrue();
}
return row -> row.isEditable()
|| ((showCustomers && row.isCustomer()) || (showVendors && row.isVendor()));
}
public DocumentFilterList extractFilters(@NonNull final JSONFilterViewRequest filterViewRequest)
{
|
return filterViewRequest.getFiltersUnwrapped(getFilterDescriptorsProvider());
}
public DocumentFilterList extractFilters(@NonNull final CreateViewRequest request)
{
return request.isUseAutoFilters()
? getDefaultFilters()
: request.getFiltersUnwrapped(getFilterDescriptorsProvider());
}
private DocumentFilterList getDefaultFilters()
{
if (defaultFilters == null)
{
final DocumentFilter isCustomer = DocumentFilter.singleParameterFilter(FILTERID_IsCustomer, PARAM_IsCustomer, Operator.EQUAL, true);
defaultFilters = DocumentFilterList.of(isCustomer);
}
return defaultFilters;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsViewFilters.java
| 1
|
请完成以下Java代码
|
public static ScannedCode ofString(@NonNull final String code) {return new ScannedCode(code);}
@Nullable
public static ScannedCode ofNullableString(@Nullable final String code)
{
final String codeNorm = StringUtils.trimBlankToNull(code);
return codeNorm != null ? new ScannedCode(codeNorm) : null;
}
@Nullable
@JsonCreator(mode = JsonCreator.Mode.DELEGATING) // IMPORTANT: keep it here because we want to handle the case when the JSON value is empty string, number etc.
public static ScannedCode ofNullableObject(@Nullable final Object obj)
{
final String code = normalizeCode(obj);
return code != null ? new ScannedCode(code) : null;
}
|
@Override
@Deprecated
public String toString() {return getAsString();}
@JsonValue
public String getAsString() {return code;}
public GlobalQRCode toGlobalQRCode() {return toGlobalQRCodeIfMatching().orThrow();}
public GlobalQRCodeParseResult toGlobalQRCodeIfMatching() {return GlobalQRCode.parse(code);}
public PrintableScannedCode toPrintableScannedCode() {return PrintableScannedCode.of(this);}
public String substring(final int beginIndex, final int endIndex) {return code.substring(beginIndex, endIndex);}
public int length() {return code.length();}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scannable_code\ScannedCode.java
| 1
|
请完成以下Java代码
|
public TimerJobConfiguration newConfiguration(String canonicalString) {
String[] configParts = canonicalString.split("\\" + JOB_HANDLER_CONFIG_PROPERTY_DELIMITER);
if (configParts.length > 3) {
throw new ProcessEngineException("Illegal timer job handler configuration: '" + canonicalString
+ "': exprecting a one, two or three part configuration seperated by '" + JOB_HANDLER_CONFIG_PROPERTY_DELIMITER + "'.");
}
TimerJobConfiguration configuration = new TimerJobConfiguration();
configuration.timerElementKey = configParts[0];
// depending on the job configuration, the next parts can be a task listener id and/or the follow-up-job flag
for (int i = 1; i < configParts.length; i++) {
adjustConfiguration(configuration, configParts[i]);
}
return configuration;
}
protected void adjustConfiguration(TimerJobConfiguration configuration, String configPart) {
if (configPart.startsWith(JOB_HANDLER_CONFIG_TASK_LISTENER_PREFIX)) {
configuration.setTimerElementSecondaryKey(configPart.substring(JOB_HANDLER_CONFIG_TASK_LISTENER_PREFIX.length()));
} else {
configuration.followUpJobCreated = JOB_HANDLER_CONFIG_PROPERTY_FOLLOW_UP_JOB_CREATED.equals(configPart);
}
}
public static class TimerJobConfiguration implements JobHandlerConfiguration {
protected String timerElementKey;
protected String timerElementSecondaryKey;
protected boolean followUpJobCreated;
public String getTimerElementKey() {
return timerElementKey;
}
public void setTimerElementKey(String timerElementKey) {
this.timerElementKey = timerElementKey;
}
public boolean isFollowUpJobCreated() {
return followUpJobCreated;
}
public void setFollowUpJobCreated(boolean followUpJobCreated) {
this.followUpJobCreated = followUpJobCreated;
}
public String getTimerElementSecondaryKey() {
|
return timerElementSecondaryKey;
}
public void setTimerElementSecondaryKey(String timerElementSecondaryKey) {
this.timerElementSecondaryKey = timerElementSecondaryKey;
}
@Override
public String toCanonicalString() {
String canonicalString = timerElementKey;
if (timerElementSecondaryKey != null) {
canonicalString += JOB_HANDLER_CONFIG_PROPERTY_DELIMITER + JOB_HANDLER_CONFIG_TASK_LISTENER_PREFIX + timerElementSecondaryKey;
}
if (followUpJobCreated) {
canonicalString += JOB_HANDLER_CONFIG_PROPERTY_DELIMITER + JOB_HANDLER_CONFIG_PROPERTY_FOLLOW_UP_JOB_CREATED;
}
return canonicalString;
}
}
public void onDelete(TimerJobConfiguration configuration, JobEntity jobEntity) {
// do nothing
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\TimerEventJobHandler.java
| 1
|
请完成以下Java代码
|
public int getM_RequisitionLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_RequisitionLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Einzelpreis.
@param PriceActual
Actual Price
*/
@Override
public void setPriceActual (java.math.BigDecimal PriceActual)
{
set_Value (COLUMNNAME_PriceActual, PriceActual);
}
/** Get Einzelpreis.
@return Actual Price
*/
@Override
public java.math.BigDecimal getPriceActual ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceActual);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
|
/** Set Menge.
@param Qty
Quantity
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Quantity
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_RequisitionLine.java
| 1
|
请完成以下Java代码
|
public void addNewCompensationLine(final GroupCompensationLineCreateRequest request)
{
final BigDecimal price = request.getPrice();
final BigDecimal qtyEntered = request.getQtyEntered();
final BigDecimal lineNetAmt = price != null && qtyEntered != null
? amountPrecision.roundIfNeeded(price.multiply(qtyEntered))
: null;
final GroupCompensationLine compensationLine = GroupCompensationLine.builder()
.productId(request.getProductId())
.uomId(request.getUomId())
.type(request.getType())
.amtType(request.getAmtType())
.percentage(request.getPercentage())
.price(price)
.qtyEntered(qtyEntered)
.lineNetAmt(lineNetAmt)
.groupTemplateLineId(request.getGroupTemplateLineId())
.build();
updateCompensationLine(compensationLine, getTotalNetAmt());
compensationLines.add(compensationLine);
}
void removeAllGeneratedLines()
{
compensationLines.removeIf(GroupCompensationLine::isGeneratedLine);
}
|
private void moveAllManualCompensationLinesToEnd()
{
final ArrayList<GroupCompensationLine> manualCompensationLines = new ArrayList<>();
for (final Iterator<GroupCompensationLine> it = compensationLines.iterator(); it.hasNext(); )
{
final GroupCompensationLine compensationLine = it.next();
if (compensationLine.isManualLine())
{
manualCompensationLines.add(compensationLine);
it.remove();
}
}
compensationLines.addAll(manualCompensationLines);
}
boolean isBasedOnGroupTemplate()
{
return getGroupTemplateId() != null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\Group.java
| 1
|
请完成以下Java代码
|
public class AccountInterest2 {
@XmlElement(name = "Tp")
protected InterestType1Choice tp;
@XmlElement(name = "Rate")
protected List<Rate3> rate;
@XmlElement(name = "FrToDt")
protected DateTimePeriodDetails frToDt;
@XmlElement(name = "Rsn")
protected String rsn;
/**
* Gets the value of the tp property.
*
* @return
* possible object is
* {@link InterestType1Choice }
*
*/
public InterestType1Choice getTp() {
return tp;
}
/**
* Sets the value of the tp property.
*
* @param value
* allowed object is
* {@link InterestType1Choice }
*
*/
public void setTp(InterestType1Choice value) {
this.tp = value;
}
/**
* Gets the value of the rate property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the rate property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRate().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Rate3 }
*
*
*/
public List<Rate3> getRate() {
if (rate == null) {
rate = new ArrayList<Rate3>();
}
return this.rate;
}
/**
* Gets the value of the frToDt property.
|
*
* @return
* possible object is
* {@link DateTimePeriodDetails }
*
*/
public DateTimePeriodDetails getFrToDt() {
return frToDt;
}
/**
* Sets the value of the frToDt property.
*
* @param value
* allowed object is
* {@link DateTimePeriodDetails }
*
*/
public void setFrToDt(DateTimePeriodDetails value) {
this.frToDt = value;
}
/**
* Gets the value of the rsn property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRsn() {
return rsn;
}
/**
* Sets the value of the rsn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRsn(String value) {
this.rsn = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\AccountInterest2.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractProxyExchange implements ProxyExchange {
private final GatewayMvcProperties properties;
protected AbstractProxyExchange(GatewayMvcProperties properties) {
this.properties = properties;
}
protected int copyResponseBody(ClientHttpResponse clientResponse, InputStream inputStream,
OutputStream outputStream) throws IOException {
Objects.requireNonNull(clientResponse, "No ClientResponse specified");
Objects.requireNonNull(inputStream, "No InputStream specified");
Objects.requireNonNull(outputStream, "No OutputStream specified");
int transferredBytes;
if (properties.getStreamingMediaTypes().contains(clientResponse.getHeaders().getContentType())) {
transferredBytes = copyResponseBodyWithFlushing(inputStream, outputStream);
}
else {
transferredBytes = StreamUtils.copy(inputStream, outputStream);
}
return transferredBytes;
}
|
private int copyResponseBodyWithFlushing(InputStream inputStream, OutputStream outputStream) throws IOException {
int readBytes;
var totalReadBytes = 0;
var buffer = new byte[properties.getStreamingBufferSize()];
while ((readBytes = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, readBytes);
outputStream.flush();
if (totalReadBytes < Integer.MAX_VALUE) {
try {
totalReadBytes = Math.addExact(totalReadBytes, readBytes);
}
catch (ArithmeticException e) {
totalReadBytes = Integer.MAX_VALUE;
}
}
}
outputStream.flush();
return totalReadBytes;
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\common\AbstractProxyExchange.java
| 1
|
请完成以下Java代码
|
public void setMaxWeight (BigDecimal MaxWeight)
{
set_Value (COLUMNNAME_MaxWeight, MaxWeight);
}
/** Get Max. Gewicht.
@return Max. Gewicht */
public BigDecimal getMaxWeight ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MaxWeight);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Verpackung.
@param M_PackagingContainer_ID Verpackung */
public void setM_PackagingContainer_ID (int M_PackagingContainer_ID)
{
if (M_PackagingContainer_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PackagingContainer_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PackagingContainer_ID, Integer.valueOf(M_PackagingContainer_ID));
}
/** Get Verpackung.
@return Verpackung */
public int getM_PackagingContainer_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PackagingContainer_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
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 Suchschluessel.
@param Value
Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschluessel.
@return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Set Breite.
@param Width Breite */
public void setWidth (BigDecimal Width)
{
set_Value (COLUMNNAME_Width, Width);
}
/** Get Breite.
@return Breite */
public BigDecimal getWidth ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Width);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_M_PackagingContainer.java
| 1
|
请完成以下Java代码
|
public class ExclusiveGatewayXMLConverter extends BaseBpmnXMLConverter {
@Override
public Class<? extends BaseElement> getBpmnElementType() {
return ExclusiveGateway.class;
}
@Override
protected String getXMLElementName() {
return ELEMENT_GATEWAY_EXCLUSIVE;
}
@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\ExclusiveGatewayXMLConverter.java
| 1
|
请完成以下Java代码
|
public boolean isAllowLoginDateOverride()
{
return getPropertyAsBoolean(Env.CTXNAME_IsAllowLoginDateOverride);
}
public RoleId getRoleId()
{
return RoleId.ofRepoId(getMandatoryPropertyAsInt(Env.CTXNAME_AD_Role_ID));
}
public void setClient(final ClientId clientId, final String clientName)
{
setProperty(Env.CTXNAME_AD_Client_ID, ClientId.toRepoId(clientId));
setProperty(Env.CTXNAME_AD_Client_Name, clientName);
Ini.setProperty(Ini.P_CLIENT, clientName);
}
public ClientId getClientId()
{
return ClientId.ofRepoId(getMandatoryPropertyAsInt(Env.CTXNAME_AD_Client_ID));
}
public LocalDate getLoginDate()
{
return getPropertyAsLocalDate(Env.CTXNAME_Date);
}
public void setLoginDate(final LocalDate date)
{
setProperty(Env.CTXNAME_Date, date);
}
public void setOrg(final OrgId orgId, final String orgName)
{
setProperty(Env.CTXNAME_AD_Org_ID, OrgId.toRepoId(orgId));
setProperty(Env.CTXNAME_AD_Org_Name, orgName);
Ini.setProperty(Ini.P_ORG, orgName);
}
public void setUserOrgs(final String userOrgs)
{
setProperty(Env.CTXNAME_User_Org, userOrgs);
}
public OrgId getOrgId()
{
return OrgId.ofRepoId(getMandatoryPropertyAsInt(Env.CTXNAME_AD_Org_ID));
}
|
public void setWarehouse(final WarehouseId warehouseId, final String warehouseName)
{
setProperty(Env.CTXNAME_M_Warehouse_ID, WarehouseId.toRepoId(warehouseId));
Ini.setProperty(Ini.P_WAREHOUSE, warehouseName);
}
@Nullable
public WarehouseId getWarehouseId()
{
return WarehouseId.ofRepoIdOrNull(getPropertyAsInt(Env.CTXNAME_M_Warehouse_ID));
}
public void setPrinterName(final String printerName)
{
setProperty(Env.CTXNAME_Printer, printerName == null ? "" : printerName);
Ini.setProperty(Ini.P_PRINTER, printerName);
}
public void setAcctSchema(final AcctSchema acctSchema)
{
setProperty("$C_AcctSchema_ID", acctSchema.getId().getRepoId());
setProperty("$C_Currency_ID", acctSchema.getCurrencyId().getRepoId());
setProperty("$HasAlias", acctSchema.getValidCombinationOptions().isUseAccountAlias());
}
@Nullable
public AcctSchemaId getAcctSchemaId()
{
return AcctSchemaId.ofRepoIdOrNull(getPropertyAsInt("$C_AcctSchema_ID"));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\LoginContext.java
| 1
|
请完成以下Java代码
|
protected List<Intervalable> checkForOverlapsToTheLeft(Intervalable interval)
{
return checkForOverlaps(interval, Direction.LEFT);
}
/**
* 往右边寻找重叠
* @param interval
* @return
*/
protected List<Intervalable> checkForOverlapsToTheRight(Intervalable interval)
{
return checkForOverlaps(interval, Direction.RIGHT);
}
/**
* 寻找重叠
* @param interval 一个区间,与该区间重叠
* @param direction 方向,表明重叠区间在interval的左边还是右边
* @return
*/
protected List<Intervalable> checkForOverlaps(Intervalable interval, Direction direction)
{
List<Intervalable> overlaps = new ArrayList<Intervalable>();
for (Intervalable currentInterval : this.intervals)
{
switch (direction)
{
case LEFT:
if (currentInterval.getStart() <= interval.getEnd())
|
{
overlaps.add(currentInterval);
}
break;
case RIGHT:
if (currentInterval.getEnd() >= interval.getStart())
{
overlaps.add(currentInterval);
}
break;
}
}
return overlaps;
}
/**
* 是对IntervalNode.findOverlaps(Intervalable)的一个包装,防止NPE
* @see IntervalNode#findOverlaps(Intervalable)
* @param node
* @param interval
* @return
*/
protected static List<Intervalable> findOverlappingRanges(IntervalNode node, Intervalable interval)
{
if (node != null)
{
return node.findOverlaps(interval);
}
return Collections.emptyList();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\ahocorasick\interval\IntervalNode.java
| 1
|
请完成以下Java代码
|
public void setAD_Process_Para(final org.compiere.model.I_AD_Process_Para AD_Process_Para)
{
set_ValueFromPO(COLUMNNAME_AD_Process_Para_ID, org.compiere.model.I_AD_Process_Para.class, AD_Process_Para);
}
@Override
public void setAD_Process_Para_ID (final int AD_Process_Para_ID)
{
if (AD_Process_Para_ID < 1)
set_Value (COLUMNNAME_AD_Process_Para_ID, null);
else
set_Value (COLUMNNAME_AD_Process_Para_ID, AD_Process_Para_ID);
}
@Override
public int getAD_Process_Para_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Process_Para_ID);
}
@Override
public void setAD_WF_Node_ID (final int AD_WF_Node_ID)
{
if (AD_WF_Node_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, AD_WF_Node_ID);
}
@Override
public int getAD_WF_Node_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_WF_Node_ID);
}
@Override
public void setAD_WF_Node_Para_ID (final int AD_WF_Node_Para_ID)
{
if (AD_WF_Node_Para_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_WF_Node_Para_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_WF_Node_Para_ID, AD_WF_Node_Para_ID);
}
@Override
public int getAD_WF_Node_Para_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_WF_Node_Para_ID);
}
@Override
public void setAttributeName (final java.lang.String AttributeName)
{
set_Value (COLUMNNAME_AttributeName, AttributeName);
}
@Override
public java.lang.String getAttributeName()
{
return get_ValueAsString(COLUMNNAME_AttributeName);
}
@Override
|
public void setAttributeValue (final java.lang.String AttributeValue)
{
set_Value (COLUMNNAME_AttributeValue, AttributeValue);
}
@Override
public java.lang.String getAttributeValue()
{
return get_ValueAsString(COLUMNNAME_AttributeValue);
}
@Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Node_Para.java
| 1
|
请完成以下Java代码
|
public RecordChangeLog getByRecordId(@NonNull final ComposedRecordId recordId)
{
final RecordChangeLog.RecordChangeLogBuilder changeLogsBuilder = RecordChangeLog.builder()
.tableName(poInfo.getTableName())
.recordId(recordId);
loadRecordSummary(changeLogsBuilder, recordId);
final List<RecordChangeLogEntry> logEntries = retrieveLogEntries(recordId);
changeLogsBuilder.entries(logEntries);
return changeLogsBuilder.build();
}
public RecordChangeLog getSummaryByRecordId(@NonNull final ComposedRecordId recordId)
{
final RecordChangeLog.RecordChangeLogBuilder changeLogsBuilder = RecordChangeLog.builder()
.tableName(poInfo.getTableName())
.recordId(recordId);
loadRecordSummary(changeLogsBuilder, recordId);
return changeLogsBuilder.build();
}
private void loadRecordSummary(final RecordChangeLog.RecordChangeLogBuilder changeLogsBuilder, final ComposedRecordId recordId)
{
DB.forFirstRowIfAny(
"SELECT Created, CreatedBy, Updated, UpdatedBy FROM " + poInfo.getTableName() + " WHERE " + poInfo.getSqlWhereClauseByKeys(),
recordId.getKeysAsList(poInfo.getKeyColumnNames()),
rs -> changeLogsBuilder.createdByUserId(UserId.ofRepoIdOrNull(rs.getInt("CreatedBy")))
.createdTimestamp(rs.getTimestamp("Created").toInstant())
.lastChangedByUserId(UserId.ofRepoIdOrNull(rs.getInt("UpdatedBy")))
.lastChangedTimestamp(rs.getTimestamp("Updated").toInstant()));
}
private List<RecordChangeLogEntry> retrieveLogEntries(@NonNull final ComposedRecordId recordId)
|
{
if (!recordId.isSingleKey())
{
return ImmutableList.of();
}
final int singleRecordId = recordId.getSingleRecordId().orElse(-1);
final TableRecordReference recordRef = TableRecordReference.of(poInfo.getAD_Table_ID(), singleRecordId);
final ImmutableListMultimap<TableRecordReference, RecordChangeLogEntry> //
logEntries = RecordChangeLogEntryLoader.retrieveLogEntries(LogEntriesQuery.of(recordRef));
return (logEntries.get(recordRef));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\RecordChangeLogLoader.java
| 1
|
请完成以下Java代码
|
public void deleteHistoricDecisionExecutionsByDeploymentId(String deploymentId) {
dataManager.deleteHistoricDecisionExecutionsByDeploymentId(deploymentId);
}
@Override
public List<DmnHistoricDecisionExecution> findHistoricDecisionExecutionsByQueryCriteria(HistoricDecisionExecutionQueryImpl decisionExecutionQuery) {
return dataManager.findHistoricDecisionExecutionsByQueryCriteria(decisionExecutionQuery);
}
@Override
public long findHistoricDecisionExecutionCountByQueryCriteria(HistoricDecisionExecutionQueryImpl decisionExecutionQuery) {
return dataManager.findHistoricDecisionExecutionCountByQueryCriteria(decisionExecutionQuery);
}
@Override
public List<DmnHistoricDecisionExecution> findHistoricDecisionExecutionsByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricDecisionExecutionsByNativeQuery(parameterMap);
}
|
@Override
public long findHistoricDecisionExecutionCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricDecisionExecutionCountByNativeQuery(parameterMap);
}
@Override
public void delete(HistoricDecisionExecutionQueryImpl query) {
dataManager.delete(query);
}
@Override
public void bulkDeleteHistoricDecisionExecutionsByInstanceIdsAndScopeType(Collection<String> instanceIds, String scopeType) {
dataManager.bulkDeleteHistoricDecisionExecutionsByInstanceIdsAndScopeType(instanceIds, scopeType);
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\HistoricDecisionExecutionEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
protected void processDI(DmnDefinition dmnDefinition, List<DecisionEntity> decisions) {
if (decisions.isEmpty()) {
return;
}
if (!dmnDefinition.getLocationMap().isEmpty()) {
for (String dmnRef : dmnDefinition.getLocationMap().keySet()) {
if (dmnDefinition.getDecisionById(dmnRef) == null && dmnDefinition.getDecisionServiceById(dmnRef) == null) {
LOGGER.warn("Invalid reference in diagram interchange definition: could not find {}", dmnRef);
}
}
for (DecisionService decisionService : dmnDefinition.getDecisionServices()) {
DecisionEntity decision = getDecision(decisionService.getId(), decisions);
if (decision != null) {
decision.setHasGraphicalNotation(true);
|
}
}
}
}
public DecisionEntity getDecision(String decisionKey, List<DecisionEntity> decisions) {
for (DecisionEntity decision : decisions) {
if (decision.getKey().equals(decisionKey)) {
return decision;
}
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\deployer\ParsedDeploymentBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Foo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
private String name;
public Foo() {
}
public Foo(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [id=").append(id).append(", name=").append(name).append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((id == null) ? 0 : id.hashCode());
result = (prime * result) + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
|
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Foo other = (Foo) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\persistence\model\Foo.java
| 2
|
请完成以下Java代码
|
public List<UserProfileDto> queryUsers(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
UserQueryDto queryDto = new UserQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryUsers(queryDto, firstResult, maxResults);
}
public List<UserProfileDto> queryUsers(UserQueryDto queryDto, Integer firstResult, Integer maxResults) {
queryDto.setObjectMapper(getObjectMapper());
UserQuery query = queryDto.toQuery(getProcessEngine());
List<User> resultList = QueryUtil.list(query, firstResult, maxResults);
return UserProfileDto.fromUserList(resultList);
}
@Override
public CountResultDto getUserCount(UriInfo uriInfo) {
UserQueryDto queryDto = new UserQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return getUserCount(queryDto);
}
protected CountResultDto getUserCount(UserQueryDto queryDto) {
UserQuery query = queryDto.toQuery(getProcessEngine());
long count = query.count();
return new CountResultDto(count);
}
@Override
public void createUser(UserDto userDto) {
final IdentityService identityService = getIdentityService();
if(identityService.isReadOnly()) {
throw new InvalidRequestException(Status.FORBIDDEN, "Identity service implementation is read-only.");
}
UserProfileDto profile = userDto.getProfile();
if(profile == null || profile.getId() == null) {
throw new InvalidRequestException(Status.BAD_REQUEST, "request object must provide profile information with valid id.");
}
User newUser = identityService.newUser(profile.getId());
profile.update(newUser);
if(userDto.getCredentials() != null) {
newUser.setPassword(userDto.getCredentials().getPassword());
}
identityService.saveUser(newUser);
}
@Override
public ResourceOptionsDto availableOperations(UriInfo context) {
|
final IdentityService identityService = getIdentityService();
UriBuilder baseUriBuilder = context.getBaseUriBuilder()
.path(relativeRootResourcePath)
.path(UserRestService.PATH);
ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto();
// GET /
URI baseUri = baseUriBuilder.build();
resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list");
// GET /count
URI countUri = baseUriBuilder.clone().path("/count").build();
resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count");
// POST /create
if(!identityService.isReadOnly() && isAuthorized(CREATE)) {
URI createUri = baseUriBuilder.clone().path("/create").build();
resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create");
}
return resourceOptionsDto;
}
// utility methods //////////////////////////////////////
protected IdentityService getIdentityService() {
return getProcessEngine().getIdentityService();
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\UserRestServiceImpl.java
| 1
|
请完成以下Java代码
|
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_CM_Chat getCM_Chat() throws RuntimeException
{
return (I_CM_Chat)MTable.get(getCtx(), I_CM_Chat.Table_Name)
.getPO(getCM_Chat_ID(), get_TrxName()); }
/** Set Chat.
@param CM_Chat_ID
Chat or discussion thread
*/
public void setCM_Chat_ID (int CM_Chat_ID)
{
if (CM_Chat_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_Chat_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_Chat_ID, Integer.valueOf(CM_Chat_ID));
}
/** Get Chat.
@return Chat or discussion thread
*/
public int getCM_Chat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Chat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Self-Service.
@param IsSelfService
|
This is a Self-Service entry or this entry can be changed via Self-Service
*/
public void setIsSelfService (boolean IsSelfService)
{
set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService));
}
/** Get Self-Service.
@return This is a Self-Service entry or this entry can be changed via Self-Service
*/
public boolean isSelfService ()
{
Object oo = get_Value(COLUMNNAME_IsSelfService);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ChatUpdate.java
| 1
|
请完成以下Java代码
|
public static DDOrderCandidateAdvisedEvent cast(@NonNull final AbstractDDOrderCandidateEvent event)
{
return (DDOrderCandidateAdvisedEvent)event;
}
public DDOrderCandidateAdvisedEvent withPPOrderId(@Nullable final PPOrderId newPPOrderId)
{
if (PPOrderId.equals(getPPOrderId(), newPPOrderId))
{
return this;
}
return new DDOrderCandidateAdvisedEvent(
getEventDescriptor(),
getDdOrderCandidate().withPPOrderId(newPPOrderId),
getSupplyRequiredDescriptorNotNull(),
advisedToCreateDDOrder,
pickIfFeasible
);
}
@Nullable
|
private PPOrderId getPPOrderId()
{
final SupplyRequiredDescriptor supplyRequiredDescriptor = getSupplyRequiredDescriptor();
if (supplyRequiredDescriptor == null)
{
return null;
}
final PPOrderRef ppOrderRef = supplyRequiredDescriptor.getPpOrderRef();
if (ppOrderRef == null)
{
return null;
}
return ppOrderRef.getPpOrderId();
}
@Override
public String getEventName() {return TYPE;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\ddordercandidate\DDOrderCandidateAdvisedEvent.java
| 1
|
请完成以下Java代码
|
public DocumentLocation withLocationId(@Nullable final LocationId locationId)
{
return !Objects.equals(this.locationId, locationId)
? toBuilder().locationId(locationId).build()
: this;
}
public DocumentLocation withRenderedAddress(@NonNull final RenderedAddressAndCapturedLocation renderedAddress)
{
return toBuilder()
.locationId(renderedAddress.getCapturedLocationId())
.bpartnerAddress(renderedAddress.getRenderedAddress())
.build();
}
private DocumentLocation withoutRenderedAddress()
{
return bpartnerAddress != null
? toBuilder().bpartnerAddress(null).build()
: this;
}
public boolean equalsIgnoringRenderedAddress(@NonNull final DocumentLocation other)
{
return Objects.equals(this.withoutRenderedAddress(), other.withoutRenderedAddress());
}
|
public BPartnerLocationAndCaptureId toBPartnerLocationAndCaptureId()
{
if (bpartnerLocationId == null)
{
throw new AdempiereException("Cannot convert " + this + " to " + BPartnerLocationAndCaptureId.class.getSimpleName() + " because bpartnerLocationId is null");
}
return BPartnerLocationAndCaptureId.of(bpartnerLocationId, locationId);
}
public DocumentLocation withContactId(@Nullable final BPartnerContactId contactId)
{
return !Objects.equals(this.contactId, contactId)
? toBuilder().contactId(contactId).build()
: this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\location\DocumentLocation.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Step zappStep1(StepBuilderFactory stepBuilderFactory,
@Qualifier("appReader") ItemReader<App> reader,
@Qualifier("appWriter") ItemWriter<App> writer,
@Qualifier("appProcessor") ItemProcessor<App, App> processor) {
return stepBuilderFactory
.get("zappStep1")
.<App, App>chunk(5000)//批处理每次提交5000条数据
.reader(reader)//给step绑定reader
.processor(processor)//给step绑定processor
.writer(writer)//给step绑定writer
.faultTolerant()
.retry(Exception.class) // 重试
.noRetry(ParseException.class)
.retryLimit(1) //每条记录重试一次
.skip(Exception.class)
|
.skipLimit(200) //一共允许跳过200次异常
// .taskExecutor(new SimpleAsyncTaskExecutor()) //设置每个Job通过并发方式执行,一般来讲一个Job就让它串行完成的好
// .throttleLimit(10) //并发任务数为 10,默认为4
.build();
}
@Bean
public Validator<App> csvBeanValidator() {
return new MyBeanValidator<>();
}
}
|
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\zapp\AppConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public OffsetDateTime getUpdated() {
return updated;
}
public void setUpdated(OffsetDateTime updated) {
this.updated = updated;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OrderedArticleLine orderedArticleLine = (OrderedArticleLine) o;
return Objects.equals(this._id, orderedArticleLine._id) &&
Objects.equals(this.salesLineId, orderedArticleLine.salesLineId) &&
Objects.equals(this.articleId, orderedArticleLine.articleId) &&
Objects.equals(this.articleCustomerNumber, orderedArticleLine.articleCustomerNumber) &&
Objects.equals(this.quantity, orderedArticleLine.quantity) &&
Objects.equals(this.unit, orderedArticleLine.unit) &&
Objects.equals(this.duration, orderedArticleLine.duration) &&
Objects.equals(this.isRentalEquipment, orderedArticleLine.isRentalEquipment) &&
Objects.equals(this.isPrivateSale, orderedArticleLine.isPrivateSale) &&
Objects.equals(this.updated, orderedArticleLine.updated);
}
@Override
public int hashCode() {
return Objects.hash(_id, salesLineId, articleId, articleCustomerNumber, quantity, unit, duration, isRentalEquipment, isPrivateSale, updated);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class OrderedArticleLine {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" salesLineId: ").append(toIndentedString(salesLineId)).append("\n");
sb.append(" articleId: ").append(toIndentedString(articleId)).append("\n");
sb.append(" articleCustomerNumber: ").append(toIndentedString(articleCustomerNumber)).append("\n");
|
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append(" unit: ").append(toIndentedString(unit)).append("\n");
sb.append(" duration: ").append(toIndentedString(duration)).append("\n");
sb.append(" isRentalEquipment: ").append(toIndentedString(isRentalEquipment)).append("\n");
sb.append(" isPrivateSale: ").append(toIndentedString(isPrivateSale)).append("\n");
sb.append(" updated: ").append(toIndentedString(updated)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderedArticleLine.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Date read(JsonReader in) throws IOException {
try {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try {
if (dateFormat != null) {
return dateFormat.parse(date);
}
return ISO8601Utils.parse(date, new ParsePosition(0));
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
} catch (IllegalArgumentException e) {
throw new JsonParseException(e);
|
}
}
}
public JSON setDateFormat(DateFormat dateFormat) {
dateTypeAdapter.setFormat(dateFormat);
return this;
}
public JSON setSqlDateFormat(DateFormat dateFormat) {
sqlDateTypeAdapter.setFormat(dateFormat);
return this;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\JSON.java
| 2
|
请完成以下Java代码
|
public abstract class DraftInventoryBase extends JavaProcess implements IProcessPrecondition
{
private final InventoryService inventoryService = SpringContextHolder.instance.getBean(InventoryService.class);
@Override
final public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final I_M_Inventory inventory = context.getSelectedModel(I_M_Inventory.class);
if (inventory.isProcessed())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("inventory is processed");
}
return ProcessPreconditionsResolution.accept();
}
|
@Override
final protected String doIt()
{
final Inventory inventory = inventoryService.getById(InventoryId.ofRepoId(getRecord_ID()));
final DraftInventoryLinesCreateResponse response = inventoryService.createDraftLines(
DraftInventoryLinesCreateRequest.builder()
.inventory(inventory)
.strategy(createStrategy(inventory))
.build()
);
return "@Created@/@Updated@ #" + response.getCountInventoryLines();
}
protected abstract HUsForInventoryStrategy createStrategy(Inventory inventory);
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\process\DraftInventoryBase.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getPAYMENTMETHODE() {
return paymentmethode;
}
/**
* Sets the value of the paymentmethode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPAYMENTMETHODE(String value) {
this.paymentmethode = value;
}
/**
* Gets the value of the termsdatefrom property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTERMSDATEFROM() {
return termsdatefrom;
}
/**
* Sets the value of the termsdatefrom property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTERMSDATEFROM(String value) {
this.termsdatefrom = value;
}
/**
* Gets the value of the termsdateto property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTERMSDATETO() {
return termsdateto;
}
/**
* Sets the value of the termsdateto property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTERMSDATETO(String value) {
this.termsdateto = value;
}
/**
* Gets the value of the discountpercent property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDISCOUNTPERCENT() {
return discountpercent;
}
/**
* Sets the value of the discountpercent property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDISCOUNTPERCENT(String value) {
this.discountpercent = value;
}
/**
|
* Gets the value of the discountamount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDISCOUNTAMOUNT() {
return discountamount;
}
/**
* Sets the value of the discountamount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDISCOUNTAMOUNT(String value) {
this.discountamount = value;
}
/**
* Gets the value of the paymentdesc property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPAYMENTDESC() {
return paymentdesc;
}
/**
* Sets the value of the paymentdesc property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPAYMENTDESC(String value) {
this.paymentdesc = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HPAYT1.java
| 2
|
请完成以下Java代码
|
public ChargeAccounts getAccounts(@NonNull final ChargeId chargeId, @NonNull final AcctSchemaId acctSchemaId)
{
final ImmutableMap<AcctSchemaId, ChargeAccounts> map = cache.getOrLoad(chargeId, this::retrieveAccounts);
final ChargeAccounts accounts = map.get(acctSchemaId);
if (accounts == null)
{
throw new AdempiereException("No Charge accounts defined for " + chargeId + " and " + acctSchemaId);
}
return accounts;
}
private ImmutableMap<AcctSchemaId, ChargeAccounts> retrieveAccounts(@NonNull final ChargeId chargeId)
{
return queryBL.createQueryBuilder(I_C_Charge_Acct.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Charge_Acct.COLUMNNAME_C_Charge_ID, chargeId)
|
.create()
.stream()
.map(ChargeAccountsRepository::fromRecord)
.collect(ImmutableMap.toImmutableMap(ChargeAccounts::getAcctSchemaId, accounts -> accounts));
}
@NonNull
private static ChargeAccounts fromRecord(@NonNull final I_C_Charge_Acct record)
{
return ChargeAccounts.builder()
.acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()))
.Ch_Expense_Acct(Account.of(AccountId.ofRepoId(record.getCh_Expense_Acct()), I_C_Charge_Acct.COLUMNNAME_Ch_Expense_Acct))
.Ch_Revenue_Acct(Account.of(AccountId.ofRepoId(record.getCh_Revenue_Acct()), I_C_Charge_Acct.COLUMNNAME_Ch_Revenue_Acct))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\ChargeAccountsRepository.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.