instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
protected static void handleTaskCountsForIdentityLinkDeletion(TaskEntity taskEntity, IdentityLinkEntity identityLink) {
if (CountingEntityUtil.isTaskRelatedEntityCountEnabledGlobally()) {
CountingTaskEntity countingTaskEntity = (CountingTaskEntity) taskEntity;
if (CountingEntityUtil.isTaskRelatedEntityCountEnabled(countingTaskEntity)) {
countingTaskEntity.setIdentityLinkCount(countingTaskEntity.getIdentityLinkCount() - 1);
}
}
}
protected static void logTaskIdentityLinkEvent(String eventType, TaskEntity taskEntity, IdentityLinkEntity identityLinkEntity) {
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration();
TaskServiceConfiguration taskServiceConfiguration = processEngineConfiguration.getTaskServiceConfiguration();
if (taskServiceConfiguration.isEnableHistoricTaskLogging()) {
BaseHistoricTaskLogEntryBuilderImpl taskLogEntryBuilder = new BaseHistoricTaskLogEntryBuilderImpl(taskEntity);
ObjectNode data = processEngineConfiguration.getObjectMapper().createObjectNode();
|
if (identityLinkEntity.isUser()) {
data.put("userId", identityLinkEntity.getUserId());
} else if (identityLinkEntity.isGroup()) {
data.put("groupId", identityLinkEntity.getGroupId());
}
data.put("type", identityLinkEntity.getType());
taskLogEntryBuilder.timeStamp(taskServiceConfiguration.getClock().getCurrentTime());
taskLogEntryBuilder.userId(Authentication.getAuthenticatedUserId());
taskLogEntryBuilder.data(data.toString());
taskLogEntryBuilder.type(eventType);
taskServiceConfiguration.getInternalHistoryTaskManager().recordHistoryUserTaskLog(taskLogEntryBuilder);
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\IdentityLinkUtil.java
| 1
|
请完成以下Java代码
|
public class OptionFormField extends FormField {
private static final long serialVersionUID = 1L;
protected String optionType;
protected Boolean hasEmptyValue;
protected List<Option> options;
protected String optionsExpression;
public String getOptionType() {
return optionType;
}
public void setOptionType(String optionType) {
this.optionType = optionType;
}
public Boolean getHasEmptyValue() {
return hasEmptyValue;
}
public void setHasEmptyValue(Boolean hasEmptyValue) {
this.hasEmptyValue = hasEmptyValue;
}
public List<Option> getOptions() {
|
return options;
}
public void setOptions(List<Option> options) {
this.options = options;
}
public String getOptionsExpression() {
return optionsExpression;
}
public void setOptionsExpression(String optionsExpression) {
this.optionsExpression = optionsExpression;
}
}
|
repos\flowable-engine-main\modules\flowable-form-model\src\main\java\org\flowable\form\model\OptionFormField.java
| 1
|
请完成以下Java代码
|
public static ConstantWorkpackagePrio urgent()
{
return prio2strategy.get(X_C_Queue_WorkPackage.PRIORITY_Urgent);
}
public static ConstantWorkpackagePrio high()
{
return prio2strategy.get(X_C_Queue_WorkPackage.PRIORITY_High);
}
public static ConstantWorkpackagePrio medium()
{
return prio2strategy.get(X_C_Queue_WorkPackage.PRIORITY_Medium);
}
public static ConstantWorkpackagePrio low()
{
return prio2strategy.get(X_C_Queue_WorkPackage.PRIORITY_Low);
}
public static ConstantWorkpackagePrio minor()
{
return prio2strategy.get(X_C_Queue_WorkPackage.PRIORITY_Minor);
}
public static ConstantWorkpackagePrio fromString(final String string)
{
return prio2strategy.get(string.toLowerCase());
}
@Override
public String getPrioriy(IWorkPackageQueue IGNORED)
|
{
return getPriority();
}
public String getPriority()
{
return prio;
}
@Override
public String toString()
{
return "ConstantWorkpackagePrio[" + prio + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\impl\ConstantWorkpackagePrio.java
| 1
|
请完成以下Java代码
|
public class ZxingBarcodeGeneratorWithText {
public static BufferedImage createQRwithText(String data, String topText, String bottomText) throws WriterException, IOException {
QRCodeWriter barcodeWriter = new QRCodeWriter();
BitMatrix matrix = barcodeWriter.encode(data, BarcodeFormat.QR_CODE, 200, 200);
return modifiedQRCode(matrix, topText, bottomText);
}
public static BufferedImage modifiedQRCode(BitMatrix matrix, String topText, String bottomText) throws IOException {
int matrixWidth = matrix.getWidth();
int matrixHeight = matrix.getHeight();
BufferedImage image = new BufferedImage(matrixWidth, matrixHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixHeight);
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++) {
for (int j = 0; j < matrixHeight; j++) {
if (matrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
|
FontMetrics fontMetrics = graphics.getFontMetrics();
int topTextWidth = fontMetrics.stringWidth(topText);
int bottomTextWidth = fontMetrics.stringWidth(bottomText);
int finalWidth = Math.max(matrixWidth, Math.max(topTextWidth, bottomTextWidth)) + 1;
int finalHeight = matrixHeight + fontMetrics.getHeight() + fontMetrics.getAscent() + 1;
BufferedImage finalImage = new BufferedImage(finalWidth, finalHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D finalGraphics = finalImage.createGraphics();
finalGraphics.setColor(Color.WHITE);
finalGraphics.fillRect(0, 0, finalWidth, finalHeight);
finalGraphics.setColor(Color.BLACK);
finalGraphics.drawImage(image, (finalWidth - matrixWidth) / 2, fontMetrics.getAscent() + 2, null);
finalGraphics.drawString(topText, (finalWidth - topTextWidth) / 2, fontMetrics.getAscent() + 2);
finalGraphics.drawString(bottomText, (finalWidth - bottomTextWidth) / 2, finalHeight - fontMetrics.getDescent() - 2);
return finalImage;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-libraries\src\main\java\com\baeldung\barcodes\generators\ZxingBarcodeGeneratorWithText.java
| 1
|
请完成以下Java代码
|
public Map<String, Collection<ITableRecordReference>> getRecords()
{
return records;
}
public Collection<ITableRecordReference> getRecordsWithTable(final String referencedTableName)
{
return records.getOrDefault(referencedTableName, Collections.emptyList());
}
public boolean isRecordsChanged()
{
return recordsChanged;
}
public boolean isComplete()
{
return complete;
}
public PartitionConfig getConfig()
{
return config;
}
public boolean isConfigChanged()
{
return configChanged;
}
public int getTargetDLMLevel()
{
return targetDLMLevel;
}
public int getCurrentDLMLevel()
{
return currentDLMLevel;
}
public Timestamp getNextInspectionDate()
{
return nextInspectionDate;
}
public int getDLM_Partition_ID()
{
return DLM_Partition_ID;
}
public boolean isAborted()
{
return aborted;
}
@Override
public String toString()
{
|
return "Partition [DLM_Partition_ID=" + DLM_Partition_ID + ", records.size()=" + records.size() + ", recordsChanged=" + recordsChanged + ", configChanged=" + configChanged + ", targetDLMLevel=" + targetDLMLevel + ", currentDLMLevel=" + currentDLMLevel + ", nextInspectionDate=" + nextInspectionDate + "]";
}
public static class WorkQueue
{
public static WorkQueue of(final I_DLM_Partition_Workqueue workqueueDB)
{
final ITableRecordReference tableRecordRef = TableRecordReference.ofReferencedOrNull(workqueueDB);
final WorkQueue result = new WorkQueue(tableRecordRef);
result.setDLM_Partition_Workqueue_ID(workqueueDB.getDLM_Partition_Workqueue_ID());
return result;
}
public static WorkQueue of(final ITableRecordReference tableRecordRef)
{
return new WorkQueue(tableRecordRef);
}
private final ITableRecordReference tableRecordReference;
private int dlmPartitionWorkqueueId;
private WorkQueue(final ITableRecordReference tableRecordReference)
{
this.tableRecordReference = tableRecordReference;
}
public ITableRecordReference getTableRecordReference()
{
return tableRecordReference;
}
public int getDLM_Partition_Workqueue_ID()
{
return dlmPartitionWorkqueueId;
}
public void setDLM_Partition_Workqueue_ID(final int dlm_Partition_Workqueue_ID)
{
dlmPartitionWorkqueueId = dlm_Partition_Workqueue_ID;
}
@Override
public String toString()
{
return "Partition.WorkQueue [DLM_Partition_Workqueue_ID=" + dlmPartitionWorkqueueId + ", tableRecordReference=" + tableRecordReference + "]";
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\Partition.java
| 1
|
请完成以下Java代码
|
protected Row computeNext() {
maybeMoveToNextPage();
return currentRows.hasNext() ? currentRows.next() : endOfData();
}
private void maybeMoveToNextPage() {
if (!currentRows.hasNext() && currentPage.hasMorePages()) {
BlockingOperation.checkNotDriverThread();
ByteBuffer nextPagingState = currentPage.getExecutionInfo().getPagingState();
this.statement = this.statement.setPagingState(nextPagingState);
AsyncResultSet nextPage = GuavaSession.getSafe(this.session.executeAsync(this.statement));
currentPage = nextPage;
remaining += nextPage.remaining();
currentRows = nextPage.currentPage().iterator();
executionInfos.add(nextPage.getExecutionInfo());
|
// The definitions can change from page to page if this result set was built from a bound
// 'SELECT *', and the schema was altered.
columnDefinitions = nextPage.getColumnDefinitions();
}
}
private boolean isFullyFetched() {
return !currentPage.hasMorePages();
}
private boolean wasApplied() {
return currentPage.wasApplied();
}
}
}
|
repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\cassandra\guava\GuavaMultiPageResultSet.java
| 1
|
请完成以下Java代码
|
public class CarServiceEjbSingleton {
private static Logger LOG = LoggerFactory.getLogger(CarServiceEjbSingleton.class);
private UUID id = UUID.randomUUID();
private static int serviceQueue;
public UUID getId() {
return this.id;
}
@Override
public String toString() {
return "CarServiceEjbSingleton [id=" + id + "]";
}
public int service(Car car) {
|
serviceQueue++;
LOG.info("Car {} is being serviced @ CarServiceEjbSingleton - serviceQueue: {}", car, serviceQueue);
simulateService(car);
serviceQueue--;
LOG.info("Car service for {} is completed - serviceQueue: {}", car, serviceQueue);
return serviceQueue;
}
private void simulateService(Car car) {
try {
Thread.sleep(100);
car.setServiced(true);
} catch (InterruptedException e) {
LOG.error("CarServiceEjbSingleton::InterruptedException: {}", e);
}
}
}
|
repos\tutorials-master\web-modules\jee-7\src\main\java\com\baeldung\singleton\CarServiceEjbSingleton.java
| 1
|
请完成以下Java代码
|
protected EventSubscriptionEntityManager getEventSubscriptionEntityManager() {
return getProcessEngineConfiguration().getEventSubscriptionEntityManager();
}
protected VariableInstanceEntityManager getVariableInstanceEntityManager() {
return getProcessEngineConfiguration().getVariableInstanceEntityManager();
}
protected JobEntityManager getJobEntityManager() {
return getProcessEngineConfiguration().getJobEntityManager();
}
protected TimerJobEntityManager getTimerJobEntityManager() {
return getProcessEngineConfiguration().getTimerJobEntityManager();
}
protected SuspendedJobEntityManager getSuspendedJobEntityManager() {
return getProcessEngineConfiguration().getSuspendedJobEntityManager();
}
protected DeadLetterJobEntityManager getDeadLetterJobEntityManager() {
return getProcessEngineConfiguration().getDeadLetterJobEntityManager();
}
protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricProcessInstanceEntityManager();
}
protected HistoricDetailEntityManager getHistoricDetailEntityManager() {
return getProcessEngineConfiguration().getHistoricDetailEntityManager();
}
protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricActivityInstanceEntityManager();
}
protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricVariableInstanceEntityManager();
}
|
protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricTaskInstanceEntityManager();
}
protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return getProcessEngineConfiguration().getHistoricIdentityLinkEntityManager();
}
protected AttachmentEntityManager getAttachmentEntityManager() {
return getProcessEngineConfiguration().getAttachmentEntityManager();
}
protected CommentEntityManager getCommentEntityManager() {
return getProcessEngineConfiguration().getCommentEntityManager();
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\AbstractManager.java
| 1
|
请完成以下Java代码
|
private void doPress (JLabel label)
{
Component labelFor = label.getLabelFor ();
if (labelFor != null && labelFor.isEnabled ())
{
Component owner = label.getLabelFor ();
if (owner instanceof Container
&& ((Container)owner).isFocusCycleRoot ())
{
owner.requestFocus ();
}
else
{
if (owner instanceof Container)
{
Container container = (Container)owner;
if (container.isFocusCycleRoot())
{
FocusTraversalPolicy policy = container.getFocusTraversalPolicy();
Component comp = policy.getDefaultComponent(container);
if (comp != null)
{
comp.requestFocus();
return;
}
}
Container rootAncestor = container.getFocusCycleRootAncestor();
if (rootAncestor != null)
{
FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy();
Component comp = policy.getComponentAfter(rootAncestor, container);
if (comp != null && SwingUtilities.isDescendingFrom(comp, container))
{
comp.requestFocus();
return;
|
}
}
}
if (owner.isFocusable())
{
owner.requestFocus();
return;
}
// No Forcus
}
}
} // doPress
} // PressAction
} // AdempiereLabelUI
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereLabelUI.java
| 1
|
请完成以下Java代码
|
public void mouseEntered(MouseEvent e) {
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
*/
@Override
public void mouseExited(MouseEvent e) {
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
*/
@Override
public void mousePressed(MouseEvent e) {
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
*/
@Override
public void mouseReleased(MouseEvent e) {
}
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == mRefresh)
{
if (m_goals != null)
{
for (MGoal m_goal : m_goals)
{
m_goal.updateGoal(true);
}
}
htmlUpdate(lastUrl);
Container parent = getParent();
if (parent != null)
{
parent.invalidate();
}
invalidate();
if (parent != null)
{
parent.repaint();
}
else
{
repaint();
}
|
}
}
class PageLoader implements Runnable
{
private JEditorPane html;
private URL url;
private Cursor cursor;
PageLoader( JEditorPane html, URL url, Cursor cursor )
{
this.html = html;
this.url = url;
this.cursor = cursor;
}
@Override
public void run()
{
if( url == null )
{
// restore the original cursor
html.setCursor( cursor );
// PENDING(prinz) remove this hack when
// automatic validation is activated.
Container parent = html.getParent();
parent.repaint();
}
else
{
Document doc = html.getDocument();
try {
html.setPage( url );
}
catch( IOException ioe )
{
html.setDocument( doc );
}
finally
{
// schedule the cursor to revert after
// the paint has happended.
url = null;
SwingUtilities.invokeLater( this );
}
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\apps\graph\HtmlDashboard.java
| 1
|
请完成以下Java代码
|
private static class DefaultRetrieveSubscriptionSpec extends RetrieveSpecSupport implements RetrieveSubscriptionSpec {
private final Flux<ClientGraphQlResponse> responseFlux;
DefaultRetrieveSubscriptionSpec(Flux<ClientGraphQlResponse> responseFlux, String path) {
super(path);
this.responseFlux = responseFlux;
}
@SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290
@Override
public <D> Flux<D> toEntity(Class<D> entityType) {
return this.responseFlux.mapNotNull(this::getValidField).mapNotNull((field) -> field.toEntity(entityType));
}
@SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290
@Override
public <D> Flux<D> toEntity(ParameterizedTypeReference<D> entityType) {
return this.responseFlux.mapNotNull(this::getValidField).mapNotNull((field) -> field.toEntity(entityType));
}
@Override
public <D> Flux<List<D>> toEntityList(Class<D> elementType) {
return this.responseFlux.map((response) -> {
ClientResponseField field = getValidField(response);
|
return (field != null) ? field.toEntityList(elementType) : Collections.emptyList();
});
}
@Override
public <D> Flux<List<D>> toEntityList(ParameterizedTypeReference<D> elementType) {
return this.responseFlux.map((response) -> {
ClientResponseField field = getValidField(response);
return (field != null) ? field.toEntityList(elementType) : Collections.emptyList();
});
}
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultGraphQlClient.java
| 1
|
请完成以下Java代码
|
public boolean exists() {
return this.delegate.exists();
}
@Override
public Spliterator<Resource> spliterator() {
return this.delegate.spliterator();
}
@Override
public boolean isDirectory() {
return this.delegate.isDirectory();
}
@Override
public boolean isReadable() {
return this.delegate.isReadable();
}
@Override
public Instant lastModified() {
return this.delegate.lastModified();
}
@Override
public long length() {
return this.delegate.length();
}
@Override
public URI getURI() {
return this.delegate.getURI();
}
@Override
public String getName() {
return this.delegate.getName();
}
@Override
public String getFileName() {
return this.delegate.getFileName();
}
@Override
public InputStream newInputStream() throws IOException {
return this.delegate.newInputStream();
}
@Override
@SuppressWarnings({ "deprecation", "removal" })
public ReadableByteChannel newReadableByteChannel() throws IOException {
return this.delegate.newReadableByteChannel();
}
@Override
public List<Resource> list() {
return asLoaderHidingResources(this.delegate.list());
}
private boolean nonLoaderResource(Resource resource) {
return !resource.getPath().startsWith(this.loaderBasePath);
}
private List<Resource> asLoaderHidingResources(Collection<Resource> resources) {
return resources.stream().filter(this::nonLoaderResource).map(this::asLoaderHidingResource).toList();
}
|
private Resource asLoaderHidingResource(Resource resource) {
return (resource instanceof LoaderHidingResource) ? resource : new LoaderHidingResource(this.base, resource);
}
@Override
public @Nullable Resource resolve(String subUriPath) {
if (subUriPath.startsWith(LOADER_RESOURCE_PATH_PREFIX)) {
return null;
}
Resource resolved = this.delegate.resolve(subUriPath);
return (resolved != null) ? new LoaderHidingResource(this.base, resolved) : null;
}
@Override
public boolean isAlias() {
return this.delegate.isAlias();
}
@Override
public URI getRealURI() {
return this.delegate.getRealURI();
}
@Override
public void copyTo(Path destination) throws IOException {
this.delegate.copyTo(destination);
}
@Override
public Collection<Resource> getAllResources() {
return asLoaderHidingResources(this.delegate.getAllResources());
}
@Override
public String toString() {
return this.delegate.toString();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\servlet\LoaderHidingResource.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
public List<String> getIds() {
return ids;
}
public String getTokenValue() {
return tokenValue;
}
public Date getTokenDate() {
return tokenDate;
}
public Date getTokenDateBefore() {
return tokenDateBefore;
}
public Date getTokenDateAfter() {
return tokenDateAfter;
}
public String getIpAddress() {
return ipAddress;
}
public String getIpAddressLike() {
return ipAddressLike;
}
|
public String getUserAgent() {
return userAgent;
}
public String getUserAgentLike() {
return userAgentLike;
}
public String getUserId() {
return userId;
}
public String getUserIdLike() {
return userIdLike;
}
public String getTokenData() {
return tokenData;
}
public String getTokenDataLike() {
return tokenDataLike;
}
}
|
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\TokenQueryImpl.java
| 1
|
请完成以下Java代码
|
public static <V> V getAndValidate(@NonNull final Properties ctx, final String propertyName, final Predicate<V> validator, final Supplier<V> valueInitializer)
{
// NOTE: we a synchronizing on "ctx" because the Hashtable methods of "Properties ctx" are declared as "synchronized"
// and we want to get the same effect and synchronize with them.
synchronized (ctx)
{
// Get the existing value. We assume it has the type "V".
@SuppressWarnings("unchecked")
V value = (V)ctx.get(propertyName);
// Check if cached value it's still valid
if (validator != null && value != null && !validator.test(value))
{
ctx.remove(propertyName);
value = null;
}
// Initialize the value if needed
if (value == null && valueInitializer != null)
{
value = valueInitializer.get();
ctx.put(propertyName, value);
}
return value;
}
}
public static <V> V getAndRemove(final Properties ctx, final String propertyName)
{
@SuppressWarnings("unchecked") final V value = (V)ctx.remove(propertyName);
return value;
}
public static void put(final Properties ctx, final String propertyName, final Object value)
{
ctx.put(propertyName, value);
|
}
/**
* Checks if given key is contained in context.
* <p>
* WARNING: this method is NOT checking the key exists in underlying "defaults". Before changing this please check the API which depends on this logic
*
* @return true if given key is contained in context
*/
public static boolean containsKey(final Properties ctx, final String key)
{
return ctx.containsKey(key);
}
/**
* Returns given <code>ctx</code> or {@link #getCtx()} if null.
*
* @return ctx or {@link #getCtx()}; never returns null
*/
public static Properties coalesce(@Nullable final Properties ctx)
{
return ctx == null ? getCtx() : ctx;
}
} // Env
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Env.java
| 1
|
请完成以下Java代码
|
public Object getReferencedObject(final String propertyName, final Method interfaceMethod) throws Exception
{
final Class<?> returnType = interfaceMethod.getReturnType();
return po.get_ValueAsPO(propertyName, returnType);
}
@Override
public void setValueFromPO(final String idPropertyName, final Class<?> parameterType, final Object value)
{
po.set_ValueFromPO(idPropertyName, parameterType, value);
}
@Override
public boolean invokeEquals(final Object[] methodArgs)
{
if (methodArgs == null || methodArgs.length != 1)
{
throw new IllegalArgumentException("Invalid method arguments to be used for equals(): " + methodArgs);
}
return po.equals(methodArgs[0]);
}
@Override
public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception
|
{
return method.invoke(po, methodArgs);
}
@Override
public boolean isCalculated(final String columnName)
{
return getPOInfo().isCalculated(columnName);
}
@Override
public boolean hasColumnName(final String columnName)
{
return getPOInfo().hasColumnName(columnName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POModelInternalAccessor.java
| 1
|
请完成以下Java代码
|
private Map<ColumnNamePair, Object> extractModelValues(final Object model)
{
final Map<ColumnNamePair, Object> modelValues = new HashMap<>();
for (final ColumnNamePair matcher : matchers)
{
final String columnName = matcher.getColumnName();
final IQueryFilterModifier modifier = matcher.getModifier();
final Object modelValue0 = InterfaceWrapperHelper.getValue(model, columnName).orElse(null);
final Object modelValue = modifier.convertValue(columnName, modelValue0, model);
modelValues.put(matcher, modelValue);
}
return modelValues;
}
private List<Map<ColumnNamePair, Object>> getSubQueryValues(final T contextModel)
{
if (_subQueryValues != null)
{
return _subQueryValues;
}
final List<?> subQueryResult = subQuery.list();
final List<Map<ColumnNamePair, Object>> subQueryValues = new ArrayList<>(subQueryResult.size());
for (final Object subModel : subQueryResult)
{
final Map<ColumnNamePair, Object> subModelValues = new HashMap<>();
for (final ColumnNamePair matcher : matchers)
{
final String subQueryColumnName = matcher.getSubQueryColumnName();
final IQueryFilterModifier modifier = matcher.getModifier();
final Object value0 = InterfaceWrapperHelper.getValue(subModel, subQueryColumnName).orElse(null);
final Object value = modifier.convertValue(IQueryFilterModifier.COLUMNNAME_Constant, value0, contextModel);
subModelValues.put(matcher, value);
}
subQueryValues.add(subModelValues);
}
this._subQueryValues = subQueryValues;
return subQueryValues;
}
@lombok.Value
@lombok.Builder
private static final class ColumnNamePair
{
@lombok.NonNull
String columnName;
@lombok.NonNull
String subQueryColumnName;
@lombok.NonNull
IQueryFilterModifier modifier;
}
|
public static final class Builder<T>
{
private String tableName;
private final List<ColumnNamePair> matchers = new ArrayList<>();
private IQuery<?> subQuery;
private Builder()
{
}
public InSubQueryFilter<T> build()
{
return new InSubQueryFilter<>(this);
}
public Builder<T> tableName(final String tableName)
{
this.tableName = tableName;
return this;
}
public Builder<T> subQuery(final IQuery<?> subQuery)
{
this.subQuery = subQuery;
return this;
}
public Builder<T> matchingColumnNames(final String columnName, final String subQueryColumnName, final IQueryFilterModifier modifier)
{
matchers.add(ColumnNamePair.builder()
.columnName(columnName)
.subQueryColumnName(subQueryColumnName)
.modifier(modifier)
.build());
return this;
}
public Builder<T> matchingColumnNames(final String columnName, final String subQueryColumnName)
{
return matchingColumnNames(columnName, subQueryColumnName, NullQueryFilterModifier.instance);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\InSubQueryFilter.java
| 1
|
请完成以下Java代码
|
public HistoricProcessInstanceQuery active() {
if(!isOrQueryActive) {
ensureEmpty(BadUserRequestException.class, "Already querying for historic process instance with another state", state);
}
state.add(HistoricProcessInstance.STATE_ACTIVE);
return this;
}
@Override
public HistoricProcessInstanceQuery suspended() {
if(!isOrQueryActive) {
ensureEmpty(BadUserRequestException.class, "Already querying for historic process instance with another state", state);
}
state.add(HistoricProcessInstance.STATE_SUSPENDED);
return this;
}
@Override
public HistoricProcessInstanceQuery completed() {
if(!isOrQueryActive) {
ensureEmpty(BadUserRequestException.class, "Already querying for historic process instance with another state", state);
}
state.add(HistoricProcessInstance.STATE_COMPLETED);
return this;
}
@Override
public HistoricProcessInstanceQuery externallyTerminated() {
if(!isOrQueryActive) {
ensureEmpty(BadUserRequestException.class, "Already querying for historic process instance with another state", state);
}
state.add(HistoricProcessInstance.STATE_EXTERNALLY_TERMINATED);
return this;
}
@Override
public HistoricProcessInstanceQuery internallyTerminated() {
if(!isOrQueryActive) {
ensureEmpty(BadUserRequestException.class, "Already querying for historic process instance with another state", state);
|
}
state.add(HistoricProcessInstance.STATE_INTERNALLY_TERMINATED);
return this;
}
@Override
public HistoricProcessInstanceQuery or() {
if (this != queries.get(0)) {
throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query");
}
HistoricProcessInstanceQueryImpl orQuery = new HistoricProcessInstanceQueryImpl();
orQuery.isOrQueryActive = true;
orQuery.queries = queries;
queries.add(orQuery);
return orQuery;
}
@Override
public HistoricProcessInstanceQuery endOr() {
if (!queries.isEmpty() && this != queries.get(queries.size()-1)) {
throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()");
}
return queries.get(0);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricProcessInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public void setC_Payment_ID (int C_Payment_ID)
{
if (C_Payment_ID < 1)
set_Value (COLUMNNAME_C_Payment_ID, null);
else
set_Value (COLUMNNAME_C_Payment_ID, Integer.valueOf(C_Payment_ID));
}
/** Get Payment.
@return Payment identifier
*/
public int getC_Payment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Payment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Not Committed Aount.
@param NonCommittedAmt
Amount not committed yet
*/
public void setNonCommittedAmt (BigDecimal NonCommittedAmt)
|
{
set_Value (COLUMNNAME_NonCommittedAmt, NonCommittedAmt);
}
/** Get Not Committed Aount.
@return Amount not committed yet
*/
public BigDecimal getNonCommittedAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_NonCommittedAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_SellerFunds.java
| 1
|
请完成以下Java代码
|
private RequestTypeId getRequestTypeId(final SOTrx soTrx)
{
return soTrx.isSales()
? requestTypeDAO.retrieveCustomerRequestTypeId()
: requestTypeDAO.retrieveVendorRequestTypeId();
}
@Override
public I_R_Request createRequestFromDDOrderLine(@NonNull final I_DD_OrderLine ddOrderLine)
{
final I_DD_Order ddOrder = ddOrderLine.getDD_Order();
final RequestTypeId requestTypeId = getRequestTypeId(SOTrx.ofBoolean(ddOrder.isSOTrx()));
final RequestCandidate requestCandidate = RequestCandidate.builder()
.summary(ddOrderLine.getDescription()) // TODO: Decide what to put here
.confidentialType(RequestConfidentialType.Internal)
.orgId(OrgId.ofRepoId(ddOrderLine.getAD_Org_ID()))
.productId(ProductId.ofRepoId(ddOrderLine.getM_Product_ID()))
.recordRef(TableRecordReference.of(ddOrder))
.requestTypeId(requestTypeId)
.partnerId(BPartnerId.ofRepoId(ddOrder.getC_BPartner_ID()))
.userId(UserId.ofRepoIdOrNull(ddOrder.getAD_User_ID()))
.dateDelivered(TimeUtil.asZonedDateTime(ddOrder.getDatePromised()))
.build();
return createRequest(requestCandidate);
}
@Override
public I_R_Request createRequestFromOrder(@NonNull final I_C_Order order)
{
final Optional<RequestTypeId> requestType = orderBL.getRequestTypeForCreatingNewRequestsAfterComplete(order);
|
final RequestCandidate requestCandidate = RequestCandidate.builder()
.summary(order.getDescription() != null ? order.getDescription() : " ")
.confidentialType(RequestConfidentialType.Internal)
.orgId(OrgId.ofRepoId(order.getAD_Org_ID()))
.recordRef(TableRecordReference.of(order))
.requestTypeId(requestType.orElseGet(() -> getRequestTypeId(SOTrx.ofBoolean(order.isSOTrx()))))
.partnerId(BPartnerId.ofRepoId(order.getC_BPartner_ID()))
.userId(UserId.ofRepoIdOrNull(order.getAD_User_ID()))
.dateDelivered(TimeUtil.asZonedDateTime(order.getDatePromised()))
.build();
return createRequest(requestCandidate);
}
@Override
public I_R_Request createRequest(final RequestCandidate requestCandidate)
{
return requestsRepo.createRequest(requestCandidate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\request\api\impl\RequestBL.java
| 1
|
请完成以下Java代码
|
public final boolean isAuthenticated() {
return !isAnonymous();
}
@Override
public final boolean isRememberMe() {
return trustResolver.isRememberMe(authentication);
}
@Override
public final boolean isFullyAuthenticated() {
return !trustResolver.isAnonymous(authentication) && !trustResolver.isRememberMe(authentication);
}
public Object getPrincipal() {
return authentication.getPrincipal();
}
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
this.trustResolver = trustResolver;
}
public void setRoleHierarchy(RoleHierarchy roleHierarchy) {
this.roleHierarchy = roleHierarchy;
}
public void setDefaultRolePrefix(String defaultRolePrefix) {
this.defaultRolePrefix = defaultRolePrefix;
}
private Set<String> getAuthoritySet() {
if (roles == null) {
Collection<? extends GrantedAuthority> userAuthorities = authentication.getAuthorities();
if (roleHierarchy != null) {
userAuthorities = roleHierarchy.getReachableGrantedAuthorities(userAuthorities);
}
roles = AuthorityUtils.authorityListToSet(userAuthorities);
}
return roles;
}
@Override
public boolean hasPermission(Object target, Object permission) {
return permissionEvaluator.hasPermission(authentication, target, permission);
}
@Override
public boolean hasPermission(Object targetId, String targetType, Object permission) {
return permissionEvaluator.hasPermission(authentication, (Serializable) targetId, targetType, permission);
}
public void setPermissionEvaluator(PermissionEvaluator permissionEvaluator) {
this.permissionEvaluator = permissionEvaluator;
}
private static String getRoleWithDefaultPrefix(String defaultRolePrefix, String role) {
if (role == null) {
return role;
}
if ((defaultRolePrefix == null) || (defaultRolePrefix.length() == 0)) {
return role;
}
if (role.startsWith(defaultRolePrefix)) {
|
return role;
}
return defaultRolePrefix + role;
}
@Override
public Object getFilterObject() {
return this.filterObject;
}
@Override
public Object getReturnObject() {
return this.returnObject;
}
@Override
public Object getThis() {
return this;
}
@Override
public void setFilterObject(Object obj) {
this.filterObject = obj;
}
@Override
public void setReturnObject(Object obj) {
this.returnObject = obj;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\security\MySecurityExpressionRoot.java
| 1
|
请完成以下Java代码
|
public class LdapUserQueryImpl extends UserQueryImpl {
private static final long serialVersionUID = 1L;
private final LdapConfiguration ldapConfiguration;
public LdapUserQueryImpl(LdapConfiguration ldapConfiguration) {
super();
this.ldapConfiguration = ldapConfiguration;
}
public LdapUserQueryImpl(CommandExecutor commandExecutor, LdapConfiguration ldapConfiguration) {
super(commandExecutor);
this.ldapConfiguration = ldapConfiguration;
}
// execute queries /////////////////////////////////////////
public long executeCount(CommandContext commandContext) {
final LdapIdentityProviderSession provider = getLdapIdentityProvider(commandContext);
return provider.findUserCountByQueryCriteria(this);
}
public List<User> executeList(CommandContext commandContext, Page page) {
final LdapIdentityProviderSession provider = getLdapIdentityProvider(commandContext);
return provider.findUserByQueryCriteria(this);
}
|
protected LdapIdentityProviderSession getLdapIdentityProvider(CommandContext commandContext) {
return (LdapIdentityProviderSession) commandContext.getReadOnlyIdentityProvider();
}
@Override
public UserQuery desc() {
// provide this exception then a popup will be visible in the admin task, but display will run correctly
if (ldapConfiguration != null && !ldapConfiguration.isSortControlSupported()) {
throw new UnsupportedOperationException("The LDAP identity provider does not support descending search order.");
}
return this;
}
}
|
repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\LdapUserQueryImpl.java
| 1
|
请完成以下Java代码
|
protected String getEngineVersion() {
return EventRegistryEngine.VERSION;
}
@Override
protected String getSchemaVersionPropertyName() {
return "eventregistry.schema.version";
}
@Override
protected String getDbSchemaLockName() {
return EVENTREGISTRY_DB_SCHEMA_LOCK_NAME;
}
@Override
protected String getEngineTableName() {
return "FLW_EVENT_DEFINITION";
}
@Override
protected String getChangeLogTableName() {
return "FLW_EV_DATABASECHANGELOG";
}
|
@Override
protected String getDbVersionForChangelogVersion(String changeLogVersion) {
if (StringUtils.isNotEmpty(changeLogVersion) && changeLogVersionMap.containsKey(changeLogVersion)) {
return changeLogVersionMap.get(changeLogVersion);
}
return "6.5.0.0";
}
@Override
protected String getResourcesRootDirectory() {
return "org/flowable/eventregistry/db/";
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\db\EventDbSchemaManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class User {
@Id
@GeneratedValue
private long id;
@Column(nullable = false)
private String username;
@Column(nullable = false)
private String password;
private int active;
private String roles ="";
private String permissions ="";
public User(){}
public User(String username, String password, String roles, String permissions) {
this.username = username;
this.password = password;
this.roles = roles;
this.permissions = permissions;
this.active = 1;
}
public void setId(long id) {
this.id = id;
}
public long getId(){
return id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
|
public void setPassword(String password) {
this.password = password;
}
public int getActive() {
return active;
}
public void setActive(int active) {
this.active = active;
}
public List<String> getRoleList() {
if(this.roles.length() > 0) {
return Arrays.asList(this.roles.split(","));
}
return new ArrayList<>();
}
public void setRoles(String roles) {
this.roles = roles;
}
public List<String> getPermissionList() {
if(this.permissions.length() > 0) {
return Arrays.asList(this.permissions.split(","));
}
return new ArrayList<>();
}
public void setPermissions(String permissions) {
this.permissions = permissions;
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\10.SpringCustomLogin\src\main\java\spring\custom\model\User.java
| 2
|
请完成以下Java代码
|
public MQMSpecificationLine[] getLines(String where)
{
if (m_lines != null)
return m_lines;
ArrayList<MQMSpecificationLine> list = new ArrayList<>();
String sql = "SELECT * FROM QM_SpecificationLine WHERE QM_SpecificationLine_ID=? AND "+ where +" ORDER BY Line";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getQM_Specification_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MQMSpecificationLine(getCtx(), rs, get_TrxName()));
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
log.error("getLines", e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
m_lines = new MQMSpecificationLine[list.size ()];
list.toArray (m_lines);
return m_lines;
} // getLines
public boolean isValid(int M_AttributeSetInstance_ID)
{
// TODO: check/uncomment/reimplement when it will be needed
// //MAttributeSet mas = MAttributeSet.get(getCtx(), getM_AttributeSet_ID());
//
//// Save Instance Attributes
//
// MAttributeSetInstance asi = new MAttributeSetInstance(getCtx(),M_AttributeSetInstance_ID, get_TrxName());
// MAttributeSet as = MAttributeSet.get(AttributeSetId.ofRepoId(asi.getM_AttributeSet_ID()));
// for (final I_M_Attribute attribute : as.getMAttributes(false))
// {
//
// //MAttribute attribute = new MAttribute(getCtx(),0,null);
|
// MAttributeInstance instance = attribute.getMAttributeInstance(M_AttributeSetInstance_ID);
// MQMSpecificationLine[] lines = getLines(" M_Attribute_ID="+attribute.getM_Attribute_ID());
// for (int s = 0; s < lines.length; i++)
// {
// MQMSpecificationLine line = lines[s];
// if (MAttribute.ATTRIBUTEVALUETYPE_Number.equals(attribute.getAttributeValueType()))
// {
// BigDecimal objValue = instance.getValueNumber();
// if(!line.evaluate(objValue,instance.getValue()));
// return false;
// }
// else
// {
// String objValue = instance.getValue();
// if(!line.evaluate(objValue,instance.getValue()))
// return false;
// }
// //if(line.evaluate(mas.getValueNumber())
// }
// } // for all attributes
return true;
}
} // MQMSpecification
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\MQMSpecification.java
| 1
|
请完成以下Java代码
|
public class X_M_QualityInsp_LagerKonf extends org.compiere.model.PO implements I_M_QualityInsp_LagerKonf, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = -1359568399L;
/** Standard Constructor */
public X_M_QualityInsp_LagerKonf (Properties ctx, int M_QualityInsp_LagerKonf_ID, String trxName)
{
super (ctx, M_QualityInsp_LagerKonf_ID, trxName);
/** if (M_QualityInsp_LagerKonf_ID == 0)
{
setM_QualityInsp_LagerKonf_ID (0);
setName (null);
} */
}
/** Load Constructor */
public X_M_QualityInsp_LagerKonf (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder ("X_M_QualityInsp_LagerKonf[")
.append(get_ID()).append("]");
return sb.toString();
}
|
/** Set Lagerkonferenz.
@param M_QualityInsp_LagerKonf_ID Lagerkonferenz */
@Override
public void setM_QualityInsp_LagerKonf_ID (int M_QualityInsp_LagerKonf_ID)
{
if (M_QualityInsp_LagerKonf_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_ID, Integer.valueOf(M_QualityInsp_LagerKonf_ID));
}
/** Get Lagerkonferenz.
@return Lagerkonferenz */
@Override
public int getM_QualityInsp_LagerKonf_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_QualityInsp_LagerKonf_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_QualityInsp_LagerKonf.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> clazz){
return applicationContext.getBean(clazz);
}
public static <T> T getBean(String name, Class<T> requiredType) {
|
return applicationContext.getBean(name, requiredType);
}
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
public static boolean isSingleton(String name) {
return applicationContext.isSingleton(name);
}
public static Class<?> getType(String name) {
return applicationContext.getType(name);
}
}
|
repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\utils\SpringContextUtil.java
| 2
|
请完成以下Java代码
|
static final class Builder implements org.apache.logging.log4j.core.util.Builder<SpringProfileArbiter> {
private static final Logger statusLogger = StatusLogger.getLogger();
@PluginBuilderAttribute
@SuppressWarnings("NullAway.Init")
private String name;
@PluginConfiguration
@SuppressWarnings("NullAway.Init")
private Configuration configuration;
@PluginLoggerContext
@SuppressWarnings("NullAway.Init")
private LoggerContext loggerContext;
private Builder() {
}
/**
* Sets the profile name or expression.
* @param name the profile name or expression
* @return this
* @see Profiles#of(String...)
*/
public Builder setName(String name) {
this.name = name;
return this;
}
@Override
public SpringProfileArbiter build() {
Environment environment = Log4J2LoggingSystem.getEnvironment(this.loggerContext);
if (environment == null) {
|
statusLogger.debug("Creating Arbiter without a Spring Environment");
}
String name = this.configuration.getStrSubstitutor().replace(this.name);
String[] profiles = trimArrayElements(StringUtils.commaDelimitedListToStringArray(name));
return new SpringProfileArbiter(environment, profiles);
}
// The array has no nulls in it, but StringUtils.trimArrayElements return
// @Nullable String[]
@SuppressWarnings("NullAway")
private String[] trimArrayElements(String[] array) {
return StringUtils.trimArrayElements(array);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\log4j2\SpringProfileArbiter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BankStatementId implements RepoIdAware
{
int repoId;
@NonNull
@JsonCreator
public static BankStatementId ofRepoId(final int repoId)
{
return new BankStatementId(repoId);
}
@Nullable
public static BankStatementId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static Optional<BankStatementId> optionalOfRepoId(final int repoId) {return Optional.ofNullable(ofRepoIdOrNull(repoId));}
public static Set<Integer> toIntSet(final Collection<BankStatementId> bankStatementIds)
{
if (bankStatementIds == null || bankStatementIds.isEmpty())
{
return ImmutableSet.of();
}
else
{
return bankStatementIds
.stream()
.map(BankStatementId::getRepoId)
|
.collect(ImmutableSet.toImmutableSet());
}
}
private BankStatementId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_BankStatement_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable BankStatementId id1, @Nullable BankStatementId id2)
{
return Objects.equals(id1, id2);
}
public static int toRepoId(@Nullable BankStatementId id) {return id != null ? id.getRepoId() : -1;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\banking\BankStatementId.java
| 2
|
请完成以下Java代码
|
public boolean isAccountNonExpired() {
return true;
}
@Override
@JsonIgnore
public boolean isAccountNonLocked() {
return true;
}
@Override
@JsonIgnore
public boolean isCredentialsNonExpired() {
return true;
}
@Override
@JsonIgnore
public boolean isEnabled() {
return true;
}
public void setUsername(String username) {
this.username = username;
}
@JsonIgnore
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public void setGrantedAuthorities(List<? extends GrantedAuthority> authorities) {
this.authorities = authorities;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCnname() {
return cnname;
}
public void setCnname(String cnname) {
this.cnname = cnname;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
|
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getRePassword() {
return rePassword;
}
public void setRePassword(String rePassword) {
this.rePassword = rePassword;
}
public String getHistoryPassword() {
return historyPassword;
}
public void setHistoryPassword(String historyPassword) {
this.historyPassword = historyPassword;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", cnname=" + cnname +
", username=" + username +
", password=" + password +
", email=" + email +
", telephone=" + telephone +
", mobilePhone=" + mobilePhone +
'}';
}
}
|
repos\springBoot-master\springboot-springSecurity4\src\main\java\com\yy\example\bean\User.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserController {
@Autowired
private UserDao _userDao;
@RequestMapping(value="/delete")
@ResponseBody
public String delete(long id) {
try {
User user = new User(id);
_userDao.delete(user);
}
catch(Exception ex) {
return ex.getMessage();
}
return "User succesfully deleted!";
}
@RequestMapping(value="/get-by-email")
@ResponseBody
public String getByEmail(String email) {
String userId;
try {
User user = _userDao.getByEmail(email);
userId = String.valueOf(user.getId());
}
catch(Exception ex) {
return "User not found";
}
|
return "The user id is: " + userId;
}
@RequestMapping(value="/save")
@ResponseBody
public String create(String email, String name) {
try {
User user = new User(email, name);
_userDao.save(user);
}
catch(Exception ex) {
return ex.getMessage();
}
return "User succesfully saved!";
}
} // class UserController
|
repos\spring-boot-samples-master\spring-boot-mysql-hibernate\src\main\java\netgloo\controllers\UserController.java
| 2
|
请完成以下Java代码
|
public void setA_User8 (String A_User8)
{
set_Value (COLUMNNAME_A_User8, A_User8);
}
/** Get A_User8.
@return A_User8 */
public String getA_User8 ()
{
return (String)get_Value(COLUMNNAME_A_User8);
}
/** Set A_User9.
@param A_User9 A_User9 */
public void setA_User9 (String A_User9)
{
set_Value (COLUMNNAME_A_User9, A_User9);
}
/** Get A_User9.
@return A_User9 */
public String getA_User9 ()
{
return (String)get_Value(COLUMNNAME_A_User9);
}
|
/** Set Text.
@param Text Text */
public void setText (String Text)
{
set_Value (COLUMNNAME_Text, Text);
}
/** Get Text.
@return Text */
public String getText ()
{
return (String)get_Value(COLUMNNAME_Text);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Oth.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Amount getTax()
{
return tax;
}
public void setTax(Amount tax)
{
this.tax = tax;
}
public PricingSummary total(Amount total)
{
this.total = total;
return this;
}
/**
* Get total
*
* @return total
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public Amount getTotal()
{
return total;
}
public void setTotal(Amount total)
{
this.total = total;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
PricingSummary pricingSummary = (PricingSummary)o;
return Objects.equals(this.adjustment, pricingSummary.adjustment) &&
Objects.equals(this.deliveryCost, pricingSummary.deliveryCost) &&
Objects.equals(this.deliveryDiscount, pricingSummary.deliveryDiscount) &&
Objects.equals(this.fee, pricingSummary.fee) &&
Objects.equals(this.priceDiscountSubtotal, pricingSummary.priceDiscountSubtotal) &&
Objects.equals(this.priceSubtotal, pricingSummary.priceSubtotal) &&
Objects.equals(this.tax, pricingSummary.tax) &&
Objects.equals(this.total, pricingSummary.total);
}
@Override
public int hashCode()
{
return Objects.hash(adjustment, deliveryCost, deliveryDiscount, fee, priceDiscountSubtotal, priceSubtotal, tax, total);
}
|
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class PricingSummary {\n");
sb.append(" adjustment: ").append(toIndentedString(adjustment)).append("\n");
sb.append(" deliveryCost: ").append(toIndentedString(deliveryCost)).append("\n");
sb.append(" deliveryDiscount: ").append(toIndentedString(deliveryDiscount)).append("\n");
sb.append(" fee: ").append(toIndentedString(fee)).append("\n");
sb.append(" priceDiscountSubtotal: ").append(toIndentedString(priceDiscountSubtotal)).append("\n");
sb.append(" priceSubtotal: ").append(toIndentedString(priceSubtotal)).append("\n");
sb.append(" tax: ").append(toIndentedString(tax)).append("\n");
sb.append(" total: ").append(toIndentedString(total)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\PricingSummary.java
| 2
|
请完成以下Java代码
|
public DocumentFilterDescriptorsProvider createFiltersProvider(@NonNull final CreateFiltersProviderContext context)
{
return StringUtils.trimBlankToOptional(context.getTableName())
.map(this::createFiltersProvider)
.orElse(null);
}
@Nullable
private DocumentFilterDescriptorsProvider createFiltersProvider(
@NonNull final String tableName)
{
final BooleanWithReason elasticsearchEnabled = ftsConfigService.getEnabled();
if (elasticsearchEnabled.isFalse())
{
logger.debug("Skip creating FTS filters because Elasticsearch is not enabled because: {}", elasticsearchEnabled.getReasonAsString());
return null;
}
final FTSFilterDescriptor ftsFilterDescriptor = ftsConfigService
.getFilterByTargetTableName(tableName)
.orElse(null);
if (ftsFilterDescriptor == null)
{
return null;
}
final FTSFilterContext context = FTSFilterContext.builder()
.filterDescriptor(ftsFilterDescriptor)
.searchService(ftsSearchService)
.build();
|
final ITranslatableString caption = msgBL.getTranslatableMsgText(MSG_FULL_TEXT_SEARCH_CAPTION);
return ImmutableDocumentFilterDescriptorsProvider.of(
DocumentFilterDescriptor.builder()
.setFilterId(FILTER_ID)
.setSortNo(DocumentFilterDescriptorsConstants.SORT_NO_FULL_TEXT_SEARCH)
.setDisplayName(caption)
.setFrequentUsed(true)
.setInlineRenderMode(DocumentFilterInlineRenderMode.INLINE_PARAMETERS)
.addParameter(DocumentFilterParamDescriptor.builder()
.fieldName(PARAM_SearchText)
.displayName(caption)
.widgetType(DocumentFieldWidgetType.Text))
.addInternalParameter(PARAM_Context, context)
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\fullTextSearch\FTSDocumentFilterDescriptorsProviderFactory.java
| 1
|
请完成以下Java代码
|
public class CustomRegisteredClientRepository implements RegisteredClientRepository {
private final RegisteredClientRepository delegate;
@Override
public void save(RegisteredClient registeredClient) {
log.info("Saving registered client: id={}, name={}",
registeredClient.getClientId(),
registeredClient.getClientName());
Set<String> scopes = ( registeredClient.getScopes() == null || registeredClient.getScopes().isEmpty())?
Set.of("openid","email","profile"):
registeredClient.getScopes();
// Disable PKCE & Consent
RegisteredClient modifiedClient = RegisteredClient.from(registeredClient)
.scopes(s -> s.addAll(scopes))
.clientSettings(ClientSettings
.withSettings(registeredClient.getClientSettings().getSettings())
.requireAuthorizationConsent(false)
.requireProofKey(false)
.build())
.build();
|
delegate.save(modifiedClient);
}
@Override
public RegisteredClient findById(String id) {
return delegate.findByClientId(id);
}
/**
* Returns the registered client identified by the provided {@code clientId},
* or {@code null} if not found.
*
* @param clientId
* the client identifier
* @return the {@link RegisteredClient} if found, otherwise {@code null}
*/
@Override
public RegisteredClient findByClientId(String clientId) {
return delegate.findByClientId(clientId);
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-dynamic-registration\oauth2-authorization-server\src\main\java\com\baeldung\spring\security\authserver\repository\CustomRegisteredClientRepository.java
| 1
|
请完成以下Java代码
|
public final class LinkMapper {
private static final JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
private LinkMapper() {
}
/**
* Map the specified links to a json model. If several links share the same relation,
* they are grouped together.
* @param links the links to map
* @return a model for the specified links
*/
public static ObjectNode mapLinks(List<Link> links) {
ObjectNode result = nodeFactory.objectNode();
Map<String, List<Link>> byRel = new LinkedHashMap<>();
links.forEach((it) -> byRel.computeIfAbsent(it.getRel(), (k) -> new ArrayList<>()).add(it));
byRel.forEach((rel, l) -> {
if (l.size() == 1) {
ObjectNode root = JsonNodeFactory.instance.objectNode();
mapLink(l.get(0), root);
result.set(rel, root);
}
else {
ArrayNode root = JsonNodeFactory.instance.arrayNode();
l.forEach((link) -> {
ObjectNode node = JsonNodeFactory.instance.objectNode();
mapLink(link, node);
|
root.add(node);
});
result.set(rel, root);
}
});
return result;
}
private static void mapLink(Link link, ObjectNode node) {
node.put("href", link.getHref());
if (link.isTemplated()) {
node.put("templated", true);
}
if (link.getDescription() != null) {
node.put("title", link.getDescription());
}
}
}
|
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\mapper\LinkMapper.java
| 1
|
请完成以下Java代码
|
public Builder setDocumentId(final String documentIdStr)
{
setDocumentId(DocumentId.ofStringOrEmpty(documentIdStr));
return this;
}
public Builder setDocumentId(final DocumentId documentId)
{
this.documentId = documentId;
return this;
}
public Builder allowNewDocumentId()
{
documentId_allowNew = true;
return this;
}
public Builder setDetailId(final String detailIdStr)
{
setDetailId(DetailId.fromJson(detailIdStr));
return this;
}
public Builder setDetailId(final DetailId detailId)
{
this.detailId = detailId;
return this;
}
public Builder setRowId(final String rowIdStr)
{
final DocumentId rowId = DocumentId.ofStringOrEmpty(rowIdStr);
setRowId(rowId);
return this;
}
public Builder setRowId(@Nullable final DocumentId rowId)
{
rowIds.clear();
if (rowId != null)
{
rowIds.add(rowId);
}
return this;
}
public Builder setRowIdsList(final String rowIdsListStr)
{
return setRowIds(DocumentIdsSelection.ofCommaSeparatedString(rowIdsListStr));
|
}
public Builder setRowIds(final DocumentIdsSelection rowIds)
{
this.rowIds.clear();
this.rowIds.addAll(rowIds.toSet());
return this;
}
public Builder allowNullRowId()
{
rowId_allowNull = true;
return this;
}
public Builder allowNewRowId()
{
rowId_allowNew = true;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentPath.java
| 1
|
请完成以下Java代码
|
public class Utils {
private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class);
public static String getHostName() {
final String DEFAULT_HOST = "localhost";
String hostName = null;
boolean canAccessSystemProps = true;
try {
// we'll do it this way mostly to determine if we should lookup the hostName
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPropertiesAccess();
}
} catch (SecurityException se) {
canAccessSystemProps = false;
}
|
if (canAccessSystemProps) {
try {
hostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException uhe) {
LOGGER.info("Cannot determine localhost name. Fallback to: " + DEFAULT_HOST, uhe);
hostName = DEFAULT_HOST;
}
} else {
hostName = DEFAULT_HOST;
}
return hostName;
}
}
|
repos\flowable-engine-main\modules\flowable-jmx\src\main\java\org\flowable\management\jmx\Utils.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void updateById(
@NonNull final SAPGLJournalId id,
@NonNull Consumer<SAPGLJournal> consumer)
{
updateById(
id,
glJournal -> {
consumer.accept(glJournal);
return null; // N/A
});
}
public <R> R updateById(
@NonNull final SAPGLJournalId id,
@NonNull Function<SAPGLJournal, R> processor)
{
final SAPGLJournal glJournal = getById(id);
final R result = processor.apply(glJournal);
save(glJournal);
return result;
}
public DocStatus getDocStatus(final SAPGLJournalId glJournalId)
{
return getHeaderRecordByIdIfExists(glJournalId)
.map(headerRecord -> DocStatus.ofNullableCodeOrUnknown(headerRecord.getDocStatus()))
.orElse(DocStatus.Unknown);
}
@NonNull
SAPGLJournal create(
@NonNull final SAPGLJournalCreateRequest createRequest,
@NonNull final SAPGLJournalCurrencyConverter currencyConverter)
{
final I_SAP_GLJournal headerRecord = InterfaceWrapperHelper.newInstance(I_SAP_GLJournal.class);
headerRecord.setTotalDr(createRequest.getTotalAcctDR().toBigDecimal());
|
headerRecord.setTotalCr(createRequest.getTotalAcctCR().toBigDecimal());
headerRecord.setC_DocType_ID(createRequest.getDocTypeId().getRepoId());
headerRecord.setC_AcctSchema_ID(createRequest.getAcctSchemaId().getRepoId());
headerRecord.setPostingType(createRequest.getPostingType().getCode());
headerRecord.setAD_Org_ID(createRequest.getOrgId().getRepoId());
headerRecord.setDescription(createRequest.getDescription());
headerRecord.setDocStatus(DocStatus.Drafted.getCode());
final SAPGLJournalCurrencyConversionCtx conversionCtx = createRequest.getConversionCtx();
headerRecord.setAcct_Currency_ID(conversionCtx.getAcctCurrencyId().getRepoId());
headerRecord.setC_Currency_ID(conversionCtx.getCurrencyId().getRepoId());
headerRecord.setC_ConversionType_ID(CurrencyConversionTypeId.toRepoId(conversionCtx.getConversionTypeId()));
Optional.ofNullable(conversionCtx.getFixedConversionRate())
.ifPresent(fixedConversionRate -> headerRecord.setCurrencyRate(fixedConversionRate.getMultiplyRate()));
headerRecord.setDateAcct(TimeUtil.asTimestamp(createRequest.getDateDoc()));
headerRecord.setDateDoc(TimeUtil.asTimestamp(createRequest.getDateDoc()));
headerRecord.setGL_Category_ID(createRequest.getGlCategoryId().getRepoId());
headerRecord.setReversal_ID(SAPGLJournalId.toRepoId(createRequest.getReversalId()));
saveRecord(headerRecord);
final SAPGLJournal createdJournal = fromRecord(headerRecord, ImmutableList.of());
createRequest.getLines()
.forEach(createLineRequest -> createdJournal.addLine(createLineRequest, currencyConverter));
save(createdJournal);
return createdJournal;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\service\SAPGLJournalLoaderAndSaver.java
| 2
|
请完成以下Java代码
|
default ConfigurationPropertySource filter(Predicate<ConfigurationPropertyName> filter) {
return new FilteredConfigurationPropertiesSource(this, filter);
}
/**
* Return a variant of this source that supports name aliases.
* @param aliases a function that returns a stream of aliases for any given name
* @return a {@link ConfigurationPropertySource} instance supporting name aliases
*/
default ConfigurationPropertySource withAliases(ConfigurationPropertyNameAliases aliases) {
return new AliasedConfigurationPropertySource(this, aliases);
}
/**
* Return a variant of this source that supports a prefix.
* @param prefix the prefix for properties in the source
* @return a {@link ConfigurationPropertySource} instance supporting a prefix
* @since 2.5.0
*/
default ConfigurationPropertySource withPrefix(@Nullable String prefix) {
return (StringUtils.hasText(prefix)) ? new PrefixedConfigurationPropertySource(this, prefix) : this;
}
/**
* Return the underlying source that is actually providing the properties.
* @return the underlying property source or {@code null}.
*/
|
default @Nullable Object getUnderlyingSource() {
return null;
}
/**
* Return a single new {@link ConfigurationPropertySource} adapted from the given
* Spring {@link PropertySource} or {@code null} if the source cannot be adapted.
* @param source the Spring property source to adapt
* @return an adapted source or {@code null} {@link SpringConfigurationPropertySource}
* @since 2.4.0
*/
static @Nullable ConfigurationPropertySource from(PropertySource<?> source) {
if (source instanceof ConfigurationPropertySourcesPropertySource) {
return null;
}
return SpringConfigurationPropertySource.from(source);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\ConfigurationPropertySource.java
| 1
|
请完成以下Java代码
|
public class RangeDatesIteration {
private static final Logger log = LoggerFactory.getLogger(RangeDatesIteration.class);
public void iterateBetweenDatesJava9(LocalDate startDate, LocalDate endDate) {
startDate.datesUntil(endDate)
.forEach(this::processDate);
}
public void iterateBetweenDatesJava8(LocalDate start, LocalDate end) {
for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
processDate(date);
}
}
public void iterateBetweenDatesJava7(Date start, Date end) {
Date current = start;
while (current.before(end)) {
processDate(current);
|
Calendar calendar = Calendar.getInstance();
calendar.setTime(current);
calendar.add(Calendar.DATE, 1);
current = calendar.getTime();
}
}
private void processDate(LocalDate date) {
log.debug(date.toString());
}
private void processDate(Date date) {
log.debug(date.toString());
}
}
|
repos\tutorials-master\core-java-modules\core-java-9\src\main\java\com\baeldung\java9\rangedates\RangeDatesIteration.java
| 1
|
请完成以下Java代码
|
public class DocumentsType {
@XmlElement(required = true)
protected List<DocumentType> document;
@XmlAttribute(name = "number", required = true)
@XmlSchemaType(name = "unsignedLong")
protected BigInteger number;
/**
* Gets the value of the document 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 document property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDocument().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DocumentType }
*
*
*/
public List<DocumentType> getDocument() {
if (document == null) {
document = new ArrayList<DocumentType>();
}
return this.document;
}
/**
* Gets the value of the number property.
|
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getNumber() {
return number;
}
/**
* Sets the value of the number property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setNumber(BigInteger value) {
this.number = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\response\DocumentsType.java
| 1
|
请完成以下Java代码
|
public class BufferedRateExecutorStats {
private static final String TENANT_ID_TAG = "tenantId";
private static final String TOTAL_ADDED = "totalAdded";
private static final String TOTAL_LAUNCHED = "totalLaunched";
private static final String TOTAL_RELEASED = "totalReleased";
private static final String TOTAL_FAILED = "totalFailed";
private static final String TOTAL_EXPIRED = "totalExpired";
private static final String TOTAL_REJECTED = "totalRejected";
private static final String TOTAL_RATE_LIMITED = "totalRateLimited";
private final StatsFactory statsFactory;
private final ConcurrentMap<TenantId, DefaultCounter> rateLimitedTenants = new ConcurrentHashMap<>();
private final List<StatsCounter> statsCounters = new ArrayList<>();
private final StatsCounter totalAdded;
private final StatsCounter totalLaunched;
private final StatsCounter totalReleased;
private final StatsCounter totalFailed;
private final StatsCounter totalExpired;
private final StatsCounter totalRejected;
private final StatsCounter totalRateLimited;
public BufferedRateExecutorStats(StatsFactory statsFactory) {
this.statsFactory = statsFactory;
String key = StatsType.RATE_EXECUTOR.getName();
this.totalAdded = statsFactory.createStatsCounter(key, TOTAL_ADDED);
this.totalLaunched = statsFactory.createStatsCounter(key, TOTAL_LAUNCHED);
this.totalReleased = statsFactory.createStatsCounter(key, TOTAL_RELEASED);
|
this.totalFailed = statsFactory.createStatsCounter(key, TOTAL_FAILED);
this.totalExpired = statsFactory.createStatsCounter(key, TOTAL_EXPIRED);
this.totalRejected = statsFactory.createStatsCounter(key, TOTAL_REJECTED);
this.totalRateLimited = statsFactory.createStatsCounter(key, TOTAL_RATE_LIMITED);
this.statsCounters.add(totalAdded);
this.statsCounters.add(totalLaunched);
this.statsCounters.add(totalReleased);
this.statsCounters.add(totalFailed);
this.statsCounters.add(totalExpired);
this.statsCounters.add(totalRejected);
this.statsCounters.add(totalRateLimited);
}
public void incrementRateLimitedTenant(TenantId tenantId){
rateLimitedTenants.computeIfAbsent(tenantId,
tId -> {
String key = StatsType.RATE_EXECUTOR.getName() + ".tenant";
return statsFactory.createDefaultCounter(key, TENANT_ID_TAG, tId.toString());
}
)
.increment();
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\util\BufferedRateExecutorStats.java
| 1
|
请完成以下Java代码
|
public static boolean isPartOfProcessApplication(DeploymentUnit unit) {
if(isProcessApplication(unit)) {
return true;
}
if(unit.getParent() != null && unit.getParent() != unit) {
return unit.getParent().hasAttachment(PART_OF_MARKER);
}
return false;
}
/**
* Returns true if the {@link DeploymentUnit} itself is a process application (carries a processes.xml)
*
*/
public static boolean isProcessApplication(DeploymentUnit deploymentUnit) {
return deploymentUnit.hasAttachment(MARKER);
}
/**
* Returns the {@link ComponentDescription} for the {@link AbstractProcessApplication} component
*/
public static ComponentDescription getProcessApplicationComponent(DeploymentUnit deploymentUnit) {
return deploymentUnit.getAttachment(PA_COMPONENT);
}
/**
* Attach the {@link ComponentDescription} for the {@link AbstractProcessApplication} component
*/
public static void attachProcessApplicationComponent(DeploymentUnit deploymentUnit, ComponentDescription componentDescription){
deploymentUnit.putAttachment(PA_COMPONENT, componentDescription);
}
/**
* Attach the {@link AnnotationInstance}s for the PostDeploy methods
*/
public static void attachPostDeployDescription(DeploymentUnit deploymentUnit, AnnotationInstance annotation){
deploymentUnit.putAttachment(POST_DEPLOY_METHOD, annotation);
}
/**
* Attach the {@link AnnotationInstance}s for the PreUndeploy methods
|
*/
public static void attachPreUndeployDescription(DeploymentUnit deploymentUnit, AnnotationInstance annotation){
deploymentUnit.putAttachment(PRE_UNDEPLOY_METHOD, annotation);
}
/**
* @return the description of the PostDeploy method
*/
public static AnnotationInstance getPostDeployDescription(DeploymentUnit deploymentUnit) {
return deploymentUnit.getAttachment(POST_DEPLOY_METHOD);
}
/**
* @return the description of the PreUndeploy method
*/
public static AnnotationInstance getPreUndeployDescription(DeploymentUnit deploymentUnit) {
return deploymentUnit.getAttachment(PRE_UNDEPLOY_METHOD);
}
private ProcessApplicationAttachments() {
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\deployment\marker\ProcessApplicationAttachments.java
| 1
|
请完成以下Java代码
|
public boolean hasRunningContracts(final I_PMM_Product pmmProduct)
{
Check.assumeNotNull(pmmProduct, "pmmProduct not null");
final Date date = null; // any date
return retrieveAllRunningContractsOnDateQuery(date)
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_PMM_Product_ID, pmmProduct.getPMM_Product_ID())
.create()
.anyMatch();
}
@Nullable
@Override
public I_C_Flatrate_DataEntry retrieveFlatrateDataEntry(
@NonNull final de.metas.contracts.model.I_C_Flatrate_Term flatrateTerm,
@NonNull final Timestamp date)
{
final IFlatrateDAO flatrateDAO = Services.get(IFlatrateDAO.class);
final List<I_C_Flatrate_DataEntry> dataEntries = InterfaceWrapperHelper.createList(
flatrateDAO.retrieveDataEntries(flatrateTerm, date, I_C_Flatrate_DataEntry.TYPE_Procurement_PeriodBased, true), // onlyNonSim = true
I_C_Flatrate_DataEntry.class);
for (final I_C_Flatrate_DataEntry dataEntry : dataEntries)
{
if (dataEntry.getM_Product_DataEntry_ID() == flatrateTerm.getM_Product_ID())
{
return dataEntry;
}
}
|
return null;
}
@Nullable
@Override
public I_C_Flatrate_Term retrieveTermForPartnerAndProduct(final Date date, final int bPartnerID, final int pmmProductId)
{
return retrieveAllRunningContractsOnDateQuery(date)
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_DropShip_BPartner_ID, bPartnerID)
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_PMM_Product_ID, pmmProductId)
.addCompareFilter(I_C_Flatrate_Term.COLUMNNAME_StartDate, Operator.LESS_OR_EQUAL, date)
.orderBy()
.addColumn(I_C_Flatrate_Term.COLUMNNAME_StartDate, Direction.Descending, Nulls.Last)
.endOrderBy()
.create()
.first(I_C_Flatrate_Term.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\PMMContractsDAO.java
| 1
|
请完成以下Java代码
|
default V get(K key, Supplier<V> supplier) {
return get(key, supplier, true);
}
default V get(K key, Supplier<V> supplier, boolean putToCache) {
return Optional.ofNullable(get(key))
.map(TbCacheValueWrapper::get)
.orElseGet(() -> {
V value = supplier.get();
if (putToCache) {
put(key, value);
}
return value;
});
}
void put(K key, V value);
|
void evict(K key);
void evict(Collection<K> keys);
void evict(K key, Long version);
default Long getVersion(V value) {
if (value == null) {
return 0L;
} else if (value.getVersion() != null) {
return value.getVersion();
} else {
return null;
}
}
}
|
repos\thingsboard-master\common\cache\src\main\java\org\thingsboard\server\cache\VersionedTbCache.java
| 1
|
请完成以下Java代码
|
public String getPermittedCrossDomainPolicies() {
return permittedCrossDomainPolicies;
}
public void setPermittedCrossDomainPolicies(String permittedCrossDomainPolicies) {
this.permittedCrossDomainPolicies = permittedCrossDomainPolicies;
}
public String getPermissionsPolicy() {
return permissionsPolicy;
}
public void setPermissionsPolicy(String permissionsPolicy) {
this.permissionsPolicy = permissionsPolicy;
}
/**
* @return the default/opt-out header names to disable
*/
public List<String> getDisable() {
return disabledHeaders.stream().toList();
}
/**
* Binds the list of default/opt-out header names to disable, transforms them into a
* lowercase set. This is to ensure case-insensitive comparison.
* @param disable - list of default/opt-out header names to disable
*/
public void setDisable(List<String> disable) {
if (disable != null) {
disabledHeaders = disable.stream().map(String::toLowerCase).collect(Collectors.toUnmodifiableSet());
}
}
/**
* @return the opt-in header names to enable
*/
public Set<String> getEnabledHeaders() {
return enabledHeaders;
}
/**
|
* Binds the list of default/opt-out header names to enable, transforms them into a
* lowercase set. This is to ensure case-insensitive comparison.
* @param enable - list of default/opt-out header enable
*/
public void setEnable(List<String> enable) {
if (enable != null) {
enabledHeaders = enable.stream().map(String::toLowerCase).collect(Collectors.toUnmodifiableSet());
}
}
/**
* @return the default/opt-out header names to disable
*/
public Set<String> getDisabledHeaders() {
return disabledHeaders;
}
/**
* @return the default/opt-out header names to apply
*/
public Set<String> getDefaultHeaders() {
return defaultHeaders;
}
@Override
public String toString() {
return "SecureHeadersProperties{" + "xssProtectionHeader='" + xssProtectionHeader + '\''
+ ", strictTransportSecurity='" + strictTransportSecurity + '\'' + ", frameOptions='" + frameOptions
+ '\'' + ", contentTypeOptions='" + contentTypeOptions + '\'' + ", referrerPolicy='" + referrerPolicy
+ '\'' + ", contentSecurityPolicy='" + contentSecurityPolicy + '\'' + ", downloadOptions='"
+ downloadOptions + '\'' + ", permittedCrossDomainPolicies='" + permittedCrossDomainPolicies + '\''
+ ", permissionsPolicy='" + permissionsPolicy + '\'' + ", defaultHeaders=" + defaultHeaders
+ ", enable=" + enabledHeaders + ", disable=" + disabledHeaders + '}';
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SecureHeadersProperties.java
| 1
|
请完成以下Java代码
|
public SplitResult splitQuantity(@NonNull final BigDecimal qtyToSplit)
{
Check.errorIf(qtyToSplit.compareTo(quantity.toBigDecimal()) >= 0,
"The given qtyToSplit={} needs to be less than this instance's quantity; this={}",
qtyToSplit, this);
final Quantity newQuantity = Quantity.of(qtyToSplit, quantity.getUOM());
final Quantity remainderQuantity = quantity.subtract(qtyToSplit);
final BigDecimal newFraction = qtyToSplit
.setScale(precision * 2, RoundingMode.HALF_UP)
.divide(quantity.toBigDecimal(), RoundingMode.HALF_UP);
final BigDecimal newMoneyValue = money
.toBigDecimal()
.setScale(precision, RoundingMode.HALF_UP)
.multiply(newFraction)
.setScale(precision, RoundingMode.HALF_UP);
final Money newMoney = Money.of(newMoneyValue, money.getCurrencyId());
final Money remainderMoney = money.subtract(newMoney);
final AssignableInvoiceCandidate remainderCandidate = toBuilder()
.quantity(remainderQuantity)
.money(remainderMoney)
|
.build();
final AssignableInvoiceCandidate newCandidate = toBuilder()
.id(id)
.quantity(newQuantity)
.money(newMoney)
.build();
return new SplitResult(remainderCandidate, newCandidate);
}
@Value
public static final class SplitResult
{
AssignableInvoiceCandidate remainder;
AssignableInvoiceCandidate newCandidate;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\AssignableInvoiceCandidate.java
| 1
|
请完成以下Java代码
|
public void actionPerformed (ActionEvent e)
{
} // actionPerformed
/**
* Get PrintService
* @return print service
*/
public PrintService getPrintService()
{
String currentService = (String)getSelectedItem();
for (int i = 0; i < s_services.length; i++)
{
if (s_services[i].getName().equals(currentService))
return s_services[i];
}
return PrintServiceLookup.lookupDefaultPrintService();
} // getPrintService
|
/**
* Refresh printer list
*/
public void refresh() {
String current = (String) getSelectedItem();
removeAllItems();
setModel(new DefaultComboBoxModel(getPrinterNames()));
if (current != null) {
for (int i = 0; i < getItemCount(); i++) {
String item = (String) getItemAt(i);
if (item.equals(current))
setSelectedIndex(i);
}
}
}
} // CPrinter
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\CPrinter.java
| 1
|
请完成以下Java代码
|
public BuiltinAggregator getAggregation() {
return aggregationAttribute.getValue(this);
}
public void setAggregation(BuiltinAggregator aggregation) {
aggregationAttribute.setValue(this, aggregation);
}
public DecisionTableOrientation getPreferredOrientation() {
return preferredOrientationAttribute.getValue(this);
}
public void setPreferredOrientation(DecisionTableOrientation preferredOrientation) {
preferredOrientationAttribute.setValue(this, preferredOrientation);
}
public String getOutputLabel() {
return outputLabelAttribute.getValue(this);
}
public void setOutputLabel(String outputLabel) {
outputLabelAttribute.setValue(this, outputLabel);
}
public Collection<Input> getInputs() {
return inputCollection.get(this);
}
public Collection<Output> getOutputs() {
return outputCollection.get(this);
}
public Collection<Rule> getRules() {
return ruleCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DecisionTable.class, DMN_ELEMENT_DECISION_TABLE)
.namespaceUri(LATEST_DMN_NS)
.extendsType(Expression.class)
|
.instanceProvider(new ModelTypeInstanceProvider<DecisionTable>() {
public DecisionTable newInstance(ModelTypeInstanceContext instanceContext) {
return new DecisionTableImpl(instanceContext);
}
});
hitPolicyAttribute = typeBuilder.namedEnumAttribute(DMN_ATTRIBUTE_HIT_POLICY, HitPolicy.class)
.defaultValue(HitPolicy.UNIQUE)
.build();
aggregationAttribute = typeBuilder.enumAttribute(DMN_ATTRIBUTE_AGGREGATION, BuiltinAggregator.class)
.build();
preferredOrientationAttribute = typeBuilder.namedEnumAttribute(DMN_ATTRIBUTE_PREFERRED_ORIENTATION, DecisionTableOrientation.class)
.defaultValue(DecisionTableOrientation.Rule_as_Row)
.build();
outputLabelAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_OUTPUT_LABEL)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
inputCollection = sequenceBuilder.elementCollection(Input.class)
.build();
outputCollection = sequenceBuilder.elementCollection(Output.class)
.required()
.build();
ruleCollection = sequenceBuilder.elementCollection(Rule.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DecisionTableImpl.java
| 1
|
请完成以下Java代码
|
public ScopeImpl getParent() {
return parent;
}
@Override
@SuppressWarnings("unchecked")
public List<PvmTransition> getIncomingTransitions() {
return (List) incomingTransitions;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
public boolean isScope() {
return isScope;
}
public void setScope(boolean isScope) {
this.isScope = isScope;
}
@Override
public int getX() {
return x;
}
@Override
public void setX(int x) {
this.x = x;
}
@Override
public int getY() {
return y;
}
@Override
|
public void setY(int y) {
this.y = y;
}
@Override
public int getWidth() {
return width;
}
@Override
public void setWidth(int width) {
this.width = width;
}
@Override
public int getHeight() {
return height;
}
@Override
public void setHeight(int height) {
this.height = height;
}
@Override
public boolean isAsync() {
return isAsync;
}
public void setAsync(boolean isAsync) {
this.isAsync = isAsync;
}
@Override
public boolean isExclusive() {
return isExclusive;
}
public void setExclusive(boolean isExclusive) {
this.isExclusive = isExclusive;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ActivityImpl.java
| 1
|
请完成以下Java代码
|
public class AddIdentityLinkForProcessDefinitionCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
protected String processDefinitionId;
protected String userId;
protected String groupId;
public AddIdentityLinkForProcessDefinitionCmd(String processDefinitionId, String userId, String groupId) {
validateParams(userId, groupId, processDefinitionId);
this.processDefinitionId = processDefinitionId;
this.userId = userId;
this.groupId = groupId;
}
protected void validateParams(String userId, String groupId, String processDefinitionId) {
if (processDefinitionId == null) {
throw new ActivitiIllegalArgumentException("processDefinitionId is null");
}
if (userId == null && groupId == null) {
throw new ActivitiIllegalArgumentException("userId and groupId cannot both be null");
}
|
}
public Void execute(CommandContext commandContext) {
ProcessDefinitionEntity processDefinition = commandContext
.getProcessDefinitionEntityManager()
.findById(processDefinitionId);
if (processDefinition == null) {
throw new ActivitiObjectNotFoundException(
"Cannot find process definition with id " + processDefinitionId,
ProcessDefinition.class
);
}
executeInternal(commandContext, processDefinition);
return null;
}
protected void executeInternal(CommandContext commandContext, ProcessDefinitionEntity processDefinition) {
commandContext.getIdentityLinkEntityManager().addIdentityLink(processDefinition, userId, groupId);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\AddIdentityLinkForProcessDefinitionCmd.java
| 1
|
请完成以下Java代码
|
public List<ProcessInstance> findProcessInstanceByNativeQuery(
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return getDbSqlSession().selectListWithRawParameter(
"selectExecutionByNativeQuery",
parameterMap,
firstResult,
maxResults
);
}
@Override
public long findExecutionCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectExecutionCountByNativeQuery", parameterMap);
}
@Override
public void updateExecutionTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateExecutionTenantIdForDeployment", params);
}
@Override
public void updateProcessInstanceLockTime(String processInstanceId, Date lockDate, Date expirationTime) {
HashMap<String, Object> params = new HashMap<String, Object>();
|
params.put("id", processInstanceId);
params.put("lockTime", lockDate);
params.put("expirationTime", expirationTime);
int result = getDbSqlSession().update("updateProcessInstanceLockTime", params);
if (result == 0) {
throw new ActivitiOptimisticLockingException("Could not lock process instance");
}
}
@Override
public void updateAllExecutionRelatedEntityCountFlags(boolean newValue) {
getDbSqlSession().update("updateExecutionRelatedEntityCountEnabled", newValue);
}
@Override
public void clearProcessInstanceLockTime(String processInstanceId) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("id", processInstanceId);
getDbSqlSession().update("clearProcessInstanceLockTime", params);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisExecutionDataManager.java
| 1
|
请完成以下Java代码
|
private static boolean isEligibleForCheckingScriptFilesRecursive(final File file)
{
return isGitRepositoryRoot(file) || isProjectsGroupDir(file) || isMavenProjectDir(file);
}
private static boolean isGitRepositoryRoot(final File dir)
{
if (!dir.isDirectory())
{
return false;
}
final File gitDir = new File(dir, ".git");
return gitDir.exists() && gitDir.isDirectory();
}
private static boolean isProjectsGroupDir(final File dir)
{
return dir.isDirectory() && "backend".equals(dir.getName()); // metasfresh/backend
}
private static boolean isMavenProjectDir(final File dir)
{
return dir.isDirectory() && new File(dir, "pom.xml").exists();
}
private List<IScript> getScriptFilesFromProjectDir(final File projectDir, final String defaultProjectName)
{
final File scriptsRootDir = new File(projectDir, "src/main/sql/postgresql/system");
if (!scriptsRootDir.isDirectory())
{
return ImmutableList.of();
}
final ArrayList<IScript> scripts = new ArrayList<>();
//
// Script files in subfolders
// e.g. .../src/main/sql/postgresql/system/10-de.metas.adempiere
for (final File subProjectDir : scriptsRootDir.listFiles(File::isDirectory))
{
final String projectName = subProjectDir.getName();
for (final File scriptFile : subProjectDir.listFiles(this::isSupportedScriptFile))
{
scripts.add(new LocalScript(projectName, scriptFile));
}
}
//
// Script files directly in .../src/main/sql/postgresql/system/ folder
for (final File scriptFile : scriptsRootDir.listFiles(File::isFile))
{
scripts.add(new LocalScript(defaultProjectName, scriptFile));
}
logger.info("Considering {} ({} scripts)", projectDir, scripts.size());
return scripts;
}
private boolean isSupportedScriptFile(final File file)
{
if (!file.exists() || !file.isFile())
{
|
return false;
}
final String fileExtLC = FileUtils.getFileExtension(file.getName(), false).toLowerCase();
return supportedFileExtensionsLC.contains(fileExtLC);
}
private static String getDefaultProjectName(final File projectDir)
{
final File mavenPOMFile = new File(projectDir, "pom.xml");
if (mavenPOMFile.exists())
{
final Document xmlDocument = XmlUtils.loadDocument(mavenPOMFile);
try
{
return XmlUtils.getString("/project/properties/migration-sql-basedir", xmlDocument);
}
catch (Exception ex)
{
ex.printStackTrace(); // FIXME remove
return null;
}
}
else
{
return null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\workspace_migrate\WorkspaceScriptScanner.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public DependencyMetadata get(InitializrMetadata metadata, Version bootVersion) {
Map<String, Dependency> dependencies = new LinkedHashMap<>();
for (Dependency dependency : metadata.getDependencies().getAll()) {
if (dependency.match(bootVersion)) {
dependencies.put(dependency.getId(), dependency.resolve(bootVersion));
}
}
Map<String, Repository> repositories = new LinkedHashMap<>();
for (Dependency dependency : dependencies.values()) {
if (dependency.getRepository() != null) {
repositories.put(dependency.getRepository(),
metadata.getConfiguration().getEnv().getRepositories().get(dependency.getRepository()));
}
}
Map<String, BillOfMaterials> boms = new LinkedHashMap<>();
for (Dependency dependency : dependencies.values()) {
|
if (dependency.getBom() != null) {
boms.put(dependency.getBom(),
metadata.getConfiguration().getEnv().getBoms().get(dependency.getBom()).resolve(bootVersion));
}
}
// Each resolved bom may require additional repositories
for (BillOfMaterials bom : boms.values()) {
for (String id : bom.getRepositories()) {
repositories.put(id, metadata.getConfiguration().getEnv().getRepositories().get(id));
}
}
return new DependencyMetadata(bootVersion, dependencies, repositories, boms);
}
}
|
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\support\DefaultDependencyMetadataProvider.java
| 2
|
请完成以下Java代码
|
public String toString()
{
// NOTE: we are making it translateable friendly because it's displayed in Prefereces->Info->Rollen
final String permissionsName = getClass().getSimpleName();
final Collection<PermissionType> permissionsList = permissions.values();
final StringBuilder sb = new StringBuilder();
sb.append(permissionsName).append(": ");
if (permissionsList.isEmpty())
{
sb.append("@NoRestrictions@");
}
else
{
sb.append(Env.NL);
}
Joiner.on(Env.NL)
.skipNulls()
.appendTo(sb, permissionsList);
return sb.toString();
}
@Override
public final int size()
{
return permissions.size();
}
@Override
public final Collection<PermissionType> getPermissionsList()
{
return permissions.values();
}
protected final ImmutableMap<Resource, PermissionType> getPermissionsMap()
{
return permissions;
}
/**
* Gets the "NO permission".
*
* It is an instance of PermissionType with all accesses revoked and with a generic {@link Resource}.
*
* <br/>
* <b>NOTE to implementor: it is highly recommended that extended classes to not return <code>null</code> here.</b>
*
* @return no permission instance
*/
protected PermissionType noPermission()
{
return null;
}
@Override
public final Optional<PermissionType> getPermissionIfExists(final Resource resource)
{
return Optional.fromNullable(permissions.get(resource));
}
@Override
public final PermissionType getPermissionOrDefault(final Resource resource)
{
//
// Get the permission for given resource
final Optional<PermissionType> permission = getPermissionIfExists(resource);
if (permission.isPresent())
|
{
return permission.get();
}
//
// Fallback: get the permission defined for the resource of "no permission", if any
final PermissionType nonePermission = noPermission();
if (nonePermission == null)
{
return null;
}
final Resource defaultResource = nonePermission.getResource();
return getPermissionIfExists(defaultResource)
// Fallback: return the "no permission"
.or(nonePermission);
}
@Override
public final boolean hasPermission(final Permission permission)
{
return permissions.values().contains(permission);
}
@Override
public final boolean hasAccess(final Resource resource, final Access access)
{
return getPermissionOrDefault(resource).hasAccess(access);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\AbstractPermissions.java
| 1
|
请完成以下Java代码
|
protected IExternalSystemChildConfigId getExternalChildConfigId()
{
final int id;
if (this.childConfigId > 0)
{
id = this.childConfigId;
}
else
{
final IExternalSystemChildConfig childConfig = externalSystemConfigDAO.getChildByParentIdAndType(ExternalSystemParentConfigId.ofRepoId(getRecord_ID()), getExternalSystemType())
.orElseThrow(() -> new AdempiereException("No childConfig found for type GRSSignum and parent config")
.appendParametersToMessage()
.setParameter("externalSystemParentConfigId:", ExternalSystemParentConfigId.ofRepoId(getRecord_ID())));
id = childConfig.getId().getRepoId();
}
return ExternalSystemGRSSignumConfigId.ofRepoId(id);
}
@Override
protected Map<String, String> extractExternalSystemParameters(@NonNull final ExternalSystemParentConfig externalSystemParentConfig)
{
final ExternalSystemGRSSignumConfig grsConfig = ExternalSystemGRSSignumConfig.cast(externalSystemParentConfig.getChildConfig());
if (EmptyUtil.isEmpty(grsConfig.getCamelHttpResourceAuthKey()))
{
throw new AdempiereException("camelHttpResourceAuthKey for childConfig should not be empty at this point")
.appendParametersToMessage()
.setParameter("childConfigId", grsConfig.getId());
}
final Map<String, String> parameters = new HashMap<>();
parameters.put(ExternalSystemConstants.PARAM_CAMEL_HTTP_RESOURCE_AUTH_KEY, grsConfig.getCamelHttpResourceAuthKey());
parameters.put(ExternalSystemConstants.PARAM_BASE_PATH, grsConfig.getBaseUrl());
return parameters;
}
@Override
protected String getTabName()
{
return ExternalSystemType.GRSSignum.getValue();
}
|
@Override
protected ExternalSystemType getExternalSystemType()
{
return ExternalSystemType.GRSSignum;
}
@Override
protected long getSelectedRecordCount(final IProcessPreconditionsContext context)
{
return context.getSelectedIncludedRecords()
.stream()
.filter(recordRef -> I_ExternalSystem_Config_GRSSignum.Table_Name.equals(recordRef.getTableName()))
.count();
}
@Override
protected String getOrgCode(@NonNull final ExternalSystemParentConfig config)
{
return orgDAO.getById(config.getOrgId()).getValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeGRSSignumAction.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static LanguageKey ofLocale(@NonNull final Locale locale)
{
return new LanguageKey(locale.getLanguage(), locale.getCountry(), locale.getVariant());
}
public static LanguageKey getDefault()
{
return ofLocale(Locale.getDefault());
}
@NonNull
String language;
@NonNull
String country;
@NonNull
String variant;
public Locale toLocale()
{
return new Locale(language, country, variant);
}
@Override
@Deprecated
public String toString()
{
return getAsString();
|
}
@JsonValue
public String getAsString()
{
final StringBuilder sb = new StringBuilder();
sb.append(language);
if (!country.isBlank())
{
sb.append("_").append(country);
}
if (!variant.isBlank())
{
sb.append("_").append(variant);
}
return sb.toString();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\util\LanguageKey.java
| 2
|
请完成以下Java代码
|
public void onProductChanged(final I_PP_Product_BOMLine bomLine)
{
final int M_Product_ID = bomLine.getM_Product_ID();
if (M_Product_ID <= 0)
{
return;
}
final I_PP_Product_BOM bom = bomLine.getPP_Product_BOM();
if (bom.getM_Product_ID() == bomLine.getM_Product_ID())
{
throw new AdempiereException("@ValidComponent@ - selected product cannot be a BOM component because it's actually the BOM product");
}
// Set BOM Line defaults
final ProductId productId = ProductId.ofRepoId(bomLine.getM_Product_ID());
final I_M_Product product = Services.get(IProductBL.class).getById(productId);
bomLine.setDescription(product.getDescription());
|
bomLine.setHelp(product.getHelp());
bomLine.setC_UOM_ID(product.getC_UOM_ID());
}
@CalloutMethod(columnNames = { I_PP_Product_BOMLine.COLUMNNAME_VariantGroup})
public void validateVariantGroup(final I_PP_Product_BOMLine bomLine)
{
final boolean valid = Services.get(IProductBOMBL.class).isValidVariantGroup(bomLine);
if (!valid)
{
throw new LiberoException("@NoSuchVariantGroup@");
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\callout\PP_Product_BOMLine.java
| 1
|
请完成以下Java代码
|
public class CityVO implements ResultItem
{
private final int C_City_ID;
private final String CityName;
private final int C_Region_ID;
private final String RegionName;
public CityVO(int city_ID, String cityName, int region_ID, String regionName)
{
super();
C_City_ID = city_ID;
CityName = cityName;
C_Region_ID = region_ID;
RegionName = regionName;
}
@Override
public int hashCode()
{
return new HashcodeBuilder()
.append(C_City_ID)
.append(C_Region_ID)
.append(CityName)
.append(RegionName)
.toHashcode();
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
final CityVO other = EqualsBuilder.getOther(this, obj);
if (other == null)
return false;
return new EqualsBuilder()
.append(C_City_ID, other.C_City_ID)
.append(C_Region_ID, other.C_Region_ID)
.append(CityName, other.CityName)
.append(RegionName, other.RegionName)
.isEqual();
}
|
@Override
public String getText()
{
return CityName;
}
@Override
public String toString()
{
// needed for ListCellRenderer
final StringBuilder sb = new StringBuilder();
if (this.CityName != null)
{
sb.append(this.CityName);
}
if (this.RegionName != null)
{
sb.append(" (").append(this.RegionName).append(")");
}
return sb.toString();
}
public int getC_City_ID()
{
return C_City_ID;
}
public String getCityName()
{
return CityName;
}
public int getC_Region_ID()
{
return C_Region_ID;
}
public String getRegionName()
{
return RegionName;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\CityVO.java
| 1
|
请完成以下Java代码
|
public ITranslatableString getTrl(final String columnName)
{
final Caption caption = captions.get(columnName);
return caption != null ? caption.toTranslatableString() : TranslatableStrings.empty();
}
}
@ToString
private static class Caption
{
@Getter
@NonNull private final String columnName;
@NonNull private final String baseAD_Language;
@NonNull private final LinkedHashMap<String, String> translations;
@Nullable private transient ITranslatableString computedTrl = null;
private Caption(
@NonNull final String columnName,
@NonNull final String baseAD_Language)
{
this.columnName = columnName;
this.baseAD_Language = baseAD_Language;
this.translations = new LinkedHashMap<>(5);
}
private Caption(@NonNull final GridTabVO.Caption from)
{
this.columnName = from.columnName;
this.baseAD_Language = from.baseAD_Language;
this.translations = new LinkedHashMap<>(from.translations);
this.computedTrl = from.computedTrl;
}
public Caption copy()
{
return new Caption(this);
}
public void putTranslation(@NonNull final String adLanguage, @Nullable final String captionTrl)
{
Check.assumeNotEmpty(adLanguage, "adLanguage is not empty");
final String captionTrlNorm = captionTrl != null ? captionTrl.trim() : "";
if (!captionTrlNorm.isEmpty())
{
translations.put(adLanguage, captionTrlNorm);
}
else
{
translations.remove(adLanguage);
}
computedTrl = null;
}
public ITranslatableString toTranslatableString()
|
{
ITranslatableString computedTrl = this.computedTrl;
if (computedTrl == null)
{
computedTrl = this.computedTrl = computeTranslatableString();
}
return computedTrl;
}
private ITranslatableString computeTranslatableString()
{
if (translations.isEmpty())
{
return TranslatableStrings.empty();
}
else if (translations.size() == 1)
{
final Map.Entry<String, String> firstEntry = translations.entrySet().iterator().next();
final String adLanguage = firstEntry.getKey();
final String value = firstEntry.getValue();
return TranslatableStrings.singleLanguage(adLanguage, value);
}
else
{
String defaultValue = translations.get(baseAD_Language);
if (defaultValue == null)
{
defaultValue = translations.values().iterator().next();
}
return TranslatableStrings.ofMap(translations, defaultValue);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTabVO.java
| 1
|
请完成以下Java代码
|
public ProcessDefinitionResource getProcessDefinition(@PathParam("id") String id) {
return new ProcessDefinitionResource(getProcessEngine().getName(), id);
}
@GET
@Path("/statistics-count")
@Produces(MediaType.APPLICATION_JSON)
public CountResultDto getStatisticsCount(@Context UriInfo uriInfo) {
QueryParameters queryDto = new ProcessDefinitionStatisticsQueryDto(uriInfo.getQueryParameters());
configureExecutionQuery(queryDto);
long count = getQueryService().executeQueryRowCount("selectPDStatisticsCount", queryDto);
return new CountResultDto(count);
}
@GET
@Path("/statistics")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
|
public List<ProcessDefinitionStatisticsDto> queryStatistics(@Context UriInfo uriInfo,
@QueryParam("firstResult") Integer firstResult,
@QueryParam("maxResults") Integer maxResults) {
QueryParameters queryDto = new ProcessDefinitionStatisticsQueryDto(uriInfo.getQueryParameters());
configureExecutionQuery(queryDto);
queryDto.setFirstResult(firstResult != null && firstResult >= 0 ? firstResult : 0);
queryDto.setMaxResults(maxResults != null && maxResults > 0 ? maxResults : Integer.MAX_VALUE);
return getQueryService().executeQuery("selectPDStatistics", queryDto);
}
protected void configureExecutionQuery(QueryParameters query) {
configureAuthorizationCheck(query);
configureTenantCheck(query);
addPermissionCheck(query, PROCESS_DEFINITION, "RES.KEY_", READ);
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\resources\ProcessDefinitionRestService.java
| 1
|
请完成以下Java代码
|
public int getAD_Scheduler_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Scheduler_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
|
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Default Parameter.
@param ParameterDefault
Default value of the parameter
*/
@Override
public void setParameterDefault (java.lang.String ParameterDefault)
{
set_Value (COLUMNNAME_ParameterDefault, ParameterDefault);
}
/** Get Default Parameter.
@return Default value of the parameter
*/
@Override
public java.lang.String getParameterDefault ()
{
return (java.lang.String)get_Value(COLUMNNAME_ParameterDefault);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Scheduler_Para.java
| 1
|
请完成以下Java代码
|
public boolean containsAll(Collection<?> c)
{
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends Entry<String, V>> c)
{
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c)
{
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c)
{
throw new UnsupportedOperationException();
}
|
@Override
public void clear()
{
MutableDoubleArrayTrie.this.clear();
}
};
}
@Override
public Iterator<Entry<String, V>> iterator()
{
return entrySet().iterator();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\MutableDoubleArrayTrie.java
| 1
|
请完成以下Java代码
|
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
|
@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(", adminId=").append(adminId);
sb.append(", createTime=").append(createTime);
sb.append(", ip=").append(ip);
sb.append(", address=").append(address);
sb.append(", userAgent=").append(userAgent);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdminLoginLog.java
| 1
|
请完成以下Spring Boot application配置
|
spring.h2.console.path=/h2
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
javers.mappingStyle=FIELD
javers.algorithm=SIMPLE
javers.commitIdGenerator=synchronized_sequence
javers.prettyPrint=true
javers.typeSafeValues=false
javers.newObjectSnapshot=true
javers.packagesToScan=
javers.auditableAspectEnabled=true
javers.springDataAuditableRepositoryAspectEnabled=true
javers.sqlSchema=
javers.sqlSchemaManagementEnabled=t
|
rue
javers.prettyPrintDateFormats.localDateTime=dd MMM yyyy, HH:mm:ss
javers.prettyPrintDateFormats.zonedDateTime=dd MMM yyyy, HH:mm:ssZ
javers.prettyPrintDateFormats.localDate=dd MMM yyyy
javers.prettyPrintDateFormats.localTime=HH:mm:ss
|
repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
private void refresh(int M_Product_ID)
{
// int M_Product_ID = 0;
String sql = m_sqlWarehouse;
// Add description to the query
sql = sql.replace(" FROM", ", DocumentNote FROM");
log.trace(sql);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, M_Product_ID);
rs = pstmt.executeQuery();
setDescription("");
warehouseTbl.loadTable(rs);
rs = pstmt.executeQuery();
if (rs.next())
{
if (rs.getString("DocumentNote") != null)
setDescription(rs.getString("DocumentNote"));
}
}
catch (Exception e)
{
log.warn(sql, e);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
}
|
private void setDescription(String description)
{
fieldDescription.setText(description);
}
public java.awt.Component getComponent(int type)
{
if (type == PANELTYPE_Stock)
return (java.awt.Component)warehouseTbl;
else if (type == PANELTYPE_Description)
return fieldDescription;
else
throw new IllegalArgumentException("Unknown panel type " + type);
}
public int getM_Warehouse_ID()
{
if (warehouseTbl.getRowCount() <= 0)
return -1;
Integer id = warehouseTbl.getSelectedRowKey();
return id == null ? -1 : id;
}
@Override
public void refresh(final int M_Product_ID, final int M_Warehouse_ID, final int M_AttributeSetInstance_ID, final int M_PriceList_Version_ID)
{
refresh(M_Product_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoProductStock.java
| 1
|
请完成以下Java代码
|
List<T> decodeRecords(@Nonnull List<R> records) {
List<T> result = new ArrayList<>(records.size());
records.forEach(record -> {
try {
if (record != null) {
result.add(decode(record));
}
} catch (Exception e) {
log.error("Failed to decode record {}", record, e);
throw new RuntimeException("Failed to decode record " + record, e);
}
});
return result;
}
List<T> sleepAndReturnEmpty(final long startNanos, final long durationInMillis) {
long durationNanos = TimeUnit.MILLISECONDS.toNanos(durationInMillis);
long spentNanos = System.nanoTime() - startNanos;
long nanosLeft = durationNanos - spentNanos;
if (nanosLeft >= ONE_MILLISECOND_IN_NANOS) {
try {
long sleepMs = TimeUnit.NANOSECONDS.toMillis(nanosLeft);
log.trace("Going to sleep after poll: topic {} for {}ms", topic, sleepMs);
Thread.sleep(sleepMs);
} catch (InterruptedException e) {
if (!stopped) {
log.error("Failed to wait", e);
}
}
}
return emptyList();
}
@Override
public void commit() {
if (consumerLock.isLocked()) {
if (stopped) {
return;
}
log.error("commit. consumerLock is locked. will wait with no timeout. it looks like a race conditions or deadlock topic " + topic, new RuntimeException("stacktrace"));
}
consumerLock.lock();
try {
doCommit();
} finally {
consumerLock.unlock();
}
}
@Override
public void stop() {
stopped = true;
}
@Override
public void unsubscribe() {
log.info("Unsubscribing and stopping consumer for {}", partitions);
stopped = true;
consumerLock.lock();
try {
if (subscribed) {
doUnsubscribe();
}
} finally {
consumerLock.unlock();
}
}
@Override
public boolean isStopped() {
return stopped;
}
|
abstract protected List<R> doPoll(long durationInMillis);
abstract protected T decode(R record) throws IOException;
abstract protected void doSubscribe(Set<TopicPartitionInfo> partitions);
abstract protected void doCommit();
abstract protected void doUnsubscribe();
@Override
public Set<TopicPartitionInfo> getPartitions() {
return partitions;
}
@Override
public List<String> getFullTopicNames() {
if (partitions == null) {
return Collections.emptyList();
}
return partitions.stream()
.map(TopicPartitionInfo::getFullTopicName)
.toList();
}
protected boolean isLongPollingSupported() {
return false;
}
}
|
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\common\AbstractTbQueueConsumerTemplate.java
| 1
|
请完成以下Java代码
|
public int size()
{
return size;
}
@Override
public boolean isQueueEmpty()
{
final boolean iteratorEmpty = !iterator.hasNext();
return iteratorEmpty && queueItemsToProcess.isEmpty();
}
@Override
public ITableRecordReference nextFromQueue()
{
final WorkQueue result = nextFromQueue0();
if (result.getDLM_Partition_Workqueue_ID() > 0)
{
queueItemsToDelete.add(result);
}
return result.getTableRecordReference();
}
private WorkQueue nextFromQueue0()
{
if (iterator.hasNext())
{
// once we get the record from the queue, we also add it to our result
final WorkQueue next = iterator.next();
final ITableRecordReference tableRecordReference = next.getTableRecordReference();
final IDLMAware model = tableRecordReference.getModel(ctxAware, IDLMAware.class);
add0(tableRecordReference, model.getDLM_Partition_ID(), true);
return next;
}
return queueItemsToProcess.removeFirst();
}
@Override
public List<WorkQueue> getQueueRecordsToStore()
{
return queueItemsToProcess;
}
@Override
public List<WorkQueue> getQueueRecordsToDelete()
{
return queueItemsToDelete;
|
}
/**
* @return the {@link Partition} from the last invokation of {@link #clearAfterPartitionStored(Partition)}, or an empty partition.
*/
@Override
public Partition getPartition()
{
return partition;
}
@Override
public void registerHandler(IIterateResultHandler handler)
{
handlerSupport.registerListener(handler);
}
@Override
public List<IIterateResultHandler> getRegisteredHandlers()
{
return handlerSupport.getRegisteredHandlers();
}
@Override
public boolean isHandlerSignaledToStop()
{
return handlerSupport.isHandlerSignaledToStop();
}
@Override
public String toString()
{
return "IterateResult [queueItemsToProcess.size()=" + queueItemsToProcess.size()
+ ", queueItemsToDelete.size()=" + queueItemsToDelete.size()
+ ", size=" + size
+ ", tableName2Record.size()=" + tableName2Record.size()
+ ", dlmPartitionId2Record.size()=" + dlmPartitionId2Record.size()
+ ", iterator=" + iterator
+ ", ctxAware=" + ctxAware
+ ", partition=" + partition + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\impl\CreatePartitionIterateResult.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CommentCollectionResource other = (CommentCollectionResource) obj;
if (taskComments == null) {
if (other.taskComments != null)
return false;
} else if (!taskComments.equals(other.taskComments))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "CommentCollectionResource [taskComments=" + taskComments + "]";
}
}
/**
* Inner class to perform the de-serialization of the comments array
*
* @author anilallewar
*
*/
class CommentsCollectionDeserializer extends JsonDeserializer<CommentCollectionResource> {
@Override
public CommentCollectionResource deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
CommentCollectionResource commentArrayResource = new CommentCollectionResource();
CommentResource commentResource = null;
|
JsonNode jsonNode = jp.readValueAsTree();
for (JsonNode childNode : jsonNode) {
if (childNode.has(CommentResource.JP_TASKID)) {
commentResource = new CommentResource();
commentResource.setTaskId(childNode.get(CommentResource.JP_TASKID).asText());
commentResource.setComment(childNode.get(CommentResource.JP_COMMENT).asText());
commentResource.setPosted(new Date(childNode.get(CommentResource.JP_POSTED).asLong()));
commentArrayResource.addComment(commentResource);
}
}
return commentArrayResource;
}
}
|
repos\spring-boot-microservices-master\task-webservice\src\main\java\com\rohitghatol\microservices\task\model\CommentCollectionResource.java
| 2
|
请完成以下Java代码
|
public ImmutableList<HUReservationEntry> getEntriesByVHUIds(@NonNull final Collection<HuId> vhuIds)
{
if (vhuIds.isEmpty())
{
return ImmutableList.of();
}
return entriesByVhuId.getAllOrLoad(vhuIds, this::retrieveEntriesByVHUId)
.stream()
.flatMap(Optionals::stream)
.collect(ImmutableList.toImmutableList());
}
private Map<HuId, Optional<HUReservationEntry>> retrieveEntriesByVHUId(@NonNull final Collection<HuId> vhuIds)
{
if (vhuIds.isEmpty())
{
return ImmutableMap.of();
} // shall not happen
final HashMap<HuId, Optional<HUReservationEntry>> result = new HashMap<>(vhuIds.size());
vhuIds.forEach(huId -> result.put(huId, Optional.empty()));
queryBL.createQueryBuilder(I_M_HU_Reservation.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_HU_Reservation.COLUMN_VHU_ID, vhuIds)
.create()
.stream()
.map(HUReservationRepository::toHUReservationEntry)
.forEach(entry -> result.put(entry.getVhuId(), Optional.of(entry)));
return ImmutableMap.copyOf(result);
}
public Optional<OrderLineId> getOrderLineIdByReservedVhuId(@NonNull final HuId vhuId)
{
return getEntryByVhuId(vhuId)
.map(entry -> entry.getDocumentRef().getSalesOrderLineId());
}
private Optional<HUReservationEntry> getEntryByVhuId(@NonNull final HuId vhuId)
{
return entriesByVhuId.getOrLoad(vhuId, this::retrieveEntryByVhuId);
}
private Optional<HUReservationEntry> retrieveEntryByVhuId(@NonNull final HuId vhuId)
{
return queryBL.createQueryBuilder(I_M_HU_Reservation.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_HU_Reservation.COLUMN_VHU_ID, vhuId) // we have a UC constraint on VHU_ID
.create()
.firstOnlyOptional(I_M_HU_Reservation.class)
.map(HUReservationRepository::toHUReservationEntry);
}
private static HUReservationDocRef extractDocumentRef(@NonNull final I_M_HU_Reservation record)
{
return HUReservationDocRef.builder()
|
.salesOrderLineId(OrderLineId.ofRepoIdOrNull(record.getC_OrderLineSO_ID()))
.projectId(ProjectId.ofRepoIdOrNull(record.getC_Project_ID()))
.pickingJobStepId(PickingJobStepId.ofRepoIdOrNull(record.getM_Picking_Job_Step_ID()))
.ddOrderLineId(DDOrderLineId.ofRepoIdOrNull(record.getDD_OrderLine_ID()))
.build();
}
public void transferReservation(
@NonNull final Collection<HUReservationDocRef> from,
@NonNull final HUReservationDocRef to,
@NonNull final Set<HuId> onlyVHUIds)
{
if (from.size() == 1 && Objects.equals(from.iterator().next(), to))
{
return;
}
final List<I_M_HU_Reservation> records = retrieveRecordsByDocumentRef(from, onlyVHUIds);
if (records.isEmpty())
{
return;
}
for (final I_M_HU_Reservation record : records)
{
updateRecordFromDocumentRef(record, to);
saveRecord(record);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\HUReservationRepository.java
| 1
|
请完成以下Java代码
|
public int getC_AcctSchema_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Charge getC_Charge() throws RuntimeException
{
return (I_C_Charge)MTable.get(getCtx(), I_C_Charge.Table_Name)
.getPO(getC_Charge_ID(), get_TrxName()); }
/** Set Charge.
@param C_Charge_ID
Additional document charges
*/
public void setC_Charge_ID (int C_Charge_ID)
{
if (C_Charge_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Charge_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Charge_ID, Integer.valueOf(C_Charge_ID));
}
/** Get Charge.
@return Additional document charges
*/
public int getC_Charge_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Charge_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getCh_Expense_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getCh_Expense_Acct(), get_TrxName()); }
/** Set Charge Expense.
@param Ch_Expense_Acct
Charge Expense Account
*/
public void setCh_Expense_Acct (int Ch_Expense_Acct)
|
{
set_Value (COLUMNNAME_Ch_Expense_Acct, Integer.valueOf(Ch_Expense_Acct));
}
/** Get Charge Expense.
@return Charge Expense Account
*/
public int getCh_Expense_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ch_Expense_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getCh_Revenue_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getCh_Revenue_Acct(), get_TrxName()); }
/** Set Charge Revenue.
@param Ch_Revenue_Acct
Charge Revenue Account
*/
public void setCh_Revenue_Acct (int Ch_Revenue_Acct)
{
set_Value (COLUMNNAME_Ch_Revenue_Acct, Integer.valueOf(Ch_Revenue_Acct));
}
/** Get Charge Revenue.
@return Charge Revenue Account
*/
public int getCh_Revenue_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ch_Revenue_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Charge_Acct.java
| 1
|
请完成以下Java代码
|
public static void forwardingEmail(Email receivedEmail) {
Email email = EmailBuilder.forwarding(receivedEmail)
.from("sender@example.com")
.prependText("This is an Forward Email. See below email:")
.buildEmail();
}
public static void handleExceptionWhenSendingEmail() {
try {
sendPlainTextEmail();
System.out.println("Email sent successfully!");
} catch (MailException e) {
System.err.println("Error: " + e.getMessage());
}
}
public static void setCustomHeaderWhenSendingEmail() {
Email email = EmailBuilder.startingBlank()
.from("sender@example.com")
.to("recipient@example.com")
.withSubject("Email with Custom Header")
.withPlainText("This is an important message.")
.withHeader("X-Priority", "1")
.buildEmail();
sendEmail(email);
}
|
private static void sendEmailWithDeliveryReadRecipient() {
Email email = EmailBuilder.startingBlank()
.from("sender@example.com")
.to("recipient@example.com")
.withSubject("Email with Delivery/Read Receipt Configured!")
.withPlainText("This is an email sending with delivery/read receipt.")
.withDispositionNotificationTo(new Recipient("name", "address@domain.com", Message.RecipientType.TO))
.withReturnReceiptTo(new Recipient("name", "address@domain.com", Message.RecipientType.TO))
.buildEmail();
sendEmail(email);
}
private static void sendEmail(Email email) {
Mailer mailer = MailerBuilder.withSMTPServer("smtp.example.com", 25, "username", "password")
.withMaximumEmailSize(1024 * 1024 * 5) // 5 Megabytes
.buildMailer();
boolean validate = mailer.validate(email);
if (validate) {
mailer.sendMail(email);
} else {
System.out.println("Invalid email address.");
}
}
}
|
repos\tutorials-master\libraries-io\src\main\java\com\baeldung\java\io\simplemail\SimpleMailExample.java
| 1
|
请完成以下Java代码
|
private <ImportRecordType> IImportProcess<ImportRecordType> newImportProcessOrNull(@NonNull final Class<ImportRecordType> modelImportClass)
{
final Class<?> importProcessClass = importProcessDescriptorsMap.getImportProcessClassByModelImportClassOrNull(modelImportClass);
if (importProcessClass == null)
{
return null;
}
return newInstance(importProcessClass);
}
private <ImportRecordType> IImportProcess<ImportRecordType> newInstance(final Class<?> importProcessClass)
{
try
{
@SuppressWarnings("unchecked")
final IImportProcess<ImportRecordType> importProcess = (IImportProcess<ImportRecordType>)importProcessClass.newInstance();
return importProcess;
}
catch (final Exception e)
{
throw new AdempiereException("Failed instantiating " + importProcessClass, e);
}
}
|
@Nullable
private <ImportRecordType> IImportProcess<ImportRecordType> newImportProcessForTableNameOrNull(@NonNull final String importTableName)
{
final Class<?> importProcessClass = importProcessDescriptorsMap.getImportProcessClassByImportTableNameOrNull(importTableName);
if (importProcessClass == null)
{
return null;
}
return newInstance(importProcessClass);
}
@Override
public <ImportRecordType> IImportProcess<ImportRecordType> newImportProcessForTableName(@NonNull final String importTableName)
{
final IImportProcess<ImportRecordType> importProcess = newImportProcessForTableNameOrNull(importTableName);
if (importProcess == null)
{
throw new AdempiereException("No import process found for " + importTableName);
}
return importProcess;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\impl\ImportProcessFactory.java
| 1
|
请完成以下Java代码
|
public void connectStart(Call call, InetSocketAddress inetSocketAddress, Proxy proxy) {
logTimedEvent("connectStart");
}
@Override
public void secureConnectStart(Call call) {
logTimedEvent("secureConnectStart");
}
@Override
public void secureConnectEnd(Call call, Handshake handshake) {
logTimedEvent("secureConnectEnd");
}
@Override
public void connectEnd(Call call, InetSocketAddress inetSocketAddress, Proxy proxy, Protocol protocol) {
logTimedEvent("connectEnd");
}
@Override
public void connectFailed(Call call, InetSocketAddress inetSocketAddress, Proxy proxy, Protocol protocol, IOException ioe) {
logTimedEvent("connectFailed");
}
@Override
public void connectionAcquired(Call call, Connection connection) {
logTimedEvent("connectionAcquired");
}
@Override
public void connectionReleased(Call call, Connection connection) {
logTimedEvent("connectionReleased");
}
@Override
public void requestHeadersStart(Call call) {
logTimedEvent("requestHeadersStart");
}
@Override
public void requestHeadersEnd(Call call, Request request) {
logTimedEvent("requestHeadersEnd");
}
@Override
public void requestBodyStart(Call call) {
logTimedEvent("requestBodyStart");
}
@Override
public void requestBodyEnd(Call call, long byteCount) {
logTimedEvent("requestBodyEnd");
}
@Override
public void requestFailed(Call call, IOException ioe) {
|
logTimedEvent("requestFailed");
}
@Override
public void responseHeadersStart(Call call) {
logTimedEvent("responseHeadersStart");
}
@Override
public void responseHeadersEnd(Call call, Response response) {
logTimedEvent("responseHeadersEnd");
}
@Override
public void responseBodyStart(Call call) {
logTimedEvent("responseBodyStart");
}
@Override
public void responseBodyEnd(Call call, long byteCount) {
logTimedEvent("responseBodyEnd");
}
@Override
public void responseFailed(Call call, IOException ioe) {
logTimedEvent("responseFailed");
}
@Override
public void callEnd(Call call) {
logTimedEvent("callEnd");
}
@Override
public void callFailed(Call call, IOException ioe) {
logTimedEvent("callFailed");
}
@Override
public void canceled(Call call) {
logTimedEvent("canceled");
}
}
|
repos\tutorials-master\libraries-http-2\src\main\java\com\baeldung\okhttp\events\EventTimer.java
| 1
|
请完成以下Java代码
|
protected abstract static class AbstractBuilder<T extends AbstractSettings, B extends AbstractBuilder<T, B>> {
private final Map<String, Object> settings = new HashMap<>();
protected AbstractBuilder() {
}
/**
* Sets a configuration setting.
* @param name the name of the setting
* @param value the value of the setting
* @return the {@link AbstractBuilder} for further configuration
*/
public B setting(String name, Object value) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(value, "value cannot be null");
getSettings().put(name, value);
return getThis();
}
/**
* A {@code Consumer} of the configuration settings {@code Map} allowing the
* ability to add, replace, or remove.
* @param settingsConsumer a {@link Consumer} of the configuration settings
* {@code Map}
* @return the {@link AbstractBuilder} for further configuration
*/
public B settings(Consumer<Map<String, Object>> settingsConsumer) {
settingsConsumer.accept(getSettings());
|
return getThis();
}
public abstract T build();
protected final Map<String, Object> getSettings() {
return this.settings;
}
@SuppressWarnings("unchecked")
protected final B getThis() {
return (B) this;
}
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\settings\AbstractSettings.java
| 1
|
请完成以下Java代码
|
public void clear()
{
}
public int size()
{
return getMaxid_();
}
public int ysize()
{
return y_.size();
}
public int getMaxid_()
{
return maxid_;
}
public void setMaxid_(int maxid_)
{
this.maxid_ = maxid_;
}
public double[] getAlpha_()
{
return alpha_;
}
public void setAlpha_(double[] alpha_)
{
this.alpha_ = alpha_;
}
public float[] getAlphaFloat_()
{
return alphaFloat_;
}
public void setAlphaFloat_(float[] alphaFloat_)
{
this.alphaFloat_ = alphaFloat_;
}
public double getCostFactor_()
{
return costFactor_;
}
public void setCostFactor_(double costFactor_)
{
this.costFactor_ = costFactor_;
}
public int getXsize_()
{
return xsize_;
}
public void setXsize_(int xsize_)
{
this.xsize_ = xsize_;
}
public int getMax_xsize_()
{
return max_xsize_;
}
public void setMax_xsize_(int max_xsize_)
{
this.max_xsize_ = max_xsize_;
}
public int getThreadNum_()
{
return threadNum_;
}
public void setThreadNum_(int threadNum_)
{
this.threadNum_ = threadNum_;
}
public List<String> getUnigramTempls_()
{
return unigramTempls_;
}
public void setUnigramTempls_(List<String> unigramTempls_)
{
this.unigramTempls_ = unigramTempls_;
|
}
public List<String> getBigramTempls_()
{
return bigramTempls_;
}
public void setBigramTempls_(List<String> bigramTempls_)
{
this.bigramTempls_ = bigramTempls_;
}
public List<String> getY_()
{
return y_;
}
public void setY_(List<String> y_)
{
this.y_ = y_;
}
public List<List<Path>> getPathList_()
{
return pathList_;
}
public void setPathList_(List<List<Path>> pathList_)
{
this.pathList_ = pathList_;
}
public List<List<Node>> getNodeList_()
{
return nodeList_;
}
public void setNodeList_(List<List<Node>> nodeList_)
{
this.nodeList_ = nodeList_;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\FeatureIndex.java
| 1
|
请完成以下Java代码
|
public class HUAttributeStorageFactory extends AbstractModelAttributeStorageFactory<I_M_HU, HUAttributeStorage>
{
@Override
public boolean isHandled(final Object model)
{
if (model == null)
{
return false;
}
return InterfaceWrapperHelper.isInstanceOf(model, I_M_HU.class);
}
@Override
protected I_M_HU getModelFromObject(final Object modelObj)
{
final I_M_HU hu = InterfaceWrapperHelper.create(modelObj, I_M_HU.class);
return hu;
}
@Override
protected final ArrayKey mkKey(final I_M_HU model)
{
return Util.mkKey(model.getClass().getName(), model.getM_HU_ID());
}
|
@Override
protected HUAttributeStorage createAttributeStorage(final I_M_HU model)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(model);
final String trxName = InterfaceWrapperHelper.getTrxName(model);
final int huId = model.getM_HU_ID();
return createAttributeStorageCached(ctx, huId, trxName, model);
}
// @Cached // commented out because it's not applied anyways
/* package */HUAttributeStorage createAttributeStorageCached(
@CacheCtx final Properties ctx,
final int huId,
@CacheTrx final String trxName,
@CacheIgnore final I_M_HU hu)
{
final HUAttributeStorage storage = new HUAttributeStorage(this, hu);
return storage;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\HUAttributeStorageFactory.java
| 1
|
请完成以下Java代码
|
public boolean setLoading(boolean loading)
{
final boolean loadingOld = this._loading;
if (loadingOld == loading)
{
return loadingOld;
}
this._loading = loading;
// Loading flag was switched from "true" to "false"
if (!this._loading)
{
firePropertyChange(PROPERTY_SelectionChanged, false, true);
}
return loadingOld;
}
public boolean isLoading()
{
return _loading;
}
private Map<String, Integer> columnName2modelIndex = new HashMap<String, Integer>();
/**
* Note: this method only works as expected if the given <code>columnName</code> was set with {@link ColumnInfo#setColumnName(String)}.
*
* @param columnName
* @return
*/
public int getColumnModelIndex(final String columnName)
{
final Integer indexModel = columnName2modelIndex.get(columnName);
if (indexModel == null)
{
return -1;
}
return indexModel;
}
/**
* Note: this method only works as expected if the given <code>columnName</code> was set with {@link ColumnInfo#setColumnName(String)}.
*
* @param rowIndexView
* @param columnName
* @return
|
*/
public Object getValueAt(final int rowIndexView, final String columnName)
{
final int colIndexModel = getColumnModelIndex(columnName);
if (colIndexModel < 0) // it starts with 0, not with 1, so it's <0, not <=0
{
throw new IllegalArgumentException("No column index found for " + columnName);
}
final int rowIndexModel = convertRowIndexToModel(rowIndexView);
return getModel().getValueAt(rowIndexModel, colIndexModel);
}
public void setValueAt(final Object value, final int rowIndexView, final String columnName)
{
final int colIndexModel = getColumnModelIndex(columnName);
if (colIndexModel <= 0)
{
throw new IllegalArgumentException("No column index found for " + columnName);
}
final int rowIndexModel = convertRowIndexToModel(rowIndexView);
getModel().setValueAt(value, rowIndexModel, colIndexModel);
}
@Override
public void clear()
{
final PO[] pos = new PO[] {};
loadTable(pos);
}
} // MiniTable
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\minigrid\MiniTable.java
| 1
|
请完成以下Java代码
|
public HistoricExternalTaskLogQuery orderByTimestamp() {
orderBy(HistoricExternalTaskLogQueryProperty.TIMESTAMP);
return this;
}
@Override
public HistoricExternalTaskLogQuery orderByExternalTaskId() {
orderBy(HistoricExternalTaskLogQueryProperty.EXTERNAL_TASK_ID);
return this;
}
@Override
public HistoricExternalTaskLogQuery orderByRetries() {
orderBy(HistoricExternalTaskLogQueryProperty.RETRIES);
return this;
}
@Override
public HistoricExternalTaskLogQuery orderByPriority() {
orderBy(HistoricExternalTaskLogQueryProperty.PRIORITY);
return this;
}
@Override
public HistoricExternalTaskLogQuery orderByTopicName() {
orderBy(HistoricExternalTaskLogQueryProperty.TOPIC_NAME);
return this;
}
@Override
public HistoricExternalTaskLogQuery orderByWorkerId() {
orderBy(HistoricExternalTaskLogQueryProperty.WORKER_ID);
return this;
}
@Override
public HistoricExternalTaskLogQuery orderByActivityId() {
orderBy(HistoricExternalTaskLogQueryProperty.ACTIVITY_ID);
return this;
}
@Override
public HistoricExternalTaskLogQuery orderByActivityInstanceId() {
orderBy(HistoricExternalTaskLogQueryProperty.ACTIVITY_INSTANCE_ID);
return this;
}
@Override
public HistoricExternalTaskLogQuery orderByExecutionId() {
orderBy(HistoricExternalTaskLogQueryProperty.EXECUTION_ID);
return this;
}
@Override
public HistoricExternalTaskLogQuery orderByProcessInstanceId() {
orderBy(HistoricExternalTaskLogQueryProperty.PROCESS_INSTANCE_ID);
return this;
}
@Override
public HistoricExternalTaskLogQuery orderByProcessDefinitionId() {
orderBy(HistoricExternalTaskLogQueryProperty.PROCESS_DEFINITION_ID);
return this;
}
@Override
|
public HistoricExternalTaskLogQuery orderByProcessDefinitionKey() {
orderBy(HistoricExternalTaskLogQueryProperty.PROCESS_DEFINITION_KEY);
return this;
}
@Override
public HistoricExternalTaskLogQuery orderByTenantId() {
orderBy(HistoricExternalTaskLogQueryProperty.TENANT_ID);
return this;
}
// results //////////////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getHistoricExternalTaskLogManager()
.findHistoricExternalTaskLogsCountByQueryCriteria(this);
}
@Override
public List<HistoricExternalTaskLog> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getHistoricExternalTaskLogManager()
.findHistoricExternalTaskLogsByQueryCriteria(this, page);
}
// getters & setters ////////////////////////////////////////////////////////////
protected void setState(ExternalTaskState state) {
this.state = state;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricExternalTaskLogQueryImpl.java
| 1
|
请完成以下Java代码
|
private void generateInvoice(int M_RMA_ID)
{
MRMA rma = new MRMA(getCtx(), M_RMA_ID, get_TrxName());
MInvoice invoice = createInvoice(rma);
MInvoiceLine invoiceLines[] = createInvoiceLines(rma, invoice);
if (invoiceLines.length == 0)
{
log.warn("No invoice lines created: M_RMA_ID="
+ M_RMA_ID + ", M_Invoice_ID=" + invoice.get_ID());
}
StringBuffer processMsg = new StringBuffer(invoice.getDocumentNo());
if (!invoice.processIt(p_docAction))
|
{
processMsg.append(" (NOT Processed)");
log.warn("Invoice Processing failed: " + invoice + " - " + invoice.getProcessMsg());
}
if (!invoice.save())
{
throw new IllegalStateException("Could not update invoice");
}
// Add processing information to process log
addLog(invoice.getC_Invoice_ID(), invoice.getDateInvoiced(), null, processMsg.toString());
m_created++;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\adempiere\process\InvoiceGenerateRMA.java
| 1
|
请完成以下Java代码
|
public String toString()
{
StringBuffer sb = new StringBuffer ("X_R_InterestArea[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set 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;
}
/** 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 Interest Area.
@param R_InterestArea_ID
Interest Area or Topic
*/
public void setR_InterestArea_ID (int R_InterestArea_ID)
{
if (R_InterestArea_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, Integer.valueOf(R_InterestArea_ID));
}
/** Get Interest Area.
@return Interest Area or Topic
*/
public int getR_InterestArea_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_InterestArea_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_InterestArea.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<RestIdentityLink> getIdentityLinks(@ApiParam(name = "processInstanceId") @PathVariable String processInstanceId) {
ProcessInstance processInstance = getProcessInstanceFromRequestWithoutAccessCheck(processInstanceId);
if (restApiInterceptor != null) {
restApiInterceptor.accessProcessInstanceIdentityLinks(processInstance);
}
return restResponseFactory.createRestIdentityLinks(runtimeService.getIdentityLinksForProcessInstance(processInstance.getId()));
}
@ApiOperation(value = "Add an involved user to a process instance", tags = {"Process Instance Identity Links" }, nickname = "createProcessInstanceIdentityLinks",
notes = "Note that the groupId in Response Body will always be null, as it’s only possible to involve users with a process-instance.",
code = 201)
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Indicates the process instance was found and the link is created."),
@ApiResponse(code = 400, message = "Indicates the requested body did not contain a userId or a type."),
@ApiResponse(code = 404, message = "Indicates the requested process instance was not found.")
})
@PostMapping(value = "/runtime/process-instances/{processInstanceId}/identitylinks", produces = "application/json")
@ResponseStatus(HttpStatus.CREATED)
public RestIdentityLink createIdentityLink(@ApiParam(name = "processInstanceId") @PathVariable String processInstanceId, @RequestBody RestIdentityLink identityLink) {
ProcessInstance processInstance = getProcessInstanceFromRequestWithoutAccessCheck(processInstanceId);
if (identityLink.getGroup() != null) {
throw new FlowableIllegalArgumentException("Only user identity links are supported on a process instance.");
}
|
if (identityLink.getUser() == null) {
throw new FlowableIllegalArgumentException("The user is required.");
}
if (identityLink.getType() == null) {
throw new FlowableIllegalArgumentException("The identity link type is required.");
}
if (restApiInterceptor != null) {
restApiInterceptor.createProcessInstanceIdentityLink(processInstance, identityLink);
}
runtimeService.addUserIdentityLink(processInstance.getId(), identityLink.getUser(), identityLink.getType());
return restResponseFactory.createRestIdentityLink(identityLink.getType(), identityLink.getUser(), identityLink.getGroup(), null, null, processInstance.getId());
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ProcessInstanceIdentityLinkCollectionResource.java
| 2
|
请完成以下Java代码
|
private void createValue()
{
// Get Warehouse Info
KeyNamePair pp = (KeyNamePair)fWarehouse.getSelectedItem();
if (pp == null)
return;
loadWarehouseInfo(pp.getKey());
//
StringBuffer buf = new StringBuffer(m_M_WarehouseValue);
buf.append(m_Separator).append(fX.getText());
buf.append(m_Separator).append(fY.getText());
buf.append(m_Separator).append(fZ.getText());
fValue.setText(buf.toString());
} // createValue
/**
* OK - check for changes (save them) & Exit
*/
private void actionOK()
{
if (fCreateNew.isSelected())
{
// Get Warehouse Info
KeyNamePair pp = (KeyNamePair)fWarehouse.getSelectedItem();
if (pp != null)
loadWarehouseInfo(pp.getKey());
// Check mandatory values
String mandatoryFields = "";
if (m_M_Warehouse_ID == null)
{
mandatoryFields += lWarehouse.getText() + " - ";
}
if (fValue.getText().length()==0)
mandatoryFields += lValue.getText() + " - ";
if (fX.getText().length()==0)
mandatoryFields += lX.getText() + " - ";
if (fY.getText().length()==0)
mandatoryFields += lY.getText() + " - ";
if (fZ.getText().length()==0)
mandatoryFields += lZ.getText() + " - ";
if (mandatoryFields.length() != 0)
{
ADialog.error(m_WindowNo, this, "FillMandatory", mandatoryFields.substring(0, mandatoryFields.length()-3));
return;
}
final I_M_Locator locator = warehousesRepo.getOrCreateLocatorByCoordinates(m_M_Warehouse_ID,
fValue.getText(),
fX.getText(),
fY.getText(),
fZ.getText());
m_M_Locator_ID = locator.getM_Locator_ID();
final MLocator locatorPO = LegacyAdapters.convertToPO(locator);
fLocator.addItem(locatorPO);
fLocator.setSelectedItem(locatorPO);
} // createNew
//
log.info("M_Locator_ID=" + m_M_Locator_ID);
} // actionOK
|
/**
* Get Selected value
*
* @return value as Integer
*/
public Integer getValue()
{
MLocator l = getSelectedLocator();
if (l != null && l.getM_Locator_ID() != 0)
return new Integer(l.getM_Locator_ID());
return null;
} // getValue
/**
* Get result
*
* @return true if changed
*/
public boolean isChanged()
{
if (m_change)
{
MLocator l = getSelectedLocator();
if (l != null)
return l.getM_Locator_ID() == m_M_Locator_ID;
}
return m_change;
} // getChange
} // VLocatorDialog
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLocatorDialog.java
| 1
|
请完成以下Java代码
|
public boolean isInitialized() {
return variables != null;
}
public void forceInitialization() {
if (!isInitialized()) {
variables = new HashMap<>();
for (T variable : variablesProvider.provideVariables()) {
variables.put(variable.getName(), variable);
}
}
}
public T removeVariable(String variableName) {
if (!getVariablesMap().containsKey(variableName)) {
return null;
}
T value = getVariablesMap().remove(variableName);
for (VariableStoreObserver<T> observer : observers) {
observer.onRemove(value);
}
removedVariables.put(variableName, value);
return value;
}
public void removeVariables() {
Iterator<T> valuesIt = getVariablesMap().values().iterator();
removedVariables.putAll(variables);
while (valuesIt.hasNext()) {
T nextVariable = valuesIt.next();
valuesIt.remove();
for (VariableStoreObserver<T> observer : observers) {
observer.onRemove(nextVariable);
}
}
}
public void addObserver(VariableStoreObserver<T> observer) {
observers.add(observer);
}
|
public void removeObserver(VariableStoreObserver<T> observer) {
observers.remove(observer);
}
public static interface VariableStoreObserver<T extends CoreVariableInstance> {
void onAdd(T variable);
void onRemove(T variable);
}
public static interface VariablesProvider<T extends CoreVariableInstance> {
Collection<T> provideVariables();
Collection<T> provideVariables(Collection<String> variableNames);
}
public boolean isRemoved(String variableName) {
return removedVariables.containsKey(variableName);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\VariableStore.java
| 1
|
请完成以下Java代码
|
public ReactiveSessionInformation withSessionId(String sessionId) {
return new ReactiveSessionInformation(this.principal, sessionId, this.lastAccessTime);
}
public Mono<Void> invalidate() {
return Mono.fromRunnable(() -> this.expired = true);
}
public Mono<Void> refreshLastRequest() {
this.lastAccessTime = Instant.now();
return Mono.empty();
}
public Instant getLastAccessTime() {
return this.lastAccessTime;
}
public Object getPrincipal() {
|
return this.principal;
}
public String getSessionId() {
return this.sessionId;
}
public boolean isExpired() {
return this.expired;
}
public void setLastAccessTime(Instant lastAccessTime) {
this.lastAccessTime = lastAccessTime;
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\core\session\ReactiveSessionInformation.java
| 1
|
请完成以下Java代码
|
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
public List<Node> getChildArray() {
return childArray;
|
}
public void setChildArray(List<Node> childArray) {
this.childArray = childArray;
}
public Node getRandomChildNode() {
int noOfPossibleMoves = this.childArray.size();
int selectRandom = (int) (Math.random() * noOfPossibleMoves);
return this.childArray.get(selectRandom);
}
public Node getChildWithMaxScore() {
return Collections.max(this.childArray, Comparator.comparing(c -> {
return c.getState().getVisitCount();
}));
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\mcts\tree\Node.java
| 1
|
请完成以下Java代码
|
public void parseStartEvent(Element startEventElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseExclusiveGateway(Element exclusiveGwElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseInclusiveGateway(Element inclusiveGwElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseParallelGateway(Element parallelGwElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseScriptTask(Element scriptTaskElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseServiceTask(Element serviceTaskElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseBusinessRuleTask(Element businessRuleTaskElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseTask(Element taskElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseManualTask(Element manualTaskElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseUserTask(Element userTaskElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseEndEvent(Element endEventElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
|
public void parseSubProcess(Element subProcessElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseCallActivity(Element callActivityElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseSendTask(Element sendTaskElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseReceiveTask(Element receiveTaskElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseEventBasedGateway(Element eventBasedGwElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseIntermediateCatchEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseBoundaryEvent(Element boundaryEventElement, ScopeImpl scopeElement, ActivityImpl activity) {
addListeners(activity);
}
public void parseMultiInstanceLoopCharacteristics(Element activityElement, Element multiInstanceLoopCharacteristicsElement, ActivityImpl activity) {
addListeners(activity);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\parser\MetricsBpmnParseListener.java
| 1
|
请完成以下Java代码
|
public Map<String, Class> getDependentEntities() {
return persistedDependentEntities;
}
@Override
public void postLoad() {
if (exceptionByteArrayId != null) {
persistedDependentEntities = new HashMap<>();
persistedDependentEntities.put(exceptionByteArrayId, ByteArrayEntity.class);
}
else {
persistedDependentEntities = Collections.EMPTY_MAP;
}
}
public String getLastFailureLogId() {
return lastFailureLogId;
}
public void setLastFailureLogId(String lastFailureLogId) {
this.lastFailureLogId = lastFailureLogId;
}
@Override
public String getFailedActivityId() {
return failedActivityId;
}
public void setFailedActivityId(String failedActivityId) {
this.failedActivityId = failedActivityId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
|
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", duedate=" + duedate
+ ", lockOwner=" + lockOwner
+ ", lockExpirationTime=" + lockExpirationTime
+ ", executionId=" + executionId
+ ", processInstanceId=" + processInstanceId
+ ", isExclusive=" + isExclusive
+ ", jobDefinitionId=" + jobDefinitionId
+ ", jobHandlerType=" + jobHandlerType
+ ", jobHandlerConfiguration=" + jobHandlerConfiguration
+ ", exceptionByteArray=" + exceptionByteArray
+ ", exceptionByteArrayId=" + exceptionByteArrayId
+ ", exceptionMessage=" + exceptionMessage
+ ", failedActivityId=" + failedActivityId
+ ", deploymentId=" + deploymentId
+ ", priority=" + priority
+ ", tenantId=" + tenantId
+ ", batchId=" + batchId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\JobEntity.java
| 1
|
请完成以下Java代码
|
public String getBusinessKey() {
return businessKey;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public String getBusinessStatus() {
return businessStatus;
}
public String getCaseInstanceName() {
return caseInstanceName;
}
public void setCaseInstanceName(String caseInstanceName) {
this.caseInstanceName = caseInstanceName;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
public Case getCaseModel() {
return caseModel;
}
public void setCaseModel(Case caseModel) {
|
this.caseModel = caseModel;
}
public CaseDefinition getCaseDefinition() {
return caseDefinition;
}
public void setCaseDefinition(CaseDefinition caseDefinition) {
this.caseDefinition = caseDefinition;
}
public CmmnModel getCmmnModel() {
return cmmnModel;
}
public void setCmmnModel(CmmnModel cmmnModel) {
this.cmmnModel = cmmnModel;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\interceptor\AbstractStartCaseInstanceBeforeContext.java
| 1
|
请完成以下Java代码
|
public void unprocess()
{
this.isProcessed = false;
}
public void updateToleranceExceededFlag()
{
assertNotProcessed();
boolean isToleranceExceededNew = false;
for (PPOrderWeightingRunCheck check : checks)
{
check.updateIsToleranceExceeded(targetWeightRange);
if (check.isToleranceExceeded())
{
isToleranceExceededNew = true;
}
}
this.isToleranceExceeded = isToleranceExceededNew;
}
public void updateTargetWeightRange()
{
assertNotProcessed();
final Quantity toleranceQty = targetWeight.multiply(tolerance).abs();
this.targetWeightRange = Range.closed(
targetWeight.subtract(toleranceQty),
targetWeight.add(toleranceQty)
);
updateToleranceExceededFlag();
}
public void updateUOMFromHeaderToChecks()
|
{
assertNotProcessed();
for (final PPOrderWeightingRunCheck check : checks)
{
check.setUomId(targetWeight.getUomId());
}
}
private void assertNotProcessed()
{
if (isProcessed)
{
throw new AdempiereException("Already processed");
}
}
public I_C_UOM getUOM()
{
return targetWeight.getUOM();
}
public SeqNo getNextLineNo()
{
final SeqNo lastLineNo = checks.stream()
.map(PPOrderWeightingRunCheck::getLineNo)
.max(Comparator.naturalOrder())
.orElseGet(() -> SeqNo.ofInt(0));
return lastLineNo.next();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\PPOrderWeightingRun.java
| 1
|
请完成以下Java代码
|
public List<Comment> getProcessInstanceComments(String processInstanceId, String type) {
return commandExecutor.execute(new GetProcessInstanceCommentsCmd(processInstanceId, type));
}
@Override
public Attachment createAttachment(String attachmentType, String taskId, String processInstanceId, String attachmentName, String attachmentDescription, InputStream content) {
return commandExecutor.execute(new CreateAttachmentCmd(attachmentType, taskId, processInstanceId, attachmentName, attachmentDescription, content, null));
}
@Override
public Attachment createAttachment(String attachmentType, String taskId, String processInstanceId, String attachmentName, String attachmentDescription, String url) {
return commandExecutor.execute(new CreateAttachmentCmd(attachmentType, taskId, processInstanceId, attachmentName, attachmentDescription, null, url));
}
@Override
public InputStream getAttachmentContent(String attachmentId) {
return commandExecutor.execute(new GetAttachmentContentCmd(attachmentId));
}
@Override
public void deleteAttachment(String attachmentId) {
commandExecutor.execute(new DeleteAttachmentCmd(attachmentId));
}
@Override
public void deleteComments(String taskId, String processInstanceId) {
commandExecutor.execute(new DeleteCommentCmd(taskId, processInstanceId, null));
}
@Override
public void deleteComment(String commentId) {
commandExecutor.execute(new DeleteCommentCmd(null, null, commentId));
}
@Override
public Attachment getAttachment(String attachmentId) {
return commandExecutor.execute(new GetAttachmentCmd(attachmentId));
}
|
@Override
public List<Attachment> getTaskAttachments(String taskId) {
return commandExecutor.execute(new GetTaskAttachmentsCmd(taskId));
}
@Override
public List<Attachment> getProcessInstanceAttachments(String processInstanceId) {
return commandExecutor.execute(new GetProcessInstanceAttachmentsCmd(processInstanceId));
}
@Override
public void saveAttachment(Attachment attachment) {
commandExecutor.execute(new SaveAttachmentCmd(attachment));
}
@Override
public List<Task> getSubTasks(String parentTaskId) {
return commandExecutor.execute(new GetSubTasksCmd(parentTaskId));
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\TaskServiceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WSTerminalSession implements Runnable, Consumer<String> {
private static final Logger LOG = LoggerFactory.getLogger(WSTerminalSession.class);
private final WebSocketSession session;
public WSTerminalSession(WebSocketSession session) {
this.session = session;
}
@Override
public void run() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
this.session.sendMessage(new TextMessage("sh -c ls -la\r\n"));
ProcessBuilder builder = new ProcessBuilder();
builder.command("sh", "-c", "ls -la");
builder.directory(new File(System.getProperty("user.home")));
Process process = builder.start();
StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), this::accept);
executorService.submit(streamGobbler);
int exitCode = process.waitFor();
assert exitCode == 0;
} catch (IOException e) {
LOG.error("IOException: ", e);
} catch (InterruptedException e) {
LOG.error("InterruptedException: ", e);
} finally {
executorService.shutdownNow();
}
}
@Override
|
public void accept(String message) {
Executors.newSingleThreadExecutor().submit(new WSSender(session, message));
//this.session.sendMessage(new TextMessage(message));
}
private class WSSender implements Runnable {
private final WebSocketSession session;
private final String message;
public WSSender(WebSocketSession session, String message) {
this.session = session;
this.message = message;
}
@Override
public void run() {
try {
this.session.sendMessage(new TextMessage(message + "\r\n"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
|
repos\spring-examples-java-17\spring-websockets\src\main\java\itx\examples\springboot\websockets\config\WSTerminalSession.java
| 2
|
请完成以下Java代码
|
public void setC_Queue_Workpackage_Preceeding(final I_C_Queue_WorkPackage C_Queue_Workpackage_Preceeding)
{
set_ValueFromPO(COLUMNNAME_C_Queue_Workpackage_Preceeding_ID, I_C_Queue_WorkPackage.class, C_Queue_Workpackage_Preceeding);
}
@Override
public void setC_Queue_Workpackage_Preceeding_ID (final int C_Queue_Workpackage_Preceeding_ID)
{
throw new IllegalArgumentException ("C_Queue_Workpackage_Preceeding_ID is virtual column"); }
@Override
public int getC_Queue_Workpackage_Preceeding_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Queue_Workpackage_Preceeding_ID);
}
|
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_Element.java
| 1
|
请完成以下Java代码
|
public AssetProfileId getAssetProfileId() {
return assetProfileId;
}
public void setAssetProfileId(AssetProfileId assetProfileId) {
this.assetProfileId = assetProfileId;
}
@Schema(description = "Additional parameters of the asset",implementation = com.fasterxml.jackson.databind.JsonNode.class)
@Override
public JsonNode getAdditionalInfo() {
return super.getAdditionalInfo();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Asset [tenantId=");
builder.append(tenantId);
builder.append(", customerId=");
builder.append(customerId);
|
builder.append(", name=");
builder.append(name);
builder.append(", type=");
builder.append(type);
builder.append(", label=");
builder.append(label);
builder.append(", assetProfileId=");
builder.append(assetProfileId);
builder.append(", additionalInfo=");
builder.append(getAdditionalInfo());
builder.append(", createdTime=");
builder.append(createdTime);
builder.append(", id=");
builder.append(id);
builder.append("]");
return builder.toString();
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\asset\Asset.java
| 1
|
请完成以下Java代码
|
public class TableMetaData {
protected String tableName;
protected List<String> columnNames = new ArrayList<String>();
protected List<String> columnTypes = new ArrayList<String>();
public TableMetaData() {}
public TableMetaData(String tableName) {
this.tableName = tableName;
}
public void addColumnMetaData(String columnName, String columnType) {
columnNames.add(columnName);
columnTypes.add(columnType);
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
|
this.tableName = tableName;
}
public List<String> getColumnNames() {
return columnNames;
}
public void setColumnNames(List<String> columnNames) {
this.columnNames = columnNames;
}
public List<String> getColumnTypes() {
return columnTypes;
}
public void setColumnTypes(List<String> columnTypes) {
this.columnTypes = columnTypes;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\management\TableMetaData.java
| 1
|
请完成以下Java代码
|
public class TomcatBpmPlatformBootstrap implements LifecycleListener {
private final static ContainerIntegrationLogger LOG = ProcessEngineLogger.CONTAINER_INTEGRATION_LOGGER;
protected ProcessEngine processEngine;
protected RuntimeContainerDelegateImpl containerDelegate;
public void lifecycleEvent(LifecycleEvent event) {
if (Lifecycle.START_EVENT.equals(event.getType())) {
// the Apache Tomcat integration uses the Jmx Container for managing process engines and applications.
containerDelegate = (RuntimeContainerDelegateImpl) RuntimeContainerDelegate.INSTANCE.get();
deployBpmPlatform(event);
}
else if (Lifecycle.STOP_EVENT.equals(event.getType())) {
undeployBpmPlatform(event);
}
}
protected void deployBpmPlatform(LifecycleEvent event) {
final StandardServer server = (StandardServer) event.getSource();
containerDelegate.getServiceContainer().createDeploymentOperation("deploy BPM platform")
.addAttachment(TomcatAttachments.SERVER, server)
.addStep(new TomcatParseBpmPlatformXmlStep())
.addStep(new DiscoverBpmPlatformPluginsStep())
.addStep(new StartManagedThreadPoolStep())
.addStep(new StartJobExecutorStep())
.addStep(new PlatformXmlStartProcessEnginesStep())
.execute();
|
LOG.camundaBpmPlatformSuccessfullyStarted(server.getServerInfo());
}
protected void undeployBpmPlatform(LifecycleEvent event) {
final StandardServer server = (StandardServer) event.getSource();
containerDelegate.getServiceContainer().createUndeploymentOperation("undeploy BPM platform")
.addAttachment(TomcatAttachments.SERVER, server)
.addStep(new StopJobExecutorStep())
.addStep(new StopManagedThreadPoolStep())
.addStep(new StopProcessApplicationsStep())
.addStep(new StopProcessEnginesStep())
.addStep(new UnregisterBpmPlatformPluginsStep())
.execute();
LOG.camundaBpmPlatformStopped(server.getServerInfo());
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\tomcat\TomcatBpmPlatformBootstrap.java
| 1
|
请完成以下Java代码
|
public Class<I_I_Replenish> getImportModelClass()
{
return I_I_Replenish.class;
}
@Override
public String getImportTableName()
{
return I_I_Replenish.Table_Name;
}
@Override
protected String getTargetTableName()
{
return I_M_Replenish.Table_Name;
}
@Override
protected void updateAndValidateImportRecordsImpl()
{
final ImportRecordsSelection selection = getImportRecordsSelection();
RepelnishmentImportTableSqlUpdater.updateReplenishmentImportTable(selection);
}
@Override
protected String getImportOrderBySql()
{
return I_I_Replenish.COLUMNNAME_ProductValue;
}
@Override
public I_I_Replenish retrieveImportRecord(final Properties ctx, final ResultSet rs) throws SQLException
{
return new X_I_Replenish(ctx, rs, ITrx.TRXNAME_ThreadInherited);
}
/*
* @param isInsertOnly ignored. This import is only for updates.
*/
@Override
protected ImportRecordResult importRecord(
@NonNull final IMutable<Object> state_NOTUSED,
@NonNull final I_I_Replenish importRecord,
final boolean isInsertOnly_NOTUSED)
{
if (ReplenishImportHelper.isValidRecordForImport(importRecord))
{
return importReplenish(importRecord);
}
else
{
throw new AdempiereException(MSG_NoValidRecord);
}
}
|
private ImportRecordResult importReplenish(@NonNull final I_I_Replenish importRecord)
{
final ImportRecordResult replenishImportResult;
final I_M_Replenish replenish;
if (importRecord.getM_Replenish_ID() <= 0)
{
replenish = ReplenishImportHelper.createNewReplenish(importRecord);
replenishImportResult = ImportRecordResult.Inserted;
}
else
{
replenish = ReplenishImportHelper.uppdateReplenish(importRecord);
replenishImportResult = ImportRecordResult.Updated;
}
InterfaceWrapperHelper.save(replenish);
importRecord.setM_Replenish_ID(replenish.getM_Replenish_ID());
InterfaceWrapperHelper.save(importRecord);
return replenishImportResult;
}
@Override
protected void markImported(@NonNull final I_I_Replenish importRecord)
{
importRecord.setI_IsImported(X_I_Replenish.I_ISIMPORTED_Imported);
importRecord.setProcessed(true);
InterfaceWrapperHelper.save(importRecord);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\replenishment\impexp\ReplenishmentImportProcess.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getEndActivityId() {
return endActivityId;
}
public void setEndActivityId(String endActivityId) {
this.endActivityId = endActivityId;
}
@ApiModelProperty(example = "null")
public String getDeleteReason() {
return deleteReason;
}
public void setDeleteReason(String deleteReason) {
this.deleteReason = deleteReason;
}
@ApiModelProperty(example = "3")
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public void setSuperProcessInstanceId(String superProcessInstanceId) {
this.superProcessInstanceId = superProcessInstanceId;
}
public List<RestVariable> getVariables() {
return variables;
}
public void setVariables(List<RestVariable> variables) {
this.variables = variables;
}
public void addVariable(RestVariable variable) {
variables.add(variable);
}
@ApiModelProperty(example = "3")
public String getCallbackId() {
return callbackId;
}
public void setCallbackId(String callbackId) {
this.callbackId = callbackId;
}
@ApiModelProperty(example = "cmmn")
public String getCallbackType() {
return callbackType;
}
public void setCallbackType(String callbackType) {
this.callbackType = callbackType;
|
}
@ApiModelProperty(example = "123")
public String getReferenceId() {
return referenceId;
}
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
@ApiModelProperty(example = "event-to-bpmn-2.0-process")
public String getReferenceType() {
return referenceType;
}
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
@ApiModelProperty(value = "The stage plan item instance id this process instance belongs to or null, if it is not part of a case at all or is not a child element of a stage")
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
public void setPropagatedStageInstanceId(String propagatedStageInstanceId) {
this.propagatedStageInstanceId = propagatedStageInstanceId;
}
@ApiModelProperty(example = "someTenantId")
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() {
return tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricProcessInstanceResponse.java
| 2
|
请完成以下Java代码
|
class StringNormalizer {
static String removeAccentsWithApacheCommons(String input) {
return StringUtils.stripAccents(input);
}
static String removeAccents(String input) {
return normalize(input).replaceAll("\\p{M}", "");
}
static String unicodeValueOfNormalizedString(String input) {
return toUnicode(normalize(input));
}
private static String normalize(String input) {
return input == null ? null : Normalizer.normalize(input, Normalizer.Form.NFKD);
}
private static String toUnicode(String input) {
if (input.length() == 1) {
return toUnicode(input.charAt(0));
} else {
StringJoiner stringJoiner = new StringJoiner(" ");
for (char c : input.toCharArray()) {
stringJoiner.add(toUnicode(c));
}
return stringJoiner.toString();
|
}
}
private static String toUnicode(char input) {
String hex = Integer.toHexString(input);
StringBuilder sb = new StringBuilder(hex);
while (sb.length() < 4) {
sb.insert(0, "0");
}
sb.insert(0, "\\u");
return sb.toString();
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-operations-3\src\main\java\com\baeldung\accentsanddiacriticsremoval\StringNormalizer.java
| 1
|
请完成以下Java代码
|
public boolean supports(ConfigAttribute attribute) {
return (attribute.getAttribute() != null) && attribute.getAttribute().equals(getProcessConfigAttribute());
}
@Override
public int vote(Authentication authentication, MethodInvocation object, Collection<ConfigAttribute> attributes) {
for (ConfigAttribute attr : attributes) {
if (!supports(attr)) {
continue;
}
// Need to make an access decision on this invocation
// Attempt to locate the domain object instance to process
Object domainObject = getDomainObjectInstance(object);
// If domain object is null, vote to abstain
if (domainObject == null) {
logger.debug("Voting to abstain - domainObject is null");
return ACCESS_ABSTAIN;
}
// Evaluate if we are required to use an inner domain object
if (StringUtils.hasText(this.internalMethod)) {
domainObject = invokeInternalMethod(domainObject);
}
// Obtain the OID applicable to the domain object
ObjectIdentity objectIdentity = this.objectIdentityRetrievalStrategy.getObjectIdentity(domainObject);
// Obtain the SIDs applicable to the principal
List<Sid> sids = this.sidRetrievalStrategy.getSids(authentication);
Acl acl;
try {
// Lookup only ACLs for SIDs we're interested in
acl = this.aclService.readAclById(objectIdentity, sids);
}
catch (NotFoundException ex) {
logger.debug("Voting to deny access - no ACLs apply for this principal");
return ACCESS_DENIED;
}
try {
if (acl.isGranted(this.requirePermission, sids, false)) {
logger.debug("Voting to grant access");
return ACCESS_GRANTED;
}
logger.debug("Voting to deny access - ACLs returned, but insufficient permissions for this principal");
return ACCESS_DENIED;
|
}
catch (NotFoundException ex) {
logger.debug("Voting to deny access - no ACLs apply for this principal");
return ACCESS_DENIED;
}
}
// No configuration attribute matched, so abstain
return ACCESS_ABSTAIN;
}
private Object invokeInternalMethod(Object domainObject) {
try {
Class<?> domainObjectType = domainObject.getClass();
Method method = domainObjectType.getMethod(this.internalMethod, new Class[0]);
return method.invoke(domainObject);
}
catch (NoSuchMethodException ex) {
throw new AuthorizationServiceException("Object of class '" + domainObject.getClass()
+ "' does not provide the requested internalMethod: " + this.internalMethod);
}
catch (IllegalAccessException ex) {
logger.debug("IllegalAccessException", ex);
throw new AuthorizationServiceException(
"Problem invoking internalMethod: " + this.internalMethod + " for object: " + domainObject);
}
catch (InvocationTargetException ex) {
logger.debug("InvocationTargetException", ex);
throw new AuthorizationServiceException(
"Problem invoking internalMethod: " + this.internalMethod + " for object: " + domainObject);
}
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\acls\AclEntryVoter.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.