instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public SqlLookupDescriptorFactory setADReferenceService(@NonNull final ADReferenceService adReferenceService)
{
this.adReferenceService = adReferenceService;
return this;
}
public ADReferenceService getADReferenceService()
{
return adReferenceService;
}
private MLookupFactory newLookupFactory()
{
return MLookupFactory.builder()
.adReferenceService(adReferenceService)
.build();
}
public SqlLookupDescriptorFactory setCtxColumnName(@Nullable final String ctxColumnName)
{
this.ctxColumnName = ctxColumnName;
this.filtersBuilder.setCtxColumnName(this.ctxColumnName);
return this;
}
public SqlLookupDescriptorFactory setCtxTableName(@Nullable final String ctxTableName)
{
this.ctxTableName = ctxTableName;
this.filtersBuilder.setCtxTableName(ctxTableName);
return this;
}
public SqlLookupDescriptorFactory setDisplayType(final ReferenceId displayType)
{
this.displayType = displayType;
this.filtersBuilder.setDisplayType(ReferenceId.toRepoId(displayType));
return this;
}
public SqlLookupDescriptorFactory setAD_Reference_Value_ID(final ReferenceId AD_Reference_Value_ID)
{
this.AD_Reference_Value_ID = AD_Reference_Value_ID;
return this;
}
public SqlLookupDescriptorFactory setAdValRuleIds(@NonNull final Map<LookupDescriptorProvider.LookupScope, AdValRuleId> adValRuleIds)
{
this.filtersBuilder.setAdValRuleIds(adValRuleIds);
return this;
}
private CompositeSqlLookupFilter getFilters()
{
return filtersBuilder.getOrBuild();
}
private static boolean computeIsHighVolume(@NonNull final ReferenceId diplayType)
{
final int displayTypeInt = diplayType.getRepoId();
return DisplayType.TableDir != displayTypeInt && DisplayType.Table != displayTypeInt && DisplayType.List != displayTypeInt && DisplayType.Button != displayTypeInt;
}
/**
* Advice the lookup to show all records on which current user has at least read only access
*/
public SqlLookupDescriptorFactory setReadOnlyAccess()
{
|
this.requiredAccess = Access.READ;
return this;
}
private Access getRequiredAccess(@NonNull final TableName tableName)
{
if (requiredAccess != null)
{
return requiredAccess;
}
// AD_Client_ID/AD_Org_ID (security fields): shall display only those entries on which current user has read-write access
if (I_AD_Client.Table_Name.equals(tableName.getAsString())
|| I_AD_Org.Table_Name.equals(tableName.getAsString()))
{
return Access.WRITE;
}
// Default: all entries on which current user has at least readonly access
return Access.READ;
}
SqlLookupDescriptorFactory addValidationRules(final Collection<IValidationRule> validationRules)
{
this.filtersBuilder.addFilter(validationRules, null);
return this;
}
SqlLookupDescriptorFactory setPageLength(final Integer pageLength)
{
this.pageLength = pageLength;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlLookupDescriptorFactory.java
| 1
|
请完成以下Java代码
|
public void setIndexQuery (String IndexQuery)
{
set_ValueNoCheck (COLUMNNAME_IndexQuery, IndexQuery);
}
/** Get Index Query.
@return Text Search Query
*/
public String getIndexQuery ()
{
return (String)get_Value(COLUMNNAME_IndexQuery);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getIndexQuery());
}
/** Set Query Result.
@param IndexQueryResult
Result of the text query
*/
public void setIndexQueryResult (int IndexQueryResult)
{
set_ValueNoCheck (COLUMNNAME_IndexQueryResult, Integer.valueOf(IndexQueryResult));
}
/** Get Query Result.
@return Result of the text query
*/
public int getIndexQueryResult ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IndexQueryResult);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Index Log.
@param K_IndexLog_ID
Text search log
*/
public void setK_IndexLog_ID (int K_IndexLog_ID)
{
if (K_IndexLog_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_IndexLog_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_IndexLog_ID, Integer.valueOf(K_IndexLog_ID));
}
|
/** Get Index Log.
@return Text search log
*/
public int getK_IndexLog_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_IndexLog_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** QuerySource AD_Reference_ID=391 */
public static final int QUERYSOURCE_AD_Reference_ID=391;
/** Collaboration Management = C */
public static final String QUERYSOURCE_CollaborationManagement = "C";
/** Java Client = J */
public static final String QUERYSOURCE_JavaClient = "J";
/** HTML Client = H */
public static final String QUERYSOURCE_HTMLClient = "H";
/** Self Service = W */
public static final String QUERYSOURCE_SelfService = "W";
/** Set Query Source.
@param QuerySource
Source of the Query
*/
public void setQuerySource (String QuerySource)
{
set_Value (COLUMNNAME_QuerySource, QuerySource);
}
/** Get Query Source.
@return Source of the Query
*/
public String getQuerySource ()
{
return (String)get_Value(COLUMNNAME_QuerySource);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_IndexLog.java
| 1
|
请完成以下Java代码
|
public ActionListener[] getActionListeners()
{
return (listenerList.getListeners(ActionListener.class));
} // getActionListeners
/**
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the <code>event</code>
* parameter.
*
* @param event the <code>ActionEvent</code> object
* @see EventListenerList
*/
protected void fireActionPerformed(MouseEvent event)
{
// Guaranteed to return a non-null array
ActionListener[] listeners = getActionListeners();
ActionEvent e = null;
// Process the listeners first to last
for (int i = 0; i < listeners.length; i++)
{
// Lazily create the event:
if (e == null)
e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
"pi", event.getWhen(), event.getModifiers());
listeners[i].actionPerformed(e);
}
} // fireActionPerformed
/**************************************************************************
* Mouse Clicked
* @param e mouse event
*/
@Override
public void mouseClicked (MouseEvent e)
{
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() > 1)
fireActionPerformed(e);
if (SwingUtilities.isRightMouseButton(e))
popupMenu.show((Component)e.getSource(), e.getX(), e.getY());
} // mouseClicked
@Override
public void mousePressed (MouseEvent e)
{
}
|
@Override
public void mouseReleased (MouseEvent e)
{
}
@Override
public void mouseEntered (MouseEvent e)
{
}
@Override
public void mouseExited (MouseEvent e)
{
}
/**
* Action Listener.
* Update Display
* @param e event
*/
@Override
public void actionPerformed (ActionEvent e)
{
if (e.getSource() == mRefresh)
{
m_goal.updateGoal(true);
updateDisplay();
//
Container parent = getParent();
if (parent != null)
parent.invalidate();
invalidate();
if (parent != null)
parent.repaint();
else
repaint();
}
} // actionPerformed
} // PerformanceIndicator
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\adempiere\apps\graph\PerformanceIndicator.java
| 1
|
请完成以下Java代码
|
public <T1> T1[] toArray(T1[] a) {
Collection<Target> modelElementCollection = ModelUtil.getModelElementCollection(getView(referenceSourceParentElement), referenceSourceParentElement.getModelInstance());
return modelElementCollection.toArray(a);
}
public boolean add(Target t) {
if (referenceSourceCollection.isImmutable()) {
throw new UnsupportedModelOperationException("add()", "collection is immutable");
}
else {
if (!contains(t)) {
performAddOperation(referenceSourceParentElement, t);
}
return true;
}
}
public boolean remove(Object o) {
if (referenceSourceCollection.isImmutable()) {
throw new UnsupportedModelOperationException("remove()", "collection is immutable");
}
else {
ModelUtil.ensureInstanceOf(o, ModelElementInstanceImpl.class);
performRemoveOperation(referenceSourceParentElement, o);
return true;
}
}
public boolean containsAll(Collection<?> c) {
Collection<Target> modelElementCollection = ModelUtil.getModelElementCollection(getView(referenceSourceParentElement), referenceSourceParentElement.getModelInstance());
return modelElementCollection.containsAll(c);
}
public boolean addAll(Collection<? extends Target> c) {
if (referenceSourceCollection.isImmutable()) {
throw new UnsupportedModelOperationException("addAll()", "collection is immutable");
}
else {
boolean result = false;
for (Target o: c) {
result |= add(o);
}
return result;
}
}
public boolean removeAll(Collection<?> c) {
|
if (referenceSourceCollection.isImmutable()) {
throw new UnsupportedModelOperationException("removeAll()", "collection is immutable");
}
else {
boolean result = false;
for (Object o: c) {
result |= remove(o);
}
return result;
}
}
public boolean retainAll(Collection<?> c) {
throw new UnsupportedModelOperationException("retainAll()", "not implemented");
}
public void clear() {
if (referenceSourceCollection.isImmutable()) {
throw new UnsupportedModelOperationException("clear()", "collection is immutable");
}
else {
Collection<DomElement> view = new ArrayList<DomElement>();
for (Source referenceSourceElement : referenceSourceCollection.get(referenceSourceParentElement)) {
view.add(referenceSourceElement.getDomElement());
}
performClearOperation(referenceSourceParentElement, view);
}
}
};
}
}
|
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\reference\ElementReferenceCollectionImpl.java
| 1
|
请完成以下Java代码
|
public class UserDTO {
private String userId;
private String username;
private String email;
// getters and setters
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
|
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-conversions-2\src\main\java\com\baeldung\modelmapper\UserDTO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public InputStream cloneInputStream(ServletInputStream inputStream) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
try {
while ((len = inputStream.read(buffer)) > -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
byteArrayOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
}
@Override
public BufferedReader getReader() {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() {
return bais.read();
}
|
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
};
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\sign\util\BodyReaderHttpServletRequestWrapper.java
| 2
|
请完成以下Java代码
|
public boolean isDeserializable() {
return getParent().isDeserializable();
}
@Override
public boolean isEnum() {
return getParent().isEnum();
}
@Override
public Object getField(String fieldName) {
return getParent().getField(fieldName);
}
@Override
public List<String> getFieldNames() {
return getParent().getFieldNames();
}
@Override
public boolean isIdentityField(String fieldName) {
return getParent().isIdentityField(fieldName);
}
@Override
public Object getObject() {
return getParent().getObject();
}
@Override
public WritablePdxInstance createWriter() {
return this;
|
}
@Override
public boolean hasField(String fieldName) {
return getParent().hasField(fieldName);
}
};
}
/**
* Determines whether the given {@link String field name} is a {@link PropertyDescriptor property}
* on the underlying, target {@link Object}.
*
* @param fieldName {@link String} containing the name of the field to match against
* a {@link PropertyDescriptor property} from the underlying, target {@link Object}.
* @return a boolean value that determines whether the given {@link String field name}
* is a {@link PropertyDescriptor property} on the underlying, target {@link Object}.
* @see #getFieldNames()
*/
@Override
public boolean hasField(String fieldName) {
return getFieldNames().contains(fieldName);
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\pdx\ObjectPdxInstanceAdapter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
TextMapPropagator textMapPropagatorWithBaggage(OtelCurrentTraceContext otelCurrentTraceContext) {
List<String> remoteFields = this.tracingProperties.getBaggage().getRemoteFields();
List<String> tagFields = this.tracingProperties.getBaggage().getTagFields();
BaggageTextMapPropagator baggagePropagator = new BaggageTextMapPropagator(remoteFields,
new OtelBaggageManager(otelCurrentTraceContext, remoteFields, tagFields));
return CompositeTextMapPropagator.create(this.tracingProperties.getPropagation(), baggagePropagator);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnBooleanProperty(name = "management.tracing.baggage.correlation.enabled", matchIfMissing = true)
Slf4JBaggageEventListener otelSlf4JBaggageEventListener() {
return new Slf4JBaggageEventListener(this.tracingProperties.getBaggage().getCorrelation().getFields());
}
}
|
/**
* Propagates neither traces nor baggage.
*/
@Configuration(proxyBeanMethods = false)
static class NoPropagation {
@Bean
@ConditionalOnMissingBean
TextMapPropagator noopTextMapPropagator() {
return TextMapPropagator.noop();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\OpenTelemetryPropagationConfigurations.java
| 2
|
请完成以下Java代码
|
public void setDateAcct (Timestamp DateAcct)
{
set_Value (COLUMNNAME_DateAcct, DateAcct);
}
/** Get Account Date.
@return Accounting Date
*/
public Timestamp getDateAcct ()
{
return (Timestamp)get_Value(COLUMNNAME_DateAcct);
}
/** Set Depreciate.
@param IsDepreciated
The asset will be depreciated
*/
public void setIsDepreciated (boolean IsDepreciated)
{
set_Value (COLUMNNAME_IsDepreciated, Boolean.valueOf(IsDepreciated));
}
/** Get Depreciate.
@return The asset will be depreciated
*/
public boolean isDepreciated ()
{
Object oo = get_Value(COLUMNNAME_IsDepreciated);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** PostingType AD_Reference_ID=125 */
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
|
public static final String POSTINGTYPE_Reservation = "R";
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Workfile.java
| 1
|
请完成以下Java代码
|
public void setFileNamePattern(final String fnp)
{
throw new UnsupportedOperationException("Setting FileNamePattern directly is not allowed");
}
public File getLogDirAsFile()
{
if (logDir == null)
{
return null;
}
return new File(logDir);
}
public File getActiveFileOrNull()
{
try
{
final String filename = getActiveFileName();
if (filename == null)
{
return null;
}
final File file = new File(filename).getAbsoluteFile();
return file;
}
catch (Exception e)
{
addError("Failed fetching active file name", e);
return null;
}
}
public List<File> getLogFiles()
{
|
final File logDir = getLogDirAsFile();
if (logDir != null && logDir.isDirectory())
{
final File[] logs = logDir.listFiles(logFileNameFilter);
for (int i = 0; i < logs.length; i++)
{
try
{
logs[i] = logs[i].getCanonicalFile();
}
catch (Exception e)
{
}
}
return ImmutableList.copyOf(logs);
}
return ImmutableList.of();
}
public void flush()
{
// TODO
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\MetasfreshTimeBasedRollingPolicy.java
| 1
|
请完成以下Java代码
|
public void setM_Movement_ID (int M_Movement_ID)
{
if (M_Movement_ID < 1)
set_Value (COLUMNNAME_M_Movement_ID, null);
else
set_Value (COLUMNNAME_M_Movement_ID, Integer.valueOf(M_Movement_ID));
}
/** Get Inventory Move.
@return Movement of Inventory
*/
public int getM_Movement_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Movement_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
|
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MovementConfirm.java
| 1
|
请完成以下Java代码
|
public ErrorInfo handleTaskAlreadyClaimed(FlowableTaskAlreadyClaimedException e, HttpServletRequest request) {
if (logger.isDebugEnabled()) {
logger.debug("Task was already claimed. Message: {}, Request: {} {}", e.getMessage(), request.getMethod(), request.getRequestURI());
}
return new ErrorInfo("Task was already claimed", e);
}
// Fall back
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 500
@ExceptionHandler(Exception.class)
@ResponseBody
public ErrorInfo handleOtherException(Exception e, HttpServletRequest request) {
if (sendFullErrorException) {
logger.error("Unhandled exception. Request: {} {}", request.getMethod(), request.getRequestURI(), e);
return new ErrorInfo("Internal server error", e);
} else {
|
String errorIdentifier = UUID.randomUUID().toString();
logger.error("Unhandled exception. Error ID: {}. Request: {} {}", errorIdentifier, request.getMethod(), request.getRequestURI(), e);
ErrorInfo errorInfo = new ErrorInfo("Internal server error", e);
errorInfo.setException("Error with ID: " + errorIdentifier);
return errorInfo;
}
}
public boolean isSendFullErrorException() {
return sendFullErrorException;
}
public void setSendFullErrorException(boolean sendFullErrorException) {
this.sendFullErrorException = sendFullErrorException;
}
}
|
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\exception\BaseExceptionHandlerAdvice.java
| 1
|
请完成以下Java代码
|
public TreePath[] getCheckingPaths() {
return getCheckingModel().getCheckingPaths();
}
/**
* @return Returns the paths that are in the checking set and are the
* (upper) roots of checked trees.
*/
public TreePath[] getCheckingRoots() {
return getCheckingModel().getCheckingRoots();
}
/**
* Clears the checking.
*/
public void clearChecking() {
getCheckingModel().clearChecking();
}
/**
* Add paths in the checking.
*/
public void addCheckingPaths(TreePath[] paths) {
getCheckingModel().addCheckingPaths(paths);
}
/**
* Add a path in the checking.
*/
public void addCheckingPath(TreePath path) {
getCheckingModel().addCheckingPath(path);
}
/**
* Set path in the checking.
*/
public void setCheckingPath(TreePath path) {
getCheckingModel().setCheckingPath(path);
}
/**
* Set paths that are in the checking.
*/
public void setCheckingPaths(TreePath[] paths) {
getCheckingModel().setCheckingPaths(paths);
}
/**
* @return Returns the paths that are in the greying.
*/
public TreePath[] getGreyingPaths() {
return getCheckingModel().getGreyingPaths();
}
/**
* Adds a listener for <code>TreeChecking</code> events.
*
* @param tsl the <code>TreeCheckingListener</code> that will be
* notified when a node is checked
*/
public void addTreeCheckingListener(TreeCheckingListener tsl) {
this.checkingModel.addTreeCheckingListener(tsl);
}
/**
* Removes a <code>TreeChecking</code> listener.
*
* @param tsl the <code>TreeChckingListener</code> to remove
|
*/
public void removeTreeCheckingListener(TreeCheckingListener tsl) {
this.checkingModel.removeTreeCheckingListener(tsl);
}
/**
* Expand completely a tree
*/
public void expandAll() {
expandSubTree(getPathForRow(0));
}
private void expandSubTree(TreePath path) {
expandPath(path);
Object node = path.getLastPathComponent();
int childrenNumber = getModel().getChildCount(node);
TreePath[] childrenPath = new TreePath[childrenNumber];
for (int childIndex = 0; childIndex < childrenNumber; childIndex++) {
childrenPath[childIndex] = path.pathByAddingChild(getModel().getChild(node, childIndex));
expandSubTree(childrenPath[childIndex]);
}
}
/**
* @return a string representation of the tree, including the checking,
* enabling and greying sets.
*/
@Override
public String toString() {
String retVal = super.toString();
TreeCheckingModel tcm = getCheckingModel();
if (tcm != null) {
return retVal + "\n" + tcm.toString();
}
return retVal;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\CheckboxTree.java
| 1
|
请完成以下Java代码
|
private HttpHeaders buildHttpHeaders(final String apiKey)
{
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add(VERSION.getValue(), EVERHOUR_API_VERSION);
headers.add(API_KEY.getValue(), apiKey);
return headers;
}
private <T> ResponseEntity<T> performWithRetry(final URI resourceURI, final HttpMethod httpMethod,
final HttpEntity<String> request, final Class<T> responseType)
{
ResponseEntity<T> response = null;
boolean retry = true;
while (retry)
{
log.debug("Performing [{}] on [{}] for request [{}]", httpMethod.name(), resourceURI, request);
retry = false;
try
{
response = restTemplate().exchange(resourceURI, httpMethod, request, responseType);
}
catch (final LimitExceededException limitEx)
{
Loggables.withLogger(log, Level.ERROR)
.addLog("*** ERROR: Limit reached! time to wait for limit reset: {} .", limitEx.getRetryAfter());
waitForLimitReset(limitEx.getRetryAfter());
retry = true;
}
catch (final Throwable t)
{
Loggables.withLogger(log, Level.ERROR)
.addLog("ERROR while trying to fetch from URI: {}, Error message: {}", resourceURI, t.getMessage(), t);
throw t;
}
}
return response;
}
|
private void waitForLimitReset(@NonNull final Duration resetAfter)
{
final int maxTimeToWaitMs = sysConfigBL.getIntValue(MAX_TIME_TO_WAIT_FOR_LIMIT_RESET.getName(),
MAX_TIME_TO_WAIT_FOR_LIMIT_RESET.getDefaultValue() );
if (resetAfter.get(MILLIS) > maxTimeToWaitMs)
{
throw new AdempiereException("Limit Reset is too far in the future! aborting!")
.appendParametersToMessage()
.setParameter("ResetAfter", resetAfter)
.setParameter("MaxMsToWaitForLimitReset", maxTimeToWaitMs);
}
try
{
Loggables.withLogger(log, Level.DEBUG)
.addLog("*** Waiting for limit reset!Time to wait: {}.", resetAfter);
Thread.sleep(resetAfter.get(MILLIS));
}
catch (final InterruptedException e)
{
throw new AdempiereException(e.getMessage(), e);
}
}
private RestTemplate restTemplate()
{
return new RestTemplateBuilder()
.errorHandler(responseErrorHandler)
.setConnectTimeout(Duration.ofMillis(sysConfigBL.getIntValue(CONNECTION_TIMEOUT.getName(), CONNECTION_TIMEOUT.getDefaultValue())))
.setReadTimeout(Duration.ofMillis(sysConfigBL.getIntValue(READ_TIMEOUT.getName(),READ_TIMEOUT.getDefaultValue())))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.issue.tracking.everhour\src\main\java\de\metas\issue\tracking\everhour\api\rest\RestService.java
| 1
|
请完成以下Java代码
|
public void sendRegisterMail(UserEntity user) {
Context context = new Context();
context.setVariable("id", user.getId());
String emailContent = templateEngine.process("emailTemplate", context);
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(user.getEmail());
helper.setSubject("注册验证邮件");
helper.setText(emailContent, true);
mailSender.send(message);
} catch (Exception e) {
logger.error("发送注册邮件时异常!", e);
}
|
}
@RequestMapping("/verified/{id}")
public String verified(@PathVariable("id") String id,ModelMap model) {
UserEntity user=userRepository.findById(id);
if (user!=null && "unverified".equals(user.getState())){
user.setState("verified");
userRepository.save(user);
model.put("userName",user.getUserName());
}
return "verified";
}
}
|
repos\spring-boot-leaning-master\1.x\第16课:综合实战用户管理系统\user-manage\src\main\java\com\neo\web\IndexController.java
| 1
|
请完成以下Java代码
|
public void save(final I_M_HU_Item_Storage storageLine)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(storageLine);
delegate.save(storageLine);
}
@Override
public List<I_M_HU_Item_Storage> retrieveItemStorages(final I_M_HU_Item item)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(item);
return delegate.retrieveItemStorages(item);
}
@Override
public I_M_HU_Item_Storage retrieveItemStorage(final I_M_HU_Item item, @NonNull final ProductId productId)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(item);
return delegate.retrieveItemStorage(item, productId);
}
@Override
public void save(final I_M_HU_Item item)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(item);
delegate.save(item);
|
}
@Override
public I_C_UOM getC_UOMOrNull(final I_M_HU hu)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(hu);
return delegate.getC_UOMOrNull(hu);
}
@Override
public UOMType getC_UOMTypeOrNull(final I_M_HU hu)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(hu);
return delegate.getC_UOMTypeOrNull(hu);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\SaveOnCommitHUStorageDAO.java
| 1
|
请完成以下Java代码
|
public void setField (GridField mField)
{
this.m_mField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField() {
return m_mField;
}
/**
* Set Text
* @param text text
*/
public void setText (String text)
{
m_text.setText (text);
validateOnTextChanged();
} // setText
/**
* Get Text (clear)
* @return text
*/
public String getText ()
{
String text = m_text.getText();
return text;
} // getText
/**
* Focus Gained.
* Enabled with Obscure
* @param e event
*/
public void focusGained (FocusEvent e)
{
m_infocus = true;
setText(getText()); // clear
} // focusGained
/**
* Focus Lost
* Enabled with Obscure
|
* @param e event
*/
public void focusLost (FocusEvent e)
{
m_infocus = false;
setText(getText()); // obscure
} // focus Lost
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VURL
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VURL.java
| 1
|
请完成以下Java代码
|
public Builder endSessionEndpoint(String endSessionEndpoint) {
return claim(OidcProviderMetadataClaimNames.END_SESSION_ENDPOINT, endSessionEndpoint);
}
/**
* Validate the claims and build the {@link OidcProviderConfiguration}.
* <p>
* The following claims are REQUIRED: {@code issuer},
* {@code authorization_endpoint}, {@code token_endpoint}, {@code jwks_uri},
* {@code response_types_supported}, {@code subject_types_supported} and
* {@code id_token_signing_alg_values_supported}.
* @return the {@link OidcProviderConfiguration}
*/
@Override
public OidcProviderConfiguration build() {
validate();
return new OidcProviderConfiguration(getClaims());
}
@Override
protected void validate() {
super.validate();
Assert.notNull(getClaims().get(OidcProviderMetadataClaimNames.JWKS_URI), "jwksUri cannot be null");
Assert.notNull(getClaims().get(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED),
"subjectTypes cannot be null");
Assert.isInstanceOf(List.class, getClaims().get(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED),
"subjectTypes must be of type List");
Assert.notEmpty((List<?>) getClaims().get(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED),
"subjectTypes cannot be empty");
Assert.notNull(getClaims().get(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED),
"idTokenSigningAlgorithms cannot be null");
Assert.isInstanceOf(List.class,
getClaims().get(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED),
"idTokenSigningAlgorithms must be of type List");
Assert.notEmpty(
(List<?>) getClaims().get(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED),
"idTokenSigningAlgorithms cannot be empty");
if (getClaims().get(OidcProviderMetadataClaimNames.USER_INFO_ENDPOINT) != null) {
validateURL(getClaims().get(OidcProviderMetadataClaimNames.USER_INFO_ENDPOINT),
"userInfoEndpoint must be a valid URL");
}
|
if (getClaims().get(OidcProviderMetadataClaimNames.END_SESSION_ENDPOINT) != null) {
validateURL(getClaims().get(OidcProviderMetadataClaimNames.END_SESSION_ENDPOINT),
"endSessionEndpoint must be a valid URL");
}
}
@SuppressWarnings("unchecked")
private void addClaimToClaimList(String name, String value) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(value, "value cannot be null");
getClaims().computeIfAbsent(name, (k) -> new LinkedList<String>());
((List<String>) getClaims().get(name)).add(value);
}
@SuppressWarnings("unchecked")
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(valuesConsumer, "valuesConsumer cannot be null");
getClaims().computeIfAbsent(name, (k) -> new LinkedList<String>());
List<String> values = (List<String>) getClaims().get(name);
valuesConsumer.accept(values);
}
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\OidcProviderConfiguration.java
| 1
|
请完成以下Java代码
|
public boolean isUnknown()
{
return this == UNKNOWN;
}
public boolean orElseTrue() {return orElse(true);}
public boolean orElseFalse() {return orElse(false);}
public boolean orElse(final boolean other)
{
if (this == TRUE)
{
return true;
}
else if (this == FALSE)
{
return false;
}
else
{
return other;
}
}
@NonNull
public OptionalBoolean ifUnknown(@NonNull final OptionalBoolean other)
{
return isPresent() ? this : other;
}
@NonNull
public OptionalBoolean ifUnknown(@NonNull final Supplier<OptionalBoolean> otherSupplier)
{
return isPresent() ? this : otherSupplier.get();
}
@JsonValue
@Nullable
public Boolean toBooleanOrNull()
{
switch (this)
{
case TRUE:
return Boolean.TRUE;
case FALSE:
return Boolean.FALSE;
case UNKNOWN:
return null;
default:
throw new IllegalStateException("Type not handled: " + this);
}
}
@Nullable
public String toBooleanString()
{
|
return StringUtils.ofBoolean(toBooleanOrNull());
}
public void ifPresent(@NonNull final BooleanConsumer action)
{
if (this == TRUE)
{
action.accept(true);
}
else if (this == FALSE)
{
action.accept(false);
}
}
public void ifTrue(@NonNull final Runnable action)
{
if (this == TRUE)
{
action.run();
}
}
public <U> Optional<U> map(@NonNull final BooleanFunction<? extends U> mapper)
{
return isPresent() ? Optional.ofNullable(mapper.apply(isTrue())) : Optional.empty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\OptionalBoolean.java
| 1
|
请完成以下Java代码
|
public IAllocationRequestBuilder setDeleteEmptyAndJustCreatedAggregatedTUs(@Nullable final Boolean deleteEmptyAndJustCreatedAggregatedTUs)
{
this.deleteEmptyAndJustCreatedAggregatedTUs = deleteEmptyAndJustCreatedAggregatedTUs;
return this;
}
private boolean isDeleteEmptyAndJustCreatedAggregatedTUs()
{
if (deleteEmptyAndJustCreatedAggregatedTUs != null)
{
return deleteEmptyAndJustCreatedAggregatedTUs;
}
else if (baseAllocationRequest != null)
{
return baseAllocationRequest.isDeleteEmptyAndJustCreatedAggregatedTUs();
}
return false;
}
@Override
public IAllocationRequest create()
{
final IHUContext huContext = getHUContextToUse();
final ProductId productId = getProductIdToUse();
|
final Quantity quantity = getQuantityToUse();
final ZonedDateTime date = getDateToUse();
final TableRecordReference fromTableRecord = getFromReferencedTableRecordToUse();
final boolean forceQtyAllocation = isForceQtyAllocationToUse();
final ClearanceStatusInfo clearanceStatusInfo = getClearanceStatusInfo();
return new AllocationRequest(
huContext,
productId,
quantity,
date,
fromTableRecord,
forceQtyAllocation,
clearanceStatusInfo,
isDeleteEmptyAndJustCreatedAggregatedTUs());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AllocationRequestBuilder.java
| 1
|
请完成以下Java代码
|
public boolean isAllowClosingPerUserRequest()
{
// don't allow closing per user request because the same view is used the Picker and the Reviewer.
// So the first one which is closing the view would delete it.
return false;
}
@Override
public String getTableNameOrNull(final DocumentId documentId)
{
return null;
}
@Override
public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors()
{
return relatedProcessDescriptors;
}
public boolean isEligibleForReview()
{
if (size() == 0)
{
return false;
}
final boolean allApproved = streamByIds(DocumentIdsSelection.ALL).allMatch(ProductsToPickRow::isApproved);
if (allApproved)
{
return false;
}
return streamByIds(DocumentIdsSelection.ALL)
.allMatch(ProductsToPickRow::isEligibleForReview);
}
|
public void updateViewRowFromPickingCandidate(@NonNull final DocumentId rowId, @NonNull final PickingCandidate pickingCandidate)
{
rowsData.updateViewRowFromPickingCandidate(rowId, pickingCandidate);
}
public boolean isApproved()
{
if (size() == 0)
{
return false;
}
return streamByIds(DocumentIdsSelection.ALL)
.allMatch(ProductsToPickRow::isApproved);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\ProductsToPickView.java
| 1
|
请完成以下Java代码
|
public void handleOtherException(Exception thrownException, Consumer<?, ?> consumer,
MessageListenerContainer container, boolean batchListener) {
if (batchListener) {
this.batchErrorHandler.handleOtherException(thrownException, consumer, container, batchListener);
}
else {
this.recordErrorHandler.handleOtherException(thrownException, consumer, container, batchListener);
}
}
@Override
public boolean handleOne(Exception thrownException, ConsumerRecord<?, ?> record, Consumer<?, ?> consumer,
MessageListenerContainer container) {
return this.recordErrorHandler.handleOne(thrownException, record, consumer, container);
}
@Override
public void handleRemaining(Exception thrownException, List<ConsumerRecord<?, ?>> records, Consumer<?, ?> consumer,
MessageListenerContainer container) {
this.recordErrorHandler.handleRemaining(thrownException, records, consumer, container);
}
@Override
public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer,
MessageListenerContainer container, Runnable invokeListener) {
this.batchErrorHandler.handleBatch(thrownException, data, consumer, container, invokeListener);
}
@Override
public int deliveryAttempt(TopicPartitionOffset topicPartitionOffset) {
return this.recordErrorHandler.deliveryAttempt(topicPartitionOffset);
|
}
@Override
public void clearThreadState() {
this.batchErrorHandler.clearThreadState();
this.recordErrorHandler.clearThreadState();
}
@Override
public boolean isAckAfterHandle() {
return this.recordErrorHandler.isAckAfterHandle();
}
@Override
public void setAckAfterHandle(boolean ack) {
this.batchErrorHandler.setAckAfterHandle(ack);
this.recordErrorHandler.setAckAfterHandle(ack);
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\CommonMixedErrorHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable Boolean getProxyRevalidate() {
return this.proxyRevalidate;
}
public void setProxyRevalidate(@Nullable Boolean proxyRevalidate) {
this.customized = true;
this.proxyRevalidate = proxyRevalidate;
}
public @Nullable Duration getStaleWhileRevalidate() {
return this.staleWhileRevalidate;
}
public void setStaleWhileRevalidate(@Nullable Duration staleWhileRevalidate) {
this.customized = true;
this.staleWhileRevalidate = staleWhileRevalidate;
}
public @Nullable Duration getStaleIfError() {
return this.staleIfError;
}
public void setStaleIfError(@Nullable Duration staleIfError) {
this.customized = true;
this.staleIfError = staleIfError;
}
public @Nullable Duration getSMaxAge() {
return this.sMaxAge;
}
public void setSMaxAge(@Nullable Duration sMaxAge) {
this.customized = true;
this.sMaxAge = sMaxAge;
}
public @Nullable CacheControl toHttpCacheControl() {
PropertyMapper map = PropertyMapper.get();
CacheControl control = createCacheControl();
map.from(this::getMustRevalidate).whenTrue().toCall(control::mustRevalidate);
|
map.from(this::getNoTransform).whenTrue().toCall(control::noTransform);
map.from(this::getCachePublic).whenTrue().toCall(control::cachePublic);
map.from(this::getCachePrivate).whenTrue().toCall(control::cachePrivate);
map.from(this::getProxyRevalidate).whenTrue().toCall(control::proxyRevalidate);
map.from(this::getStaleWhileRevalidate)
.to((duration) -> control.staleWhileRevalidate(duration.getSeconds(), TimeUnit.SECONDS));
map.from(this::getStaleIfError)
.to((duration) -> control.staleIfError(duration.getSeconds(), TimeUnit.SECONDS));
map.from(this::getSMaxAge)
.to((duration) -> control.sMaxAge(duration.getSeconds(), TimeUnit.SECONDS));
// check if cacheControl remained untouched
if (control.getHeaderValue() == null) {
return null;
}
return control;
}
private CacheControl createCacheControl() {
if (Boolean.TRUE.equals(this.noStore)) {
return CacheControl.noStore();
}
if (Boolean.TRUE.equals(this.noCache)) {
return CacheControl.noCache();
}
if (this.maxAge != null) {
return CacheControl.maxAge(this.maxAge.getSeconds(), TimeUnit.SECONDS);
}
return CacheControl.empty();
}
private boolean hasBeenCustomized() {
return this.customized;
}
}
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\web\WebProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class DataSourceClosingSpringLiquibase extends SpringLiquibase implements DisposableBean {
private volatile boolean closeDataSourceOnceMigrated = true;
public void setCloseDataSourceOnceMigrated(boolean closeDataSourceOnceMigrated) {
this.closeDataSourceOnceMigrated = closeDataSourceOnceMigrated;
}
@Override
public void afterPropertiesSet() throws LiquibaseException {
super.afterPropertiesSet();
if (this.closeDataSourceOnceMigrated) {
closeDataSource();
}
}
|
private void closeDataSource() {
Class<?> dataSourceClass = getDataSource().getClass();
Method closeMethod = ReflectionUtils.findMethod(dataSourceClass, "close");
if (closeMethod != null) {
ReflectionUtils.invokeMethod(closeMethod, getDataSource());
}
}
@Override
public void destroy() throws Exception {
if (!this.closeDataSourceOnceMigrated) {
closeDataSource();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\DataSourceClosingSpringLiquibase.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public OrderDeliveryAddress postalCode(String postalCode) {
this.postalCode = postalCode;
return this;
}
/**
* Get postalCode
* @return postalCode
**/
@Schema(example = "90489", required = true, description = "")
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public OrderDeliveryAddress city(String city) {
this.city = city;
return this;
}
/**
* Get city
* @return city
**/
@Schema(example = "Nürnberg", required = true, description = "")
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OrderDeliveryAddress orderDeliveryAddress = (OrderDeliveryAddress) o;
return Objects.equals(this.gender, orderDeliveryAddress.gender) &&
Objects.equals(this.title, orderDeliveryAddress.title) &&
Objects.equals(this.name, orderDeliveryAddress.name) &&
Objects.equals(this.address, orderDeliveryAddress.address) &&
Objects.equals(this.additionalAddress, orderDeliveryAddress.additionalAddress) &&
Objects.equals(this.additionalAddress2, orderDeliveryAddress.additionalAddress2) &&
Objects.equals(this.postalCode, orderDeliveryAddress.postalCode) &&
Objects.equals(this.city, orderDeliveryAddress.city);
}
@Override
public int hashCode() {
return Objects.hash(gender, title, name, address, additionalAddress, additionalAddress2, postalCode, city);
}
|
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class OrderDeliveryAddress {\n");
sb.append(" gender: ").append(toIndentedString(gender)).append("\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" address: ").append(toIndentedString(address)).append("\n");
sb.append(" additionalAddress: ").append(toIndentedString(additionalAddress)).append("\n");
sb.append(" additionalAddress2: ").append(toIndentedString(additionalAddress2)).append("\n");
sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n");
sb.append(" city: ").append(toIndentedString(city)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderDeliveryAddress.java
| 2
|
请完成以下Java代码
|
private boolean isPackToLuAllowed(final I_M_HU hu)
{
final I_M_HU_PI_Version mHuPiVersion = hu.getM_HU_PI_Version();
if (mHuPiVersion == null
|| mHuPiVersion.getHU_UnitType() != null && !mHuPiVersion.getHU_UnitType().equals(X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit))
{
return false;
}
final BPartnerId bPartnerId = IHandlingUnitsBL.extractBPartnerIdOrNull(hu);
final I_M_HU_PI_Item actualLUItem = handlingUnitsDAO.retrieveDefaultParentPIItem(mHuPiVersion.getM_HU_PI(), X_M_HU_PI_Version.HU_UNITTYPE_LoadLogistiqueUnit, bPartnerId);
return actualLUItem != null;
|
}
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
// Invalidate views
getPickingSlotsClearingView().invalidateAll();
getPackingHUsView().invalidateAll();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PickingSlotsClearingView_TakeOutTUsAndAddToNewLUs.java
| 1
|
请完成以下Java代码
|
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
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
*/
@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);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public org.compiere.util.KeyNamePair getKeyNamePair()
{
return new org.compiere.util.KeyNamePair(get_ID(), getName());
}
/** Set Sql ORDER BY.
@param OrderByClause
Fully qualified ORDER BY clause
*/
@Override
public void setOrderByClause (java.lang.String OrderByClause)
{
set_Value (COLUMNNAME_OrderByClause, OrderByClause);
}
/** Get Sql ORDER BY.
@return Fully qualified ORDER BY clause
*/
@Override
public java.lang.String getOrderByClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_OrderByClause);
}
/** Set Other SQL Clause.
@param OtherClause
Other SQL Clause
*/
@Override
public void setOtherClause (java.lang.String OtherClause)
{
set_Value (COLUMNNAME_OtherClause, OtherClause);
}
/** Get Other SQL Clause.
@return Other SQL Clause
*/
@Override
public java.lang.String getOtherClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_OtherClause);
}
|
/** Set Verarbeiten.
@param Processing Verarbeiten */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set ShowInMenu.
@param ShowInMenu ShowInMenu */
@Override
public void setShowInMenu (boolean ShowInMenu)
{
set_Value (COLUMNNAME_ShowInMenu, Boolean.valueOf(ShowInMenu));
}
/** Get ShowInMenu.
@return ShowInMenu */
@Override
public boolean isShowInMenu ()
{
Object oo = get_Value(COLUMNNAME_ShowInMenu);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoWindow.java
| 1
|
请完成以下Java代码
|
public boolean isDeliveryDayMatches(final I_M_DeliveryDay deliveryDay, final IDeliveryDayQueryParams params)
{
if (deliveryDay == null)
{
return false;
}
return createDeliveryDayMatcher(params)
.accept(deliveryDay);
}
@Override
public List<I_M_DeliveryDay> retrieveDeliveryDays(final I_M_Tour tour, final Timestamp deliveryDate)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryBuilder<I_M_DeliveryDay> queryBuilder = queryBL.createQueryBuilder(I_M_DeliveryDay.class, tour)
.addEqualsFilter(I_M_DeliveryDay.COLUMN_M_Tour_ID, tour.getM_Tour_ID())
.addEqualsFilter(I_M_DeliveryDay.COLUMN_DeliveryDate, deliveryDate, DateTruncQueryFilterModifier.DAY)
.addOnlyActiveRecordsFilter();
queryBuilder.orderBy()
.addColumn(I_M_DeliveryDay.COLUMN_DeliveryDate, Direction.Ascending, Nulls.Last);
return queryBuilder
.create()
.list();
}
@Override
public I_M_DeliveryDay_Alloc retrieveDeliveryDayAllocForModel(final IContextAware context, final IDeliveryDayAllocable deliveryDayAllocable)
{
|
Check.assumeNotNull(deliveryDayAllocable, "deliveryDayAllocable not null");
final String tableName = deliveryDayAllocable.getTableName();
final int adTableId = Services.get(IADTableDAO.class).retrieveTableId(tableName);
final int recordId = deliveryDayAllocable.getRecord_ID();
return Services.get(IQueryBL.class)
.createQueryBuilder(I_M_DeliveryDay_Alloc.class, context)
.addEqualsFilter(I_M_DeliveryDay_Alloc.COLUMN_AD_Table_ID, adTableId)
.addEqualsFilter(I_M_DeliveryDay_Alloc.COLUMN_Record_ID, recordId)
.addOnlyActiveRecordsFilter()
.create()
.firstOnly(I_M_DeliveryDay_Alloc.class);
}
@Override
public boolean hasAllocations(final I_M_DeliveryDay deliveryDay)
{
Check.assumeNotNull(deliveryDay, "deliveryDay not null");
return Services.get(IQueryBL.class)
.createQueryBuilder(I_M_DeliveryDay_Alloc.class, deliveryDay)
.addEqualsFilter(I_M_DeliveryDay_Alloc.COLUMN_M_DeliveryDay_ID, deliveryDay.getM_DeliveryDay_ID())
.addOnlyActiveRecordsFilter()
.create()
.anyMatch();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\DeliveryDayDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RedisSentinelApplication {
static final RedisSentinelConfiguration SENTINEL_CONFIG = new RedisSentinelConfiguration().master("mymaster") //
.sentinel("localhost", 26379) //
.sentinel("localhost", 26380) //
.sentinel("localhost", 26381);
@Autowired RedisConnectionFactory factory;
public static void main(String[] args) throws Exception {
ApplicationContext context = SpringApplication.run(RedisSentinelApplication.class, args);
var template = context.getBean(StringRedisTemplate.class);
template.opsForValue().set("loop-forever", "0");
var stopWatch = new StopWatch();
while (true) {
try {
var value = "IT:= " + template.opsForValue().increment("loop-forever", 1);
printBackFromErrorStateInfoIfStopWatchIsRunning(stopWatch);
System.out.println(value);
} catch (RuntimeException e) {
System.err.println(e.getCause().getMessage());
startStopWatchIfNotRunning(stopWatch);
}
Thread.sleep(1000);
}
}
public @Bean StringRedisTemplate redisTemplate() {
return new StringRedisTemplate(connectionFactory());
}
public @Bean RedisConnectionFactory connectionFactory() {
return new LettuceConnectionFactory(sentinelConfig(), LettuceClientConfiguration.defaultConfiguration());
}
|
public @Bean RedisSentinelConfiguration sentinelConfig() {
return SENTINEL_CONFIG;
}
/**
* Clear database before shut down.
*/
public @PreDestroy void flushTestDb() {
factory.getConnection().flushDb();
}
private static void startStopWatchIfNotRunning(StopWatch stopWatch) {
if (!stopWatch.isRunning()) {
stopWatch.start();
}
}
private static void printBackFromErrorStateInfoIfStopWatchIsRunning(StopWatch stopWatch) {
if (stopWatch.isRunning()) {
stopWatch.stop();
System.err.println("INFO: Recovered after: " + stopWatch.getLastTaskInfo().getTimeSeconds());
}
}
}
|
repos\spring-data-examples-main\redis\sentinel\src\main\java\example\springdata\redis\sentinel\RedisSentinelApplication.java
| 2
|
请完成以下Java代码
|
protected boolean isCopyRecord(final PO fromPO) {return true;}
protected boolean isCopyChildRecord(final CopyTemplate parentTemplate, final PO fromChildPO, final CopyTemplate childTemplate) {return true;}
@Override
public final GeneralCopyRecordSupport setParentLink(@NonNull final PO parentPO, @NonNull final String parentLinkColumnName)
{
this.parentPO = parentPO;
this.parentLinkColumnName = parentLinkColumnName;
return this;
}
@Override
public final GeneralCopyRecordSupport setAdWindowId(final @Nullable AdWindowId adWindowId)
{
this.adWindowId = adWindowId;
return this;
}
@SuppressWarnings("SameParameterValue")
@Nullable
protected final <T> T getParentModel(final Class<T> modelType)
{
return parentPO != null ? InterfaceWrapperHelper.create(parentPO, modelType) : null;
}
private int getParentID()
{
return parentPO != null ? parentPO.get_ID() : -1;
}
/**
* Allows other modules to install customer code to be executed each time a record was copied.
*/
|
@Override
public final GeneralCopyRecordSupport onRecordCopied(@NonNull final OnRecordCopiedListener listener)
{
if (!recordCopiedListeners.contains(listener))
{
recordCopiedListeners.add(listener);
}
return this;
}
@Override
public final CopyRecordSupport onChildRecordCopied(@NonNull final OnRecordCopiedListener listener)
{
if (!childRecordCopiedListeners.contains(listener))
{
childRecordCopiedListeners.add(listener);
}
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\copy_with_details\GeneralCopyRecordSupport.java
| 1
|
请完成以下Java代码
|
public Message getMessage() {
return messageRefAttribute.getReferenceTargetElement(this);
}
public void setMessage(Message message) {
messageRefAttribute.setReferenceTargetElement(this, message);
}
public Operation getOperation() {
return operationRefChild.getReferenceTargetElement(this);
}
public void setOperation(Operation operation) {
operationRefChild.setReferenceTargetElement(this, operation);
}
/** camunda extensions */
public String getCamundaClass() {
return camundaClassAttribute.getValue(this);
}
public void setCamundaClass(String camundaClass) {
camundaClassAttribute.setValue(this, camundaClass);
}
public String getCamundaDelegateExpression() {
return camundaDelegateExpressionAttribute.getValue(this);
}
public void setCamundaDelegateExpression(String camundaExpression) {
camundaDelegateExpressionAttribute.setValue(this, camundaExpression);
}
public String getCamundaExpression() {
return camundaExpressionAttribute.getValue(this);
}
public void setCamundaExpression(String camundaExpression) {
camundaExpressionAttribute.setValue(this, camundaExpression);
}
public String getCamundaResultVariable() {
|
return camundaResultVariableAttribute.getValue(this);
}
public void setCamundaResultVariable(String camundaResultVariable) {
camundaResultVariableAttribute.setValue(this, camundaResultVariable);
}
public String getCamundaTopic() {
return camundaTopicAttribute.getValue(this);
}
public void setCamundaTopic(String camundaTopic) {
camundaTopicAttribute.setValue(this, camundaTopic);
}
public String getCamundaType() {
return camundaTypeAttribute.getValue(this);
}
public void setCamundaType(String camundaType) {
camundaTypeAttribute.setValue(this, camundaType);
}
@Override
public String getCamundaTaskPriority() {
return camundaTaskPriorityAttribute.getValue(this);
}
@Override
public void setCamundaTaskPriority(String taskPriority) {
camundaTaskPriorityAttribute.setValue(this, taskPriority);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\MessageEventDefinitionImpl.java
| 1
|
请完成以下Java代码
|
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
|
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
@Override
public String toString() {
return "Transaction [username=" + username + ", userId=" + userId + ", age=" + age + ", postCode=" + postCode + ", transactionDate=" + transactionDate + ", amount=" + amount + "]";
}
}
|
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batch\model\Transaction.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setRegistries(Map<String, RegistryConfig> registries) {
this.registries = registries;
}
public Map<String, ProtocolConfig> getProtocols() {
return protocols;
}
public void setProtocols(Map<String, ProtocolConfig> protocols) {
this.protocols = protocols;
}
public Map<String, MonitorConfig> getMonitors() {
return monitors;
}
public void setMonitors(Map<String, MonitorConfig> monitors) {
this.monitors = monitors;
}
public Map<String, ProviderConfig> getProviders() {
return providers;
}
public void setProviders(Map<String, ProviderConfig> providers) {
this.providers = providers;
}
public Map<String, ConsumerConfig> getConsumers() {
return consumers;
}
public void setConsumers(Map<String, ConsumerConfig> consumers) {
this.consumers = consumers;
}
public Map<String, ConfigCenterBean> getConfigCenters() {
return configCenters;
}
public void setConfigCenters(Map<String, ConfigCenterBean> configCenters) {
this.configCenters = configCenters;
}
public Map<String, MetadataReportConfig> getMetadataReports() {
return metadataReports;
}
public void setMetadataReports(Map<String, MetadataReportConfig> metadataReports) {
this.metadataReports = metadataReports;
}
static class Config {
/**
* Indicates multiple properties binding from externalized configuration or not.
*/
private boolean multiple = DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE;
/**
|
* The property name of override Dubbo config
*/
private boolean override = DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE;
public boolean isOverride() {
return override;
}
public void setOverride(boolean override) {
this.override = override;
}
public boolean isMultiple() {
return multiple;
}
public void setMultiple(boolean multiple) {
this.multiple = multiple;
}
}
static class Scan {
/**
* The basePackages to scan , the multiple-value is delimited by comma
*
* @see EnableDubbo#scanBasePackages()
*/
private Set<String> basePackages = new LinkedHashSet<>();
public Set<String> getBasePackages() {
return basePackages;
}
public void setBasePackages(Set<String> basePackages) {
this.basePackages = basePackages;
}
}
}
|
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\autoconfigure\DubboConfigurationProperties.java
| 2
|
请完成以下Java代码
|
public JsonPOSOrder updateOrder(@RequestBody @NonNull final JsonPOSOrder remoteOrder)
{
final POSOrder order = posService.updateOrderFromRemote(remoteOrder.toRemotePOSOrder(), getLoggedUserId());
return JsonPOSOrder.from(order, newJsonContext()::getCurrencySymbol);
}
@PostMapping("/orders/checkoutPayment")
public JsonPOSOrder checkoutPayment(@RequestBody JsonPOSPaymentCheckoutRequest request)
{
final POSOrder order = posService.checkoutPayment(POSPaymentCheckoutRequest.builder()
.posTerminalId(request.getPosTerminalId())
.posOrderExternalId(request.getOrder_uuid())
.posPaymentExternalId(request.getPayment_uuid())
.userId(getLoggedUserId())
.cardPayAmount(request.getCardPayAmount())
.cashTenderedAmount(request.getCashTenderedAmount())
.build());
return JsonPOSOrder.from(order, newJsonContext()::getCurrencySymbol);
}
@PostMapping("/orders/refundPayment")
public JsonPOSOrder refundPayment(@RequestBody JsonPOSPaymentRefundRequest request)
{
final POSOrder order = posService.refundPayment(request.getPosTerminalId(), request.getOrder_uuid(), request.getPayment_uuid(), getLoggedUserId());
return JsonPOSOrder.from(order, newJsonContext()::getCurrencySymbol);
}
@GetMapping("/orders/receipt/{filename:.*}")
@PostMapping("/orders/receipt/{filename:.*}")
public ResponseEntity<Resource> getReceiptPdf(
@PathVariable("filename") final String filename,
@RequestParam(value = "id") final String idStr)
{
final POSOrderExternalId posOrderExternalId = POSOrderExternalId.ofString(idStr);
|
return posService.getReceiptPdf(posOrderExternalId)
.map(resource -> createPDFResponseEntry(resource, filename))
.orElseGet(() -> ResponseEntity.notFound().build());
}
private static ResponseEntity<Resource> createPDFResponseEntry(@NonNull final Resource resource, @NonNull final String filename)
{
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MimeType.getMediaType(filename));
headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"");
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.rest-api\src\main\java\de\metas\pos\rest_api\POSRestController.java
| 1
|
请完成以下Java代码
|
private void onEmailRemoved(final WebuiEmail email)
{
eventPublisher.publishEvent(new WebuiEmailRemovedEvent(email));
}
public LookupValuesPage getToTypeahead(final String ignoredEmailId, final String query)
{
final Evaluatee ctx = Evaluatees.empty(); // TODO
// TODO: filter only those which have a valid email address
return emailToLookup.findEntities(ctx, query);
}
public LookupValue getToByUserId(final Integer adUserId)
{
return emailToLookup.findById(adUserId);
}
@ToString
private static final class WebuiEmailEntry
{
private WebuiEmail email;
public WebuiEmailEntry(@NonNull final WebuiEmail email)
{
this.email = email;
}
public synchronized WebuiEmail getEmail()
{
return email;
}
|
public synchronized WebuiEmailChangeResult compute(final UnaryOperator<WebuiEmail> modifier)
{
final WebuiEmail emailOld = email;
final WebuiEmail emailNew = modifier.apply(emailOld);
if (emailNew == null)
{
throw new NullPointerException("email");
}
email = emailNew;
return WebuiEmailChangeResult.builder().email(emailNew).originalEmail(emailOld).build();
}
}
@Value
@AllArgsConstructor
public static class WebuiEmailRemovedEvent
{
@NonNull WebuiEmail email;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\mail\WebuiMailRepository.java
| 1
|
请完成以下Java代码
|
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_PA_Benchmark[")
.append(get_ID()).append("]");
return sb.toString();
}
/** AccumulationType AD_Reference_ID=370 */
public static final int ACCUMULATIONTYPE_AD_Reference_ID=370;
/** Average = A */
public static final String ACCUMULATIONTYPE_Average = "A";
/** Sum = S */
public static final String ACCUMULATIONTYPE_Sum = "S";
/** Set Accumulation Type.
@param AccumulationType
How to accumulate data on time axis
*/
public void setAccumulationType (String AccumulationType)
{
set_Value (COLUMNNAME_AccumulationType, AccumulationType);
}
/** Get Accumulation Type.
@return How to accumulate data on time axis
*/
public String getAccumulationType ()
{
return (String)get_Value(COLUMNNAME_AccumulationType);
}
/** 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 Comment/Help.
@param Help
|
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set 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 Benchmark.
@param PA_Benchmark_ID
Performance Benchmark
*/
public void setPA_Benchmark_ID (int PA_Benchmark_ID)
{
if (PA_Benchmark_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, Integer.valueOf(PA_Benchmark_ID));
}
/** Get Benchmark.
@return Performance Benchmark
*/
public int getPA_Benchmark_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Benchmark_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Benchmark.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class LetterRepository
{
public Letter toCLetter(@NonNull final I_C_Letter letterRecord)
{
return Letter.builder()
.bpartnerId(BPartnerId.ofRepoId(letterRecord.getC_BPartner_ID()))
.id(LetterId.ofRepoId(letterRecord.getC_BP_Contact_ID()))
.address(letterRecord.getBPartnerAddress())
.boilerPlateId(BoilerPlateId.ofRepoId(letterRecord.getAD_BoilerPlate_ID()))
.body(letterRecord.getLetterBody())
.body(letterRecord.getLetterBodyParsed())
.subject(letterRecord.getLetterSubject())
.build();
}
public Letter save(@NonNull final Letter letter)
{
final I_C_Letter letterRecord;
if (letter.getId() == null)
{
letterRecord = newInstance(I_C_Letter.class);
}
else
{
letterRecord = load(letter.getId().getRepoId(), I_C_Letter.class);
|
}
letterRecord.setAD_BoilerPlate_ID(letter.getBoilerPlateId() == null ? -1 : letter.getBoilerPlateId().getRepoId());
letterRecord.setLetterSubject(letter.getSubject());
letterRecord.setLetterBody(letter.getBody());
letterRecord.setLetterBodyParsed(letter.getBodyParsed());
letterRecord.setBPartnerAddress(letter.getAddress());
letterRecord.setC_BP_Contact_ID(letter.getUserId() == null ? -1 : letter.getUserId().getRepoId());
letterRecord.setC_BPartner_ID(letter.getBpartnerId() == null ? -1 : letter.getBpartnerId().getRepoId());
letterRecord.setC_BPartner_Location_ID(letter.getBpartnerLocationId() == null ? -1 : letter.getBpartnerLocationId().getRepoId());
saveRecord(letterRecord);
return letter
.toBuilder()
.id(LetterId.ofRepoId(letterRecord.getC_Letter_ID()))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\model\LetterRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void init(List<TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> msgs) {
orderedMsgList = msgs.stream().map(msg -> new IdMsgPair<>(UUID.randomUUID(), msg)).collect(Collectors.toList());
}
@Override
public ConcurrentMap<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> getPendingMap() {
return orderedMsgList.stream().collect(Collectors.toConcurrentMap(pair -> pair.uuid, pair -> pair.msg));
}
@Override
public void update(ConcurrentMap<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> reprocessMap) {
List<IdMsgPair<TransportProtos.ToRuleEngineMsg>> newOrderedMsgList = new ArrayList<>(reprocessMap.size());
for (IdMsgPair<TransportProtos.ToRuleEngineMsg> pair : orderedMsgList) {
if (reprocessMap.containsKey(pair.uuid)) {
if (StringUtils.isNotEmpty(pair.getMsg().getValue().getFailureMessage())) {
var toRuleEngineMsg = TransportProtos.ToRuleEngineMsg.newBuilder(pair.getMsg().getValue())
.clearFailureMessage()
.clearRelationTypes()
.build();
var newMsg = new TbProtoQueueMsg<>(pair.getMsg().getKey(), toRuleEngineMsg, pair.getMsg().getHeaders());
newOrderedMsgList.add(new IdMsgPair<>(pair.getUuid(), newMsg));
} else {
newOrderedMsgList.add(pair);
}
}
}
|
orderedMsgList = newOrderedMsgList;
}
@Override
public void onSuccess(UUID id) {
if (!stopped) {
doOnSuccess(id);
}
}
@Override
public void stop() {
stopped = true;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\processing\AbstractTbRuleEngineSubmitStrategy.java
| 2
|
请完成以下Java代码
|
public EntityType getEntityType() {
return EntityType.WIDGET_TYPE;
}
private final PaginatedRemover<TenantId, WidgetTypeInfo> tenantWidgetTypeRemover = new PaginatedRemover<>() {
@Override
protected PageData<WidgetTypeInfo> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return widgetTypeDao.findTenantWidgetTypesByTenantId(
WidgetTypeFilter.builder()
.tenantId(id)
.fullSearch(false)
.deprecatedFilter(DeprecatedFilter.ALL)
.widgetTypes(null).build(),
pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, WidgetTypeInfo entity) {
deleteWidgetType(tenantId, new WidgetTypeId(entity.getUuidId()));
}
};
|
private final PaginatedRemover<WidgetsBundleId, WidgetTypeInfo> bundleWidgetTypesRemover = new PaginatedRemover<>() {
@Override
protected PageData<WidgetTypeInfo> findEntities(TenantId tenantId, WidgetsBundleId widgetsBundleId, PageLink pageLink) {
return findWidgetTypesInfosByWidgetsBundleId(tenantId, widgetsBundleId, false, DeprecatedFilter.ALL, null, pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, WidgetTypeInfo widgetTypeInfo) {
deleteWidgetType(tenantId, widgetTypeInfo.getId());
}
};
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\widget\WidgetTypeServiceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setMethodSecurityExpressionHandler(List<MethodSecurityExpressionHandler> handlers) {
if (handlers.size() != 1) {
logger.debug("Not autowiring MethodSecurityExpressionHandler since size != 1. Got " + handlers);
return;
}
this.expressionHandler = handlers.get(0);
}
@Autowired(required = false)
void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.context = beanFactory;
}
private AuthenticationConfiguration getAuthenticationConfiguration() {
return this.context.getBean(AuthenticationConfiguration.class);
}
private boolean prePostEnabled() {
return enableMethodSecurity().getBoolean("prePostEnabled");
}
private boolean securedEnabled() {
return enableMethodSecurity().getBoolean("securedEnabled");
}
private boolean jsr250Enabled() {
return enableMethodSecurity().getBoolean("jsr250Enabled");
}
|
private boolean isAspectJ() {
return enableMethodSecurity().getEnum("mode") == AdviceMode.ASPECTJ;
}
private AnnotationAttributes enableMethodSecurity() {
if (this.enableMethodSecurity == null) {
// if it is null look at this instance (i.e. a subclass was used)
EnableGlobalMethodSecurity methodSecurityAnnotation = AnnotationUtils.findAnnotation(getClass(),
EnableGlobalMethodSecurity.class);
Assert.notNull(methodSecurityAnnotation, () -> EnableGlobalMethodSecurity.class.getName() + " is required");
Map<String, Object> methodSecurityAttrs = AnnotationUtils.getAnnotationAttributes(methodSecurityAnnotation);
this.enableMethodSecurity = AnnotationAttributes.fromMap(methodSecurityAttrs);
}
return this.enableMethodSecurity;
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\GlobalMethodSecurityConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void record(long processingTime) {
executionCount.incrementAndGet();
executionTime.addAndGet(processingTime);
while (true) {
long value = maxExecutionTime.get();
if (value >= processingTime) {
break;
}
if (maxExecutionTime.compareAndSet(value, processingTime)) {
break;
}
}
}
int getExecutionCount() {
return executionCount.get();
}
|
long getMaxExecutionTime() {
return maxExecutionTime.get();
}
double getAvgExecutionTime() {
double executionCnt = (double) executionCount.get();
if (executionCnt > 0) {
return executionTime.get() / executionCnt;
} else {
return 0.0;
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\TbRuleNodeProfilerInfo.java
| 2
|
请完成以下Java代码
|
private IAllocationResult processCandidate(final AllocCandidate candidate, final IAllocationRequest initialRequest)
{
final IAllocationRequest requestActual = AllocationUtils.derive(initialRequest)
.setQuantity(candidate.getQtyToAllocate())
.setForceQtyAllocation(true)
.create();
if (requestActual.isZeroQty())
{
return AllocationUtils.nullResult();
}
if (AllocCandidateType.MATERIAL.equals(candidate.getType()))
{
return processCandidate_Material(candidate, initialRequest, requestActual);
}
else if (AllocCandidateType.INCLUDED_HU.equals(candidate.getType()))
{
return execute(candidate.getIncludedHU(), requestActual);
}
else
{
throw new AdempiereException("Unknown type: " + candidate.getType());
}
}
private IAllocationResult processCandidate_Material(final AllocCandidate candidate, final IAllocationRequest initialRequest, final IAllocationRequest requestActual)
{
final I_M_HU_Item vhuItem = candidate.getHuItem();
final I_M_HU_Item itemFirstNotPureVirtual = services.getFirstNotPureVirtualItem(vhuItem);
final Quantity qtyTrx = AllocationUtils.getQuantity(requestActual, direction);
final Object referencedModel = AllocationUtils.getReferencedModel(requestActual);
final HUTransactionCandidate trx = HUTransactionCandidate.builder()
.model(referencedModel)
.huItem(itemFirstNotPureVirtual)
.vhuItem(vhuItem)
.productId(requestActual.getProductId())
.quantity(qtyTrx)
.date(requestActual.getDate())
.build();
final BigDecimal qtyToAllocate = initialRequest.getQty();
final BigDecimal qtyAllocated = requestActual.getQty();
return AllocationUtils.createQtyAllocationResult(
qtyToAllocate,
|
qtyAllocated,
ImmutableList.of(trx), // trxs
ImmutableList.of()); // attributeTrxs
}
private enum AllocCandidateType
{
MATERIAL, INCLUDED_HU
}
@Data
@Builder
private static class AllocCandidate
{
@NonNull
private final AllocCandidateType type;
@NonNull
private final I_M_HU_Item huItem;
@Nullable
private final I_M_HU includedHU;
@NonNull
private final Quantity currentQty;
private Quantity qtyToAllocate;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\strategy\UniformAllocationStrategy.java
| 1
|
请完成以下Java代码
|
public String getY_TargetLabel ()
{
return m_Y_TargetLabel;
} // getY_TargetLabel
/**
* @param targetLabel The y_TargetLabel to set.
*/
public void setY_TargetLabel (String targetLabel, double target)
{
m_Y_TargetLabel = targetLabel;
m_Y_Target = target;
} // setY_TargetLabel
/**
* Get BarGraphColumn for ChartEntity
* @param event
* @return BarGraphColumn or null if not found
*/
private GraphColumn getGraphColumn(ChartMouseEvent event)
{
ChartEntity entity = event.getEntity();
String key = null;
if (entity instanceof CategoryItemEntity)
{
Comparable<?> colKey = ((CategoryItemEntity)entity).getColumnKey();
if (colKey != null)
{
key = colKey.toString();
}
}
else if (entity instanceof PieSectionEntity)
{
Comparable<?> sectionKey = ((PieSectionEntity)entity).getSectionKey();
if (sectionKey != null)
{
key = sectionKey.toString();
}
}
if (key == null)
{
return null;
}
for (int i = 0; i < list.size(); i++)
{
final String label = list.get(i).getLabel();
if (key.equals(label))
{
return list.get(i);
}
}
//
return null;
}
@Override
|
public void chartMouseClicked(ChartMouseEvent event)
{
if ((event.getEntity()!=null) && (event.getTrigger().getClickCount() > 1))
{
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try
{
GraphColumn bgc = getGraphColumn(event);
if (bgc == null)
{
return;
}
MQuery query = bgc.getMQuery(builder.getMGoal());
if (query != null)
AEnv.zoom(query);
else
log.warn("Nothing to zoom to - " + bgc);
}
finally
{
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
}
@Override
public void chartMouseMoved(ChartMouseEvent event)
{
}
public GraphColumn[] getGraphColumnList()
{
return list.toArray(new GraphColumn[list.size()]);
}
} // BarGraph
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\adempiere\apps\graph\Graph.java
| 1
|
请完成以下Java代码
|
public final class StoragePA implements IStoragePA
{
private static final String SQL_SELECT_QTY_ORDERED = //
"SELECT SUM(" + I_M_Storage.COLUMNNAME_QtyOrdered + ") " //
+ "FROM " + I_M_Storage.Table_Name + " s " //
+ " LEFT JOIN " + I_M_Locator.Table_Name + " l " //
+ " ON s." + I_M_Storage.COLUMNNAME_M_Locator_ID //
+ " = l." + I_M_Locator.COLUMNNAME_M_Locator_ID //
+ " WHERE s." + I_M_Storage.COLUMNNAME_M_Product_ID + "=? " //
+ "AND l." + I_M_Locator.COLUMNNAME_M_Warehouse_ID + "=?";
@Override
public Collection<I_M_Storage> retrieveStorages(final int productId,
final String trxName)
{
final I_M_Storage[] storages = MStorage.getOfProduct(Env.getCtx(),
productId, trxName);
return Arrays.asList(storages);
}
@Override
public WarehouseId retrieveWarehouseId(final I_M_Storage storage)
{
final int locatorId = storage.getM_Locator_ID();
return Services.get(IWarehouseDAO.class).getWarehouseIdByLocatorRepoId(locatorId);
}
/**
* Invokes {@link MStorage#getQtyAvailable(int, int, int, int, String)}.
*/
@Override
public BigDecimal retrieveQtyAvailable(final int wareHouseId,
final int locatorId, final int productId,
final int attributeSetInstanceId, final String trxName)
{
return MStorage.getQtyAvailable(wareHouseId, locatorId, productId,
attributeSetInstanceId, trxName);
}
@Override
public BigDecimal retrieveQtyOrdered(final int productId,
final int warehouseId)
{
ResultSet rs = null;
final PreparedStatement pstmt = DB.prepareStatement(
SQL_SELECT_QTY_ORDERED, null);
try
{
pstmt.setInt(1, productId);
pstmt.setInt(2, warehouseId);
rs = pstmt.executeQuery();
if (rs.next())
|
{
final BigDecimal qtyOrdered = rs.getBigDecimal(1);
if (qtyOrdered == null)
{
return BigDecimal.ZERO;
}
return qtyOrdered;
}
throw new RuntimeException(
"Unable to retrive qtyOrdererd for M_Product_ID '"
+ productId + "'");
}
catch (SQLException e)
{
throw new RuntimeException(e);
}
finally
{
DB.close(rs, pstmt);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\impl\StoragePA.java
| 1
|
请完成以下Java代码
|
public void setIsValid (final boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, IsValid);
}
@Override
public boolean isValid()
{
return get_ValueAsBoolean(COLUMNNAME_IsValid);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
|
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoicePaySchedule.java
| 1
|
请完成以下Java代码
|
public void setM_HU(final de.metas.handlingunits.model.I_M_HU M_HU)
{
set_ValueFromPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class, M_HU);
}
@Override
public void setM_HU_ID (final int M_HU_ID)
{
if (M_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID);
}
@Override
public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
@Override
public void setM_Package_HU_ID (final int M_Package_HU_ID)
{
if (M_Package_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Package_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Package_HU_ID, M_Package_HU_ID);
}
@Override
public int getM_Package_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Package_HU_ID);
}
@Override
public org.compiere.model.I_M_Package getM_Package()
{
return get_ValueAsPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class);
|
}
@Override
public void setM_Package(final org.compiere.model.I_M_Package M_Package)
{
set_ValueFromPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class, M_Package);
}
@Override
public void setM_Package_ID (final int M_Package_ID)
{
if (M_Package_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Package_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Package_ID, M_Package_ID);
}
@Override
public int getM_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Package_ID);
}
@Override
public void setM_PickingSlot_ID (final int M_PickingSlot_ID)
{
if (M_PickingSlot_ID < 1)
set_Value (COLUMNNAME_M_PickingSlot_ID, null);
else
set_Value (COLUMNNAME_M_PickingSlot_ID, M_PickingSlot_ID);
}
@Override
public int getM_PickingSlot_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PickingSlot_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Package_HU.java
| 1
|
请完成以下Java代码
|
public Object execute(CommandContext commandContext) {
if (callback != null) {
return callback.execute(commandContext);
}
throw new ProcessEngineException("Query can't be executed. Use either sum or interval to query the metrics.");
}
@Override
public MetricsQuery offset(int offset) {
setFirstResult(offset);
return this;
}
@Override
public MetricsQuery limit(int maxResults) {
setMaxResults(maxResults);
return this;
}
@Override
public MetricsQuery aggregateByReporter() {
aggregateByReporter = true;
return this;
}
@Override
public void setMaxResults(int maxResults) {
if (maxResults > DEFAULT_LIMIT_SELECT_INTERVAL) {
throw new ProcessEngineException("Metrics interval query row limit can't be set larger than " + DEFAULT_LIMIT_SELECT_INTERVAL + '.');
}
this.maxResults = maxResults;
}
public Date getStartDate() {
return startDate;
}
public Date getEndDate() {
return endDate;
}
public Long getStartDateMilliseconds() {
return startDateMilliseconds;
}
public Long getEndDateMilliseconds() {
return endDateMilliseconds;
}
public String getName() {
return name;
}
public String getReporter() {
return reporter;
}
public Long getInterval() {
|
if (interval == null) {
return DEFAULT_SELECT_INTERVAL;
}
return interval;
}
@Override
public int getMaxResults() {
if (maxResults > DEFAULT_LIMIT_SELECT_INTERVAL) {
return DEFAULT_LIMIT_SELECT_INTERVAL;
}
return super.getMaxResults();
}
protected class MetricsQueryIntervalCmd implements Command<Object> {
protected MetricsQueryImpl metricsQuery;
public MetricsQueryIntervalCmd(MetricsQueryImpl metricsQuery) {
this.metricsQuery = metricsQuery;
}
@Override
public Object execute(CommandContext commandContext) {
return commandContext.getMeterLogManager()
.executeSelectInterval(metricsQuery);
}
}
protected class MetricsQuerySumCmd implements Command<Object> {
protected MetricsQueryImpl metricsQuery;
public MetricsQuerySumCmd(MetricsQueryImpl metricsQuery) {
this.metricsQuery = metricsQuery;
}
@Override
public Object execute(CommandContext commandContext) {
return commandContext.getMeterLogManager()
.executeSelectSum(metricsQuery);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\MetricsQueryImpl.java
| 1
|
请完成以下Java代码
|
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_CM_Ad_Cat[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Advertisement Category.
@param CM_Ad_Cat_ID
Advertisement Category like Banner Homepage
*/
public void setCM_Ad_Cat_ID (int CM_Ad_Cat_ID)
{
if (CM_Ad_Cat_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_Ad_Cat_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_Ad_Cat_ID, Integer.valueOf(CM_Ad_Cat_ID));
}
/** Get Advertisement Category.
@return Advertisement Category like Banner Homepage
*/
public int getCM_Ad_Cat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Ad_Cat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_CM_WebProject getCM_WebProject() throws RuntimeException
{
return (I_CM_WebProject)MTable.get(getCtx(), I_CM_WebProject.Table_Name)
.getPO(getCM_WebProject_ID(), get_TrxName()); }
/** Set Web Project.
@param CM_WebProject_ID
A web project is the main data container for Containers, URLs, Ads, Media etc.
*/
public void setCM_WebProject_ID (int CM_WebProject_ID)
{
if (CM_WebProject_ID < 1)
set_Value (COLUMNNAME_CM_WebProject_ID, null);
else
set_Value (COLUMNNAME_CM_WebProject_ID, Integer.valueOf(CM_WebProject_ID));
}
/** Get Web Project.
@return A web project is the main data container for Containers, URLs, Ads, Media etc.
*/
public int getCM_WebProject_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_WebProject_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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 Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Ad_Cat.java
| 1
|
请完成以下Java代码
|
public boolean isFocusable()
{
if (!isExpanded())
{
return false;
}
return findPanel.isFocusable();
}
/**
* Adds a runnable to be executed when the this panel is collapsed or expanded.
*
* @param runnable
*/
@Override
public void runOnExpandedStateChange(final Runnable runnable)
{
Check.assumeNotNull(runnable, "runnable not null");
final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel();
findPanelCollapsible.addPropertyChangeListener("collapsed", new PropertyChangeListener()
{
@Override
public void propertyChange(final PropertyChangeEvent evt)
{
runnable.run();
}
});
}
|
private static final class CollapsiblePanel extends JXTaskPane implements IUISubClassIDAware
{
private static final long serialVersionUID = 1L;
public CollapsiblePanel()
{
super();
}
@Override
public String getUISubClassID()
{
return AdempiereTaskPaneUI.UISUBCLASSID_VPanel_FindPanel;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelContainer_Collapsible.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean hmSet(String key, Map<String, Object> map, long milliseconds) {
hmSet(key, map);
if (milliseconds > 0) {
return expire(key, milliseconds);
}
return false;
}
public void hashSet(String key, String item, Object value) {
hashOperations.put(key, item, value);
}
public void hashDelete(String key, Object... item) {
hashOperations.delete(key, item);
}
public boolean hashHasKey(String key, String item) {
return hashOperations.hasKey(key, item);
}
//============================set=============================
public Set<Object> setMembers(String key) {
return setOperations.members(key);
}
public boolean setIsMember(String key, Object value) {
return setOperations.isMember(key, value);
}
public long setAdd(String key, Object... values) {
return setOperations.add(key, values);
}
public long setAdd(String key, long milliseconds, Object... values) {
Long count = setOperations.add(key, values);
if (milliseconds > 0) {
expire(key, milliseconds);
}
return count;
}
public long setSize(String key) {
return setOperations.size(key);
}
public long setRemove(String key, Object... values) {
return setOperations.remove(key, values);
}
//===============================list=================================
public List<Object> lGet(String key, long start, long end) {
return listOperations.range(key, start, end);
}
public long listSize(String key) {
return listOperations.size(key);
}
|
public Object listIndex(String key, long index) {
return listOperations.index(key, index);
}
public void listRightPush(String key, Object value) {
listOperations.rightPush(key, value);
}
public boolean listRightPush(String key, Object value, long milliseconds) {
listOperations.rightPush(key, value);
if (milliseconds > 0) {
return expire(key, milliseconds);
}
return false;
}
public long listRightPushAll(String key, List<Object> value) {
return listOperations.rightPushAll(key, value);
}
public boolean listRightPushAll(String key, List<Object> value, long milliseconds) {
listOperations.rightPushAll(key, value);
if (milliseconds > 0) {
return expire(key, milliseconds);
}
return false;
}
public void listSet(String key, long index, Object value) {
listOperations.set(key, index, value);
}
public long listRemove(String key, long count, Object value) {
return listOperations.remove(key, count, value);
}
//===============================zset=================================
public boolean zsAdd(String key, Object value, double score) {
return zSetOperations.add(key, value, score);
}
}
|
repos\spring-boot-best-practice-master\spring-boot-redis\src\main\java\cn\javastack\springboot\redis\service\RedisOptService.java
| 2
|
请完成以下Java代码
|
public static <T> InstantRangeQueryFilter<T> of(@NonNull final String columnName, @NonNull Range<Instant> range)
{
return new InstantRangeQueryFilter<>(columnName, range);
}
@Override
public boolean accept(final T model)
{
final Instant value = InterfaceWrapperHelper.getValue(model, columnName)
.map(TimeUtil::asInstant)
.orElse(null);
return value != null && range.contains(value);
}
@Override
public final String getSql()
{
buildSql();
return sqlWhereClause;
}
@Override
public final List<Object> getSqlParams(final Properties ctx)
{
return getSqlParams();
}
public final List<Object> getSqlParams()
{
buildSql();
return sqlParams;
}
private void buildSql()
{
if (sqlBuilt)
{
return;
}
final ArrayList<Object> sqlParams = new ArrayList<>();
final StringBuilder sql = new StringBuilder();
sql.append(columnName).append(" IS NOT NULL");
if (range.hasLowerBound())
{
final String operator;
final BoundType boundType = range.lowerBoundType();
switch (boundType)
{
case OPEN:
operator = ">";
break;
|
case CLOSED:
operator = ">=";
break;
default:
throw new AdempiereException("Unknown bound: " + boundType);
}
sql.append(" AND ").append(columnName).append(operator).append("?");
sqlParams.add(range.lowerEndpoint());
}
if (range.hasUpperBound())
{
final String operator;
final BoundType boundType = range.upperBoundType();
switch (boundType)
{
case OPEN:
operator = "<";
break;
case CLOSED:
operator = "<=";
break;
default:
throw new AdempiereException("Unknown bound: " + boundType);
}
sql.append(" AND ").append(columnName).append(operator).append("?");
sqlParams.add(range.upperEndpoint());
}
//
this.sqlWhereClause = sql.toString();
this.sqlParams = !sqlParams.isEmpty() ? Collections.unmodifiableList(sqlParams) : ImmutableList.of();
this.sqlBuilt = true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\InstantRangeQueryFilter.java
| 1
|
请完成以下Java代码
|
public class MultipartFormData {
protected Map<String, FormPart> formParts = new HashMap<String, FormPart>();
public void addPart(FormPart formPart) {
formParts.put(formPart.getFieldName(), formPart);
}
public FormPart getNamedPart(String name) {
return formParts.get(name);
}
public Set<String> getPartNames() {
return formParts.keySet();
}
/**
* Dto representing a part in a multipart form.
*
*/
public static class FormPart {
protected String fieldName;
protected String contentType;
protected String textContent;
protected String fileName;
protected byte[] binaryContent;
public FormPart(FileItemStream stream) {
fieldName = stream.getFieldName();
contentType = stream.getContentType();
binaryContent = readBinaryContent(stream);
fileName = stream.getName();
if(contentType == null || contentType.contains(MediaType.TEXT_PLAIN)) {
textContent = new String(binaryContent, StandardCharsets.UTF_8);
}
}
public FormPart() {
}
protected byte[] readBinaryContent(FileItemStream stream) {
InputStream inputStream = getInputStream(stream);
return IoUtil.readInputStream(inputStream, stream.getFieldName());
}
|
protected InputStream getInputStream(FileItemStream stream) {
try {
return stream.openStream();
} catch (IOException e) {
throw new RestException(Status.INTERNAL_SERVER_ERROR, e);
}
}
public String getFieldName() {
return fieldName;
}
public String getContentType() {
return contentType;
}
public String getTextContent() {
return textContent;
}
public byte[] getBinaryContent() {
return binaryContent;
}
public String getFileName() {
return fileName;
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\mapper\MultipartFormData.java
| 1
|
请完成以下Java代码
|
private void writeObject(ObjectOutputStream aOutputStream) throws IOException {
aOutputStream.writeObject(statusCode);
aOutputStream.writeObject(headers);
aOutputStream.write(this.bodyAsByteArray());
aOutputStream.writeObject(timestamp);
}
public static Builder create(HttpStatusCode statusCode) {
return new Builder(statusCode);
}
public HttpStatusCode statusCode() {
return this.statusCode;
}
public HttpHeaders headers() {
return this.headers;
}
public List<ByteBuffer> body() {
return Collections.unmodifiableList(body);
}
public Date timestamp() {
return this.timestamp;
}
byte[] bodyAsByteArray() throws IOException {
var bodyStream = new ByteArrayOutputStream();
var channel = Channels.newChannel(bodyStream);
for (ByteBuffer byteBuffer : body()) {
channel.write(byteBuffer);
}
return bodyStream.toByteArray();
}
String bodyAsString() throws IOException {
InputStream byteStream = new ByteArrayInputStream(bodyAsByteArray());
if (headers.getOrEmpty(HttpHeaders.CONTENT_ENCODING).contains("gzip")) {
byteStream = new GZIPInputStream(byteStream);
}
return new String(FileCopyUtils.copyToByteArray(byteStream));
}
public static class Builder {
private final HttpStatusCode statusCode;
private final HttpHeaders headers = new HttpHeaders();
private final List<ByteBuffer> body = new ArrayList<>();
private @Nullable Instant timestamp;
public Builder(HttpStatusCode statusCode) {
this.statusCode = statusCode;
}
public Builder header(String name, String value) {
this.headers.add(name, value);
|
return this;
}
public Builder headers(HttpHeaders headers) {
this.headers.addAll(headers);
return this;
}
public Builder timestamp(Instant timestamp) {
this.timestamp = timestamp;
return this;
}
public Builder timestamp(Date timestamp) {
this.timestamp = timestamp.toInstant();
return this;
}
public Builder body(String data) {
return appendToBody(ByteBuffer.wrap(data.getBytes(StandardCharsets.UTF_8)));
}
public Builder appendToBody(ByteBuffer byteBuffer) {
this.body.add(byteBuffer);
return this;
}
public CachedResponse build() {
return new CachedResponse(statusCode, headers, body, timestamp == null ? new Date() : Date.from(timestamp));
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\CachedResponse.java
| 1
|
请完成以下Java代码
|
public String remove(String key) {
try {
writeLock.lock();
return syncHashMap.remove(key);
} finally {
writeLock.unlock();
}
}
public boolean containsKey(String key) {
try {
readLock.lock();
return syncHashMap.containsKey(key);
} finally {
readLock.unlock();
}
}
boolean isReadLockAvailable() {
return readLock.tryLock();
}
public static void main(String[] args) throws InterruptedException {
final int threadCount = 3;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
service.execute(new Thread(new Writer(object), "Writer"));
service.execute(new Thread(new Reader(object), "Reader1"));
service.execute(new Thread(new Reader(object), "Reader2"));
service.shutdown();
}
private static class Reader implements Runnable {
SynchronizedHashMapWithRWLock object;
|
Reader(SynchronizedHashMapWithRWLock object) {
this.object = object;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
object.get("key" + i);
}
}
}
private static class Writer implements Runnable {
SynchronizedHashMapWithRWLock object;
public Writer(SynchronizedHashMapWithRWLock object) {
this.object = object;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
object.put("key" + i, "value" + i);
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\concurrent\locks\SynchronizedHashMapWithRWLock.java
| 1
|
请完成以下Java代码
|
public void setPolicy(CrossOriginEmbedderPolicy embedderPolicy) {
Assert.notNull(embedderPolicy, "embedderPolicy cannot be null");
this.policy = embedderPolicy;
}
@Override
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
if (this.policy != null && !response.containsHeader(EMBEDDER_POLICY)) {
response.addHeader(EMBEDDER_POLICY, this.policy.getPolicy());
}
}
public enum CrossOriginEmbedderPolicy {
UNSAFE_NONE("unsafe-none"),
REQUIRE_CORP("require-corp"),
CREDENTIALLESS("credentialless");
private final String policy;
CrossOriginEmbedderPolicy(String policy) {
this.policy = policy;
}
|
public String getPolicy() {
return this.policy;
}
public static @Nullable CrossOriginEmbedderPolicy from(String embedderPolicy) {
for (CrossOriginEmbedderPolicy policy : values()) {
if (policy.getPolicy().equals(embedderPolicy)) {
return policy;
}
}
return null;
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\CrossOriginEmbedderPolicyHeaderWriter.java
| 1
|
请完成以下Java代码
|
public void createDisposeCandidatesInTrx(
@NonNull final HuId huId,
@NonNull final QtyRejectedReasonCode reasonCode)
{
final I_M_HU hu = handlingUnitsBL.getById(huId);
if (!huStatusBL.isQtyOnHand(hu.getHUStatus()))
{
throw new AdempiereException("Invalid HU status: " + hu.getHUStatus());
}
final ImmutableMap<ProductId, I_M_Inventory_Candidate> existingRecords = Maps.uniqueIndex(
queryByHuIdAndNotProcessed(huId).create().list(),
record -> ProductId.ofRepoId(record.getM_Product_ID()));
handlingUnitsBL.getStorageFactory()
.getStorage(hu)
.getProductStorages()
.forEach(huProductStorage -> {
final I_M_Inventory_Candidate existingRecord = existingRecords.get(huProductStorage.getProductId());
createOrUpdateDisposeCandidate(huProductStorage, reasonCode, existingRecord);
});
}
private void createOrUpdateDisposeCandidate(
@NonNull final IHUProductStorage huProductStorage,
@NonNull final QtyRejectedReasonCode reasonCode,
@Nullable final I_M_Inventory_Candidate existingRecord)
{
final I_M_Inventory_Candidate record;
if (existingRecord == null)
{
record = InterfaceWrapperHelper.newInstance(I_M_Inventory_Candidate.class);
record.setM_HU_ID(huProductStorage.getHuId().getRepoId());
record.setM_Product_ID(huProductStorage.getProductId().getRepoId());
}
else
|
{
record = existingRecord;
}
final Quantity qty = huProductStorage.getQty();
record.setC_UOM_ID(qty.getUomId().getRepoId());
record.setQtyToDispose(qty.toBigDecimal());
record.setIsWholeHU(true);
record.setDisposeReason(reasonCode.getCode());
InterfaceWrapperHelper.save(record);
}
private IQueryBuilder<I_M_Inventory_Candidate> queryByHuIdAndNotProcessed(final @NonNull HuId huId)
{
return queryBL.createQueryBuilder(I_M_Inventory_Candidate.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_Inventory_Candidate.COLUMNNAME_M_HU_ID, huId)
.addEqualsFilter(I_M_Inventory_Candidate.COLUMNNAME_Processed, false);
}
public boolean isDisposalPending(final @NonNull HuId huId)
{
return queryByHuIdAndNotProcessed(huId)
.addNotNull(I_M_Inventory_Candidate.COLUMNNAME_DisposeReason)
.create()
.anyMatch();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inventory\InventoryCandidateService.java
| 1
|
请完成以下Java代码
|
public Object convertValueToFieldType(final Object valueObj)
{
return UserQueryFieldHelper.parseValueObjectByColumnDisplayType(valueObj, getDisplayType(), getColumnName());
}
@Override
public String getValueDisplay(final Object value)
{
String infoDisplay = value == null ? "" : value.toString();
if (isLookup())
{
final Lookup lookup = getLookup();
if (lookup != null)
{
infoDisplay = lookup.getDisplay(value);
}
}
else if (getDisplayType() == DisplayType.YesNo)
{
final IMsgBL msgBL = Services.get(IMsgBL.class);
infoDisplay = msgBL.getMsg(Env.getCtx(), infoDisplay);
}
return infoDisplay;
}
@Override
public boolean matchesColumnName(final String columnName)
{
if (columnName == null || columnName.isEmpty())
{
return false;
}
if (columnName.equals(getColumnName()))
{
return true;
|
}
if (gridField.isVirtualColumn())
{
if (columnName.equals(gridField.getColumnSQL(false)))
{
return true;
}
if (columnName.equals(gridField.getColumnSQL(true)))
{
return true;
}
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelSearchField.java
| 1
|
请完成以下Java代码
|
public final class ConfirmableDTOs
{
public static final Set<String> extractUUIDs(final Collection<? extends IConfirmableDTO> syncModels)
{
final Set<String> uuids = new HashSet<>();
if (syncModels == null || syncModels.isEmpty())
{
return uuids;
}
for (final IConfirmableDTO syncModel : syncModels)
{
if (syncModel == null)
{
// shall not happen
continue;
}
|
final String uuid = syncModel.getUuid();
if (uuid == null)
{
// shall not happen
continue;
}
uuids.add(uuid);
}
return uuids;
}
private ConfirmableDTOs()
{
super();
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-procurement\src\main\java\de\metas\common\procurement\sync\util\ConfirmableDTOs.java
| 1
|
请完成以下Java代码
|
private boolean isBlockFinished(String line) {
return StringUtils.isBlank(line) || line.equals("\\.");
}
private void processAllTables(LineIterator lineIterator) throws IOException {
String currentLine;
try {
while (lineIterator.hasNext()) {
currentLine = lineIterator.nextLine();
for(Map.Entry<String, EntityType> entry : tableNameAndEntityType.entrySet()) {
if(currentLine.startsWith(entry.getKey())) {
processBlock(lineIterator, entry.getValue());
}
}
}
|
} finally {
lineIterator.close();
}
}
private void processBlock(LineIterator lineIterator, EntityType entityType) {
String currentLine;
while(lineIterator.hasNext()) {
currentLine = lineIterator.nextLine();
if(isBlockFinished(currentLine)) {
return;
}
allEntityIdsAndTypes.put(currentLine.split("\t")[0], entityType.name());
}
}
}
|
repos\thingsboard-master\tools\src\main\java\org\thingsboard\client\tools\migrator\RelatedEntitiesParser.java
| 1
|
请完成以下Java代码
|
static void getReadLockFromOutputStream() throws IOException {
Path path = Files.createTempFile("foo", "txt");
try (FileOutputStream fis = new FileOutputStream(path.toFile());
FileLock lock = fis.getChannel()
.lock(0, Long.MAX_VALUE, true)) {
LOG.debug("This won't happen");
} catch (NonReadableChannelException e) {
LOG.error("The channel obtained through a FileOutputStream isn't readable. " + "You can't obtain an shared lock on it!");
throw e;
}
}
/**
* Gets a lock from an <tt>InputStream</tt>.
* @param from beginning of the locked region
* @param size how many bytes to lock
* @return A lock object representing the newly-acquired lock
* @throws IOException if there is a problem creating the temporary file
*/
static FileLock getReadLockFromInputStream(long from, long size) throws IOException {
Path path = Files.createTempFile("foo", "txt");
try (FileInputStream fis = new FileInputStream(path.toFile());
FileLock lock = fis.getChannel()
.lock(from, size, true)) {
if (lock.isValid()) {
LOG.debug("This is a valid shared lock");
return lock;
}
return null;
}
}
/**
* Gets an exclusive lock from a RandomAccessFile. Works because the file is readable.
* @param from beginning of the locked region
|
* @param size how many bytes to lock
* @return A lock object representing the newly-acquired lock
* @throws IOException if there is a problem creating the temporary file
*/
static FileLock getReadLockFromRandomAccessFile(long from, long size) throws IOException {
Path path = Files.createTempFile("foo", "txt");
try (RandomAccessFile file = new RandomAccessFile(path.toFile(), "r"); // could also be "rw", but "r" is sufficient for reading
FileLock lock = file.getChannel()
.lock(from, size, true)) {
if (lock.isValid()) {
LOG.debug("This is a valid shared lock");
return lock;
}
} catch (Exception e) {
LOG.error(e.getMessage());
}
return null;
}
}
|
repos\tutorials-master\core-java-modules\core-java-nio\src\main\java\com\baeldung\lock\FileLocks.java
| 1
|
请完成以下Java代码
|
public boolean isFreightCostProduct(@NonNull final ProductId productId)
{
return freightCostRepo.existsByFreightCostProductId(productId);
}
public boolean checkIfFree(@NonNull final FreightCostContext context)
{
if (!context.getDeliveryViaRule().isShipper())
{
logger.debug("No freight cost because DeliveryViaRule is not shipper: ", context);
return true;
}
if (context.getShipToBPartnerId() == null)
{
logger.debug("No freight cost because ShipToBPartner is not set: {}", context);
return true;
}
if (context.getFreightCostRule() == FreightCostRule.FreightIncluded)
{
logger.debug("No freight cost because the freight is included: {}", context);
return true;
}
if (context.getShipperId() == null)
{
logger.debug("No freightcost because no shipper is set: {}", context);
return true;
}
return false;
}
/**
* Attempts to load the freight costs for a given business partner and location (actually the location's country).
* Looks at different freight cost records in this context:
* <ul>
* <li>Freight cost attached to the bParter</li>
* <li>Freight cost attached to the bParter's bPartnerGroup</li>
* <li>Default freight cost</li>
* </ul>
*
* @throws AdempiereException if there is no freight cost record for the given inOut
*/
public FreightCost findBestMatchingFreightCost(final FreightCostContext context)
{
final BPartnerId shipToBPartnerId = context.getShipToBPartnerId();
if (shipToBPartnerId == null)
{
throw new AdempiereException("ShipToBPartner not set");
}
final CountryId shipToCountryId = context.getShipToCountryId();
if (shipToCountryId == null)
{
throw new AdempiereException("ShipToCountryId not set");
}
final ShipperId shipperId = context.getShipperId();
if (shipperId == null)
{
throw new AdempiereException(MSG_Order_No_Shipper);
|
}
//
//
final FreightCost freightCost = getFreightCostByBPartnerId(shipToBPartnerId);
final FreightCostShipper shipper = freightCost.getShipper(shipperId, context.getDate());
if (!shipper.isShipToCountry(shipToCountryId))
{
throw new AdempiereException("@NotFound@ @M_FreightCost_ID@ (@M_Shipper_ID@:" + shipperId + ", @C_Country_ID@:" + shipToCountryId + ")");
}
return freightCost;
}
public FreightCost getFreightCostByBPartnerId(final BPartnerId bpartnerId)
{
final IBPartnerBL bpartnerBL = Services.get(IBPartnerBL.class);
final FreightCostId bpFreightCostId = FreightCostId.ofRepoIdOrNull(bpartnerBL.getFreightCostIdByBPartnerId(bpartnerId));
if (bpFreightCostId != null)
{
return freightCostRepo.getById(bpFreightCostId);
}
final FreightCost defaultFreightCost = freightCostRepo.getDefaultFreightCost().orElse(null);
if (defaultFreightCost != null)
{
return defaultFreightCost;
}
throw new AdempiereException("@NotFound@ @M_FreightCost_ID@: " + bpartnerId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\freighcost\FreightCostService.java
| 1
|
请完成以下Java代码
|
public void renumberLinesIfCompensationGroupChanged(@NonNull final I_C_OrderLine orderLine)
{
if (!OrderGroupCompensationUtils.isInGroup(orderLine))
{
return;
}
groupChangesHandler.renumberOrderLinesForOrderId(OrderId.ofRepoId(orderLine.getC_Order_ID()));
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE },
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_M_Product_ID, I_C_OrderLine.COLUMNNAME_QtyOrdered })
public void updateWeight(@NonNull final I_C_OrderLine orderLine)
{
final I_C_Order order = orderBL.getById(OrderId.ofRepoId(orderLine.getC_Order_ID()));
orderBL.setWeightFromLines(order);
saveRecord(order);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_IsWithoutCharge, I_C_OrderLine.COLUMNNAME_PriceActual, I_C_OrderLine.COLUMNNAME_PriceEntered })
public void updatePriceToZero(final I_C_OrderLine orderLine)
{
if (orderLine.isWithoutCharge())
{
orderLine.setPriceActual(BigDecimal.ZERO);
orderLine.setPriceEntered(BigDecimal.ZERO);
orderLine.setIsManualPrice(true);
final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class);
orderLineBL.updateLineNetAmtFromQtyEntered(orderLine);
|
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_IsWithoutCharge})
public void updatePriceToStd(final I_C_OrderLine orderLine)
{
if (!orderLine.isWithoutCharge())
{
orderLine.setPriceActual(orderLine.getPriceStd());
orderLine.setPriceEntered(orderLine.getPriceStd());
orderLine.setIsManualPrice(false);
final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class);
orderLineBL.updateLineNetAmtFromQtyEntered(orderLine);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\model\interceptor\C_OrderLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private JsonError getRemoteJsonError(@NonNull final String httpResponse, @NonNull final Exchange exchange)
{
Optional<JsonError> jsonError = getJsonErrorFromV2Response(httpResponse, exchange);
if (jsonError.isEmpty())
{
jsonError = getJsonErrorFromV1Response(httpResponse);
}
if (jsonError.isPresent())
{
return jsonError.get().toBuilder()
.error(getErrorItem(exchange))
.build();
}
logger.log(Level.WARNING, "*** processHttpErrorEncounteredResponse: couldn't process HttpOperationFailedException.ResponseBody! Defaulting to stacktrace...");
return JsonError.ofSingleItem(getErrorItem(exchange));
}
@NonNull
private Optional<JsonError> getJsonErrorFromV2Response(@NonNull final String response, @NonNull final Exchange exchange)
{
try
{
final ObjectMapper objectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
final JsonApiResponse apiResponse = objectMapper
.readValue(response, JsonApiResponse.class);
final JsonError jsonError = objectMapper.convertValue(apiResponse.getEndpointResponse(), JsonError.class)
.toBuilder()
.requestId(apiResponse.getRequestId())
.build();
return Optional.of(jsonError);
}
catch (final JsonProcessingException e)
{
return Optional.empty();
|
}
catch (final IllegalArgumentException illegalArgumentException)
{
logger.log(Level.WARNING, "*** getJsonErrorFromV2Response: couldn't cast JsonApiResponse.endpointResponse to JsonError!"
+ " Defaulting to stacktrace... see exception:" + illegalArgumentException.getMessage());
return Optional.empty();
}
}
@NonNull
private Optional<JsonError> getJsonErrorFromV1Response(@NonNull final String response)
{
try
{
final JsonError jsonError = JsonObjectMapperHolder.sharedJsonObjectMapper()
.readValue(response, JsonError.class);
return Optional.of(jsonError);
}
catch (final JsonProcessingException e)
{
return Optional.empty();
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\common\src\main\java\de\metas\camel\externalsystems\common\error\ErrorProcessor.java
| 2
|
请完成以下Java代码
|
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_R_StandardResponse[")
.append(get_ID()).append("]");
return sb.toString();
}
/** 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 Response Text.
@param ResponseText
Request Response Text
*/
public void setResponseText (String ResponseText)
{
set_Value (COLUMNNAME_ResponseText, ResponseText);
}
/** Get Response Text.
@return Request Response Text
*/
public String getResponseText ()
{
return (String)get_Value(COLUMNNAME_ResponseText);
}
|
/** Set Standard Response.
@param R_StandardResponse_ID
Request Standard Response
*/
public void setR_StandardResponse_ID (int R_StandardResponse_ID)
{
if (R_StandardResponse_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_StandardResponse_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_StandardResponse_ID, Integer.valueOf(R_StandardResponse_ID));
}
/** Get Standard Response.
@return Request Standard Response
*/
public int getR_StandardResponse_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_StandardResponse_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_StandardResponse.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class TotpTwoFaProvider implements TwoFaProvider<TotpTwoFaProviderConfig, TotpTwoFaAccountConfig> {
@Override
public final TotpTwoFaAccountConfig generateNewAccountConfig(User user, TotpTwoFaProviderConfig providerConfig) {
TotpTwoFaAccountConfig config = new TotpTwoFaAccountConfig();
String secretKey = generateSecretKey();
config.setAuthUrl(getTotpAuthUrl(user, secretKey, providerConfig));
return config;
}
@Override
public final boolean checkVerificationCode(SecurityUser user, String code, TotpTwoFaProviderConfig providerConfig, TotpTwoFaAccountConfig accountConfig) {
String secretKey = UriComponentsBuilder.fromUriString(accountConfig.getAuthUrl()).build().getQueryParams().getFirst("secret");
return new Totp(secretKey).verify(code);
}
@SneakyThrows
private String getTotpAuthUrl(User user, String secretKey, TotpTwoFaProviderConfig providerConfig) {
URIBuilder uri = new URIBuilder()
.setScheme("otpauth")
.setHost("totp")
.setParameter("issuer", providerConfig.getIssuerName())
|
.setPath("/" + providerConfig.getIssuerName() + ":" + user.getEmail())
.setParameter("secret", secretKey);
return uri.build().toASCIIString();
}
private String generateSecretKey() {
return Base32.encode(RandomUtils.nextBytes(20));
}
@Override
public TwoFaProviderType getType() {
return TwoFaProviderType.TOTP;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\mfa\provider\impl\TotpTwoFaProvider.java
| 2
|
请完成以下Java代码
|
public class BookInformationHiding {
private String author;
private int isbn;
private int id = 1;
public BookInformationHiding(String author, int isbn) {
setAuthor(author);
setIsbn(isbn);
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
|
public int getIsbn() {
return isbn;
}
public void setIsbn(int isbn) {
if (isbn < 0) {
throw new IllegalArgumentException("ISBN can't be negative");
}
this.isbn = isbn;
}
public String getBookDetails() {
return "author id: " + id + " author name: " + author + " ISBN: " + isbn;
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-others\src\main\java\com\baeldung\encapsulation\BookInformationHiding.java
| 1
|
请完成以下Java代码
|
public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut)
{
set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut);
}
@Override
public void setM_InOut_ID (final int M_InOut_ID)
{
if (M_InOut_ID < 1)
set_Value (COLUMNNAME_M_InOut_ID, null);
else
set_Value (COLUMNNAME_M_InOut_ID, M_InOut_ID);
}
@Override
public int getM_InOut_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOut_ID);
}
@Override
public void setMovementDate (final @Nullable java.sql.Timestamp MovementDate)
{
set_Value (COLUMNNAME_MovementDate, MovementDate);
}
@Override
public java.sql.Timestamp getMovementDate()
{
return get_ValueAsTimestamp(COLUMNNAME_MovementDate);
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_Value (COLUMNNAME_POReference, POReference);
}
|
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setShipment_DocumentNo (final @Nullable java.lang.String Shipment_DocumentNo)
{
set_Value (COLUMNNAME_Shipment_DocumentNo, Shipment_DocumentNo);
}
@Override
public java.lang.String getShipment_DocumentNo()
{
return get_ValueAsString(COLUMNNAME_Shipment_DocumentNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_111_v.java
| 1
|
请完成以下Java代码
|
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Item item = (Item) o;
if (code != null ? !code.equals(item.code) : item.code != null)
return false;
|
if (price != null ? !price.equals(item.price) : item.price != null)
return false;
return quantity != null ? quantity.equals(item.quantity) : item.quantity == null;
}
@Override
public int hashCode() {
int result = code != null ? code.hashCode() : 0;
result = 31 * result + (price != null ? price.hashCode() : 0);
result = 31 * result + (quantity != null ? quantity.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Item{" + "code='" + code + '\'' + ", price=" + price + ", quantity=" + quantity + '}';
}
}
|
repos\tutorials-master\libraries-data-io-2\src\main\java\com\baeldung\libraries\smooks\model\Item.java
| 1
|
请完成以下Java代码
|
abstract class BPartnerNewUpdateContextEditorAction extends AbstractContextMenuAction
{
private final boolean createNew;
public BPartnerNewUpdateContextEditorAction(boolean createNew)
{
super();
this.createNew = createNew;
}
@Override
public String getIcon()
{
return "InfoBPartner16";
}
@Override
public boolean isAvailable()
{
final int adClientId = Env.getAD_Client_ID(Env.getCtx());
if (!Services.get(ISysConfigBL.class).getBooleanValue("UI_EnableBPartnerContextMenu", true, adClientId))
{
return false;
}
final VEditor editor = getEditor();
final GridField gridField = editor.getField();
if (gridField == null)
{
return false;
}
if (!gridField.isLookup())
{
return false;
}
final Lookup lookup = gridField.getLookup();
if (lookup == null)
{
// No Lookup???
log.warn("No lookup found for " + gridField + " even if is marked as Lookup");
return false;
}
final String tableName = lookup.getTableName();
if (!I_C_BPartner.Table_Name.equals(tableName))
{
return false;
}
return true;
}
|
@Override
public boolean isRunnable()
{
final VEditor editor = getEditor();
return editor.isReadWrite();
}
@Override
public void run()
{
final VEditor editor = getEditor();
final GridField gridField = editor.getField();
final Lookup lookup = gridField.getLookup();
final int windowNo = gridField.getWindowNo();
final VBPartner vbp = new VBPartner(Env.getWindow(windowNo), windowNo);
int BPartner_ID = 0;
// if update, get current value
if (!createNew)
{
final Object value = editor.getValue();
if (value instanceof Integer)
BPartner_ID = ((Integer)value).intValue();
else if (value != null)
BPartner_ID = Integer.parseInt(value.toString());
}
vbp.loadBPartner(BPartner_ID);
vbp.setVisible(true);
// get result
int result = vbp.getC_BPartner_ID();
if (result == 0 // 0 = not saved
&& result == BPartner_ID) // the same
return;
// Maybe new BPartner - put in cache
lookup.getDirect(IValidationContext.NULL, new Integer(result), false, true);
// actionCombo (new Integer(result)); // data binding
gridField.getGridTab().setValue(gridField, result);
} // actionBPartner
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\menu\BPartnerNewUpdateContextEditorAction.java
| 1
|
请完成以下Java代码
|
public Integer getMenuType() {
return menuType;
}
public void setMenuType(Integer menuType) {
this.menuType = menuType;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isRoute() {
return route;
}
public void setRoute(boolean route) {
this.route = route;
}
public Integer getDelFlag() {
return delFlag;
}
public void setDelFlag(Integer delFlag) {
this.delFlag = delFlag;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getPerms() {
return perms;
}
|
public void setPerms(String perms) {
this.perms = perms;
}
public boolean getIsLeaf() {
return isLeaf;
}
public void setIsLeaf(boolean isLeaf) {
this.isLeaf = isLeaf;
}
public String getPermsType() {
return permsType;
}
public void setPermsType(String permsType) {
this.permsType = permsType;
}
public java.lang.String getStatus() {
return status;
}
public void setStatus(java.lang.String status) {
this.status = status;
}
/*update_begin author:wuxianquan date:20190908 for:get set方法 */
public boolean isInternalOrExternal() {
return internalOrExternal;
}
public void setInternalOrExternal(boolean internalOrExternal) {
this.internalOrExternal = internalOrExternal;
}
/*update_end author:wuxianquan date:20190908 for:get set 方法 */
public boolean isHideTab() {
return hideTab;
}
public void setHideTab(boolean hideTab) {
this.hideTab = hideTab;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\SysPermissionTree.java
| 1
|
请完成以下Java代码
|
public class HtmlDocument {
private final String content;
private HtmlDocument(String html) {
this.content = html;
}
public HtmlDocument() {
this("");
}
public String html() {
return String.format("<html>%s</html>", content);
}
public HtmlDocument header(String header) {
return new HtmlDocument(String.format("%s <h1>%s</h1>", content, header));
}
public HtmlDocument secondaryHeader(String header) {
return new HtmlDocument(String.format("%s <h2>%s</h2>", content, header));
}
public HtmlDocument paragraph(String paragraph) {
return new HtmlDocument(String.format("%s <p>%s</p>", content, paragraph));
}
|
public HtmlDocument horizontalLine() {
return new HtmlDocument(String.format("%s <hr>", content));
}
public HtmlDocument orderedList(String... items) {
String listItems = stream(items).map(el -> String.format("<li>%s</li>", el)).collect(joining());
return new HtmlDocument(String.format("%s <ol>%s</ol>", content, listItems));
}
public HtmlDocument unorderedList(String... items) {
String listItems = stream(items).map(el -> String.format("<li>%s</li>", el)).collect(joining());
return new HtmlDocument(String.format("%s <ul>%s</ul>", content, listItems));
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-behavioral-2\src\main\java\com\baeldung\fluentinterface\HtmlDocument.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
/**
* 删除路由
*
* @param id
* @return
*/
public synchronized void delete(String id) {
try {
repository.delete(Mono.just(id)).subscribe();
this.publisher.publishEvent(new RefreshRoutesEvent(this));
}catch (Exception e){
log.warn(e.getMessage(),e);
}
}
/**
* 更新路由
*
* @param definition
* @return
*/
public synchronized String update(RouteDefinition definition) {
try {
log.info("gateway update route {}", definition);
} catch (Exception e) {
|
return "update fail,not find route routeId: " + definition.getId();
}
try {
repository.save(Mono.just(definition)).subscribe();
this.publisher.publishEvent(new RefreshRoutesEvent(this));
return "success";
} catch (Exception e) {
return "update route fail";
}
}
/**
* 增加路由
*
* @param definition
* @return
*/
public synchronized String add(RouteDefinition definition) {
log.info("gateway add route {}", definition);
try {
repository.save(Mono.just(definition)).subscribe();
} catch (Exception e) {
log.warn(e.getMessage(),e);
}
return "success";
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-gateway\src\main\java\org\jeecg\loader\repository\DynamicRouteService.java
| 2
|
请完成以下Java代码
|
public class Course {
private String name;
private String description;
private Date startDate;
private Date endDate;
private String teacher;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
|
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getTeacher() {
return teacher;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
}
|
repos\tutorials-master\spring-web-modules\spring-thymeleaf-2\src\main\java\com\baeldung\thymeleaf\customhtml\Course.java
| 1
|
请完成以下Java代码
|
public class EnumFormType extends SimpleFormFieldType {
public final static String TYPE_NAME = "enum";
protected Map<String, String> values;
public EnumFormType(Map<String, String> values) {
this.values = values;
}
public String getName() {
return TYPE_NAME;
}
@Override
public Object getInformation(String key) {
if (key.equals("values")) {
return values;
}
return null;
}
public TypedValue convertValue(TypedValue propertyValue) {
Object value = propertyValue.getValue();
if(value == null || String.class.isInstance(value)) {
validateValue(value);
return Variables.stringValue((String) value, propertyValue.isTransient());
}
else {
throw new ProcessEngineException("Value '"+value+"' is not of type String.");
}
}
protected void validateValue(Object value) {
if(value != null) {
|
if(values != null && !values.containsKey(value)) {
throw new ProcessEngineException("Invalid value for enum form property: " + value);
}
}
}
public Map<String, String> getValues() {
return values;
}
//////////////////// deprecated ////////////////////////////////////////
@Override
public Object convertFormValueToModelValue(Object propertyValue) {
validateValue(propertyValue);
return propertyValue;
}
@Override
public String convertModelValueToFormValue(Object modelValue) {
if(modelValue != null) {
if(!(modelValue instanceof String)) {
throw new ProcessEngineException("Model value should be a String");
}
validateValue(modelValue);
}
return (String) modelValue;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\type\EnumFormType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SessionCache {
private static final int EXPIRE_TIME = 30; // 30s
// public static final String V1 = "V1";
public static final String V2 = "V2";
public static final String V3 = "V3";
private static final String VOICE_OPENID_V1_SESSION = "openid:voice:session:v1:";
private static final String TEXT_OPENID_V1_SESSION = "openid:text:session:v1:";
private static final String VOICE_OPENID_V2_SESSION = "openid:voice:session:v2:";
private static final String TEXT_OPENID_V2_SESSION = "openid:text:session:v2:";
private static final String VOICE_OPENID_V3_SESSION = "openid:voice:session:v3:";
private static final String TEXT_OPENID_V3_SESSION = "openid:text:session:v3:";
public static final String DIALOG_VOICE_TYPE = "voice";
public static final String DIALOG_TEXT_TYPE = "text";
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
*
* @param version 版本号
* @param openId 用户唯一识别,可位微信端的openid,也可以是通话过程的callid
* @param session 通过模块与交互模块的session,通话系统中,callid就是session
* @param type
*/
public void refreshSession(String version, String openId, String session, String type) {
set(generateKey(version, openId, type), session);
}
public Boolean isExist(String version, String openId, String type) {
return stringRedisTemplate.hasKey(generateKey(version, openId, type));
}
public String getSession(String version, String openId, String type) {
return get(generateKey(version, openId, type));
}
public void delSession(String version, String openId, String type) {
del(version, openId, type);
}
private String get(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
private void set(String key, String value) {
|
stringRedisTemplate.opsForValue().set(key, value, EXPIRE_TIME, TimeUnit.SECONDS);
}
private void del(String version, String openId, String type) {
stringRedisTemplate.delete(generateKey(version, openId, type));
}
private String generateKey(String version, String openId, String type) {
// if (V1.equals(version)) {
// if (DIALOG_VOICE_TYPE.equals(type)) {
// return VOICE_OPENID_V1_SESSION + openId;
// } else {
// return TEXT_OPENID_V1_SESSION + openId;
// }
// } else
if (V2.equals(version)) {
if (DIALOG_VOICE_TYPE.equals(type)) {
return VOICE_OPENID_V2_SESSION + openId;
} else {
return TEXT_OPENID_V2_SESSION + openId;
}
} else {
if (DIALOG_VOICE_TYPE.equals(type)) {
return VOICE_OPENID_V3_SESSION + openId;
} else {
return TEXT_OPENID_V3_SESSION + openId;
}
}
}
}
|
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\config\SessionCache.java
| 2
|
请完成以下Spring Boot application配置
|
spring.application.name=Eurekaclient
server.port=${PORT:0}
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka
eureka.instance.preferIpAddress = true
eureka.client.should-u
|
nregister-on-shutdown=false
eureka.instance.lease-renewal-interval-in-seconds=30
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-eureka-self-preservation\spring-cloud-eureka-client\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public DmnDecisionQuery createDecisionQuery() {
return new DecisionQueryImpl(commandExecutor);
}
@Override
public NativeDecisionQuery createNativeDecisionQuery() {
return new NativeDecisionTableQueryImpl(commandExecutor);
}
@Override
public List<String> getDeploymentResourceNames(String deploymentId) {
return commandExecutor.execute(new GetDeploymentResourceNamesCmd(deploymentId));
}
@Override
public InputStream getResourceAsStream(String deploymentId, String resourceName) {
return commandExecutor.execute(new GetDeploymentResourceCmd(deploymentId, resourceName));
}
@Override
public void setDeploymentCategory(String deploymentId, String category) {
commandExecutor.execute(new SetDeploymentCategoryCmd(deploymentId, category));
}
@Override
public void setDeploymentTenantId(String deploymentId, String newTenantId) {
commandExecutor.execute(new SetDeploymentTenantIdCmd(deploymentId, newTenantId));
}
@Override
public void changeDeploymentParentDeploymentId(String deploymentId, String newParentDeploymentId) {
commandExecutor.execute(new SetDeploymentParentDeploymentIdCmd(deploymentId, newParentDeploymentId));
}
@Override
public DmnDeploymentQuery createDeploymentQuery() {
return new DmnDeploymentQueryImpl(commandExecutor);
}
@Override
public NativeDmnDeploymentQuery createNativeDeploymentQuery() {
|
return new NativeDmnDeploymentQueryImpl(commandExecutor);
}
@Override
public DmnDecision getDecision(String decisionId) {
return commandExecutor.execute(new GetDeploymentDecisionCmd(decisionId));
}
@Override
public DmnDefinition getDmnDefinition(String decisionId) {
return commandExecutor.execute(new GetDmnDefinitionCmd(decisionId));
}
@Override
public InputStream getDmnResource(String decisionId) {
return commandExecutor.execute(new GetDeploymentDmnResourceCmd(decisionId));
}
@Override
public void setDecisionCategory(String decisionId, String category) {
commandExecutor.execute(new SetDecisionTableCategoryCmd(decisionId, category));
}
@Override
public InputStream getDecisionRequirementsDiagram(String decisionId) {
return commandExecutor.execute(new GetDeploymentDecisionRequirementsDiagramCmd(decisionId));
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\DmnRepositoryServiceImpl.java
| 1
|
请完成以下Java代码
|
public static LocatorId findLocatorIdOrNull(
@NonNull final I_M_InOutLine receiptLine,
@Nullable final LocatorId locatorToId)
{
// In case the line is in dispute, use the Warehouse for Issues as destination warehouse (see 06365)
// NOTE: we apply this rule only where and not in general, because general we don't want to do this for every warehouse.
if (create(receiptLine, de.metas.inout.model.I_M_InOutLine.class).isInDispute())
{
// TODO: output nice message whenever I_M_InOutLine.isInDispute is set to true
final I_M_Warehouse warehouseForIssues = Services.get(IWarehouseDAO.class).retrieveWarehouseForIssuesOrNull(Env.getCtx());
Check.assumeNotNull(warehouseForIssues, "Warehouse for issues shall be defined");
final IWarehouseBL warehouseBL = Services.get(IWarehouseBL.class);
final LocatorId locatorIdForIssues = warehouseBL.getOrCreateDefaultLocatorId(WarehouseId.ofRepoId(warehouseForIssues.getM_Warehouse_ID()));
return locatorIdForIssues;
}
final LocatorId effectiveLocatorToId = coalesceSuppliers(
() -> locatorToId,
() -> ReceiptLineFindForwardToLocatorTool.findDestinationLocatorOrNull(receiptLine));
final IWarehouseDAO warehouseDAO = Services.get(IWarehouseDAO.class);
final LocatorId receiptLineLocatorId = warehouseDAO.getLocatorIdByRepoIdOrNull(receiptLine.getM_Locator_ID());
if (Objects.equals(effectiveLocatorToId, receiptLineLocatorId))
{
return null;
}
return effectiveLocatorToId;
}
private static LocatorId findDestinationLocatorOrNull(@NonNull final I_M_InOutLine receiptLine)
{
final IReceiptScheduleDAO receiptScheduleDAO = Services.get(IReceiptScheduleDAO.class);
final List<I_M_ReceiptSchedule> receiptScheduleRecords = receiptScheduleDAO.retrieveRsForInOutLine(receiptLine);
return findDestinationLocatorOrNullForReceiptSchedules(receiptScheduleRecords);
}
|
private static LocatorId findDestinationLocatorOrNullForReceiptSchedules(
@NonNull final List<I_M_ReceiptSchedule> receiptScheduleRecords)
{
final Integer warehouseDestRepoId = CollectionUtils.extractSingleElementOrDefault(receiptScheduleRecords, I_M_ReceiptSchedule::getM_Warehouse_Dest_ID, -1);
if (warehouseDestRepoId <= 0)
{
return null;
}
final IWarehouseBL warehouseBL = Services.get(IWarehouseBL.class);
final I_M_Warehouse targetWarehouse = loadOutOfTrx(warehouseDestRepoId, I_M_Warehouse.class);
final I_M_Locator locatorTo = warehouseBL.getOrCreateDefaultLocator(targetWarehouse);
// Skip if we don't have a target warehouse
if (locatorTo == null)
{
return null;
}
return LocatorId.ofRecordOrNull(locatorTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\api\ReceiptLineFindForwardToLocatorTool.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserRepository {
private EntityManagerFactory emf = null;
public UserRepository() {
emf = Persistence.createEntityManagerFactory("entity-default-values");
}
public User find(Long id) {
EntityManager entityManager = emf.createEntityManager();
User user = entityManager.find(User.class, id);
entityManager.close();
return user;
}
|
public void save(User user, Long id) {
user.setId(id);
EntityManager entityManager = emf.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(user);
entityManager.getTransaction().commit();
entityManager.close();
}
public void clean() {
emf.close();
}
}
|
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\defaultvalues\UserRepository.java
| 2
|
请完成以下Java代码
|
public Optional<String> getAndIncrementLotNo(@NonNull final LotNoContext context)
{
final IDocumentNoBuilderFactory documentNoFactory = Services.get(IDocumentNoBuilderFactory.class);
final String lotNo = documentNoFactory.forSequenceId(context.getSequenceId())
.setFailOnError(true)
.setClientId(context.getClientId())
.setEvaluationContext(Evaluatees.empty())
.build();
return lotNo != null && !Objects.equals(lotNo, IDocumentNoBuilder.NO_DOCUMENTNO)
? Optional.of(lotNo)
: Optional.empty();
}
@Override
public String getLotNumberAttributeValueOrNull(@NonNull final I_M_AttributeSetInstance asi)
{
final AttributeId lotNumberAttrId = Services.get(ILotNumberDateAttributeDAO.class).getLotNumberAttributeId();
if (lotNumberAttrId == null)
{
|
return null;
}
final IAttributeSetInstanceBL asiBL = Services.get(IAttributeSetInstanceBL.class);
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(asi.getM_AttributeSetInstance_ID());
final I_M_AttributeInstance lotNumberAI = asiBL.getAttributeInstance(asiId, lotNumberAttrId);
if (lotNumberAI == null)
{
return null;
}
return lotNumberAI.getValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\LotNumberBL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MenuService {
private List<Meal> meals = new ArrayList<Meal>();
public MenuService() {
meals.add(new Meal("Java beans",42.0f));
}
@GET
@Path("/")
@Produces({ "application/json" })
public Response index() {
return Response.ok()
.entity(meals)
.build();
}
@GET
@Path("/{id}")
@Produces({ "application/json" })
public Response meal(@PathParam("id") int id) {
return Response.ok()
.entity(meals.get(id))
.build();
}
@POST
@Path("/")
@Consumes("application/json")
@Produces({ "application/json" })
public Response create(Meal meal) {
meals.add(meal);
return Response.ok()
.entity(meal)
.build();
|
}
@PUT
@Path("/{id}")
@Consumes("application/json")
@Produces({ "application/json" })
public Response update(@PathParam("id") int id, Meal meal) {
meals.set(id, meal);
return Response.ok()
.entity(meal)
.build();
}
@DELETE
@Path("/{id}")
@Produces({ "application/json" })
public Response delete(@PathParam("id") int id) {
Meal meal = meals.get(id);
meals.remove(id);
return Response.ok()
.entity(meal)
.build();
}
}
|
repos\tutorials-master\microservices-modules\msf4j\src\main\java\com\baeldung\msf4j\msf4japi\MenuService.java
| 2
|
请完成以下Java代码
|
public void setM_ProductPrice_ID (int M_ProductPrice_ID)
{
if (M_ProductPrice_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ProductPrice_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ProductPrice_ID, Integer.valueOf(M_ProductPrice_ID));
}
/** Get Produkt-Preis.
@return Produkt-Preis */
@Override
public int getM_ProductPrice_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductPrice_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Mindestpreis.
@param PriceLimit
Unterster Preis für Kostendeckung
*/
@Override
public void setPriceLimit (java.math.BigDecimal PriceLimit)
{
set_Value (COLUMNNAME_PriceLimit, PriceLimit);
}
/** Get Mindestpreis.
@return Unterster Preis für Kostendeckung
*/
@Override
public java.math.BigDecimal getPriceLimit ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceLimit);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Auszeichnungspreis.
@param PriceList
Auszeichnungspreis
*/
@Override
public void setPriceList (java.math.BigDecimal PriceList)
{
set_Value (COLUMNNAME_PriceList, PriceList);
}
/** Get Auszeichnungspreis.
@return Auszeichnungspreis
*/
@Override
public java.math.BigDecimal getPriceList ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceList);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Standardpreis.
@param PriceStd Standardpreis */
@Override
public void setPriceStd (java.math.BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
|
/** Get Standardpreis.
@return Standardpreis */
@Override
public java.math.BigDecimal getPriceStd ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\pricing\attributebased\X_M_ProductPrice_Attribute.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private I_PP_Order_BOMLine getBomLine(@NonNull final RawMaterialsIssueLine issueLine)
{
if (_bomLineRecordsById == null)
{
_bomLineRecordsById = Maps.uniqueIndex(ppOrderBOMBL.getOrderBOMLines(ppOrderId), IssueWhatWasReceivedCommand::extractOrderBOMLineId);
}
final I_PP_Order_BOMLine bomLineRecord = _bomLineRecordsById.get(issueLine.getOrderBOMLineId());
if (bomLineRecord == null)
{
throw new AdempiereException("No PP_Order_BOMLine found for " + issueLine);
}
return bomLineRecord;
}
@NonNull
private static PPOrderBOMLineId extractOrderBOMLineId(@NonNull final I_PP_Order_BOMLine record)
{
return PPOrderBOMLineId.ofRepoId(record.getPP_Order_BOMLine_ID());
}
private List<I_M_HU> splitOutCUsFromSourceHUs(@NonNull final ProductId productId, @NonNull final Quantity qtyCU)
{
final SourceHUsCollection sourceHUsCollection = getSourceHUsCollectionProvider().getByProductId(productId);
if (sourceHUsCollection.isEmpty())
{
return ImmutableList.of();
}
return HUTransformService.builder()
.emptyHUListener(
EmptyHUListener.doBeforeDestroyed(hu -> sourceHUsCollection
.getSourceHU(HuId.ofRepoId(hu.getM_HU_ID()))
.ifPresent(sourceHUsService::snapshotSourceHU),
"Create snapshot of source-HU before it is destroyed")
|
)
.build()
.husToNewCUs(
HUsToNewCUsRequest.builder()
.sourceHUs(sourceHUsCollection.getHusThatAreFlaggedAsSource())
.productId(productId)
.qtyCU(qtyCU)
.build()
)
.getNewCUs();
}
private void createIssueSchedule(final I_PP_Order_Qty ppOrderQtyRecord)
{
final Quantity qtyIssued = Quantitys.of(ppOrderQtyRecord.getQty(), UomId.ofRepoId(ppOrderQtyRecord.getC_UOM_ID()));
issueScheduleService.createSchedule(
PPOrderIssueScheduleCreateRequest.builder()
.ppOrderId(ppOrderId)
.ppOrderBOMLineId(PPOrderBOMLineId.ofRepoId(ppOrderQtyRecord.getPP_Order_BOMLine_ID()))
.seqNo(SeqNo.ofInt(0))
.productId(ProductId.ofRepoId(ppOrderQtyRecord.getM_Product_ID()))
.qtyToIssue(qtyIssued)
.issueFromHUId(HuId.ofRepoId(ppOrderQtyRecord.getM_HU_ID()))
.issueFromLocatorId(warehouseDAO.getLocatorIdByRepoId(ppOrderQtyRecord.getM_Locator_ID()))
.isAlternativeIssue(true)
.qtyIssued(qtyIssued)
.build()
);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\issue_what_was_received\IssueWhatWasReceivedCommand.java
| 2
|
请完成以下Java代码
|
public Builder setWindowId(final WindowId windowId)
{
this.windowId = windowId;
return this;
}
public Builder setCaption(final ITranslatableString caption)
{
this.caption = TranslatableStrings.nullToEmpty(caption);
return this;
}
public Builder setDocumentSummaryElement(@Nullable final DocumentLayoutElementDescriptor documentSummaryElement)
{
this.documentSummaryElement = documentSummaryElement;
return this;
}
public Builder setDocActionElement(@Nullable final DocumentLayoutElementDescriptor docActionElement)
{
this.docActionElement = docActionElement;
return this;
}
public Builder setGridView(final ViewLayout.Builder gridView)
{
this._gridView = gridView;
return this;
}
public Builder setSingleRowLayout(@NonNull final DocumentLayoutSingleRow.Builder singleRowLayout)
{
this.singleRowLayout = singleRowLayout;
return this;
}
private DocumentLayoutSingleRow.Builder getSingleRowLayout()
{
return singleRowLayout;
}
private ViewLayout.Builder getGridView()
{
return _gridView;
}
public Builder addDetail(@Nullable final DocumentLayoutDetailDescriptor detail)
{
if (detail == null)
{
return this;
}
if (detail.isEmpty())
{
logger.trace("Skip adding detail to layout because it is empty; detail={}", detail);
return this;
}
details.add(detail);
return this;
|
}
public Builder setSideListView(final ViewLayout sideListViewLayout)
{
this._sideListView = sideListViewLayout;
return this;
}
private ViewLayout getSideList()
{
Preconditions.checkNotNull(_sideListView, "sideList");
return _sideListView;
}
public Builder putDebugProperty(final String name, final String value)
{
debugProperties.put(name, value);
return this;
}
public Builder setStopwatch(final Stopwatch stopwatch)
{
this.stopwatch = stopwatch;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutDescriptor.java
| 1
|
请完成以下Java代码
|
private String asUserPasswordProperty(String userProperty) {
return String.format("%s.password", userProperty);
}
private String asUserRolesProperty(String userProperty) {
return String.format("%s.roles", userProperty);
}
private String asUserUsernameProperty(String userProperty) {
return String.format("%s.username", userProperty);
}
@Nullable
@Override
public Object getProperty(String name) {
return getSource().getProperty(name);
}
@NonNull
protected Predicate<String> getVcapServicePredicate() {
return this.vcapServicePredicate != null
? this.vcapServicePredicate
: propertyName -> true;
}
@Override
public Iterator<String> iterator() {
return Collections.unmodifiableList(Arrays.asList(getSource().getPropertyNames())).iterator();
}
|
@NonNull
public VcapPropertySource withVcapServiceName(@NonNull String serviceName) {
Assert.hasText(serviceName, "Service name is required");
String resolvedServiceName = StringUtils.trimAllWhitespace(serviceName);
Predicate<String> vcapServiceNamePredicate = propertyName ->
propertyName.startsWith(String.format("%1$s%2$s.", VCAP_SERVICES_PROPERTY, resolvedServiceName));
return withVcapServicePredicate(vcapServiceNamePredicate);
}
@NonNull
public VcapPropertySource withVcapServicePredicate(@Nullable Predicate<String> vcapServicePredicate) {
this.vcapServicePredicate = vcapServicePredicate;
return this;
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\VcapPropertySource.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static class Exporters {
@Bean
@ConditionalOnProperty(name = "management.opentelemetry.logging.export.otlp.transport", havingValue = "http",
matchIfMissing = true)
OtlpHttpLogRecordExporter otlpHttpLogRecordExporter(OtlpLoggingProperties properties,
OtlpLoggingConnectionDetails connectionDetails, ObjectProvider<MeterProvider> meterProvider) {
OtlpHttpLogRecordExporterBuilder builder = OtlpHttpLogRecordExporter.builder()
.setEndpoint(connectionDetails.getUrl(Transport.HTTP))
.setTimeout(properties.getTimeout())
.setConnectTimeout(properties.getConnectTimeout())
.setCompression(properties.getCompression().name().toLowerCase(Locale.US));
properties.getHeaders().forEach(builder::addHeader);
meterProvider.ifAvailable(builder::setMeterProvider);
return builder.build();
}
@Bean
@ConditionalOnProperty(name = "management.opentelemetry.logging.export.otlp.transport", havingValue = "grpc")
|
OtlpGrpcLogRecordExporter otlpGrpcLogRecordExporter(OtlpLoggingProperties properties,
OtlpLoggingConnectionDetails connectionDetails, ObjectProvider<MeterProvider> meterProvider) {
OtlpGrpcLogRecordExporterBuilder builder = OtlpGrpcLogRecordExporter.builder()
.setEndpoint(connectionDetails.getUrl(Transport.GRPC))
.setTimeout(properties.getTimeout())
.setConnectTimeout(properties.getConnectTimeout())
.setCompression(properties.getCompression().name().toLowerCase(Locale.US));
properties.getHeaders().forEach(builder::addHeader);
meterProvider.ifAvailable(builder::setMeterProvider);
return builder.build();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-opentelemetry\src\main\java\org\springframework\boot\opentelemetry\autoconfigure\logging\otlp\OtlpLoggingConfigurations.java
| 2
|
请完成以下Java代码
|
private String getBPartnerLanguage(@NonNull final I_AD_User userRecord)
{
final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(userRecord.getC_BPartner_ID());
if (bpartnerId == null)
{
return null;
}
final I_C_BPartner bpartner = bpartnerDAO.getByIdInTrx(bpartnerId);
return bpartner.getAD_Language();
}
@Override
public UserEMailConfig getEmailConfigById(@NonNull final UserId userId)
{
final I_AD_User userRecord = userDAO.getById(userId);
return toUserEMailConfig(userRecord);
}
@Override
public ExplainedOptional<EMailAddress> getEMailAddressById(@NonNull final UserId userId)
{
final I_AD_User adUser = getById(userId);
final String email = StringUtils.trimBlankToNull(adUser.getEMail());
if (email == null)
{
return ExplainedOptional.emptyBecause("User " + adUser.getName() + " does not have email");
}
return ExplainedOptional.of(EMailAddress.ofString(email));
}
public static UserEMailConfig toUserEMailConfig(@NonNull final I_AD_User userRecord)
{
return UserEMailConfig.builder()
.userId(UserId.ofRepoId(userRecord.getAD_User_ID()))
.email(EMailAddress.ofNullableString(userRecord.getEMail()))
.username(userRecord.getEMailUser())
.password(userRecord.getEMailUserPW())
.build();
}
@Override
public void deleteUserDependency(@NonNull final I_AD_User userRecord)
|
{
UserId userId = UserId.ofRepoId(userRecord.getAD_User_ID());
valuePreferenceDAO.deleteUserPreferenceByUserId(userId);
getUserAuthTokenRepository().deleteUserAuthTokenByUserId(userId);
userRolePermissionsDAO.deleteUserOrgAccessByUserId(userId);
userRolePermissionsDAO.deleteUserOrgAssignmentByUserId(userId);
roleDAO.deleteUserRolesByUserId(userId);
getUserSubstituteRepository().deleteUserSubstituteByUserId(userId);
getUserMailRepository().deleteUserMailByUserId(userId);
getUserQueryRepository().deleteUserQueryByUserId(userId);
}
@Override
public String getUserFullNameById(@NonNull final UserId userId) {return userDAO.retrieveUserFullName(userId);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\api\impl\UserBL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Jsp getJsp() {
return this.jsp;
}
public Session getSession() {
return this.session;
}
}
/**
* Reactive server properties.
*/
public static class Reactive {
private final Session session = new Session();
public Session getSession() {
return this.session;
}
public static class Session {
/**
* Session timeout. If a duration suffix is not specified, seconds will be
* used.
*/
@DurationUnit(ChronoUnit.SECONDS)
private Duration timeout = Duration.ofMinutes(30);
/**
* Maximum number of sessions that can be stored.
*/
private int maxSessions = 10000;
@NestedConfigurationProperty
private final Cookie cookie = new Cookie();
public Duration getTimeout() {
return this.timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public int getMaxSessions() {
return this.maxSessions;
}
public void setMaxSessions(int maxSessions) {
this.maxSessions = maxSessions;
|
}
public Cookie getCookie() {
return this.cookie;
}
}
}
/**
* Strategies for supporting forward headers.
*/
public enum ForwardHeadersStrategy {
/**
* Use the underlying container's native support for forwarded headers.
*/
NATIVE,
/**
* Use Spring's support for handling forwarded headers.
*/
FRAMEWORK,
/**
* Ignore X-Forwarded-* headers.
*/
NONE
}
public static class Encoding {
/**
* Mapping of locale to charset for response encoding.
*/
private @Nullable Map<Locale, Charset> mapping;
public @Nullable Map<Locale, Charset> getMapping() {
return this.mapping;
}
public void setMapping(@Nullable Map<Locale, Charset> mapping) {
this.mapping = mapping;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\autoconfigure\ServerProperties.java
| 2
|
请完成以下Java代码
|
public void setDocBaseType (final @Nullable java.lang.String DocBaseType)
{
set_Value (COLUMNNAME_DocBaseType, DocBaseType);
}
@Override
public java.lang.String getDocBaseType()
{
return get_ValueAsString(COLUMNNAME_DocBaseType);
}
@Override
public void setIsAutoSendDocument (final boolean IsAutoSendDocument)
{
set_Value (COLUMNNAME_IsAutoSendDocument, IsAutoSendDocument);
}
@Override
public boolean isAutoSendDocument()
{
return get_ValueAsBoolean(COLUMNNAME_IsAutoSendDocument);
}
@Override
public void setIsDirectEnqueue (final boolean IsDirectEnqueue)
{
set_Value (COLUMNNAME_IsDirectEnqueue, IsDirectEnqueue);
|
}
@Override
public boolean isDirectEnqueue()
{
return get_ValueAsBoolean(COLUMNNAME_IsDirectEnqueue);
}
@Override
public void setIsDirectProcessQueueItem (final boolean IsDirectProcessQueueItem)
{
set_Value (COLUMNNAME_IsDirectProcessQueueItem, IsDirectProcessQueueItem);
}
@Override
public boolean isDirectProcessQueueItem()
{
return get_ValueAsBoolean(COLUMNNAME_IsDirectProcessQueueItem);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java-gen\de\metas\document\archive\model\X_C_Doc_Outbound_Config.java
| 1
|
请完成以下Java代码
|
public class GreetingStandardType
{
public static final GreetingStandardType MR = new GreetingStandardType(X_C_Greeting.GREETINGSTANDARDTYPE_MR);
public static final GreetingStandardType MRS = new GreetingStandardType(X_C_Greeting.GREETINGSTANDARDTYPE_MRS);
public static final GreetingStandardType MR_AND_MRS = new GreetingStandardType(X_C_Greeting.GREETINGSTANDARDTYPE_MRPlusMRS);
public static final GreetingStandardType MRS_AND_MR = new GreetingStandardType(X_C_Greeting.GREETINGSTANDARDTYPE_MRSPlusMR);
private static final ConcurrentHashMap<String, GreetingStandardType> cache = new ConcurrentHashMap<>();
static
{
cache.put(MR.getCode(), MR);
cache.put(MRS.getCode(), MRS);
cache.put(MR_AND_MRS.getCode(), MR_AND_MRS);
cache.put(MRS_AND_MR.getCode(), MRS_AND_MR);
}
private final String code;
private GreetingStandardType(@NonNull final String code)
{
this.code = StringUtils.trimBlankToNull(code);
if (this.code == null)
{
throw new AdempiereException("Invalid code: " + code);
}
}
@Nullable
public static GreetingStandardType ofNullableCode(@Nullable final String code)
{
final String codeNorm = StringUtils.trimBlankToNull(code);
return codeNorm != null ? ofCode(codeNorm) : null;
}
@JsonCreator
public static GreetingStandardType ofCode(@NonNull final String code)
{
final String codeNorm = StringUtils.trimBlankToNull(code);
if (codeNorm == null)
{
throw new AdempiereException("Invalid code: `" + code + "`");
}
return cache.computeIfAbsent(codeNorm, GreetingStandardType::new);
}
@Override
@Deprecated
|
public String toString()
{
return getCode();
}
@JsonValue
public String getCode()
{
return code;
}
@Nullable
public static String toCode(@Nullable final GreetingStandardType type)
{
return type != null ? type.getCode() : null;
}
public GreetingStandardType composeWith(@NonNull final GreetingStandardType other)
{
return ofCode(code + "+" + other.code);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\greeting\GreetingStandardType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isOnlyTimers() {
return onlyTimers;
}
public boolean isOnlyMessages() {
return onlyMessages;
}
public Date getDuedateHigherThan() {
return duedateHigherThan;
}
public Date getDuedateLowerThan() {
return duedateLowerThan;
}
public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual;
}
public Date getDuedateLowerThanOrEqual() {
|
return duedateLowerThanOrEqual;
}
public String getLockOwner() {
return lockOwner;
}
public boolean isOnlyLocked() {
return onlyLocked;
}
public boolean isOnlyUnlocked() {
return onlyUnlocked;
}
public boolean isWithoutScopeType() {
return withoutScopeType;
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\JobQueryImpl.java
| 2
|
请完成以下Java代码
|
public class FlowableJackson2ArrayNode extends FlowableJackson2JsonNode<ArrayNode> implements FlowableArrayNode {
public FlowableJackson2ArrayNode(ArrayNode arrayNode) {
super(arrayNode);
}
@Override
public Iterator<FlowableJsonNode> iterator() {
Iterator<JsonNode> delegate = jsonNode.elements();
return new Iterator<>() {
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public FlowableJsonNode next() {
return FlowableJackson2JsonNode.wrap(delegate.next());
}
@Override
public void remove() {
delegate.remove();
}
};
}
@Override
public void set(int index, String value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, Boolean value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, Short value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, Integer value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, Long value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, Double value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, BigDecimal value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, BigInteger value) {
jsonNode.set(index, value);
}
@Override
public void setNull(int index) {
jsonNode.setNull(index);
}
@Override
public void set(int index, FlowableJsonNode value) {
|
jsonNode.set(index, asJsonNode(value));
}
@Override
public void add(Short value) {
jsonNode.add(value);
}
@Override
public void add(Integer value) {
jsonNode.add(value);
}
@Override
public void add(Long value) {
jsonNode.add(value);
}
@Override
public void add(Float value) {
jsonNode.add(value);
}
@Override
public void add(Double value) {
jsonNode.add(value);
}
@Override
public void add(byte[] value) {
jsonNode.add(value);
}
@Override
public void add(String value) {
jsonNode.add(value);
}
@Override
public void add(Boolean value) {
jsonNode.add(value);
}
@Override
public void add(BigDecimal value) {
jsonNode.add(value);
}
@Override
public void add(BigInteger value) {
jsonNode.add(value);
}
@Override
public void add(FlowableJsonNode value) {
jsonNode.add(asJsonNode(value));
}
@Override
public void addNull() {
jsonNode.addNull();
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\json\jackson2\FlowableJackson2ArrayNode.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
Map<String, VariableElement> getFields() {
return Collections.unmodifiableMap(this.fields);
}
Map<String, RecordComponentElement> getRecordComponents() {
return Collections.unmodifiableMap(this.recordComponents);
}
Map<String, List<ExecutableElement>> getPublicGetters() {
return Collections.unmodifiableMap(this.publicGetters);
}
ExecutableElement getPublicGetter(String name, TypeMirror type) {
List<ExecutableElement> candidates = this.publicGetters.get(name);
return getPublicAccessor(candidates, type, (specificType) -> getMatchingGetter(candidates, specificType));
}
ExecutableElement getPublicSetter(String name, TypeMirror type) {
List<ExecutableElement> candidates = this.publicSetters.get(name);
return getPublicAccessor(candidates, type, (specificType) -> getMatchingSetter(candidates, specificType));
}
|
private ExecutableElement getPublicAccessor(List<ExecutableElement> candidates, TypeMirror type,
Function<TypeMirror, ExecutableElement> matchingAccessorExtractor) {
if (candidates != null) {
ExecutableElement matching = matchingAccessorExtractor.apply(type);
if (matching != null) {
return matching;
}
TypeMirror alternative = this.env.getTypeUtils().getWrapperOrPrimitiveFor(type);
if (alternative != null) {
return matchingAccessorExtractor.apply(alternative);
}
}
return null;
}
}
|
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\TypeElementMembers.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public abstract class AbstractExternalWorkerJobCmd implements Command<Void> {
protected final String externalJobId;
protected final String workerId;
protected final JobServiceConfiguration jobServiceConfiguration;
protected AbstractExternalWorkerJobCmd(String externalJobId, String workerId, JobServiceConfiguration jobServiceConfiguration) {
this.externalJobId = externalJobId;
this.workerId = workerId;
this.jobServiceConfiguration = jobServiceConfiguration;
}
@Override
public Void execute(CommandContext commandContext) {
ExternalWorkerJobEntity externalWorkerJob = resolveJob();
runJobLogic(externalWorkerJob, commandContext);
if (externalWorkerJob.isExclusive()) {
// Part of the same transaction to avoid a race condition with the
// potentially new jobs (wrt process instance locking) that are created
// during the execution of the original job
new UnlockExclusiveJobCmd(externalWorkerJob, jobServiceConfiguration).execute(commandContext);
}
return null;
}
|
protected abstract void runJobLogic(ExternalWorkerJobEntity externalWorkerJob, CommandContext commandContext);
protected ExternalWorkerJobEntity resolveJob() {
if (StringUtils.isEmpty(externalJobId)) {
throw new FlowableIllegalArgumentException("externalJobId must not be empty");
}
if (StringUtils.isEmpty(workerId)) {
throw new FlowableIllegalArgumentException("workerId must not be empty");
}
ExternalWorkerJobEntityManager externalWorkerJobEntityManager = jobServiceConfiguration.getExternalWorkerJobEntityManager();
ExternalWorkerJobEntity job = externalWorkerJobEntityManager.findById(externalJobId);
if (job == null) {
throw new FlowableObjectNotFoundException("No External Worker job found for id: " + externalJobId, ExternalWorkerJobEntity.class);
}
if (!Objects.equals(workerId, job.getLockOwner())) {
throw new FlowableIllegalArgumentException(workerId + " does not hold a lock on the requested job");
}
return job;
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\AbstractExternalWorkerJobCmd.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Map<String, String> getValuesForPrefix(final String prefix, final int adClientId, final int adOrgId)
{
final boolean removePrefix = false;
return getValuesForPrefix(prefix, removePrefix, ClientAndOrgId.ofClientAndOrg(adClientId, adOrgId));
}
@Override
public Map<String, String> getValuesForPrefix(final String prefix, final boolean removePrefix, @NonNull final ClientAndOrgId clientAndOrgId)
{
final Set<String> paramNames = getNamesForPrefix(prefix, clientAndOrgId);
final ImmutableMap.Builder<String, String> result = ImmutableMap.builder();
for (final String paramName : paramNames)
{
final String value = sysConfigDAO.getValue(paramName, clientAndOrgId).orElse(null);
if (value == null)
{
continue;
}
final String name;
if (removePrefix && paramName.startsWith(prefix) && !paramName.equals(prefix))
{
name = paramName.substring(prefix.length());
}
else
{
name = paramName;
}
result.put(name, value);
}
return result.build();
}
@Override
@Nullable
@Contract("_, !null, _ -> !null")
public String getValue(@NonNull final String name, @Nullable final String defaultValue, @NonNull final ClientAndOrgId clientAndOrgId)
{
return sysConfigDAO.getValue(name, clientAndOrgId).orElse(defaultValue);
|
}
@Override
public <T extends ReferenceListAwareEnum> T getReferenceListAware(final String name, final T defaultValue, final Class<T> type)
{
final String code = sysConfigDAO.getValue(name, ClientAndOrgId.SYSTEM).orElse(null);
return code != null && !Check.isBlank(code)
? ReferenceListAwareEnums.ofCode(code, type)
: defaultValue;
}
@Override
public <T extends Enum<T>> ImmutableSet<T> getCommaSeparatedEnums(@NonNull final String sysconfigName, @NonNull final Class<T> enumType)
{
final String string = StringUtils.trimBlankToNull(sysConfigDAO.getValue(sysconfigName, ClientAndOrgId.SYSTEM).orElse(null));
if (string == null || string.equals("-"))
{
return ImmutableSet.of();
}
return Splitter.on(",")
.trimResults()
.omitEmptyStrings()
.splitToList(string)
.stream()
.map(name -> {
try
{
return Enum.valueOf(enumType, name);
}
catch (final Exception ex)
{
logger.warn("Failed converting `{}` to enum {}. Ignoring it.", name, enumType, ex);
return null;
}
})
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\SysConfigBL.java
| 2
|
请完成以下Java代码
|
void addTextMsg(@Nullable final String textMsg)
{
if (textMsg == null || textMsg.isEmpty())
{
return;
}
final String oldText = StringUtils.trimBlankToNull(getTextMsg());
if (oldText == null)
{
setTextMsg(textMsg.trim());
}
else
{
setTextMsg(oldText + "\n" + textMsg.trim());
}
}
private void addTextMsg(@Nullable final Throwable ex)
{
if (ex == null)
{
return;
}
addTextMsg(AdempiereException.extractMessage(ex));
final AdempiereException metasfreshException = AdempiereException.wrapIfNeeded(ex);
final AdIssueId adIssueId = context.createIssue(metasfreshException);
setIssueId(adIssueId);
}
|
void setProcessingResultMessage(@Nullable final String msg)
{
this.processingResultMessage = msg;
this.processingResultException = null;
addTextMsg(msg);
}
void setProcessingResultMessage(@NonNull final Throwable ex)
{
this.processingResultMessage = AdempiereException.extractMessage(ex);
this.processingResultException = ex;
addTextMsg(ex);
}
@Nullable
public String getProcessingResultMessage() { return processingResultMessage; }
@Nullable
public Throwable getProcessingResultException() { return processingResultException; }
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\execution\WFProcess.java
| 1
|
请完成以下Java代码
|
public void removeAttributeStorageListener(final IAttributeStorageListener listener)
{
if (listener == null)
{
return;
}
attributeStorageListeners.remove(listener);
// Unregister the listner from factory(the delegate)
if (factory != null)
{
factory.removeAttributeStorageListener(listener);
}
}
@Override
public boolean isHandled(final Object model)
{
final IAttributeStorageFactory delegate = getDelegate();
return delegate.isHandled(model);
}
@Override
public IAttributeStorage getAttributeStorage(final Object model)
{
final IAttributeStorageFactory delegate = getDelegate();
return delegate.getAttributeStorage(model);
}
@Override
public IAttributeStorage getAttributeStorageIfHandled(final Object model)
{
final IAttributeStorageFactory delegate = getDelegate();
return delegate.getAttributeStorageIfHandled(model);
}
@Override
public final IHUAttributesDAO getHUAttributesDAO()
{ // TODO tbp: this exception is false: this.huAttributesDAO is NOT NULL!
throw new HUException("No IHUAttributesDAO found on " + this);
}
@Override
public void setHUAttributesDAO(final IHUAttributesDAO huAttributesDAO)
|
{
this.huAttributesDAO = huAttributesDAO;
//
// Update factory if is instantiated
if (factory != null)
{
factory.setHUAttributesDAO(huAttributesDAO);
}
}
@Override
public IHUStorageDAO getHUStorageDAO()
{
return getHUStorageFactory().getHUStorageDAO();
}
@Override
public void setHUStorageFactory(final IHUStorageFactory huStorageFactory)
{
this.huStorageFactory = huStorageFactory;
//
// Update factory if is instantiated
if (factory != null)
{
factory.setHUStorageFactory(huStorageFactory);
}
}
@Override
public IHUStorageFactory getHUStorageFactory()
{
return huStorageFactory;
}
@Override
public void flush()
{
final IHUAttributesDAO huAttributesDAO = this.huAttributesDAO;
if (huAttributesDAO != null)
{
huAttributesDAO.flush();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\ClassAttributeStorageFactory.java
| 1
|
请完成以下Java代码
|
public void setM_Product_Order_ID (final int M_Product_Order_ID)
{
if (M_Product_Order_ID < 1)
set_Value (COLUMNNAME_M_Product_Order_ID, null);
else
set_Value (COLUMNNAME_M_Product_Order_ID, M_Product_Order_ID);
}
@Override
public int getM_Product_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Order_ID);
}
@Override
public void setPointsBase_Forecasted (final BigDecimal PointsBase_Forecasted)
{
set_Value (COLUMNNAME_PointsBase_Forecasted, PointsBase_Forecasted);
}
@Override
public BigDecimal getPointsBase_Forecasted()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Forecasted);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPointsBase_Invoiceable (final BigDecimal PointsBase_Invoiceable)
{
set_Value (COLUMNNAME_PointsBase_Invoiceable, PointsBase_Invoiceable);
}
@Override
public BigDecimal getPointsBase_Invoiceable()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Invoiceable);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPointsBase_Invoiced (final BigDecimal PointsBase_Invoiced)
{
set_Value (COLUMNNAME_PointsBase_Invoiced, PointsBase_Invoiced);
}
@Override
public BigDecimal getPointsBase_Invoiced()
|
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Invoiced);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_Value (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Instance.java
| 1
|
请完成以下Java代码
|
public AdTabId getAdTabId()
{
return AdTabId.ofRepoId(gridTab.getAD_Tab_ID());
}
@Override
public String getTableName()
{
return gridTab.getTableName();
}
@Override
public <T> T getSelectedModel(final Class<T> modelClass)
{
return gridTab.getModel(modelClass);
}
@Override
public <T> List<T> getSelectedModels(final Class<T> modelClass)
{
// backward compatibility
return streamSelectedModels(modelClass)
.collect(ImmutableList.toImmutableList());
}
@NonNull
@Override
public <T> Stream<T> streamSelectedModels(@NonNull final Class<T> modelClass)
{
|
return Stream.of(getSelectedModel(modelClass));
}
@Override
public int getSingleSelectedRecordId()
{
return gridTab.getRecord_ID();
}
@Override
public SelectionSize getSelectionSize()
{
// backward compatibility
return SelectionSize.ofSize(1);
}
@Override
public <T> IQueryFilter<T> getQueryFilter(@NonNull Class<T> recordClass)
{
return gridTab.createCurrentRecordsQueryFilter(recordClass);
}
}
} // GridTab
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTab.java
| 1
|
请完成以下Java代码
|
public Stream<T> stream() {return getRowsIndex().stream();}
public Stream<T> stream(Predicate<T> predicate) {return getRowsIndex().stream(predicate);}
public long count(Predicate<T> predicate) {return getRowsIndex().count(predicate);}
public boolean anyMatch(final Predicate<T> predicate) {return getRowsIndex().anyMatch(predicate);}
public List<T> list() {return getRowsIndex().list();}
public void compute(@NonNull final UnaryOperator<ImmutableRowsIndex<T>> remappingFunction)
{
holder.compute(remappingFunction);
}
public void addRow(@NonNull final T row)
{
compute(rows -> rows.addingRow(row));
}
@SuppressWarnings("unused")
public void removeRowsById(@NonNull final DocumentIdsSelection rowIds)
{
if (rowIds.isEmpty())
{
return;
}
compute(rows -> rows.removingRowIds(rowIds));
}
@SuppressWarnings("unused")
public void removingIf(@NonNull final Predicate<T> predicate)
{
compute(rows -> rows.removingIf(predicate));
}
public void changeRowById(@NonNull DocumentId rowId, @NonNull final UnaryOperator<T> rowMapper)
{
compute(rows -> rows.changingRow(rowId, rowMapper));
}
public void changeRowsByIds(@NonNull DocumentIdsSelection rowIds, @NonNull final UnaryOperator<T> rowMapper)
{
compute(rows -> rows.changingRows(rowIds, rowMapper));
}
public void setRows(@NonNull final List<T> rows)
{
holder.setValue(ImmutableRowsIndex.of(rows));
|
}
@NonNull
private ImmutableRowsIndex<T> getRowsIndex()
{
final ImmutableRowsIndex<T> rowsIndex = holder.getValue();
// shall not happen
if (rowsIndex == null)
{
throw new AdempiereException("rowsIndex shall be set");
}
return rowsIndex;
}
public Predicate<DocumentId> isRelevantForRefreshingByDocumentId()
{
final ImmutableRowsIndex<T> rows = getRowsIndex();
return rows::isRelevantForRefreshing;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\template\SynchronizedRowsIndexHolder.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.