instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class ReverseStackUsingQueue {
public Stack reverseIntegerStack(Stack<Integer> inputStack) {
Queue<Integer> queue = new LinkedList<>();
while (!inputStack.isEmpty()) {
queue.add(inputStack.pop());
}
while (!queue.isEmpty()) {
inputStack.add(queue.remove());
}
return inputStack;
}
public Stack reverseStringStack(Stack<String> inputStack) {
Queue<String> queue = new LinkedList<>();
while (!inputStack.isEmpty()) {
queue.add(inputStack.pop());
}
while (!queue.isEmpty()) { | inputStack.add(queue.remove());
}
return inputStack;
}
public Stack reverseEmployeeStack(Stack<Employee> inputStack) {
Queue<Employee> employeeQ = new LinkedList<>();
while (!inputStack.isEmpty()) {
employeeQ.add(inputStack.pop());
}
while (!employeeQ.isEmpty()) {
inputStack.add(employeeQ.remove());
}
return inputStack;
}
} | repos\tutorials-master\core-java-modules\core-java-collections-4\src\main\java\com\baeldung\collections\stackreversal\ReverseStackUsingQueue.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FlowableDefaultPropertiesLocationRuntimeHints implements RuntimeHintsRegistrar {
// This is similar to what is being done in ConfigDataLocationRuntimeHints
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
// This will register all the flowable-default configuration properties
FilePatternResourceHintsRegistrar.forClassPathLocations("/")
.withFileExtensions(getExtensions(classLoader))
.withFilePrefixes("flowable-default")
.registerHints(hints.resources(), classLoader);
}
// The logic below is the same as for the ConfigDataLocationRuntimeHints
/**
* Get the application file extensions to consider. A valid extension starts with a
* dot.
* @param classLoader the classloader to use
* @return the configuration file extensions | */
protected List<String> getExtensions(ClassLoader classLoader) {
List<String> extensions = new ArrayList<>();
List<PropertySourceLoader> propertySourceLoaders = getSpringFactoriesLoader(classLoader)
.load(PropertySourceLoader.class);
for (PropertySourceLoader propertySourceLoader : propertySourceLoaders) {
for (String fileExtension : propertySourceLoader.getFileExtensions()) {
String candidate = "." + fileExtension;
if (!extensions.contains(candidate)) {
extensions.add(candidate);
}
}
}
return extensions;
}
protected SpringFactoriesLoader getSpringFactoriesLoader(ClassLoader classLoader) {
return SpringFactoriesLoader.forDefaultResourceLocation(classLoader);
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\environment\FlowableDefaultPropertiesLocationRuntimeHints.java | 2 |
请完成以下Java代码 | public String getImageLink ()
{
return (String)get_Value(COLUMNNAME_ImageLink);
}
/** Set Menu Link.
@param MenuLink Menu Link */
public void setMenuLink (String MenuLink)
{
set_Value (COLUMNNAME_MenuLink, MenuLink);
}
/** Get Menu Link.
@return Menu Link */
public String getMenuLink ()
{
return (String)get_Value(COLUMNNAME_MenuLink);
}
/** Set Module.
@param Module Module */
public void setModule (String Module)
{
set_Value (COLUMNNAME_Module, Module);
}
/** Get Module.
@return Module */
public String getModule ()
{
return (String)get_Value(COLUMNNAME_Module);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
public I_U_WebMenu getParentMenu() throws RuntimeException
{
return (I_U_WebMenu)MTable.get(getCtx(), I_U_WebMenu.Table_Name)
.getPO(getParentMenu_ID(), get_TrxName()); }
/** Set Parent Menu.
@param ParentMenu_ID Parent Menu */
public void setParentMenu_ID (int ParentMenu_ID)
{
if (ParentMenu_ID < 1)
set_Value (COLUMNNAME_ParentMenu_ID, null);
else
set_Value (COLUMNNAME_ParentMenu_ID, Integer.valueOf(ParentMenu_ID));
}
/** Get Parent Menu.
@return Parent Menu */
public int getParentMenu_ID ()
{ | Integer ii = (Integer)get_Value(COLUMNNAME_ParentMenu_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Position.
@param Position Position */
public void setPosition (String Position)
{
set_Value (COLUMNNAME_Position, Position);
}
/** Get Position.
@return Position */
public String getPosition ()
{
return (String)get_Value(COLUMNNAME_Position);
}
/** Set Sequence.
@param Sequence Sequence */
public void setSequence (BigDecimal Sequence)
{
set_Value (COLUMNNAME_Sequence, Sequence);
}
/** Get Sequence.
@return Sequence */
public BigDecimal getSequence ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Sequence);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Web Menu.
@param U_WebMenu_ID Web Menu */
public void setU_WebMenu_ID (int U_WebMenu_ID)
{
if (U_WebMenu_ID < 1)
set_ValueNoCheck (COLUMNNAME_U_WebMenu_ID, null);
else
set_ValueNoCheck (COLUMNNAME_U_WebMenu_ID, Integer.valueOf(U_WebMenu_ID));
}
/** Get Web Menu.
@return Web Menu */
public int getU_WebMenu_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_U_WebMenu_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_U_WebMenu.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public RedisSessionRepository sessionRepository() {
RedisTemplate<String, Object> redisTemplate = createRedisTemplate();
RedisSessionRepository sessionRepository = new RedisSessionRepository(redisTemplate);
sessionRepository.setDefaultMaxInactiveInterval(getMaxInactiveInterval());
if (StringUtils.hasText(getRedisNamespace())) {
sessionRepository.setRedisKeyNamespace(getRedisNamespace());
}
sessionRepository.setFlushMode(getFlushMode());
sessionRepository.setSaveMode(getSaveMode());
sessionRepository.setSessionIdGenerator(this.sessionIdGenerator);
getSessionRepositoryCustomizers()
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(sessionRepository));
return sessionRepository;
}
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
this.embeddedValueResolver = resolver;
}
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
Map<String, Object> attributeMap = importMetadata
.getAnnotationAttributes(EnableRedisHttpSession.class.getName()); | AnnotationAttributes attributes = AnnotationAttributes.fromMap(attributeMap);
if (attributes == null) {
return;
}
setMaxInactiveInterval(Duration.ofSeconds(attributes.<Integer>getNumber("maxInactiveIntervalInSeconds")));
String redisNamespaceValue = attributes.getString("redisNamespace");
if (StringUtils.hasText(redisNamespaceValue)) {
setRedisNamespace(this.embeddedValueResolver.resolveStringValue(redisNamespaceValue));
}
setFlushMode(attributes.getEnum("flushMode"));
setSaveMode(attributes.getEnum("saveMode"));
}
@Autowired(required = false)
public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) {
this.sessionIdGenerator = sessionIdGenerator;
}
} | repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\http\RedisHttpSessionConfiguration.java | 2 |
请完成以下Java代码 | public class CalloutFactory implements ICalloutFactory
{
private static final transient Logger logger = LogManager.getLogger(CalloutFactory.class);
private ICalloutProvider providers = ICalloutProvider.NULL;
public CalloutFactory()
{
// Register standard providers
registerCalloutProvider(Services.get(IDefaultCalloutProvider.class));
// NOTE: IProgramaticCalloutProvider will be registered just in time
// registerCalloutProvider(Services.get(IProgramaticCalloutProvider.class));
}
@Override
public void registerCalloutProvider(final ICalloutProvider providerToAdd)
{
final ICalloutProvider providersOld = providers;
final ICalloutProvider providersNew = CompositeCalloutProvider.compose(providersOld, providerToAdd);
if (providersNew == providersOld)
{
return;
}
providers = providersNew;
logger.info("Registered provider: {}", providerToAdd);
}
/**
*
* @return registered providers
*/
@VisibleForTesting
final List<ICalloutProvider> getCalloutProvidersList()
{
final ICalloutProvider providers = this.providers;
if (providers instanceof CompositeCalloutProvider)
{
return ((CompositeCalloutProvider)providers).getProvidersList();
}
else if (NullCalloutProvider.isNull(providers)) | {
return ImmutableList.of();
}
else
{
return ImmutableList.of(providers);
}
}
@Override
public ICalloutProvider getProvider()
{
return providers;
}
@Override
public TableCalloutsMap getCallouts(final Properties ctx, final String tableName)
{
return providers.getCallouts(ctx, tableName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\impl\CalloutFactory.java | 1 |
请完成以下Java代码 | public ItemDefinition getItemSubject() {
return itemSubjectRefAttribute.getReferenceTargetElement(this);
}
@Override
public void setItemSubject(ItemDefinition itemSubject) {
itemSubjectRefAttribute.setReferenceTargetElement(this, itemSubject);
}
@Override
public DataState getDataState() {
return dataStateChild.getChild(this);
}
@Override | public void setDataState(DataState dataState) {
dataStateChild.setChild(this, dataState);
}
@Override
public boolean isCollection() {
return isCollectionAttribute.getValue(this);
}
@Override
public void setCollection(boolean isCollection) {
isCollectionAttribute.setValue(this, isCollection);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DataObjectImpl.java | 1 |
请完成以下Java代码 | public final List<Map<String, Object>> listColumns(final String... columnNames)
{
final boolean distinct = false;
return listColumns(distinct, columnNames);
}
@Override
public final List<Map<String, Object>> listDistinct(final String... columnNames)
{
final boolean distinct = true;
return listColumns(distinct, columnNames);
}
/**
* Selects given columns and return the result as a list of ColumnName to Value map.
*
* @param distinct true if the value rows shall be district
* @return a list of rows, where each row is a {@link Map} having the required columns as keys.
*/
protected abstract List<Map<String, Object>> listColumns(final boolean distinct, final String... columnNames);
@Override
public <K, ET extends T> ImmutableMap<K, ET> map(final Class<ET> modelClass, final Function<ET, K> keyFunction)
{
final List<ET> list = list(modelClass);
return Maps.uniqueIndex(list, keyFunction::apply);
}
@Override
public <K> ImmutableMap<K, T> map(@NonNull final Function<T, K> keyFunction)
{
final List<T> list = list();
return Maps.uniqueIndex(list, keyFunction::apply);
}
@Override
public <K, ET extends T> ListMultimap<K, ET> listMultimap(final Class<ET> modelClass, final Function<ET, K> keyFunction)
{
final ListMultimap<K, ET> map = LinkedListMultimap.create();
final List<ET> list = list(modelClass);
for (final ET item : list)
{ | final K key = keyFunction.apply(item);
map.put(key, item);
}
return map;
}
@Override
public <K, ET extends T> Collection<List<ET>> listAndSplit(final Class<ET> modelClass, final Function<ET, K> keyFunction)
{
final ListMultimap<K, ET> map = listMultimap(modelClass, keyFunction);
return Multimaps.asMap(map).values();
}
@Override
public ICompositeQueryUpdaterExecutor<T> updateDirectly()
{
return new CompositeQueryUpdaterExecutor<>(this);
}
@Override
public <ToModelType> IQueryInsertExecutor<ToModelType, T> insertDirectlyInto(final Class<ToModelType> toModelClass)
{
return new QueryInsertExecutor<>(toModelClass, this);
}
/**
* Convenience method that evaluates {@link IQuery#OPTION_ReturnReadOnlyRecords}.
*/
protected boolean isReadOnlyRecords()
{
return Boolean.TRUE.equals(getOption(OPTION_ReturnReadOnlyRecords));
}
abstract <ToModelType> QueryInsertExecutorResult executeInsert(final QueryInsertExecutor<ToModelType, T> queryInserter);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\AbstractTypedQuery.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final void configure()
{
// Generic Exception and DeadLetterChannel handlers
onException(Exception.class)
.handled(true)
.to(AbstractEDIRoute.EP_EDI_ERROR);
errorHandler(deadLetterChannel(AbstractEDIRoute.EP_EDI_DEADLETTER)
.useOriginalMessage()
.disableRedelivery());
final JaxbDataFormat jaxbDataFormat = new JaxbDataFormat(Constants.JAXB_ContextPath);
final DecimalFormat decimalFormat = getDecimalFormatForConfiguration();
configureEDIRoute(jaxbDataFormat, decimalFormat);
}
/**
* @return {@link SmooksDataFormat} data format for properties configuration
*/
protected final SmooksDataFormat getSDFForConfiguration(final String propertiesConfigurationPath)
{
final String smooksConfigurationPath = Util.resolveProperty(getContext(), propertiesConfigurationPath);
try
{
return new SmooksDataFormat(smooksConfigurationPath);
}
catch (final Exception e)
{
throw new RuntimeCamelException(e);
}
} | /**
* @return Decimal format from EDI configuration
*/
private DecimalFormat getDecimalFormatForConfiguration()
{
final DecimalFormat decimalFormat = (DecimalFormat)NumberFormat.getInstance();
final CamelContext context = getContext();
decimalFormat.setMaximumFractionDigits(Integer.parseInt(Util.resolveProperty(context, "edi.decimalformat.maximumFractionDigits")));
final boolean isGroupingUsed = Boolean.parseBoolean(Util.resolveProperty(context, "edi.decimalformat.isGroupingUsed"));
decimalFormat.setGroupingUsed(isGroupingUsed);
final DecimalFormatSymbols decimalFormatSymbols = decimalFormat.getDecimalFormatSymbols();
if (isGroupingUsed)
{
final char groupingSeparator = Util.resolveProperty(context, "edi.decimalformat.symbol.groupingSeparator").charAt(0);
decimalFormatSymbols.setGroupingSeparator(groupingSeparator);
}
final char decimalSeparator = Util.resolveProperty(context, "edi.decimalformat.symbol.decimalSeparator").charAt(0);
decimalFormatSymbols.setDecimalSeparator(decimalSeparator);
decimalFormat.setDecimalFormatSymbols(decimalFormatSymbols); // though it seems redundant, it won't be set otherwise for some reason...
return decimalFormat;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\commons\route\AbstractEDIRoute.java | 2 |
请完成以下Java代码 | public static PPOrderRoutingActivityId ofRepoIdOrNull(@NonNull final PPOrderId orderId, final int repoId)
{
return repoId > 0 ? new PPOrderRoutingActivityId(orderId, repoId) : null;
}
public static int toRepoId(@Nullable final PPOrderRoutingActivityId id)
{
return id != null ? id.getRepoId() : -1;
}
PPOrderId orderId;
int repoId;
private PPOrderRoutingActivityId(@NonNull final PPOrderId orderId, final int repoId)
{ | this.orderId = orderId;
this.repoId = Check.assumeGreaterThanZero(repoId, "PP_Order_Node_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
public static boolean equals(@Nullable final PPOrderRoutingActivityId id1, @Nullable final PPOrderRoutingActivityId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderRoutingActivityId.java | 1 |
请完成以下Java代码 | protected int calculateRepeatValue(JobEntity timerEntity) {
int times = -1;
List<String> expression = asList(timerEntity.getRepeat().split("/"));
if (expression.size() > 1 && expression.get(0).startsWith("R") && expression.get(0).length() > 1) {
times = Integer.parseInt(expression.get(0).substring(1));
if (times > 0) {
times--;
}
}
return times;
}
protected String getBusinessCalendarName(String calendarName, VariableScope variableScope) {
String businessCalendarName = CycleBusinessCalendar.NAME;
if (StringUtils.isNotEmpty(calendarName)) {
businessCalendarName = (String) Context.getProcessEngineConfiguration() | .getExpressionManager()
.createExpression(calendarName)
.getValue(variableScope);
}
return businessCalendarName;
}
protected TimerJobDataManager getDataManager() {
return jobDataManager;
}
public void setJobDataManager(TimerJobDataManager jobDataManager) {
this.jobDataManager = jobDataManager;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TimerJobEntityManagerImpl.java | 1 |
请完成以下Java代码 | public void setEMail_To (java.lang.String EMail_To)
{
set_Value (COLUMNNAME_EMail_To, EMail_To);
}
/** Get EMail Empfänger.
@return EMail address to send requests to - e.g. edi@manufacturer.com
*/
@Override
public java.lang.String getEMail_To ()
{
return (java.lang.String)get_Value(COLUMNNAME_EMail_To);
}
@Override
public org.compiere.model.I_M_Shipper getM_Shipper() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class);
}
@Override
public void setM_Shipper(org.compiere.model.I_M_Shipper M_Shipper)
{
set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper);
} | /** Set Lieferweg.
@param M_Shipper_ID
Methode oder Art der Warenlieferung
*/
@Override
public void setM_Shipper_ID (int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID));
}
/** Get Lieferweg.
@return Methode oder Art der Warenlieferung
*/
@Override
public int getM_Shipper_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_Shipper_Config.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_U_BlackListCheque[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Bank Name.
@param BankName Bank Name */
public void setBankName (String BankName)
{
set_Value (COLUMNNAME_BankName, BankName);
}
/** Get Bank Name.
@return Bank Name */
public String getBankName ()
{
return (String)get_Value(COLUMNNAME_BankName);
}
/** Set Cheque No.
@param ChequeNo Cheque No */
public void setChequeNo (String ChequeNo)
{
set_Value (COLUMNNAME_ChequeNo, ChequeNo);
}
/** Get Cheque No.
@return Cheque No */ | public String getChequeNo ()
{
return (String)get_Value(COLUMNNAME_ChequeNo);
}
/** Set Black List Cheque.
@param U_BlackListCheque_ID Black List Cheque */
public void setU_BlackListCheque_ID (int U_BlackListCheque_ID)
{
if (U_BlackListCheque_ID < 1)
set_ValueNoCheck (COLUMNNAME_U_BlackListCheque_ID, null);
else
set_ValueNoCheck (COLUMNNAME_U_BlackListCheque_ID, Integer.valueOf(U_BlackListCheque_ID));
}
/** Get Black List Cheque.
@return Black List Cheque */
public int getU_BlackListCheque_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_U_BlackListCheque_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_U_BlackListCheque.java | 1 |
请完成以下Java代码 | public class CustomMethodSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {
private Object filterObject;
private Object returnObject;
public CustomMethodSecurityExpressionRoot(Authentication authentication) {
super(authentication);
}
public boolean isMember(Long OrganizationId) {
final User user = ((MyUserPrincipal) this.getPrincipal()).getUser();
return user.getOrganization().getId().longValue() == OrganizationId.longValue();
}
@Override
public Object getFilterObject() {
return this.filterObject;
}
@Override
public Object getReturnObject() {
return this.returnObject;
} | @Override
public Object getThis() {
return this;
}
@Override
public void setFilterObject(Object obj) {
this.filterObject = obj;
}
@Override
public void setReturnObject(Object obj) {
this.returnObject = obj;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\security\CustomMethodSecurityExpressionRoot.java | 1 |
请完成以下Java代码 | public final class AuthorizeReturnObjectHintsRegistrar implements SecurityHintsRegistrar {
private final AuthorizationProxyFactory proxyFactory;
private final SecurityAnnotationScanner<AuthorizeReturnObject> scanner = SecurityAnnotationScanners
.requireUnique(AuthorizeReturnObject.class);
private final Set<Class<?>> visitedClasses = new HashSet<>();
private final List<Class<?>> classesToProxy;
public AuthorizeReturnObjectHintsRegistrar(AuthorizationProxyFactory proxyFactory, Class<?>... classes) {
Assert.notNull(proxyFactory, "proxyFactory cannot be null");
Assert.noNullElements(classes, "classes cannot contain null elements");
this.proxyFactory = proxyFactory;
this.classesToProxy = new ArrayList(List.of(classes));
}
/**
* Construct this registrar
* @param proxyFactory the proxy factory to use to produce the proxy class
* implementations to be registered
* @param classes the classes to proxy
*/
public AuthorizeReturnObjectHintsRegistrar(AuthorizationProxyFactory proxyFactory, List<Class<?>> classes) {
this.proxyFactory = proxyFactory;
this.classesToProxy = new ArrayList<>(classes);
}
/**
* {@inheritDoc}
*/
@Override
public void registerHints(RuntimeHints hints, ConfigurableListableBeanFactory beanFactory) {
List<Class<?>> toProxy = new ArrayList<>();
for (Class<?> clazz : this.classesToProxy) {
toProxy.add(clazz);
traverseType(toProxy, clazz);
}
for (Class<?> clazz : toProxy) { | registerProxy(hints, clazz);
}
}
private void registerProxy(RuntimeHints hints, Class<?> clazz) {
Class<?> proxied = this.proxyFactory.proxy(clazz);
if (proxied == null) {
return;
}
if (Proxy.isProxyClass(proxied)) {
hints.proxies().registerJdkProxy(proxied.getInterfaces());
return;
}
if (SpringProxy.class.isAssignableFrom(proxied)) {
hints.reflection()
.registerType(clazz, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS)
.registerType(proxied, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.ACCESS_DECLARED_FIELDS);
}
}
private void traverseType(List<Class<?>> toProxy, Class<?> clazz) {
if (clazz == Object.class || this.visitedClasses.contains(clazz)) {
return;
}
this.visitedClasses.add(clazz);
for (Method m : clazz.getDeclaredMethods()) {
AuthorizeReturnObject object = this.scanner.scan(m, clazz);
if (object == null) {
continue;
}
Class<?> returnType = m.getReturnType();
toProxy.add(returnType);
traverseType(toProxy, returnType);
}
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\aot\hint\AuthorizeReturnObjectHintsRegistrar.java | 1 |
请完成以下Java代码 | public double prob(int i)
{
return 0.0;
}
public double prob()
{
return 0.0;
}
public double alpha(int i, int j)
{
return 0.0;
}
public double beta(int i, int j)
{
return 0.0;
}
public double emissionCost(int i, int j)
{
return 0.0;
}
public double nextTransitionCost(int i, int j, int k)
{
return 0.0;
}
public double prevTransitionCost(int i, int j, int k)
{
return 0.0;
}
public double bestCost(int i, int j)
{
return 0.0;
}
public List<Integer> emissionVector(int i, int j)
{
return null;
}
public List<Integer> nextTransitionVector(int i, int j, int k)
{
return null;
}
public List<Integer> prevTransitionVector(int i, int j, int k)
{
return null;
}
public double Z()
{
return 0.0;
}
public boolean parse()
{
return true; | }
public boolean empty()
{
return true;
}
public boolean clear()
{
return true;
}
public boolean next()
{
return true;
}
public String parse(String str)
{
return "";
}
public String toString()
{
return "";
}
public String toString(String result, int size)
{
return "";
}
public String parse(String str, int size)
{
return "";
}
public String parse(String str, int size1, String result, int size2)
{
return "";
}
// set token-level penalty. It would be useful for implementing
// Dual decompositon decoding.
// e.g.
// "Dual Decomposition for Parsing with Non-Projective Head Automata"
// Terry Koo Alexander M. Rush Michael Collins Tommi Jaakkola David Sontag
public void setPenalty(int i, int j, double penalty)
{
}
public double penalty(int i, int j)
{
return 0.0;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\Tagger.java | 1 |
请完成以下Java代码 | protected void invalidateDeviceProfileCache(DeviceId deviceId, DeviceProfileId deviceProfileId) {
DeviceState deviceState = deviceStates.get(deviceId);
if (deviceState != null) {
if (!deviceState.getProfileId().equals(deviceProfileId)) {
removeDeviceState(deviceId);
}
}
}
private void removeDeviceState(DeviceId deviceId) {
DeviceState state = deviceStates.remove(deviceId);
if (config.isPersistAlarmRulesState() && (state != null || !config.isFetchAlarmRulesStateOnStart())) {
ctx.removeRuleNodeStateForEntity(deviceId);
}
}
@Override
public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException {
boolean hasChanges = false;
switch (fromVersion) {
case 0: | String persistAlarmRulesState = "persistAlarmRulesState";
String fetchAlarmRulesStateOnStart = "fetchAlarmRulesStateOnStart";
if (oldConfiguration.has(persistAlarmRulesState)) {
if (!oldConfiguration.get(persistAlarmRulesState).asBoolean()) {
hasChanges = true;
((ObjectNode) oldConfiguration).put(fetchAlarmRulesStateOnStart, false);
}
}
break;
default:
break;
}
return new TbPair<>(hasChanges, oldConfiguration);
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\profile\TbDeviceProfileNode.java | 1 |
请完成以下Java代码 | protected void doPost(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
doCommand(request, response);
}
private void doCommand(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
FrontCommand command = getCommand(request);
command.init(request, response);
command.process();
} | private FrontCommand getCommand(HttpServletRequest request) {
try {
Class type = Class.forName(
String.format(
"com.baeldung.patterns.intercepting.filter.commands.%sCommand",
request.getParameter("command")
)
);
return (FrontCommand) type
.asSubclass(FrontCommand.class)
.newInstance();
} catch (Exception e) {
return new UnknownCommand();
}
}
} | repos\tutorials-master\patterns-modules\intercepting-filter\src\main\java\com\baeldung\patterns\intercepting\filter\FrontControllerServlet.java | 1 |
请完成以下Java代码 | public void syncBPartners(@NonNull final PutBPartnersRequest request)
{
senderToProcurementWebUI.send(request);
}
@Override
public void syncProducts(@NonNull final PutProductsRequest request)
{
senderToProcurementWebUI.send(request);
}
@Override
public void syncInfoMessage(@NonNull final PutInfoMessageRequest request)
{
senderToProcurementWebUI.send(request);
}
@Override
public void confirm(@NonNull final List<SyncConfirmation> syncConfirmations)
{ | senderToProcurementWebUI.send(PutConfirmationToProcurementWebRequest.of(syncConfirmations));
}
@Override
public void syncRfQs(@NonNull final List<SyncRfQ> syncRfqs)
{
senderToProcurementWebUI.send(PutRfQsRequest.builder()
.syncRfqs(syncRfqs)
.build());
}
@Override
public void closeRfQs(@NonNull final List<SyncRfQCloseEvent> syncRfQCloseEvents)
{
senderToProcurementWebUI.send(PutRfQCloseEventsRequest.of(syncRfQCloseEvents));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\AgentSyncBL.java | 1 |
请完成以下Java代码 | public boolean isFunctionRow(final int row)
{
return m_printData.isFunctionRow(row);
}
@Override
protected void formatPage(final Sheet sheet)
{
super.formatPage(sheet);
MPrintPaper paper = MPrintPaper.get(this.m_printFormat.getAD_PrintPaper_ID());
//
// Set paper size:
short paperSize = -1;
MediaSizeName mediaSizeName = paper.getMediaSize().getMediaSizeName();
if (MediaSizeName.NA_LETTER.equals(mediaSizeName))
{
paperSize = PrintSetup.LETTER_PAPERSIZE;
}
else if (MediaSizeName.NA_LEGAL.equals(mediaSizeName))
{
paperSize = PrintSetup.LEGAL_PAPERSIZE;
}
else if (MediaSizeName.EXECUTIVE.equals(mediaSizeName))
{
paperSize = PrintSetup.EXECUTIVE_PAPERSIZE;
}
else if (MediaSizeName.ISO_A4.equals(mediaSizeName))
{
paperSize = PrintSetup.A4_PAPERSIZE;
}
else if (MediaSizeName.ISO_A5.equals(mediaSizeName))
{
paperSize = PrintSetup.A5_PAPERSIZE;
}
else if (MediaSizeName.NA_NUMBER_10_ENVELOPE.equals(mediaSizeName))
{
paperSize = PrintSetup.ENVELOPE_10_PAPERSIZE;
}
// else if (MediaSizeName..equals(mediaSizeName)) {
// paperSize = PrintSetup.ENVELOPE_DL_PAPERSIZE;
// }
// else if (MediaSizeName..equals(mediaSizeName)) {
// paperSize = PrintSetup.ENVELOPE_CS_PAPERSIZE;
// }
else if (MediaSizeName.MONARCH_ENVELOPE.equals(mediaSizeName))
{
paperSize = PrintSetup.ENVELOPE_MONARCH_PAPERSIZE;
}
if (paperSize != -1) | {
sheet.getPrintSetup().setPaperSize(paperSize);
}
//
// Set Landscape/Portrait:
sheet.getPrintSetup().setLandscape(paper.isLandscape());
//
// Set Paper Margin:
sheet.setMargin(Sheet.TopMargin, ((double)paper.getMarginTop()) / 72);
sheet.setMargin(Sheet.RightMargin, ((double)paper.getMarginRight()) / 72);
sheet.setMargin(Sheet.LeftMargin, ((double)paper.getMarginLeft()) / 72);
sheet.setMargin(Sheet.BottomMargin, ((double)paper.getMarginBottom()) / 72);
//
}
@Override
protected List<CellValue> getNextRow()
{
final ArrayList<CellValue> result = new ArrayList<>();
for (int i = 0; i < getColumnCount(); i++)
{
result.add(getValueAt(rowNumber, i));
}
rowNumber++;
return result;
}
@Override
protected boolean hasNextRow()
{
return rowNumber < getRowCount();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\print\export\PrintDataExcelExporter.java | 1 |
请完成以下Java代码 | public class MyGameMain {
public byte[] serialiseDesertTerrainData() {
int INITIAL_BUFFER = 1024;
FlatBufferBuilder builder = new FlatBufferBuilder(INITIAL_BUFFER);
int sandstormOffset = builder.createString("Sandstorm");
short damage = 3;
int sandStorm = MyGame.terrains.Effect.createEffect(builder, sandstormOffset, damage);
int droughtOffset = builder.createString("Drought");
short damageDrought = 1;
int drought = MyGame.terrains.Effect.createEffect(builder, droughtOffset, damageDrought);
int[] effects = new int[2];
effects[0] = sandStorm;
effects[1] = drought;
byte color = MyGame.terrains.Color.Brown;
int terrainName = builder.createString("Desert");
int navigationName = builder.createString("south");
int effectOffset = MyGame.terrains.Terrain.createEffectsVector(builder, effects);
startTerrain(builder);
MyGame.terrains.Terrain.addName(builder, terrainName); | addColor(builder, color);
addNavigation(builder, navigationName);
addEffects(builder, effectOffset);
int desert = endTerrain(builder);
builder.finish(desert);
return builder.sizedByteArray();
}
public MyGame.terrains.Terrain deserialiseDataToTerrain(byte[] buffer) {
ByteBuffer buf = ByteBuffer.wrap(buffer);
return Terrain.getRootAsTerrain(buf);
}
public Effect.Vector deserialiseDataToEffect(byte[] buffer) {
ByteBuffer buf = ByteBuffer.wrap(buffer);
return Terrain.getRootAsTerrain(buf)
.effectsVector();
}
} | repos\tutorials-master\libraries-data-io-2\src\main\java\com\baeldung\flatbuffers\MyGameMain.java | 1 |
请完成以下Java代码 | public class ThreadAwaitContainer {
private final Map<String, Set<Thread>> threadMap = new ConcurrentHashMap<>();
/**
* 线程等待,最大等待100毫秒
* @param key 缓存Key
* @param milliseconds 等待时间
* @throws InterruptedException
*/
public final void await(String key, long milliseconds) throws InterruptedException {
// 测试当前线程是否已经被中断
if (Thread.interrupted()) {
throw new InterruptedException();
}
Set<Thread> threadSet = threadMap.get(key);
// 判断线程容器是否是null,如果是就新创建一个
if (threadSet == null) {
threadSet = new HashSet<>();
threadMap.put(key, threadSet);
}
// 将线程放到容器
threadSet.add(Thread.currentThread());
// 阻塞一定的时间
LockSupport.parkNanos(this, TimeUnit.MILLISECONDS.toNanos(milliseconds));
}
/** | * 线程唤醒
* @param key
*/
public final void signalAll(String key) {
Set<Thread> threadSet = threadMap.get(key);
// 判断key所对应的等待线程容器是否是null
if (!CollectionUtils.isEmpty(threadSet)) {
for (Thread thread : threadSet) {
LockSupport.unpark(thread);
}
// 清空等待线程容器
threadSet.clear();
}
}
} | repos\spring-boot-student-master\spring-boot-student-cache-redis-caffeine\src\main\java\com\xiaolyuh\cache\redis\cache\ThreadAwaitContainer.java | 1 |
请完成以下Java代码 | private boolean hasTokenExpired(OAuth2Token token) {
return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew));
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint for the {@code token-exchange} grant.
* @param accessTokenResponseClient the client used when requesting an access token
* credential at the Token Endpoint for the {@code token-exchange} grant
*/
public void setAccessTokenResponseClient(
ReactiveOAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
}
/**
* Sets the resolver used for resolving the {@link OAuth2Token subject token}.
* @param subjectTokenResolver the resolver used for resolving the {@link OAuth2Token
* subject token}
*/
public void setSubjectTokenResolver(Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> subjectTokenResolver) {
Assert.notNull(subjectTokenResolver, "subjectTokenResolver cannot be null");
this.subjectTokenResolver = subjectTokenResolver;
}
/**
* Sets the resolver used for resolving the {@link OAuth2Token actor token}.
* @param actorTokenResolver the resolver used for resolving the {@link OAuth2Token
* actor token}
*/
public void setActorTokenResolver(Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> actorTokenResolver) {
Assert.notNull(actorTokenResolver, "actorTokenResolver cannot be null");
this.actorTokenResolver = actorTokenResolver; | }
/**
* Sets the maximum acceptable clock skew, which is used when checking the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is
* 60 seconds.
*
* <p>
* An access token is considered expired if
* {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
*/
public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
this.clockSkew = clockSkew;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access
* token expiry.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\TokenExchangeReactiveOAuth2AuthorizedClientProvider.java | 1 |
请完成以下Java代码 | public IDunnableSourceFactory getDunnableSourceFactory()
{
return dunnableSourceFactory;
}
@Override
public void setDunnableSourceFactory(IDunnableSourceFactory dunnableSourceFactory)
{
Check.assume(dunnableSourceFactory != null, "dunnableSourceFactory is not null");
this.dunnableSourceFactory = dunnableSourceFactory;
}
@Override
public IDunningCandidateProducerFactory getDunningCandidateProducerFactory()
{
return dunningCandidateProducerFactory;
}
@Override
public void setDunningCandidateProducerFactory(IDunningCandidateProducerFactory dunningCandidateProducerFactory)
{
Check.assume(dunningCandidateProducerFactory != null, "dunningCandidateProducerFactory is not null");
this.dunningCandidateProducerFactory = dunningCandidateProducerFactory;
}
@Override
public IDunningProducer createDunningProducer()
{
try
{
final IDunningProducer producer = dunningProducerClass.newInstance();
return producer;
}
catch (Exception e)
{
throw new DunningException("Cannot create " + IDunningProducer.class + " for " + dunningProducerClass, e);
}
}
@Override
public void setDunningProducerClass(Class<IDunningProducer> dunningProducerClass)
{
Check.assume(dunningProducerClass != null, "dunningProducerClass is not null");
this.dunningProducerClass = dunningProducerClass;
} | @Override
public IDunningCandidateSource createDunningCandidateSource()
{
try
{
final IDunningCandidateSource source = dunningCandidateSourceClass.newInstance();
return source;
}
catch (Exception e)
{
throw new DunningException("Cannot create " + IDunningCandidateSource.class + " for " + dunningCandidateSourceClass, e);
}
}
@Override
public void setDunningCandidateSourceClass(Class<? extends IDunningCandidateSource> dunningCandidateSourceClass)
{
Check.assume(dunningCandidateSourceClass != null, "dunningCandidateSourceClass is not null");
this.dunningCandidateSourceClass = dunningCandidateSourceClass;
}
@Override
public String toString()
{
return "DunningConfig ["
+ "dunnableSourceFactory=" + dunnableSourceFactory
+ ", dunningCandidateProducerFactory=" + dunningCandidateProducerFactory
+ ", dunningCandidateSourceClass=" + dunningCandidateSourceClass
+ ", dunningProducerClass=" + dunningProducerClass
+ "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningConfig.java | 1 |
请完成以下Java代码 | public void setWebhookUrl(@Nullable URI webhookUrl) {
this.webhookUrl = webhookUrl;
}
public boolean isTts() {
return tts;
}
public void setTts(boolean tts) {
this.tts = tts;
}
@Nullable
public String getUsername() {
return username;
}
public void setUsername(@Nullable String username) {
this.username = username; | }
@Nullable
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(@Nullable String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\DiscordNotifier.java | 1 |
请完成以下Java代码 | protected void internalExecute() {
planItemInstanceEntity.setLastStartedTime(getCurrentTime(commandContext));
CommandContextUtil.getCmmnHistoryManager(commandContext).recordPlanItemInstanceStarted(planItemInstanceEntity);
createAsyncJob((Task) planItemInstanceEntity.getPlanItem().getPlanItemDefinition());
}
protected void createAsyncJob(Task task) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
JobService jobService = cmmnEngineConfiguration.getJobServiceConfiguration().getJobService();
JobEntity job = JobUtil.createJob(planItemInstanceEntity, task, AsyncActivatePlanItemInstanceJobHandler.TYPE, cmmnEngineConfiguration);
job.setJobHandlerConfiguration(entryCriterionId);
jobService.createAsyncJob(job, task.isExclusive());
jobService.scheduleAsyncJob(job);
if (cmmnEngineConfiguration.isLoggingSessionEnabled()) {
CmmnLoggingSessionUtil.addAsyncActivityLoggingData("Created async job for " + planItemInstanceEntity.getPlanItemDefinitionId() + ", with job id " + job.getId(),
CmmnLoggingSessionConstants.TYPE_SERVICE_TASK_ASYNC_JOB, job, planItemInstanceEntity.getPlanItemDefinition(),
planItemInstanceEntity, cmmnEngineConfiguration.getObjectMapper());
}
}
@Override
public String toString() {
PlanItem planItem = planItemInstanceEntity.getPlanItem();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("[Async activate PlanItem] "); | stringBuilder.append(planItem);
if (entryCriterionId != null) {
stringBuilder.append(" via entry criterion ").append(entryCriterionId);
}
return stringBuilder.toString();
}
@Override
public String getOperationName() {
return "[Async activate plan item]";
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\ActivateAsyncPlanItemInstanceOperation.java | 1 |
请完成以下Java代码 | public static void updateCache(Authentications authentications,
HttpSession session,
long cacheTimeToLive) {
synchronized (getSessionMutex(session)) {
for (UserAuthentication authentication : authentications.getAuthentications()) {
Date cacheValidationTime = authentication.getCacheValidationTime();
if (cacheValidationTime == null ||
ClockUtil.getCurrentTime().after(cacheValidationTime)) {
String userId = authentication.getIdentityId();
String engineName = authentication.getProcessEngineName();
UserAuthentication updatedAuth = createAuthentication(engineName, userId);
if (updatedAuth != null) {
if (cacheTimeToLive > 0) {
Date newCacheValidationTime = new Date(ClockUtil.getCurrentTime().getTime() + cacheTimeToLive);
updatedAuth.setCacheValidationTime(newCacheValidationTime);
LOGGER.traceCacheValidationTimeUpdated(cacheValidationTime, newCacheValidationTime);
}
LOGGER.traceAuthenticationUpdated(engineName);
authentications.addOrReplace(updatedAuth);
} else { | authentications.removeByEngineName(engineName);
LOGGER.traceAuthenticationRemoved(engineName);
}
}
}
}
}
/**
* <p>Returns the session mutex to synchronize on.
* <p>Avoids updating the auth cache by multiple HTTP requests in parallel.
*/
protected static Object getSessionMutex(HttpSession session) {
Object mutex = session.getAttribute(AUTH_TIME_SESSION_MUTEX);
if (mutex == null) {
mutex = session; // synchronize on session if session mutex doesn't exist
}
return mutex;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\auth\AuthenticationUtil.java | 1 |
请完成以下Java代码 | public void setMSV3_Server_ID (int MSV3_Server_ID)
{
if (MSV3_Server_ID < 1)
set_ValueNoCheck (COLUMNNAME_MSV3_Server_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MSV3_Server_ID, Integer.valueOf(MSV3_Server_ID));
}
/** Get MSV3 Server.
@return MSV3 Server */
@Override
public int getMSV3_Server_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Server_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Warehouse_PickingGroup getM_Warehouse_PickingGroup() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Warehouse_PickingGroup_ID, org.compiere.model.I_M_Warehouse_PickingGroup.class);
}
@Override
public void setM_Warehouse_PickingGroup(org.compiere.model.I_M_Warehouse_PickingGroup M_Warehouse_PickingGroup)
{
set_ValueFromPO(COLUMNNAME_M_Warehouse_PickingGroup_ID, org.compiere.model.I_M_Warehouse_PickingGroup.class, M_Warehouse_PickingGroup);
}
/** Set Kommissionier-Lagergruppe . | @param M_Warehouse_PickingGroup_ID Kommissionier-Lagergruppe */
@Override
public void setM_Warehouse_PickingGroup_ID (int M_Warehouse_PickingGroup_ID)
{
if (M_Warehouse_PickingGroup_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_PickingGroup_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_PickingGroup_ID, Integer.valueOf(M_Warehouse_PickingGroup_ID));
}
/** Get Kommissionier-Lagergruppe .
@return Kommissionier-Lagergruppe */
@Override
public int getM_Warehouse_PickingGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_PickingGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java-gen\de\metas\vertical\pharma\msv3\server\model\X_MSV3_Server.java | 1 |
请完成以下Java代码 | public class ApiKeyInfo extends BaseData<ApiKeyId> implements HasTenantId {
@Serial
private static final long serialVersionUID = -2313196723950490263L;
@Schema(description = "JSON object with Tenant Id. Tenant Id of the API key cannot be changed.", accessMode = Schema.AccessMode.READ_ONLY)
private TenantId tenantId;
@Schema(description = "JSON object with User Id. User Id of the API key cannot be changed.")
private UserId userId;
@Schema(description = "Expiration time of the API key.")
private long expirationTime;
@NoXss
@NotBlank
@Length(fieldName = "description")
@Schema(description = "API Key description.", example = "API Key description")
private String description;
@Schema(description = "Enabled/disabled API key.", example = "true")
private boolean enabled;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
@Schema(description = "Indicates if the API key is expired based on current time. Returns false if expirationTime is 0 (no expiry).",
example = "false",
accessMode = Schema.AccessMode.READ_ONLY)
public boolean isExpired() {
if (expirationTime == 0) {
return false;
}
return System.currentTimeMillis() > expirationTime;
}
@Schema(description = "JSON object with the API Key Id. " +
"Specify this field to update the API Key. " +
"Referencing non-existing API Key Id will cause error. " +
"Omit this field to create new API Key.")
@Override
public ApiKeyId getId() {
return super.getId(); | }
public ApiKeyInfo() {
super();
}
public ApiKeyInfo(ApiKeyId id) {
super(id);
}
public ApiKeyInfo(ApiKeyInfo apiKeyInfo) {
super(apiKeyInfo);
this.tenantId = apiKeyInfo.getTenantId();
this.userId = apiKeyInfo.getUserId();
this.expirationTime = apiKeyInfo.getExpirationTime();
this.enabled = apiKeyInfo.isEnabled();
this.description = apiKeyInfo.getDescription();
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\pat\ApiKeyInfo.java | 1 |
请完成以下Java代码 | public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest.Builder requestBuilder = null;
Map<String, List<String>> aggregatedHeaders = new HashMap<>();
for (KeyValue keyValue : config.getKeyValues()) {
String key = keyValue.getKey();
List<String> candidateValue = aggregatedHeaders.get(key);
if (candidateValue == null) {
candidateValue = new ArrayList<>();
candidateValue.add(keyValue.getValue());
}
else {
candidateValue.add(keyValue.getValue());
}
aggregatedHeaders.put(key, candidateValue);
}
for (Map.Entry<String, List<String>> kv : aggregatedHeaders.entrySet()) {
String headerName = kv.getKey();
boolean headerIsMissingOrBlank = exchange.getRequest()
.getHeaders()
.getOrEmpty(headerName)
.stream()
.allMatch(h -> !StringUtils.hasText(h));
if (headerIsMissingOrBlank) {
if (requestBuilder == null) {
requestBuilder = exchange.getRequest().mutate();
}
ServerWebExchange finalExchange = exchange;
requestBuilder.headers(httpHeaders -> {
List<String> replacedValues = kv.getValue()
.stream()
.map(value -> ServerWebExchangeUtils.expand(finalExchange, value))
.collect(Collectors.toList());
httpHeaders.addAll(headerName, replacedValues);
});
}
}
if (requestBuilder != null) {
exchange = exchange.mutate().request(requestBuilder.build()).build();
}
return chain.filter(exchange);
}
@Override
public String toString() {
ToStringCreator toStringCreator = filterToStringCreator( | AddRequestHeadersIfNotPresentGatewayFilterFactory.this);
for (KeyValue keyValue : config.getKeyValues()) {
toStringCreator.append(keyValue.getKey(), keyValue.getValue());
}
return toStringCreator.toString();
}
};
}
public ShortcutType shortcutType() {
return ShortcutType.GATHER_LIST;
}
@Override
public List<String> shortcutFieldOrder() {
return Collections.singletonList("keyValues");
}
@Override
public KeyValueConfig newConfig() {
return new KeyValueConfig();
}
@Override
public Class<KeyValueConfig> getConfigClass() {
return KeyValueConfig.class;
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\AddRequestHeadersIfNotPresentGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public int getKeyLength() {
return this.VALUE.length;
}
@Override
public byte[] generateKey() {
return this.VALUE;
}
};
public enum CipherAlgorithm {
CBC(AES_CBC_ALGORITHM, NULL_IV_GENERATOR),
GCM(AES_GCM_ALGORITHM, KeyGenerators.secureRandom(16));
private BytesKeyGenerator ivGenerator;
private String name;
CipherAlgorithm(String name, BytesKeyGenerator ivGenerator) {
this.name = name;
this.ivGenerator = ivGenerator;
}
@Override
public String toString() { | return this.name;
}
public AlgorithmParameterSpec getParameterSpec(byte[] iv) {
return (this != CBC) ? new GCMParameterSpec(128, iv) : new IvParameterSpec(iv);
}
public Cipher createCipher() {
return CipherUtils.newCipher(this.toString());
}
public BytesKeyGenerator defaultIvGenerator() {
return this.ivGenerator;
}
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\AesBytesEncryptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DDOrderCreatedHandler extends DDOrderAdvisedOrCreatedHandler<DDOrderCreatedEvent>
{
public DDOrderCreatedHandler(
@NonNull final CandidateRepositoryRetrieval candidateRepository,
@NonNull final CandidateRepositoryWriteService candidateRepositoryCommands,
@NonNull final CandidateChangeService candidateChangeHandler,
@NonNull final DDOrderDetailRequestHandler ddOrderDetailRequestHandler,
@NonNull final MainDataRequestHandler mainDataRequestHandler)
{
super(
candidateRepository,
candidateRepositoryCommands,
candidateChangeHandler,
ddOrderDetailRequestHandler,
mainDataRequestHandler);
}
@Override
public Collection<Class<? extends DDOrderCreatedEvent>> getHandledEventType()
{
return ImmutableList.of(DDOrderCreatedEvent.class);
}
@Override
public void handleEvent(DDOrderCreatedEvent event)
{
createAndProcessCandidates(event);
}
@Override
protected CandidatesQuery createPreExistingCandidatesQuery(
@NonNull final AbstractDDOrderEvent ddOrderEvent,
@NonNull final DDOrderLine ddOrderLine,
@NonNull final CandidateType candidateType)
{
final SupplyRequiredDescriptor supplyRequiredDescriptor = ddOrderEvent.getSupplyRequiredDescriptor(); | if (supplyRequiredDescriptor != null && supplyRequiredDescriptor.getSupplyCandidateId() > 0)
{
return CandidatesQuery.fromId(CandidateId.ofRepoId(supplyRequiredDescriptor.getSupplyCandidateId()));
}
final DDOrderCreatedEvent ddOrderCreatedEvent = DDOrderCreatedEvent.cast(ddOrderEvent);
final DDOrder ddOrder = ddOrderCreatedEvent.getDdOrder();
final MaterialDispoGroupId groupId = ddOrder.getMaterialDispoGroupId();
if (groupId == null)
{
// returned false, but don't write another log message; we already logged in the other createQuery() method
return CandidatesQuery.FALSE;
}
return CandidatesQuery.builder()
.type(candidateType)
.businessCase(CandidateBusinessCase.DISTRIBUTION)
.groupId(groupId)
.materialDescriptorQuery(toMaterialDescriptorQuery(ddOrderLine.getProductDescriptor()))
.build();
}
private static MaterialDescriptorQuery toMaterialDescriptorQuery(@NonNull final ProductDescriptor productDescriptor)
{
return MaterialDescriptorQuery.builder()
.productId(productDescriptor.getProductId())
.storageAttributesKey(productDescriptor.getStorageAttributesKey())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ddorder\DDOrderCreatedHandler.java | 2 |
请完成以下Java代码 | public class Person {
private String firstName;
private String lastName;
private String contact;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() { | return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
} | repos\tutorials-master\jackson-modules\jackson-exceptions\src\main\java\com\baeldung\exceptions\Person.java | 1 |
请完成以下Java代码 | public void hit(int begin, int end, Pinyin[] value)
{
int length = end - begin;
if (length == 1 && value.length > 1)
{
value = new Pinyin[]{value[0]};
}
if (length > lengths[begin])
{
wordNet[begin] = value;
lengths[begin] = length;
}
}
});
List<Pinyin> pinyinList = new ArrayList<Pinyin>(charArray.length);
for (int offset = 0; offset < wordNet.length; )
{
if (wordNet[offset] == null)
{
if (remainNone)
{
pinyinList.add(Pinyin.none5);
}
++offset;
continue;
}
for (Pinyin pinyin : wordNet[offset])
{
pinyinList.add(pinyin);
}
offset += lengths[offset];
}
return pinyinList;
}
public static class Searcher extends BaseSearcher<Pinyin[]>
{
/**
* 分词从何处开始,这是一个状态
*/
int begin;
DoubleArrayTrie<Pinyin[]> trie; | protected Searcher(char[] c, DoubleArrayTrie<Pinyin[]> trie)
{
super(c);
this.trie = trie;
}
protected Searcher(String text, DoubleArrayTrie<Pinyin[]> trie)
{
super(text);
this.trie = trie;
}
@Override
public Map.Entry<String, Pinyin[]> next()
{
// 保证首次调用找到一个词语
Map.Entry<String, Pinyin[]> result = null;
while (begin < c.length)
{
LinkedList<Map.Entry<String, Pinyin[]>> entryList = trie.commonPrefixSearchWithValue(c, begin);
if (entryList.size() == 0)
{
++begin;
}
else
{
result = entryList.getLast();
offset = begin;
begin += result.getKey().length();
break;
}
}
if (result == null)
{
return null;
}
return result;
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\py\PinyinDictionary.java | 1 |
请完成以下Java代码 | public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
/**
* Set a specific validation query to use to validate a connection. If none is set, a
* validation based on {@link Connection#isValid(int)} is used.
* @param query the validation query to use
*/
public void setQuery(String query) {
this.query = query;
}
/**
* Return the validation query or {@code null}.
* @return the query
*/
public @Nullable String getQuery() {
return this.query;
}
/**
* {@link RowMapper} that expects and returns results from a single column.
*/
private static final class SingleColumnRowMapper implements RowMapper<Object> { | @Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
if (columns != 1) {
throw new IncorrectResultSetColumnCountException(1, columns);
}
Object result = JdbcUtils.getResultSetValue(rs, 1);
Assert.state(result != null, "'result' must not be null");
return result;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\health\DataSourceHealthIndicator.java | 1 |
请完成以下Java代码 | public static LoggingSystem get(ClassLoader classLoader) {
String loggingSystemClassName = System.getProperty(SYSTEM_PROPERTY);
if (StringUtils.hasLength(loggingSystemClassName)) {
if (NONE.equals(loggingSystemClassName)) {
return new NoOpLoggingSystem();
}
return get(classLoader, loggingSystemClassName);
}
LoggingSystem loggingSystem = SYSTEM_FACTORY.getLoggingSystem(classLoader);
Assert.state(loggingSystem != null, "No suitable logging system located");
return loggingSystem;
}
private static LoggingSystem get(ClassLoader classLoader, String loggingSystemClassName) {
try {
Class<?> systemClass = ClassUtils.forName(loggingSystemClassName, classLoader);
Constructor<?> constructor = systemClass.getDeclaredConstructor(ClassLoader.class);
constructor.setAccessible(true);
return (LoggingSystem) constructor.newInstance(classLoader);
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
/**
* {@link LoggingSystem} that does nothing. | */
static class NoOpLoggingSystem extends LoggingSystem {
@Override
public void beforeInitialize() {
}
@Override
public void setLogLevel(@Nullable String loggerName, @Nullable LogLevel level) {
}
@Override
public List<LoggerConfiguration> getLoggerConfigurations() {
return Collections.emptyList();
}
@Override
public @Nullable LoggerConfiguration getLoggerConfiguration(String loggerName) {
return null;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\LoggingSystem.java | 1 |
请完成以下Java代码 | public class GlobalResponseBodyHandler extends ResponseBodyResultHandler {
private static Logger LOGGER = LoggerFactory.getLogger(GlobalResponseBodyHandler.class);
private static MethodParameter METHOD_PARAMETER_MONO_COMMON_RESULT;
private static final CommonResult COMMON_RESULT_SUCCESS = CommonResult.success(null);
static {
try {
// 获得 METHOD_PARAMETER_MONO_COMMON_RESULT 。其中 -1 表示 `#methodForParams()` 方法的返回值
METHOD_PARAMETER_MONO_COMMON_RESULT = new MethodParameter(
GlobalResponseBodyHandler.class.getDeclaredMethod("methodForParams"), -1);
} catch (NoSuchMethodException e) {
LOGGER.error("[static][获取 METHOD_PARAMETER_MONO_COMMON_RESULT 时,找不都方法");
throw new RuntimeException(e);
}
}
public GlobalResponseBodyHandler(List<HttpMessageWriter<?>> writers, RequestedContentTypeResolver resolver) {
super(writers, resolver);
}
public GlobalResponseBodyHandler(List<HttpMessageWriter<?>> writers, RequestedContentTypeResolver resolver, ReactiveAdapterRegistry registry) {
super(writers, resolver, registry);
}
@Override
@SuppressWarnings("unchecked")
public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
Object returnValue = result.getReturnValue();
Object body;
// 处理返回结果为 Mono 的情况
if (returnValue instanceof Mono) {
body = ((Mono<Object>) result.getReturnValue())
.map((Function<Object, Object>) GlobalResponseBodyHandler::wrapCommonResult)
.defaultIfEmpty(COMMON_RESULT_SUCCESS);
// 处理返回结果为 Flux 的情况
} else if (returnValue instanceof Flux) {
body = ((Flux<Object>) result.getReturnValue())
.collectList()
.map((Function<Object, Object>) GlobalResponseBodyHandler::wrapCommonResult)
.defaultIfEmpty(COMMON_RESULT_SUCCESS);
// 处理结果为其它类型 | } else {
body = wrapCommonResult(returnValue);
}
return writeBody(body, METHOD_PARAMETER_MONO_COMMON_RESULT, exchange);
}
private static Mono<CommonResult> methodForParams() {
return null;
}
private static CommonResult<?> wrapCommonResult(Object body) {
// 如果已经是 CommonResult 类型,则直接返回
if (body instanceof CommonResult) {
return (CommonResult<?>) body;
}
// 如果不是,则包装成 CommonResult 类型
return CommonResult.success(body);
}
} | repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-02\src\main\java\cn\iocoder\springboot\lab27\springwebflux\core\web\GlobalResponseBodyHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<FlowRuleEntity> apiUpdateFlowRule(@PathVariable("id") Long id,
@RequestBody FlowRuleEntity entity) {
if (id == null || id <= 0) {
return Result.ofFail(-1, "Invalid id");
}
FlowRuleEntity oldEntity = repository.findById(id);
if (oldEntity == null) {
return Result.ofFail(-1, "id " + id + " does not exist");
}
if (entity == null) {
return Result.ofFail(-1, "invalid body");
}
entity.setApp(oldEntity.getApp());
entity.setIp(oldEntity.getIp());
entity.setPort(oldEntity.getPort());
Result<FlowRuleEntity> checkResult = checkEntityInternal(entity);
if (checkResult != null) {
return checkResult;
}
entity.setId(id);
Date date = new Date();
entity.setGmtCreate(oldEntity.getGmtCreate());
entity.setGmtModified(date);
try {
entity = repository.save(entity);
if (entity == null) {
return Result.ofFail(-1, "save entity fail");
}
publishRules(oldEntity.getApp());
} catch (Throwable throwable) {
logger.error("Failed to update flow rule", throwable);
return Result.ofThrowable(-1, throwable);
}
return Result.ofSuccess(entity);
}
@DeleteMapping("/rule/{id}")
@AuthAction(PrivilegeType.DELETE_RULE)
public Result<Long> apiDeleteRule(@PathVariable("id") Long id) { | if (id == null || id <= 0) {
return Result.ofFail(-1, "Invalid id");
}
FlowRuleEntity oldEntity = repository.findById(id);
if (ObjectUtils.isEmpty(oldEntity)) {
return Result.ofSuccess(null);
}
try {
repository.delete(id);
publishRules(oldEntity.getApp());
} catch (Exception e) {
return Result.ofFail(-1, e.getMessage());
}
return Result.ofSuccess(id);
}
private void publishRules(/*@NonNull*/ String app) throws Exception {
List<FlowRuleEntity> rules = repository.findAllByApp(app);
rulePublisher.publish(app, rules);
//延迟加载
delayTime();
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\v2\FlowControllerV2.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public PublicKeyCredentialUserEntity findByUsername(String username) {
log.info("findByUsername: username={}", username);
return userRepository.findByName(username)
.map(DbPublicKeyCredentialUserEntityRepository::mapToUserEntity)
.orElse(null);
}
@Override
public void save(PublicKeyCredentialUserEntity userEntity) {
log.info("save: username={}, externalId={}", userEntity.getName(),userEntity.getId().toBase64UrlString());
var entity = userRepository.findByExternalId(userEntity.getId().toBase64UrlString())
.orElse(new PasskeyUser());
entity.setExternalId(userEntity.getId().toBase64UrlString());
entity.setName(userEntity.getName());
entity.setDisplayName(userEntity.getDisplayName()); | userRepository.save(entity);
}
@Override
public void delete(Bytes id) {
log.info("delete: id={}", id.toBase64UrlString());
userRepository.findByExternalId(id.toBase64UrlString())
.ifPresent(userRepository::delete);
}
private static PublicKeyCredentialUserEntity mapToUserEntity(PasskeyUser user) {
return ImmutablePublicKeyCredentialUserEntity.builder()
.id(Bytes.fromBase64(user.getExternalId()))
.name(user.getName())
.displayName(user.getDisplayName())
.build();
}
} | repos\tutorials-master\spring-security-modules\spring-security-passkey\src\main\java\com\baeldung\tutorials\passkey\repository\DbPublicKeyCredentialUserEntityRepository.java | 2 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonIgnore
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getDivisionId() {
return divisionId;
}
public void setDivisionId(Integer divisionId) {
this.divisionId = divisionId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMobilephone() {
return mobilephone;
}
public void setMobilephone(String mobilephone) {
this.mobilephone = mobilephone;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime; | }
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getDisabled() {
return disabled;
}
public void setDisabled(Integer disabled) {
this.disabled = disabled;
}
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public Integer getIsLdap() {
return isLdap;
}
public void setIsLdap(Integer isLdap) {
this.isLdap = isLdap;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
} | repos\springBoot-master\springboot-jpa\src\main\java\com\us\example\bean\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<User> getUsers() {
return userService.getUsers();
}
@PostMapping
public User createUser(User user) {
return userService.createUser(user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable String id) {
userService.deleteUser(id);
}
@PutMapping("/{id}")
public void updateUser(@PathVariable String id, User user) {
userService.updateUser(id, user);
}
/**
* 根据用户 id查找
* 存在返回,不存在返回 null
*/
@GetMapping("/{id}")
public User getUser(@PathVariable String id) {
return userService.getUser(id).orElse(null);
}
/**
* 根据年龄段来查找
*/
@GetMapping("/age/{from}/{to}")
public List<User> getUserByAge(@PathVariable Integer from, @PathVariable Integer to) { | return userService.getUserByAge(from, to);
}
/**
* 根据用户名查找
*/
@GetMapping("/name/{name}")
public List<User> getUserByName(@PathVariable String name) {
return userService.getUserByName(name);
}
/**
* 根据用户描述模糊查找
*/
@GetMapping("/description/{description}")
public List<User> getUserByDescription(@PathVariable String description) {
return userService.getUserByDescription(description);
}
/**
* 根据多个检索条件查询
*/
@GetMapping("/condition")
public Page<User> getUserByCondition(int size, int page, User user) {
return userService.getUserByCondition(size, page, user);
}
} | repos\SpringAll-master\56.Spring-Boot-MongoDB-crud\src\main\java\com\example\mongodb\controller\UserController.java | 2 |
请完成以下Java代码 | public Element getElement()
{
return m_view.getElement();
}
/**
* Sets the view size.
*
* @param width the width
* @param height the height
*/
public void setSize(float width, float height)
{
this.m_width = (int) width;
m_view.setSize(width, height);
}
/** | * Fetches the factory to be used for building the
* various view fragments that make up the view that
* represents the model. This is what determines
* how the model will be represented. This is implemented
* to fetch the factory provided by the associated
* EditorKit.
*
* @return the factory
*/
public ViewFactory getViewFactory()
{
return m_factory;
}
} // HTMLRenderer | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\HTMLRenderer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static String cacheExchangeRates() {
String result = null;
try {
URL exchangeRateUrl = new URI("https://api.exchangeratesapi.io/latest").toURL();
URLConnection con = exchangeRateUrl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = in.readLine();
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
return result;
}
@LogExceptions
public static void divideByZero() {
int x = 1/0;
} | @RetryOnFailure(attempts = 2, types = { NumberFormatException.class})
@Quietly
public static void divideByZeroQuietly() {
int x = 1/0;
}
@UnitedThrow(IllegalStateException.class)
public static void processFile() throws IOException, InterruptedException {
BufferedReader reader = new BufferedReader(new FileReader("baeldung.txt"));
reader.readLine();
Thread thread = new Thread();
thread.wait(2000);
}
} | repos\tutorials-master\libraries-6\src\main\java\com\baeldung\jcabi\JcabiAspectJ.java | 2 |
请完成以下Java代码 | public class TbSendRpcReplyNodeConfiguration implements NodeConfiguration<TbSendRpcReplyNodeConfiguration> {
public static final String SERVICE_ID = "serviceId";
public static final String SESSION_ID = "sessionId";
public static final String REQUEST_ID = "requestId";
private String serviceIdMetaDataAttribute;
private String sessionIdMetaDataAttribute;
private String requestIdMetaDataAttribute;
@Override
public TbSendRpcReplyNodeConfiguration defaultConfiguration() {
TbSendRpcReplyNodeConfiguration configuration = new TbSendRpcReplyNodeConfiguration();
configuration.setServiceIdMetaDataAttribute(SERVICE_ID);
configuration.setSessionIdMetaDataAttribute(SESSION_ID);
configuration.setRequestIdMetaDataAttribute(REQUEST_ID); | return configuration;
}
public String getServiceIdMetaDataAttribute() {
return !StringUtils.isEmpty(serviceIdMetaDataAttribute) ? serviceIdMetaDataAttribute : SERVICE_ID;
}
public String getSessionIdMetaDataAttribute() {
return !StringUtils.isEmpty(sessionIdMetaDataAttribute) ? sessionIdMetaDataAttribute : SESSION_ID;
}
public String getRequestIdMetaDataAttribute() {
return !StringUtils.isEmpty(requestIdMetaDataAttribute) ? requestIdMetaDataAttribute : REQUEST_ID;
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\rpc\TbSendRpcReplyNodeConfiguration.java | 1 |
请完成以下Java代码 | public static void write40000RowsToSXSSFWorkbook(Blackhole blackhole) throws IOException {
writeRowsToWorkbook(getSXSSFWorkbook(), 40000, blackhole);
}
private static SXSSFWorkbook getSXSSFWorkbook() {
SXSSFWorkbook workbook = new SXSSFWorkbook();
workbook.setCompressTempFiles(true);
return workbook;
}
public static void writeRowsToWorkbook(Workbook workbook, int iterations, Blackhole blackhole) throws IOException {
Sheet sheet = workbook.createSheet();
for (int n=0;n<iterations;n++) {
Row row = sheet.createRow(sheet.getLastRowNum()+1);
for (int c=0;c<256;c++) {
Cell cell = row.createCell(c);
cell.setCellValue("abcdefghijklmnopqrstuvwxyz");
} | }
workbook.close();
blackhole.consume(workbook);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(WorkbookBenchmark.class.getSimpleName()).threads(1)
.shouldFailOnError(true)
.shouldDoGC(true)
.addProfiler(MemPoolProfiler.class)
.jvmArgs("-server").build();
new Runner(options).run();
}
} | repos\tutorials-master\apache-poi-3\src\main\java\com\baeldung\poi\benchmark\WorkbookBenchmark.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void log(ToEdgeNotificationMsg msg) {
totalCounter.increment();
if (msg.hasEdgeHighPriority()) {
edgeHighPriorityCounter.increment();
} else if (msg.hasEdgeEventUpdate()) {
edgeEventUpdateCounter.increment();
} else if (msg.hasToEdgeSyncRequest()) {
edgeSyncRequestCounter.increment();
} else if (msg.hasFromEdgeSyncResponse()) {
edgeSyncResponseCounter.increment();
} else if (msg.hasComponentLifecycle()) {
edgeComponentLifecycle.increment();
}
}
public void log(ToEdgeMsg msg) {
totalCounter.increment();
edgeNotificationsCounter.increment();
} | public void printStats() {
int total = totalCounter.get();
if (total > 0) {
StringBuilder stats = new StringBuilder();
counters.forEach(counter -> stats.append(counter.getName()).append(" = [").append(counter.get()).append("] "));
log.info("Edge Stats: {}", stats);
}
}
public void reset() {
counters.forEach(StatsCounter::clear);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\EdgeConsumerStats.java | 2 |
请完成以下Java代码 | private static void validate(EntityId entityId) {
Validator.validateEntityId(entityId, id -> "Incorrect entityId " + id);
}
private void validate(ReadTsKvQuery query) {
if (query == null) {
throw new IncorrectParameterException("ReadTsKvQuery can't be null");
} else if (isBlank(query.getKey())) {
throw new IncorrectParameterException("Incorrect ReadTsKvQuery. Key can't be empty");
} else if (query.getAggregation() == null) {
throw new IncorrectParameterException("Incorrect ReadTsKvQuery. Aggregation can't be empty");
}
if (!Aggregation.NONE.equals(query.getAggregation())) {
long interval = query.getInterval();
if (interval < 1) {
throw new IncorrectParameterException("Invalid TsKvQuery: 'interval' must be greater than 0, but got " + interval +
". Please check your query parameters and ensure 'endTs' is greater than 'startTs' or increase 'interval'.");
}
long step = Math.max(interval, 1000);
long intervalCounts = (query.getEndTs() - query.getStartTs()) / step; | if (intervalCounts > maxTsIntervals || intervalCounts < 0) {
throw new IncorrectParameterException("Incorrect TsKvQuery. Number of intervals is to high - " + intervalCounts + ". " +
"Please increase 'interval' parameter for your query or reduce the time range of the query.");
}
}
}
private static void validate(DeleteTsKvQuery query) {
if (query == null) {
throw new IncorrectParameterException("DeleteTsKvQuery can't be null");
} else if (isBlank(query.getKey())) {
throw new IncorrectParameterException("Incorrect DeleteTsKvQuery. Key can't be empty");
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\timeseries\BaseTimeseriesService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WorkplaceRestController
{
@NonNull private final WorkplaceService workplaceService;
@NonNull private final WarehouseService warehouseService;
@GetMapping
public JsonWorkplaceSettings getStatus()
{
return JsonWorkplaceSettings.builder()
.workplaceRequired(workplaceService.isAnyWorkplaceActive())
.assignedWorkplace(workplaceService.getWorkplaceByUserId(Env.getLoggedUserId())
.map(this::toJson)
.orElse(null))
.build();
}
@PostMapping("/{workplaceId}/assign")
public JsonWorkplace assignWorkplace(@PathVariable("workplaceId") @NonNull final Integer workplaceIdInt)
{
final WorkplaceId workplaceId = WorkplaceId.ofRepoId(workplaceIdInt);
workplaceService.assignWorkplace(WorkplaceAssignmentCreateRequest.builder()
.workplaceId(workplaceId)
.userId(Env.getLoggedUserId())
.build());
return getWorkplaceById(workplaceId);
}
@PostMapping("/byQRCode")
public JsonWorkplace getWorkplaceByQRCode(@RequestBody @NonNull final JsonGetWorkplaceByQRCodeRequest request)
{ | final WorkplaceQRCode qrCode = WorkplaceQRCode.ofGlobalQRCodeJsonString(request.getQrCode());
return getWorkplaceById(qrCode.getWorkplaceId());
}
private JsonWorkplace getWorkplaceById(@NonNull final WorkplaceId workplaceId)
{
final Workplace workplace = workplaceService.getById(workplaceId);
return toJson(workplace);
}
private JsonWorkplace toJson(final Workplace workplace)
{
return JsonWorkplace.builder()
.id(workplace.getId())
.name(workplace.getName())
.qrCode(WorkplaceQRCode.ofWorkplace(workplace).toGlobalQRCodeJsonString())
.warehouseName(workplace.getWarehouseId() != null ? warehouseService.getWarehouseName(workplace.getWarehouseId()) : null)
.isUserAssigned(workplaceService.isUserAssigned(Env.getLoggedUserId(), workplace.getId()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\workplace\WorkplaceRestController.java | 2 |
请完成以下Java代码 | public class SignUtil {
public static final String X_PATH_VARIABLE = "x-path-variable";
/**
* @param params
* 所有的请求参数都会在这里进行排序加密
* @return 验证签名结果
*/
public static boolean verifySign(SortedMap<String, String> params,String headerSign) {
if (params == null || StringUtils.isEmpty(headerSign)) {
return false;
}
// 把参数加密
String paramsSign = getParamsSign(params);
log.debug("Param Sign : {}", paramsSign);
return !StringUtils.isEmpty(paramsSign) && headerSign.equals(paramsSign);
}
/**
* @param params
* 所有的请求参数都会在这里进行排序加密
* @return 得到签名
*/
public static String getParamsSign(SortedMap<String, String> params) {
//去掉 Url 里的时间戳
params.remove("_t");
String paramsJsonStr = JSONObject.toJSONString(params);
log.debug("Param paramsJsonStr : {}", paramsJsonStr); | //设置签名秘钥
JeecgBaseConfig jeecgBaseConfig = SpringContextUtils.getBean(JeecgBaseConfig.class);
String signatureSecret = jeecgBaseConfig.getSignatureSecret();
String curlyBracket = SymbolConstant.DOLLAR + SymbolConstant.LEFT_CURLY_BRACKET;
if(oConvertUtils.isEmpty(signatureSecret) || signatureSecret.contains(curlyBracket)){
throw new JeecgBootException("签名密钥 ${jeecg.signatureSecret} 缺少配置 !!");
}
try {
//【issues/I484RW】2.4.6部署后,下拉搜索框提示“sign签名检验失败”
return DigestUtils.md5DigestAsHex((paramsJsonStr + signatureSecret).getBytes("UTF-8")).toUpperCase();
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(),e);
return null;
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\sign\util\SignUtil.java | 1 |
请完成以下Java代码 | public static boolean isLicensed()
{
return true;
}
/**
* Converts given image to PDF.
*
* @param image
* @return PDF file as bytes array.
*/
public static byte[] toPDFBytes(final BufferedImage image)
{
try
{
//
// PDF Image
final ByteArrayOutputStream imageBytes = new ByteArrayOutputStream();
ImageIO.write(image, "PNG", imageBytes);
final Image pdfImage = Image.getInstance(imageBytes.toByteArray());
//
// PDF page size: image size + margins
final com.itextpdf.text.Rectangle pageSize = new com.itextpdf.text.Rectangle(0, 0,
(int)(pdfImage.getWidth() + 100),
(int)(pdfImage.getHeight() + 100));
// PDF document | final com.itextpdf.text.Document document = new com.itextpdf.text.Document(pageSize, 50, 50, 50, 50);
//
// Add image to document
final ByteArrayOutputStream pdfBytes = new ByteArrayOutputStream();
final PdfWriter writer = PdfWriter.getInstance(document, pdfBytes);
writer.open();
document.open();
document.add(pdfImage);
document.close();
writer.close();
return pdfBytes.toByteArray();
}
catch (final Exception e)
{
throw new AdempiereException("Failed converting the image to PDF", e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\pdf\Document.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<Node> getNodes() {
return this.nodes;
}
}
/**
* {@link MasterReplica} implementation backed by properties.
*/
private class PropertiesMasterReplica implements MasterReplica {
private final List<Node> nodes;
PropertiesMasterReplica(DataRedisProperties.Masterreplica properties) {
this.nodes = asNodes(properties.getNodes());
}
@Override
public List<Node> getNodes() {
return this.nodes;
}
}
/**
* {@link Sentinel} implementation backed by properties.
*/
private class PropertiesSentinel implements Sentinel {
private final int database;
private final DataRedisProperties.Sentinel properties;
PropertiesSentinel(int database, DataRedisProperties.Sentinel properties) {
this.database = database;
this.properties = properties;
}
@Override
public int getDatabase() {
return this.database;
}
@Override
public String getMaster() {
String master = this.properties.getMaster();
Assert.state(master != null, "'master' must not be null"); | return master;
}
@Override
public List<Node> getNodes() {
return asNodes(this.properties.getNodes());
}
@Override
public @Nullable String getUsername() {
return this.properties.getUsername();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\PropertiesDataRedisConnectionDetails.java | 2 |
请完成以下Java代码 | public boolean isEUOneStopShop(@NonNull final OrgId orgId)
{
final I_AD_Org org = getById(orgId);
if (org == null)
{
throw new AdempiereException("No Organization found for ID: " + orgId);
}
return org.isEUOneStopShop();
}
@Override
public UserGroupId getSupplierApprovalExpirationNotifyUserGroupID(final OrgId orgId)
{
return getOrgInfoById(orgId).getSupplierApprovalExpirationNotifyUserGroupID();
}
@Override
public UserGroupId getPartnerCreatedFromAnotherOrgNotifyUserGroupID(final OrgId orgId)
{
return getOrgInfoById(orgId).getPartnerCreatedFromAnotherOrgNotifyUserGroupID();
}
@Override | public String getOrgName(@NonNull final OrgId orgId)
{
return getById(orgId).getName();
}
@Override
public boolean isAutoInvoiceFlatrateTerm(@NonNull final OrgId orgId)
{
final OrgInfo orgInfo = getOrgInfoById(orgId);
return orgInfo.isAutoInvoiceFlatrateTerms();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\impl\OrgDAO.java | 1 |
请完成以下Java代码 | public void removeVariables() {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
public void removeVariablesLocal() {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
public void removeVariables(Collection<String> variableNames) {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
public void removeVariablesLocal(Collection<String> variableNames) {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
public Map<String, CoreVariableInstance> getVariableInstances() {
return Collections.emptyMap(); | }
public CoreVariableInstance getVariableInstance(String name) {
return null;
}
public Map<String, CoreVariableInstance> getVariableInstancesLocal() {
return Collections.emptyMap();
}
public CoreVariableInstance getVariableInstanceLocal(String name) {
return null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\el\StartProcessVariableScope.java | 1 |
请完成以下Java代码 | protected void doGet(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
doCommand(request, response);
}
@Override
protected void doPost(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
doCommand(request, response);
}
private void doCommand(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
FrontCommand command = getCommand(request);
command.init(request, response);
command.process(); | }
private FrontCommand getCommand(HttpServletRequest request) {
try {
Class type = Class.forName(
String.format(
"com.baeldung.patterns.intercepting.filter.commands.%sCommand",
request.getParameter("command")
)
);
return (FrontCommand) type
.asSubclass(FrontCommand.class)
.newInstance();
} catch (Exception e) {
return new UnknownCommand();
}
}
} | repos\tutorials-master\patterns-modules\intercepting-filter\src\main\java\com\baeldung\patterns\intercepting\filter\FrontControllerServlet.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ExpressionResolver expressionResolver(ExpressionManager expressionManager, ObjectMapper objectMapper) {
return new ExpressionResolver(expressionManager, objectMapper, new DefaultDelegateInterceptor());
}
@Bean
@ConditionalOnMissingBean
public IntegrationContextBuilder integrationContextBuilder(
ExtensionsVariablesMappingProvider variablesMappingProvider,
ExpressionManager expressionManager
) {
return new IntegrationContextBuilder(variablesMappingProvider, expressionManager);
}
@Bean(name = DefaultActivityBehaviorFactory.DEFAULT_SERVICE_TASK_BEAN_NAME)
@ConditionalOnMissingBean(name = DefaultActivityBehaviorFactory.DEFAULT_SERVICE_TASK_BEAN_NAME)
public DefaultServiceTaskBehavior defaultServiceTaskBehavior(
ApplicationContext applicationContext,
IntegrationContextBuilder integrationContextBuilder,
VariablesPropagator variablesPropagator
) {
return new DefaultServiceTaskBehavior(applicationContext, integrationContextBuilder, variablesPropagator);
}
@Bean | @ConditionalOnMissingBean
public ExtensionsVariablesMappingProvider variablesMappingProvider(
ProcessExtensionService processExtensionService,
ExpressionResolver expressionResolver,
VariableParsingService variableParsingService
) {
return new ExtensionsVariablesMappingProvider(
processExtensionService,
expressionResolver,
variableParsingService
);
}
@Bean
@ConditionalOnMissingBean
public VariablesPropagator variablesPropagator(VariablesCalculator variablesCalculator) {
return new VariablesPropagator(variablesCalculator);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\conf\ConnectorsAutoConfiguration.java | 2 |
请完成以下Java代码 | public ResponseEntity userLogin(@Valid @RequestBody LoginParam loginParam, BindingResult bindingResult) {
Optional<User> optional = userRepository.findByEmail(loginParam.getEmail());
if (optional.isPresent() && encryptService.check(loginParam.getPassword(), optional.get().getPassword())) {
UserData userData = userQueryService.findById(optional.get().getId()).get();
return ResponseEntity.ok(userResponse(new UserWithToken(userData, jwtService.toToken(optional.get()))));
} else {
bindingResult.rejectValue("password", "INVALID", "invalid email or password");
throw new InvalidRequestException(bindingResult);
}
}
private Map<String, Object> userResponse(UserWithToken userWithToken) {
return new HashMap<String, Object>() {{
put("user", userWithToken);
}};
}
}
@Getter
@JsonRootName("user")
@NoArgsConstructor
class LoginParam {
@NotBlank(message = "can't be empty")
@Email(message = "should be an email")
private String email; | @NotBlank(message = "can't be empty")
private String password;
}
@Getter
@JsonRootName("user")
@NoArgsConstructor
class RegisterParam {
@NotBlank(message = "can't be empty")
@Email(message = "should be an email")
private String email;
@NotBlank(message = "can't be empty")
private String username;
@NotBlank(message = "can't be empty")
private String password;
} | repos\spring-boot-realworld-example-app-master (1)\src\main\java\io\spring\api\UsersApi.java | 1 |
请完成以下Java代码 | public class AuthorId implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "name")
private String name;
@Column(name = "age")
private int age;
public AuthorId() {
}
public AuthorId(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int hashCode() {
int hash = 3;
hash = 23 * hash + Objects.hashCode(this.name);
hash = 23 * hash + this.age;
return hash;
} | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final AuthorId other = (AuthorId) obj;
if (this.age != other.age) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
return "AuthorId{" + "name=" + name + ", age=" + age + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootCompositeKeyEmbeddable\src\main\java\com\bookstore\entity\AuthorId.java | 1 |
请完成以下Java代码 | protected void setFrom(Email email, String from) {
String fromAddress = null;
if (from != null) {
fromAddress = from;
} else { // use default configured from address in process engine config
fromAddress = Context.getProcessEngineConfiguration().getMailServerDefaultFrom();
}
try {
email.setFrom(fromAddress);
} catch (EmailException e) {
throw LOG.addSenderException(from, e);
}
}
protected void addCc(Email email, String cc) {
String[] ccs = splitAndTrim(cc);
if (ccs != null) {
for (String c : ccs) {
try {
email.addCc(c);
} catch (EmailException e) {
throw LOG.addCcException(c, e);
}
}
}
}
protected void addBcc(Email email, String bcc) {
String[] bccs = splitAndTrim(bcc);
if (bccs != null) {
for (String b : bccs) {
try {
email.addBcc(b);
} catch (EmailException e) {
throw LOG.addBccException(b, e);
}
}
}
}
protected void setSubject(Email email, String subject) {
email.setSubject(subject != null ? subject : "");
}
protected void setMailServerProperties(Email email) {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
String host = processEngineConfiguration.getMailServerHost();
ensureNotNull("Could not send email: no SMTP host is configured", "host", host);
email.setHostName(host);
int port = processEngineConfiguration.getMailServerPort(); | email.setSmtpPort(port);
email.setTLS(processEngineConfiguration.getMailServerUseTLS());
String user = processEngineConfiguration.getMailServerUsername();
String password = processEngineConfiguration.getMailServerPassword();
if (user != null && password != null) {
email.setAuthentication(user, password);
}
}
protected void setCharset(Email email, String charSetStr) {
if (charset != null) {
email.setCharset(charSetStr);
}
}
protected String[] splitAndTrim(String str) {
if (str != null) {
String[] splittedStrings = str.split(",");
for (int i = 0; i < splittedStrings.length; i++) {
splittedStrings[i] = splittedStrings[i].trim();
}
return splittedStrings;
}
return null;
}
protected String getStringFromField(Expression expression, DelegateExecution execution) {
if(expression != null) {
Object value = expression.getValue(execution);
if(value != null) {
return value.toString();
}
}
return null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\MailActivityBehavior.java | 1 |
请完成以下Java代码 | public static BPartnerContactId ofRepoIdOrNull(
@Nullable final BPartnerId bpartnerId,
@Nullable final Integer contactRepoId)
{
if(bpartnerId == null)
{
return null;
}
final UserId userId = toValidContactUserIdOrNull(contactRepoId);
return userId != null ? of(bpartnerId, userId) : null;
}
@Nullable
public static BPartnerContactId ofRepoIdOrNull(
@Nullable final Integer bpartnerRepoId,
@Nullable final Integer contactRepoId)
{
final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(bpartnerRepoId);
if (bpartnerId == null)
{
return null;
}
final UserId userId = toValidContactUserIdOrNull(contactRepoId);
if (userId == null)
{
return null;
}
return of(bpartnerId, userId);
}
@Nullable
private static UserId toValidContactUserIdOrNull(@Nullable final Integer userRepoId)
{
final UserId userId = userRepoId != null ? UserId.ofRepoIdOrNull(userRepoId) : null;
// NOTE: system user is not a valid BP contact
return userId != null && userId.isRegularUser() ? userId : null;
}
private BPartnerContactId(@NonNull final BPartnerId bpartnerId, @NonNull final UserId userId)
{
this.bpartnerId = bpartnerId;
this.userId = userId;
}
@Override
public int getRepoId()
{
return userId.getRepoId();
}
public static int toRepoId(@Nullable final BPartnerContactId id)
{
return id != null ? id.getRepoId() : -1; | }
@Nullable
public static UserId toUserIdOrNull(@Nullable final BPartnerContactId id)
{
return id != null ? id.getUserId() : null;
}
public static boolean equals(@Nullable final BPartnerContactId id1, @Nullable final BPartnerContactId id2)
{
return Objects.equals(id1, id2);
}
@JsonCreator
public static BPartnerContactId ofJsonString(@NonNull final String idStr)
{
try
{
final List<String> parts = Splitter.on("-").splitToList(idStr);
return of(
BPartnerId.ofRepoId(Integer.parseInt(parts.get(0))),
UserId.ofRepoId(Integer.parseInt(parts.get(1))));
}
catch (Exception ex)
{
throw new AdempiereException("Invalid BPartnerContactId string: " + idStr, ex);
}
}
@JsonValue
public String toJson()
{
return bpartnerId.getRepoId() + "-" + userId.getRepoId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPartnerContactId.java | 1 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CallConversation.class, BPMN_ELEMENT_CALL_CONVERSATION)
.namespaceUri(BPMN20_NS)
.extendsType(ConversationNode.class)
.instanceProvider(new ModelTypeInstanceProvider<CallConversation>() {
public CallConversation newInstance(ModelTypeInstanceContext instanceContext) {
return new CallConversationImpl(instanceContext);
}
});
calledCollaborationRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_CALLED_COLLABORATION_REF)
.qNameAttributeReference(GlobalConversation.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
participantAssociationCollection = sequenceBuilder.elementCollection(ParticipantAssociation.class)
.build();
typeBuilder.build();
} | public CallConversationImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public GlobalConversation getCalledCollaboration() {
return calledCollaborationRefAttribute.getReferenceTargetElement(this);
}
public void setCalledCollaboration(GlobalConversation calledCollaboration) {
calledCollaborationRefAttribute.setReferenceTargetElement(this, calledCollaboration);
}
public Collection<ParticipantAssociation> getParticipantAssociations() {
return participantAssociationCollection.get(this);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CallConversationImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GlobalSunJaasKerberosConfig implements BeanPostProcessor, InitializingBean {
private boolean debug = false;
private String krbConfLocation;
@Override
public void afterPropertiesSet() throws Exception {
if (this.debug) {
System.setProperty("sun.security.krb5.debug", "true");
}
if (this.krbConfLocation != null) {
System.setProperty("java.security.krb5.conf", this.krbConfLocation);
}
}
/**
* Enable debug logs from the Sun Kerberos Implementation. Default is false.
* @param debug true if debug should be enabled
*/
public void setDebug(boolean debug) {
this.debug = debug;
}
/**
* Kerberos config file location can be specified here.
* @param krbConfLocation the path to krb config file
*/
public void setKrbConfLocation(String krbConfLocation) {
this.krbConfLocation = krbConfLocation;
}
// The following methods are not used here. This Bean implements only | // BeanPostProcessor to ensure that it
// is created before any other bean is created, because the system properties needed
// to be set very early
// in the startup-phase, but after the BeanFactoryPostProcessing.
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
} | repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\sun\GlobalSunJaasKerberosConfig.java | 2 |
请完成以下Java代码 | public class DeleteTaskMetricsCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
protected Date timestamp;
public DeleteTaskMetricsCmd(Date timestamp) {
this.timestamp = timestamp;
}
public Void execute(CommandContext commandContext) {
commandContext.getAuthorizationManager().checkCamundaAdminOrPermission(CommandChecker::checkDeleteTaskMetrics);
writeUserOperationLog(commandContext);
commandContext.getMeterLogManager().deleteTaskMetricsByTimestamp(timestamp);
return null; | }
protected void writeUserOperationLog(CommandContext commandContext) {
List<PropertyChange> propertyChanges = new ArrayList<>();
if (timestamp != null) {
propertyChanges.add(new PropertyChange("timestamp", null, timestamp));
}
if (propertyChanges.isEmpty()) {
propertyChanges.add(PropertyChange.EMPTY_CHANGE);
}
commandContext.getOperationLogManager().logTaskMetricsOperation(
UserOperationLogEntry.OPERATION_TYPE_DELETE,
propertyChanges);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteTaskMetricsCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isIncludeCaseVariables() {
return includeCaseVariables;
}
public boolean isIncludeIdentityLinks() {
return includeIdentityLinks;
}
public boolean isBothCandidateAndAssigned() {
return bothCandidateAndAssigned;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public String getDescriptionLikeIgnoreCase() {
return descriptionLikeIgnoreCase;
}
public String getAssigneeLikeIgnoreCase() {
return assigneeLikeIgnoreCase;
}
public String getOwnerLikeIgnoreCase() {
return ownerLikeIgnoreCase;
}
public String getProcessInstanceBusinessKeyLikeIgnoreCase() {
return processInstanceBusinessKeyLikeIgnoreCase;
}
public String getProcessDefinitionKeyLikeIgnoreCase() {
return processDefinitionKeyLikeIgnoreCase;
}
public String getLocale() {
return locale;
}
public boolean isOrActive() {
return orActive;
}
public boolean isUnassigned() {
return unassigned;
}
public boolean isNoDelegationState() {
return noDelegationState;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getCaseDefinitionKeyLike() {
return caseDefinitionKeyLike;
}
public String getCaseDefinitionKeyLikeIgnoreCase() {
return caseDefinitionKeyLikeIgnoreCase;
}
public Collection<String> getCaseDefinitionKeys() {
return caseDefinitionKeys;
}
public boolean isExcludeSubtasks() {
return excludeSubtasks;
}
public boolean isWithLocalizationFallback() {
return withLocalizationFallback;
} | @Override
public List<Task> list() {
cachedCandidateGroups = null;
return super.list();
}
@Override
public List<Task> listPage(int firstResult, int maxResults) {
cachedCandidateGroups = null;
return super.listPage(firstResult, maxResults);
}
@Override
public long count() {
cachedCandidateGroups = null;
return super.count();
}
public List<List<String>> getSafeCandidateGroups() {
return safeCandidateGroups;
}
public void setSafeCandidateGroups(List<List<String>> safeCandidateGroups) {
this.safeCandidateGroups = safeCandidateGroups;
}
public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
}
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
public List<List<String>> getSafeScopeIds() {
return safeScopeIds;
}
public void setSafeScopeIds(List<List<String>> safeScopeIds) {
this.safeScopeIds = safeScopeIds;
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\TaskQueryImpl.java | 2 |
请完成以下Java代码 | public Object getInstance() {
return instance;
}
public void setInstance(Object instance) {
this.instance = instance;
}
@Override
public FlowableListener clone() {
FlowableListener clone = new FlowableListener();
clone.setValues(this);
return clone;
}
public void setValues(FlowableListener otherListener) {
super.setValues(otherListener); | setEvent(otherListener.getEvent());
setSourceState(otherListener.getSourceState());
setTargetState(otherListener.getTargetState());
setImplementation(otherListener.getImplementation());
setImplementationType(otherListener.getImplementationType());
setOnTransaction(otherListener.getOnTransaction());
Optional.ofNullable(otherListener.getScriptInfo()).map(ScriptInfo::clone).ifPresent(this::setScriptInfo);
fieldExtensions = new ArrayList<>();
if (otherListener.getFieldExtensions() != null && !otherListener.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherListener.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\FlowableListener.java | 1 |
请完成以下Java代码 | public void assertAllowCheckout()
{
if (!isAllowCheckout())
{
throw new AdempiereException("Payments with status " + this + " cannot be checked out");
}
}
public BooleanWithReason checkAllowDeleteFromDB()
{
return isNew() ? BooleanWithReason.TRUE : BooleanWithReason.falseBecause("Payments with status " + this + " cannot be deleted from DB");
}
public BooleanWithReason checkAllowDelete(final POSPaymentMethod paymentMethod)
{
if (checkAllowDeleteFromDB().isTrue())
{
return BooleanWithReason.TRUE;
} | else if (paymentMethod.isCash() && isPending())
{
return BooleanWithReason.TRUE;
}
else if (isCanceled() || isFailed())
{
return BooleanWithReason.TRUE;
}
else
{
return BooleanWithReason.falseBecause("Payments with status " + this + " cannot be deleted");
}
}
public boolean isAllowRefund()
{
return isSuccessful();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSPaymentProcessingStatus.java | 1 |
请完成以下Java代码 | public class ApiExceptionHandler {
@SuppressWarnings("rawtypes")
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<ErrorResponse> handle(ConstraintViolationException e) {
ErrorResponse errors = new ErrorResponse();
for (ConstraintViolation violation : e.getConstraintViolations()) {
ErrorItem error = new ErrorItem();
error.setCode(violation.getMessageTemplate());
error.setMessage(violation.getMessage());
errors.addError(error);
}
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
@SuppressWarnings("rawtypes")
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorItem> handle(ResourceNotFoundException e) {
ErrorItem error = new ErrorItem();
error.setMessage(e.getMessage());
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
public static class ErrorItem {
@JsonInclude(JsonInclude.Include.NON_NULL) private String code;
private String message;
public String getCode() {
return code; | }
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
public static class ErrorResponse {
private List<ErrorItem> errors = new ArrayList<>();
public List<ErrorItem> getErrors() {
return errors;
}
public void setErrors(List<ErrorItem> errors) {
this.errors = errors;
}
public void addError(ErrorItem error) {
this.errors.add(error);
}
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\ecommerce\exception\ApiExceptionHandler.java | 1 |
请完成以下Java代码 | private boolean markAsReadNoSave(@NonNull final I_AD_Note notificationPO)
{
if (notificationPO.isProcessed())
{
return false;
}
notificationPO.setProcessed(true);
return true;
}
@Override
public void markAllAsReadByUserId(final UserId adUserId)
{
retrieveNotesByUserId(adUserId)
.create()
.update(this::markAsReadNoSave);
}
private I_AD_Note retrieveAD_Note(final int adNoteId)
{
Check.assumeGreaterThanZero(adNoteId, "adNoteId");
return InterfaceWrapperHelper.loadOutOfTrx(adNoteId, I_AD_Note.class);
}
@Override
public boolean deleteById(final int notificationId)
{
final I_AD_Note notificationPO = retrieveAD_Note(notificationId);
if (notificationPO == null)
{
return false;
}
deleteNotification(notificationPO);
return true;
}
@Override
public void deleteByUserAndTableRecordRef(final @NonNull UserId adUserId, final @NonNull TableRecordReference tableRecordReference)
{
retrieveNotesByUserId(adUserId)
.addEqualsFilter(I_AD_Note.COLUMNNAME_AD_Table_ID, tableRecordReference.getAdTableId())
.addEqualsFilter(I_AD_Note.COLUMNNAME_Record_ID, tableRecordReference.getRecord_ID())
.create()
.delete(false);
}
@Override
public void deleteAllByUserId(final UserId adUserId)
{ | retrieveNotesByUserId(adUserId)
.create()
.list()
.forEach(this::deleteNotification);
}
private void deleteNotification(final I_AD_Note notificationPO)
{
notificationPO.setProcessed(false);
InterfaceWrapperHelper.delete(notificationPO);
}
@Override
public int getUnreadCountByUserId(final UserId adUserId)
{
return retrieveNotesByUserId(adUserId)
.addEqualsFilter(I_AD_Note.COLUMN_Processed, false)
.create()
.count();
}
@Override
public int getTotalCountByUserId(final UserId adUserId)
{
return retrieveNotesByUserId(adUserId)
.create()
.count();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\impl\NotificationRepository.java | 1 |
请完成以下Java代码 | public class TaskTemplateDefinition {
private TemplateDefinition assignee;
private TemplateDefinition candidate;
private boolean isEmailNotificationEnabled = true;
public TemplateDefinition getAssignee() {
return assignee;
}
public boolean isEmailNotificationEnabled() {
return isEmailNotificationEnabled;
}
public void setAssignee(TemplateDefinition assignee) {
this.assignee = assignee;
}
public TemplateDefinition getCandidate() {
return candidate;
}
public void setCandidate(TemplateDefinition candidate) {
this.candidate = candidate;
}
public void setEmailNotificationEnabled(boolean emailNotificationEnabled) {
this.isEmailNotificationEnabled = emailNotificationEnabled;
} | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TaskTemplateDefinition that = (TaskTemplateDefinition) o;
return (
Objects.equals(assignee, that.assignee) &&
Objects.equals(candidate, that.candidate) &&
isEmailNotificationEnabled == that.isEmailNotificationEnabled
);
}
@Override
public int hashCode() {
return Objects.hash(assignee, candidate, isEmailNotificationEnabled);
}
} | repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\TaskTemplateDefinition.java | 1 |
请完成以下Java代码 | public XMLGregorianCalendar getDt() {
return dt;
}
/**
* Sets the value of the dt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDt(XMLGregorianCalendar value) {
this.dt = value;
}
/**
* Gets the value of the rmtdAmt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public ActiveOrHistoricCurrencyAndAmount getRmtdAmt() {
return rmtdAmt;
}
/**
* Sets the value of the rmtdAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setRmtdAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.rmtdAmt = value;
}
/**
* Gets the value of the fmlyMdclInsrncInd property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isFmlyMdclInsrncInd() {
return fmlyMdclInsrncInd;
}
/**
* Sets the value of the fmlyMdclInsrncInd property.
*
* @param value | * allowed object is
* {@link Boolean }
*
*/
public void setFmlyMdclInsrncInd(Boolean value) {
this.fmlyMdclInsrncInd = value;
}
/**
* Gets the value of the mplyeeTermntnInd property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isMplyeeTermntnInd() {
return mplyeeTermntnInd;
}
/**
* Sets the value of the mplyeeTermntnInd property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setMplyeeTermntnInd(Boolean value) {
this.mplyeeTermntnInd = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\Garnishment1.java | 1 |
请完成以下Java代码 | public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** 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 Report Line Set.
@param PA_ReportLineSet_ID Report Line Set */
public void setPA_ReportLineSet_ID (int PA_ReportLineSet_ID)
{
if (PA_ReportLineSet_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_ReportLineSet_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_ReportLineSet_ID, Integer.valueOf(PA_ReportLineSet_ID));
}
/** Get Report Line Set. | @return Report Line Set */
public int getPA_ReportLineSet_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLineSet_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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_PA_ReportLineSet.java | 1 |
请完成以下Java代码 | public PartitionConfig getConfig()
{
return config;
}
public boolean isOldestFirst()
{
return oldestFirst;
}
public OnNotDLMTable getOnNotDLMTable()
{
return onNotDLMTable;
}
/**
* See {@link PartitionerRequestBuilder#setRecordToAttach(ITableRecordReference)}
*
* @return
*/
public ITableRecordReference getRecordToAttach()
{
return recordToAttach;
}
public I_DLM_Partition getPartitionToComplete()
{
return partitionToComplete;
}
@Override
public String toString()
{
return "CreatePartitionRequest [onNotDLMTable=" + onNotDLMTable + ", oldestFirst=" + oldestFirst + ", partitionToComplete=" + partitionToComplete + ", recordToAttach=" + recordToAttach + ", config=" + config + "]";
}
}
/**
* Passed to {@link DLMPartitionerWorkpackageProcessor#schedule(CreatePartitionAsyncRequest, int)} to create a workpackage to invoke {@link IPartitionerService#createPartition(CreatePartitionRequest)} asynchronously.
* The additional members of this class tell the work package processor if it shall enqueue another workpackage after it did its job.
*
* @author metas-dev <dev@metasfresh.com>
*
*/
@Immutable
public static class CreatePartitionAsyncRequest extends CreatePartitionRequest
{
private final int count; | private final Date dontReEnqueueAfter;
private final CreatePartitionRequest partitionRequest;
private CreatePartitionAsyncRequest(
final CreatePartitionRequest partitionRequest,
final int count,
final Date dontReEnqueueAfter)
{
super(partitionRequest.getConfig(),
partitionRequest.isOldestFirst(),
partitionRequest.getRecordToAttach(),
partitionRequest.getPartitionToComplete(),
partitionRequest.getOnNotDLMTable());
this.partitionRequest = partitionRequest; // we use it for the toString() method
this.count = count;
this.dontReEnqueueAfter = dontReEnqueueAfter;
}
/**
* Only enqueue the given number of work packages (one after each other).
*
* @return
*/
public int getCount()
{
return count;
}
/**
* Don't enqueue another workpackage after the given time has passed. One intended usage scenario is to start partitioning in the evening and stop in the morning.
*
* @return never returns <code>null</code>, but might return <code>9999-12-31</code>.
*/
public Date getDontReEnqueueAfter()
{
return dontReEnqueueAfter;
}
@Override
public String toString()
{
return "CreatePartitionAsyncRequest [count=" + count + ", dontReEnqueueAfter=" + dontReEnqueueAfter + ", partitionRequest=" + partitionRequest + "]";
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\PartitionRequestFactory.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception
{
final Iterator<I_C_Doc_Outbound_Log> docOutboundLogRecords = retrieveSelectedDocOutboundLogs();
while (docOutboundLogRecords.hasNext())
{
final I_C_Doc_Outbound_Log docOutboundLogRecord = docOutboundLogRecords.next();
final I_C_Doc_Outbound_Log_Line docOutboundLogLine = retrieveDocumentLogLine(docOutboundLogRecord);
if (docOutboundLogLine != null)
{
printArchive(docOutboundLogLine);
}
}
return MSG_OK;
}
private void printArchive(final I_C_Doc_Outbound_Log_Line logLine)
{
if (logLine == null)
{
//nothing to do
return;
}
final int archiveRecordId = logLine.getAD_Archive_ID();
if (archiveRecordId <= 0)
{
//nothing to do
return;
}
final I_AD_Archive archive = archiveDAO.retrieveArchive(ArchiveId.ofRepoId(archiveRecordId), I_AD_Archive.class);
if (archive == null)
{
//nothing to do
return;
}
final HardwareTrayId hwTrayId = HardwareTrayId.ofRepoIdOrNull(hwPrinterId, hwTrayRecordId);
final PrintArchiveParameters printArchiveParameters = PrintArchiveParameters.builder()
.archive(archive)
.printOutputFacade(printOutputFacade)
.hwPrinterId(hwPrinterId) | .hwTrayId(hwTrayId)
.enforceEnqueueToPrintQueue(true)
.build();
printingQueueBL.printArchive(printArchiveParameters);
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
final SelectionSize selectionSize = context.getSelectionSize();
if (selectionSize.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
private final Iterator<I_C_Doc_Outbound_Log> retrieveSelectedDocOutboundLogs()
{
final IQueryFilter<I_C_Doc_Outbound_Log> filter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false));
final Stream<I_C_Doc_Outbound_Log> stream = queryBL
.createQueryBuilder(I_C_Doc_Outbound_Log.class)
.addOnlyActiveRecordsFilter()
.filter(filter)
.create()
.iterateAndStream();
return stream.iterator();
}
protected I_C_Doc_Outbound_Log_Line retrieveDocumentLogLine(final I_C_Doc_Outbound_Log log)
{
final I_C_Doc_Outbound_Log_Line logLine = docOutboundDAO.retrieveCurrentPDFArchiveLogLineOrNull(log);
return logLine;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\process\C_Doc_Outbound_Log_PrintSelected.java | 1 |
请完成以下Java代码 | private static String discoverClassName(ClassLoader tccl) {
// First services API
String className = getClassNameServices(tccl);
if (className == null) {
// Second el.properties file
className = getClassNameJreDir();
}
if (className == null) {
// Third system property
className = getClassNameSysProp();
}
if (className == null) {
// Fourth - default
className = "org.flowable.common.engine.impl.de.odysseus.el.ExpressionFactoryImpl";
}
return className;
}
private static String getClassNameServices(ClassLoader tccl) {
ExpressionFactory result = null;
ServiceLoader<ExpressionFactory> serviceLoader = ServiceLoader.load(ExpressionFactory.class, tccl);
Iterator<ExpressionFactory> iter = serviceLoader.iterator();
while (result == null && iter.hasNext()) {
result = iter.next();
}
if (result == null) {
return null;
} | return result.getClass().getName();
}
private static String getClassNameJreDir() {
File file = new File(PROPERTY_FILE);
if (file.canRead()) {
try (InputStream is = new FileInputStream(file)) {
Properties props = new Properties();
props.load(is);
String value = props.getProperty(PROPERTY_NAME);
if (value != null && !value.trim().isEmpty()) {
return value.trim();
}
} catch (FileNotFoundException e) {
// Should not happen - ignore it if it does
} catch (IOException ioe) {
throw new ELException("Failed to read " + PROPERTY_NAME, ioe);
}
}
return null;
}
private static String getClassNameSysProp() {
String value = System.getProperty(PROPERTY_NAME);
if (value != null && !value.trim().isEmpty()) {
return value.trim();
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\ExpressionFactory.java | 1 |
请完成以下Java代码 | public boolean canHandle(File artifact) {
try {
if (artifact.isFile() && artifact.getName().endsWith(".xml")) {
Document doc = parse(artifact);
String name = doc.getDocumentElement().getLocalName();
String uri = doc.getDocumentElement().getNamespaceURI();
if ("definitions".equals(name) && "http://www.omg.org/spec/BPMN/20100524/MODEL".equals(uri)) {
return true;
}
}
} catch (Exception e) {
LOGGER.error("Unable to parse deployed file {}", artifact.getAbsolutePath(), e);
}
return false;
}
@Override
public URL transform(URL artifact) {
try {
return new URL("bpmn", null, artifact.toString());
} catch (Exception e) {
LOGGER.error("Unable to build BPMN bundle", e);
return null;
}
}
protected Document parse(File artifact) throws Exception {
if (dbf == null) {
dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
} | DocumentBuilder db = dbf.newDocumentBuilder();
db.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException exception) throws SAXException {
}
@Override
public void error(SAXParseException exception) throws SAXException {
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
throw exception;
}
});
return db.parse(artifact);
}
} | repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\BpmnDeploymentListener.java | 1 |
请完成以下Java代码 | public AppDeploymentBuilder createDeployment() {
return commandExecutor.execute(new Command<>() {
@Override
public AppDeploymentBuilder execute(CommandContext commandContext) {
return new AppDeploymentBuilderImpl();
}
});
}
@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));
}
public AppDeployment deploy(AppDeploymentBuilderImpl deploymentBuilder) {
return commandExecutor.execute(new DeployCmd(deploymentBuilder));
}
@Override
public AppDefinition getAppDefinition(String appDefinitionId) {
return commandExecutor.execute(new GetDeploymentAppDefinitionCmd(appDefinitionId));
}
@Override | public AppModel getAppModel(String appDefinitionId) {
return commandExecutor.execute(new GetAppModelCmd(appDefinitionId));
}
@Override
public String convertAppModelToJson(String appDefinitionId) {
return commandExecutor.execute(new GetAppModelJsonCmd(appDefinitionId));
}
@Override
public void deleteDeployment(String deploymentId, boolean cascade) {
commandExecutor.execute(new DeleteDeploymentCmd(deploymentId, cascade));
}
@Override
public AppDeploymentQuery createDeploymentQuery() {
return configuration.getAppDeploymentEntityManager().createDeploymentQuery();
}
@Override
public AppDefinitionQuery createAppDefinitionQuery() {
return configuration.getAppDefinitionEntityManager().createAppDefinitionQuery();
}
@Override
public void setAppDefinitionCategory(String appDefinitionId, String category) {
commandExecutor.execute(new SetAppDefinitionCategoryCmd(appDefinitionId, category));
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\AppRepositoryServiceImpl.java | 1 |
请完成以下Java代码 | List<UserId> retrieveOrgDefaultContactByGLN(@NonNull final String gln)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final List<Integer> bpartnerIds = queryBL
.createQueryBuilder(I_C_BPartner_Location.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_BPartner_Location.COLUMN_GLN, gln)
.orderBy(I_C_BPartner.COLUMNNAME_C_BPartner_ID) // just to have an predictable order
.create()
.listDistinct(I_C_BPartner_Location.COLUMNNAME_C_BPartner_ID, Integer.class);
return queryBL
.createQueryBuilder(I_AD_User.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_AD_User.COLUMNNAME_C_BPartner_ID, bpartnerIds)
.addEqualsFilter(I_AD_User.COLUMNNAME_IsSubjectMatterContact, true)
.orderBy(I_AD_User.COLUMN_AD_User_ID)
.create()
.listIds().stream().map(UserId::ofRepoId)
.collect(ImmutableList.toImmutableList());
}
// package visibility
OrgId retrieveOrgByGLN(final GLN gln)
{
final BPartnerQuery query = BPartnerQuery.builder()
.gln(gln)
.build();
final Optional<BPartnerId> partnerIdOptional = ibPartnerDAO.retrieveBPartnerIdBy(query); | OrgId billerOrg = OrgId.ANY;
if (partnerIdOptional.isPresent())
{
ibPartnerDAO.getById(partnerIdOptional.get()).getAD_OrgBP_ID();
billerOrg = OrgId.ofRepoIdOrAny(ibPartnerDAO.getById(partnerIdOptional.get()).getAD_Org_ID());
}
return billerOrg;
}
// package visibility
void sendNotificationNotAllFilesImported(final UserId userId, final PInstanceId pinstanceId, final int repoId)
{
final UserNotificationRequest userNotificationRequest = UserNotificationRequest
.builder()
.recipient(Recipient.user(userId))
.contentADMessage(MSG_NOT_ALL_FILES_IMPORTED_NOTIFICATION)
.contentADMessageParam(repoId)
.targetAction(TargetRecordAction.ofRecordAndWindow(TableRecordReference.of(I_AD_PInstance.Table_Name, pinstanceId), WINDOW_ID_AD_PInstance_ID))
.build();
notificationBL.send(userNotificationRequest);
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\imp\process\ImportInvoiceResponseService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Quantity getQtyScheduledForPicking(@NonNull final I_M_ShipmentSchedule shipmentScheduleRecord)
{
return huShipmentScheduleBL.getQtyScheduledForPicking(shipmentScheduleRecord);
}
public ImmutableList<ShipmentSchedule> getBy(@NonNull final ShipmentScheduleQuery query)
{
return shipmentScheduleRepository.getBy(query);
}
private ShipmentScheduleInfo fromRecord(final I_M_ShipmentSchedule shipmentSchedule)
{
return ShipmentScheduleInfo.builder()
.clientAndOrgId(ClientAndOrgId.ofClientAndOrg(shipmentSchedule.getAD_Client_ID(), shipmentSchedule.getAD_Org_ID()))
.warehouseId(shipmentScheduleBL.getWarehouseId(shipmentSchedule))
.bpartnerId(shipmentScheduleBL.getBPartnerId(shipmentSchedule))
.salesOrderLineId(Optional.ofNullable(OrderLineId.ofRepoIdOrNull(shipmentSchedule.getC_OrderLine_ID())))
.productId(ProductId.ofRepoId(shipmentSchedule.getM_Product_ID()))
.asiId(AttributeSetInstanceId.ofRepoIdOrNone(shipmentSchedule.getM_AttributeSetInstance_ID()))
.bestBeforePolicy(ShipmentAllocationBestBeforePolicy.optionalOfNullableCode(shipmentSchedule.getShipmentAllocation_BestBefore_Policy()))
.record(shipmentSchedule)
.build();
}
public void addQtyPickedAndUpdateHU(final AddQtyPickedRequest request)
{
huShipmentScheduleBL.addQtyPickedAndUpdateHU(request);
}
public void deleteByTopLevelHUsAndShipmentScheduleId(@NonNull final Collection<I_M_HU> topLevelHUs, @NonNull final ShipmentScheduleId shipmentScheduleId)
{
huShipmentScheduleBL.deleteByTopLevelHUsAndShipmentScheduleId(topLevelHUs, shipmentScheduleId);
}
public Stream<Packageable> stream(@NonNull final PackageableQuery query)
{
return packagingDAO.stream(query); | }
public Quantity getQtyRemainingToScheduleForPicking(@NonNull final I_M_ShipmentSchedule shipmentScheduleRecord)
{
return huShipmentScheduleBL.getQtyRemainingToScheduleForPicking(shipmentScheduleRecord);
}
public void flagForRecompute(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIds)
{
huShipmentScheduleBL.flagForRecompute(shipmentScheduleIds);
}
public ShipmentScheduleLoadingCache<de.metas.handlingunits.model.I_M_ShipmentSchedule> newHuShipmentLoadingCache()
{
return huShipmentScheduleBL.newLoadingCache();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\shipmentschedule\PickingJobShipmentScheduleService.java | 2 |
请完成以下Java代码 | public void setDD_OrderLine_ID (final int DD_OrderLine_ID)
{
if (DD_OrderLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_DD_OrderLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DD_OrderLine_ID, DD_OrderLine_ID);
}
@Override
public int getDD_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_DD_OrderLine_ID);
}
@Override
public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstance()
{
return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class);
}
@Override
public void setM_AttributeSetInstance(final org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance)
{
set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance);
}
@Override
public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID)
{
if (M_AttributeSetInstance_ID < 0)
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null);
else
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID);
}
@Override
public int getM_AttributeSetInstance_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
} | @Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQtyDelivered (final BigDecimal QtyDelivered)
{
set_Value (COLUMNNAME_QtyDelivered, QtyDelivered);
}
@Override
public BigDecimal getQtyDelivered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDelivered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyInTransit (final BigDecimal QtyInTransit)
{
set_Value (COLUMNNAME_QtyInTransit, QtyInTransit);
}
@Override
public BigDecimal getQtyInTransit()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInTransit);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOrdered (final BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_OrderLine_Alternative.java | 1 |
请完成以下Java代码 | public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getEventDefinitionKey() {
return eventDefinitionKey;
}
public String getEventDefinitionKeyLike() {
return eventDefinitionKeyLike;
} | public String getParentDeploymentId() {
return parentDeploymentId;
}
public String getParentDeploymentIdLike() {
return parentDeploymentIdLike;
}
public String getChannelDefinitionKey() {
return channelDefinitionKey;
}
public String getChannelDefinitionKeyLike() {
return channelDefinitionKeyLike;
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\EventDeploymentQueryImpl.java | 1 |
请完成以下Java代码 | public class AsciiArt {
public AsciiArt() {
}
public void drawString(String text, String artChar, Settings settings) {
BufferedImage image = getImageIntegerMode(settings.width, settings.height);
Graphics2D graphics2D = getGraphics2D(image.getGraphics(), settings);
graphics2D.drawString(text, 6, ((int) (settings.height * 0.67)));
for (int y = 0; y < settings.height; y++) {
StringBuilder stringBuilder = new StringBuilder();
for (int x = 0; x < settings.width; x++) {
stringBuilder.append(image.getRGB(x, y) == -16777216 ? " " : artChar);
}
if (stringBuilder.toString()
.trim()
.isEmpty()) {
continue;
}
System.out.println(stringBuilder);
}
}
private BufferedImage getImageIntegerMode(int width, int height) {
return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
} | private Graphics2D getGraphics2D(Graphics graphics, Settings settings) {
graphics.setFont(settings.font);
Graphics2D graphics2D = (Graphics2D) graphics;
graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
return graphics2D;
}
public class Settings {
public Font font;
public int width;
public int height;
public Settings(Font font, int width, int height) {
this.font = font;
this.width = width;
this.height = height;
}
}
} | repos\tutorials-master\core-java-modules\core-java-console\src\main\java\com\baeldung\asciiart\AsciiArt.java | 1 |
请完成以下Java代码 | public int getMD_Candidate_Transaction_Detail_ID()
{
return get_ValueAsInt(COLUMNNAME_MD_Candidate_Transaction_Detail_ID);
}
@Override
public void setMD_Stock_ID (final int MD_Stock_ID)
{
if (MD_Stock_ID < 1)
set_Value (COLUMNNAME_MD_Stock_ID, null);
else
set_Value (COLUMNNAME_MD_Stock_ID, MD_Stock_ID);
}
@Override
public int getMD_Stock_ID()
{
return get_ValueAsInt(COLUMNNAME_MD_Stock_ID);
}
@Override
public void setMovementQty (final BigDecimal MovementQty)
{
set_Value (COLUMNNAME_MovementQty, MovementQty);
} | @Override
public BigDecimal getMovementQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MovementQty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTransactionDate (final @Nullable java.sql.Timestamp TransactionDate)
{
set_Value (COLUMNNAME_TransactionDate, TransactionDate);
}
@Override
public java.sql.Timestamp getTransactionDate()
{
return get_ValueAsTimestamp(COLUMNNAME_TransactionDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_Transaction_Detail.java | 1 |
请完成以下Java代码 | @Nullable Authentication getAuthentication() {
return this.authen;
}
@Nullable Subject getSubject() {
return this.subject;
}
/**
* Initialize this <code>LoginModule</code>. Ignores the callback handler, since the
* code establishing the <code>LoginContext</code> likely won't provide one that
* understands Spring Security. Also ignores the <code>sharedState</code> and
* <code>options</code> parameters, since none are recognized.
* @param subject the <code>Subject</code> to be authenticated.
* @param callbackHandler is ignored
* @param sharedState is ignored
* @param options are ignored
*/
@Override
@SuppressWarnings("unchecked")
public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
this.subject = subject;
if (options != null) {
this.ignoreMissingAuthentication = "true".equals(options.get("ignoreMissingAuthentication"));
}
}
/**
* Authenticate the <code>Subject</code> (phase one) by extracting the Spring Security
* <code>Authentication</code> from the current <code>SecurityContext</code>.
* @return true if the authentication succeeded, or false if this
* <code>LoginModule</code> should be ignored.
* @throws LoginException if the authentication fails
*/
@Override
public boolean login() throws LoginException {
this.authen = this.securityContextHolderStrategy.getContext().getAuthentication();
if (this.authen != null) {
return true;
}
String msg = "Login cannot complete, authentication not found in security context"; | if (!this.ignoreMissingAuthentication) {
throw new LoginException(msg);
}
log.warn(msg);
return false;
}
/**
* Log out the <code>Subject</code>.
* @return true if this method succeeded, or false if this <code>LoginModule</code>
* should be ignored.
*/
@Override
public boolean logout() {
if (this.authen == null) {
return false;
}
Assert.notNull(this.subject, "subject cannot be null");
this.subject.getPrincipals().remove(this.authen);
this.authen = null;
return true;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\jaas\SecurityContextLoginModule.java | 1 |
请完成以下Java代码 | protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if(!isHUEditorView())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view");
}
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (selectedRowIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (!streamSelectedHUIds(rowsFilter).findAny().isPresent())
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(WEBUI_HU_Constants.MSG_WEBUI_ONLY_TOP_LEVEL_HU));
}
return ProcessPreconditionsResolution.accept(); | }
@Override
@RunOutOfTrx
protected String doIt()
{
final Stream<I_M_HU> selectedTopLevelHUs = streamSelectedHUs(rowsFilter);
HUMoveToDirectWarehouseService.newInstance()
.setDocumentsCollection(documentsCollection)
.setHUView(getView())
.setMovementDate(SystemTime.asInstant()) // now
// .setDescription(description) // none
.setFailOnFirstError(true)
.setFailIfNoHUs(true)
.setLoggable(this)
.move(selectedTopLevelHUs.iterator());
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_MoveToDirectWarehouse.java | 1 |
请完成以下Java代码 | public void setQuantityOnHand (final @Nullable BigDecimal QuantityOnHand)
{
set_ValueNoCheck (COLUMNNAME_QuantityOnHand, QuantityOnHand);
}
@Override
public BigDecimal getQuantityOnHand()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QuantityOnHand);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotal_Qty_Five_Weeks_Ago (final @Nullable BigDecimal Total_Qty_Five_Weeks_Ago)
{
set_ValueNoCheck (COLUMNNAME_Total_Qty_Five_Weeks_Ago, Total_Qty_Five_Weeks_Ago);
}
@Override
public BigDecimal getTotal_Qty_Five_Weeks_Ago()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Total_Qty_Five_Weeks_Ago);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotal_Qty_Four_Weeks_Ago (final @Nullable BigDecimal Total_Qty_Four_Weeks_Ago)
{
set_ValueNoCheck (COLUMNNAME_Total_Qty_Four_Weeks_Ago, Total_Qty_Four_Weeks_Ago);
}
@Override
public BigDecimal getTotal_Qty_Four_Weeks_Ago()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Total_Qty_Four_Weeks_Ago);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotal_Qty_One_Week_Ago (final @Nullable BigDecimal Total_Qty_One_Week_Ago)
{
set_ValueNoCheck (COLUMNNAME_Total_Qty_One_Week_Ago, Total_Qty_One_Week_Ago);
}
@Override
public BigDecimal getTotal_Qty_One_Week_Ago()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Total_Qty_One_Week_Ago);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotal_Qty_Six_Weeks_Ago (final @Nullable BigDecimal Total_Qty_Six_Weeks_Ago)
{
set_ValueNoCheck (COLUMNNAME_Total_Qty_Six_Weeks_Ago, Total_Qty_Six_Weeks_Ago);
}
@Override | public BigDecimal getTotal_Qty_Six_Weeks_Ago()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Total_Qty_Six_Weeks_Ago);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotal_Qty_Three_Weeks_Ago (final @Nullable BigDecimal Total_Qty_Three_Weeks_Ago)
{
set_ValueNoCheck (COLUMNNAME_Total_Qty_Three_Weeks_Ago, Total_Qty_Three_Weeks_Ago);
}
@Override
public BigDecimal getTotal_Qty_Three_Weeks_Ago()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Total_Qty_Three_Weeks_Ago);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotal_Qty_Two_Weeks_Ago (final @Nullable BigDecimal Total_Qty_Two_Weeks_Ago)
{
set_ValueNoCheck (COLUMNNAME_Total_Qty_Two_Weeks_Ago, Total_Qty_Two_Weeks_Ago);
}
@Override
public BigDecimal getTotal_Qty_Two_Weeks_Ago()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Total_Qty_Two_Weeks_Ago);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\replenishment\X_M_Material_Needs_Planner_V.java | 1 |
请完成以下Java代码 | private void addToModelUserDetails(HttpSession session) {
log.info("================= addToModelUserDetails ============================");
String loggedUsername = SecurityContextHolder.getContext()
.getAuthentication()
.getName();
session.setAttribute("username", loggedUsername);
log.info("user(" + loggedUsername + ") session : " + session);
log.info("================= addToModelUserDetails ============================");
}
/**
* Used when model is available
*/
private void addToModelUserDetails(ModelAndView model) {
log.info("================= addToModelUserDetails ============================");
String loggedUsername = SecurityContextHolder.getContext()
.getAuthentication()
.getName();
model.addObject("loggedUsername", loggedUsername);
log.trace("session : " + model.getModel());
log.info("================= addToModelUserDetails ============================"); | }
public static boolean isRedirectView(ModelAndView mv) {
String viewName = mv.getViewName();
if (viewName.startsWith("redirect:/")) {
return true;
}
View view = mv.getView();
return (view != null && view instanceof SmartView && ((SmartView) view).isRedirectView());
}
public static boolean isUserLogged() {
try {
return !SecurityContextHolder.getContext()
.getAuthentication()
.getName()
.equals("anonymousUser");
} catch (Exception e) {
return false;
}
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-mvc-custom\src\main\java\com\baeldung\web\interceptor\UserInterceptor.java | 1 |
请完成以下Java代码 | public Map<String, VariableInstance> getVariableInstancesLocal(String taskId) {
return commandExecutor.execute(new GetTaskVariableInstancesCmd(taskId, null, true));
}
@Override
public Map<String, VariableInstance> getVariableInstancesLocal(String taskId, Collection<String> variableNames) {
return commandExecutor.execute(new GetTaskVariableInstancesCmd(taskId, variableNames, true));
}
@Override
public void setAssignee(String taskId, String userId) {
commandExecutor.execute(new AddIdentityLinkCmd(taskId, userId, AddIdentityLinkCmd.IDENTITY_USER,
IdentityLinkType.ASSIGNEE));
}
@Override
public void setOwner(String taskId, String userId) {
commandExecutor.execute(new AddIdentityLinkCmd(taskId, userId, AddIdentityLinkCmd.IDENTITY_USER,
IdentityLinkType.OWNER));
}
@Override
public void addUserIdentityLink(String taskId, String userId, String identityLinkType) {
commandExecutor.execute(new AddIdentityLinkCmd(taskId, userId, AddIdentityLinkCmd.IDENTITY_USER,
identityLinkType));
}
@Override
public void addGroupIdentityLink(String taskId, String groupId, String identityLinkType) {
commandExecutor.execute(new AddIdentityLinkCmd(taskId, groupId, AddIdentityLinkCmd.IDENTITY_GROUP,
identityLinkType));
}
@Override
public void deleteGroupIdentityLink(String taskId, String groupId, String identityLinkType) {
commandExecutor.execute(new DeleteIdentityLinkCmd(taskId, null, groupId, identityLinkType)); | }
@Override
public void deleteUserIdentityLink(String taskId, String userId, String identityLinkType) {
commandExecutor.execute(new DeleteIdentityLinkCmd(taskId, userId, null, identityLinkType));
}
@Override
public List<IdentityLink> getIdentityLinksForTask(String taskId) {
return commandExecutor.execute(new GetIdentityLinksForTaskCmd(taskId));
}
@Override
public TaskBuilder createTaskBuilder() {
return new CmmnTaskBuilderImpl(commandExecutor, configuration);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnTaskServiceImpl.java | 1 |
请完成以下Java代码 | static Mono<Map<String, Object>> getConfigurationForIssuerLocation(String issuer, WebClient web) {
return getConfiguration(issuer, web, oidc(issuer), oidcRfc8414(issuer), oauth(issuer));
}
static UriComponents oidc(String issuer) {
UriComponents uri = UriComponentsBuilder.fromUriString(issuer).build();
// @formatter:off
return UriComponentsBuilder.newInstance().uriComponents(uri)
.replacePath(uri.getPath() + OIDC_METADATA_PATH)
.build();
// @formatter:on
}
static UriComponents oidcRfc8414(String issuer) {
UriComponents uri = UriComponentsBuilder.fromUriString(issuer).build();
// @formatter:off
return UriComponentsBuilder.newInstance().uriComponents(uri)
.replacePath(OIDC_METADATA_PATH + uri.getPath())
.build();
// @formatter:on
}
static UriComponents oauth(String issuer) {
UriComponents uri = UriComponentsBuilder.fromUriString(issuer).build();
// @formatter:off
return UriComponentsBuilder.newInstance().uriComponents(uri)
.replacePath(OAUTH_METADATA_PATH + uri.getPath())
.build();
// @formatter:on
}
private static Mono<Map<String, Object>> getConfiguration(String issuer, WebClient web, UriComponents... uris) {
String errorMessage = "Unable to resolve the Configuration with the provided Issuer of " + "\"" + issuer + "\"";
return Flux.just(uris)
.concatMap((uri) -> web.get().uri(uri.toUriString()).retrieve().bodyToMono(STRING_OBJECT_MAP))
.flatMap((configuration) -> {
if (configuration.get("jwks_uri") == null) {
return Mono.error(() -> new IllegalArgumentException("The public JWK set URI must not be null")); | }
return Mono.just(configuration);
})
.onErrorContinue((ex) -> ex instanceof WebClientResponseException
&& ((WebClientResponseException) ex).getStatusCode().is4xxClientError(), (ex, object) -> {
})
.onErrorMap(RuntimeException.class,
(ex) -> (ex instanceof IllegalArgumentException) ? ex
: new IllegalArgumentException(errorMessage, ex))
.next()
.switchIfEmpty(Mono.error(() -> new IllegalArgumentException(errorMessage)));
}
private ReactiveJwtDecoderProviderConfigurationUtils() {
}
} | repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\ReactiveJwtDecoderProviderConfigurationUtils.java | 1 |
请完成以下Java代码 | public boolean retainAll(Collection<?> c)
{
boolean modified = false;
Iterator<String> it = iterator();
while (it.hasNext())
{
if (!c.contains(it.next()))
{
it.remove();
modified = true;
}
}
return modified;
}
@Override
public boolean removeAll(Collection<?> c)
{
boolean modified = false;
Iterator<?> it = iterator();
while (it.hasNext())
{
if (c.contains(it.next())) | {
it.remove();
modified = true;
}
}
return modified;
}
@Override
public void clear()
{
sourceNode = new MDAGNode(false);
simplifiedSourceNode = null;
if (equivalenceClassMDAGNodeHashMap != null)
equivalenceClassMDAGNodeHashMap.clear();
mdagDataArray = null;
charTreeSet.clear();
transitionCount = 0;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\MDAG\MDAGSet.java | 1 |
请完成以下Java代码 | public class DmnHitPolicyLogger extends DmnLogger {
public DmnHitPolicyException uniqueHitPolicyOnlyAllowsSingleMatchingRule(List<DmnEvaluatedDecisionRule> matchingRules) {
return new DmnHitPolicyException(exceptionMessage(
"001",
"Hit policy '{}' only allows a single rule to match. Actually match rules: '{}'.", HitPolicy.UNIQUE, matchingRules)
);
}
public DmnHitPolicyException anyHitPolicyRequiresThatAllOutputsAreEqual(List<DmnEvaluatedDecisionRule> matchingRules) {
return new DmnHitPolicyException(exceptionMessage(
"002",
"Hit policy '{}' only allows multiple matching rules with equal output. Matching rules: '{}'.", HitPolicy.ANY, matchingRules)
);
} | public DmnHitPolicyException aggregationNotApplicableOnCompoundOutput(BuiltinAggregator aggregator, Map<String, DmnEvaluatedOutput> outputEntries) {
return new DmnHitPolicyException(exceptionMessage(
"003",
"Unable to execute aggregation '{}' on compound decision output '{}'. Only one output entry allowed.", aggregator, outputEntries)
);
}
public DmnHitPolicyException unableToConvertValuesToAggregatableTypes(List<TypedValue> values, Class<?>... targetClasses) {
return new DmnHitPolicyException(exceptionMessage(
"004",
"Unable to convert value '{}' to a support aggregatable type '{}'.", values, targetClasses)
);
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\hitpolicy\DmnHitPolicyLogger.java | 1 |
请完成以下Java代码 | public void invalidateJWT(HttpServletRequest request) {
String jwt = getJwtFromRequest(request);
String username = getUsernameFromJWT(jwt);
// 从redis中清除JWT
stringRedisTemplate.delete(Consts.REDIS_JWT_KEY_PREFIX + username);
}
/**
* 根据 jwt 获取用户名
*
* @param jwt JWT
* @return 用户名
*/
public String getUsernameFromJWT(String jwt) {
Claims claims = parseJWT(jwt);
return claims.getSubject(); | }
/**
* 从 request 的 header 中获取 JWT
*
* @param request 请求
* @return JWT
*/
public String getJwtFromRequest(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (StrUtil.isNotBlank(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
return null;
}
} | repos\spring-boot-demo-master\demo-rbac-security\src\main\java\com\xkcoding\rbac\security\util\JwtUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DemoApplication implements CommandLineRunner {
private ProcessRuntime processRuntime;
public DemoApplication(ProcessRuntime processRuntime) {
this.processRuntime = processRuntime;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@PostMapping("/documents")
public String processFile(@RequestBody String content) {
ProcessInstance processInstance = processRuntime.start(
ProcessPayloadBuilder.start()
.withProcessDefinitionKey("categorizeProcess")
.withVariable("fileContent", content)
.build()
);
String message = ">>> Created Process Instance: " + processInstance;
System.out.println(message);
return message;
}
@GetMapping("/process-definitions")
public List<ProcessDefinition> getProcessDefinition() {
return processRuntime.processDefinitions(Pageable.of(0, 100)).getContent();
}
@Override
public void run(String... args) {}
@Bean
public Connector processTextConnector() {
return integrationContext -> {
Map<String, Object> inBoundVariables = integrationContext.getInBoundVariables();
String contentToProcess = (String) inBoundVariables.get("fileContent");
// Logic Here to decide if content is approved or not
if (contentToProcess.contains("activiti")) {
integrationContext.addOutBoundVariable("approved", true); | } else {
integrationContext.addOutBoundVariable("approved", false);
}
return integrationContext;
};
}
@Bean
public Connector tagTextConnector() {
return integrationContext -> {
String contentToTag = (String) integrationContext.getInBoundVariables().get("fileContent");
contentToTag += " :) ";
integrationContext.addOutBoundVariable("fileContent", contentToTag);
System.out.println("Final Content: " + contentToTag);
return integrationContext;
};
}
@Bean
public Connector discardTextConnector() {
return integrationContext -> {
String contentToDiscard = (String) integrationContext.getInBoundVariables().get("fileContent");
contentToDiscard += " :( ";
integrationContext.addOutBoundVariable("fileContent", contentToDiscard);
System.out.println("Final Content: " + contentToDiscard);
return integrationContext;
};
}
} | repos\Activiti-develop\activiti-examples\activiti-api-web-example\src\main\java\org\activiti\examples\DemoApplication.java | 2 |
请完成以下Java代码 | public static StockEstimateCreatedEvent cast(@NonNull final AbstractStockEstimateEvent event)
{
return (StockEstimateCreatedEvent)event;
}
public static final String TYPE = "StockEstimateDeletedEvent";
@JsonCreator
@Builder
public StockEstimateDeletedEvent(
@NonNull @JsonProperty("eventDescriptor") final EventDescriptor eventDescriptor,
@NonNull @JsonProperty("materialDescriptor") final MaterialDescriptor materialDescriptor,
@NonNull @JsonProperty("date") final Instant date,
@JsonProperty("plantId") final int plantId,
@JsonProperty("freshQtyOnHandId") final int freshQtyOnHandId,
@JsonProperty("freshQtyOnHandLineId") final int freshQtyOnHandLineId,
@NonNull @JsonProperty("eventDate") final Instant eventDate
)
{
super(eventDescriptor,
materialDescriptor,
date, | plantId,
freshQtyOnHandId,
freshQtyOnHandLineId,
null /*qtyStockEstimateSeqNo*/,
eventDate);
}
@Override
public BigDecimal getQuantityDelta()
{
return getMaterialDescriptor().getQuantity().negate();
}
@Override
public String getEventName() {return TYPE;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\stockestimate\StockEstimateDeletedEvent.java | 1 |
请完成以下Java代码 | public class ConsumerRecordMetadata {
private final RecordMetadata delegate;
private final TimestampType timestampType;
public ConsumerRecordMetadata(RecordMetadata delegate, TimestampType timestampType) {
this.delegate = delegate;
this.timestampType = timestampType;
}
public boolean hasOffset() {
return this.delegate.hasOffset();
}
public long offset() {
return this.delegate.offset();
}
public boolean hasTimestamp() {
return this.delegate.hasTimestamp();
}
public long timestamp() {
return this.delegate.timestamp();
}
public int serializedKeySize() {
return this.delegate.serializedKeySize();
}
public int serializedValueSize() {
return this.delegate.serializedValueSize();
}
public String topic() {
return this.delegate.topic();
} | public int partition() {
return this.delegate.partition();
}
public TimestampType timestampType() {
return this.timestampType;
}
@Override
public int hashCode() {
return this.delegate.hashCode() + this.timestampType.name().hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ConsumerRecordMetadata)) {
return false;
}
ConsumerRecordMetadata crm = (ConsumerRecordMetadata) obj;
return this.delegate.equals(crm.delegate)
&& this.timestampType.equals(crm.timestampType());
}
@Override
public String toString() {
return this.delegate.toString();
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\adapter\ConsumerRecordMetadata.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CustomerReturnInOutRecordFactory
{
private final IInOutDAO inOutDAO = Services.get(IInOutDAO.class);
private final IWarehouseBL warehouseBL = Services.get(IWarehouseBL.class);
private final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
public I_M_InOut createCustomerReturnHeader(@NonNull final CreateCustomerReturnHeaderReq request)
{
final I_M_InOut inOut = InterfaceWrapperHelper.newInstance(I_M_InOut.class);
inOut.setAD_Org_ID(request.getOrgId().getRepoId());
ReturnsInOutHeaderFiller.newInstance()
.setMovementDate(asTimestamp(request.getMovementDate()))
.setDateReceived(asTimestamp(request.getDateReceived()))
.setMovementType(MOVEMENTTYPE_CustomerReturns)
.setReturnsDocTypeIdProvider(request.getReturnDocTypeIdProvider())
.setBPartnerId(request.getBPartnerLocationId().getBpartnerId().getRepoId())
.setBPartnerLocationId(request.getBPartnerLocationId().getRepoId())
.setWarehouseId(request.getWarehouseId().getRepoId())
.setOrder(request.getOrder())
.setExternalId(request.getExternalId())
.setExternalResourceURL(request.getExternalResourceURL())
.fill(inOut);
InterfaceWrapperHelper.saveRecord(inOut);
return inOut;
}
public I_M_InOutLine createReturnLine(@NonNull final CreateCustomerReturnLineReq request)
{
final I_M_InOut returnHeader = inOutDAO.getById(request.getHeaderId(), I_M_InOut.class);
final I_M_InOutLine returnLine = InterfaceWrapperHelper.newInstance(I_M_InOutLine.class);
returnLine.setAD_Org_ID(returnHeader.getAD_Org_ID());
returnLine.setM_InOut_ID(request.getHeaderId().getRepoId());
returnLine.setM_Product_ID(request.getProductId().getRepoId());
returnLine.setC_UOM_ID(request.getQtyReturned().getUomId().getRepoId());
returnLine.setQtyEntered(request.getQtyReturned().toBigDecimal());
final Quantity movementQty = uomConversionBL.convertToProductUOM(request.getQtyReturned(), request.getProductId()); | returnLine.setMovementQty(movementQty.toBigDecimal());
final WarehouseId warehouseId = WarehouseId.ofRepoId(returnHeader.getM_Warehouse_ID());
returnLine.setM_Locator_ID(warehouseBL.getOrCreateDefaultLocatorId(warehouseId).getRepoId());
if (request.getAttributeSetInstanceId() != null)
{
returnLine.setM_AttributeSetInstance_ID(request.getAttributeSetInstanceId().getRepoId());
}
returnLine.setIsWarrantyCase(request.isWarrantyCase());
if (request.getHupiItemProductId() != null && request.getQtyTU() != null)
{
returnLine.setQtyEnteredTU(request.getQtyTU().toBigDecimal());
returnLine.setM_HU_PI_Item_Product_ID(request.getHupiItemProductId().getRepoId());
}
if (request.getOriginShipmentLineId() != null)
{
returnLine.setReturn_Origin_InOutLine_ID(request.getOriginShipmentLineId().getRepoId());
}
InterfaceWrapperHelper.save(returnLine);
return returnLine;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\customer\CustomerReturnInOutRecordFactory.java | 2 |
请完成以下Java代码 | public void addModelInterceptor(final IModelInterceptor interceptor)
{
Check.assumeNotNull(interceptor, "interceptor not null");
interceptors.addIfAbsent(interceptor);
if (interceptor instanceof IUserLoginListener)
{
userLoginListeners.addIfAbsent((IUserLoginListener)interceptor);
}
}
public void removeModelInterceptor(final IModelInterceptor interceptor)
{
Check.assumeNotNull(interceptor, "interceptor not null");
interceptors.remove(interceptor);
if (interceptor instanceof IUserLoginListener)
{
userLoginListeners.remove(interceptor);
}
}
@Override
public void initialize(final IModelValidationEngine engine, final I_AD_Client client)
{
if (client != null)
{
adClientId = client.getAD_Client_ID();
}
for (final IModelInterceptor interceptor : interceptors)
{
interceptor.initialize(engine, client);
}
}
@Override
public int getAD_Client_ID()
{
return adClientId;
}
@Override
public void onModelChange(final Object model, final ModelChangeType changeType) throws Exception
{
for (final IModelInterceptor interceptor : interceptors)
{
interceptor.onModelChange(model, changeType);
}
}
@Override
public void onDocValidate(final Object model, final DocTimingType timing) throws Exception
{
for (final IModelInterceptor interceptor : interceptors)
{
interceptor.onDocValidate(model, timing);
}
} | @Override
public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
// NOTE: we use "interceptors" instead of userLoginListeners because the "onUserLogin" it's implemented on IModelInterceptor level
for (final IModelInterceptor interceptor : interceptors)
{
interceptor.onUserLogin(AD_Org_ID, AD_Role_ID, AD_User_ID);
}
}
@Override
public void beforeLogout(final MFSession session)
{
for (final IUserLoginListener listener : userLoginListeners)
{
listener.beforeLogout(session);
}
}
@Override
public void afterLogout(final MFSession session)
{
for (final IUserLoginListener listener : userLoginListeners)
{
listener.afterLogout(session);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\CompositeModelInterceptor.java | 1 |
请完成以下Java代码 | public void setM_Warehouse(org.compiere.model.I_M_Warehouse M_Warehouse)
{
set_ValueFromPO(COLUMNNAME_M_Warehouse_ID, org.compiere.model.I_M_Warehouse.class, M_Warehouse);
}
/** Set Lager.
@param M_Warehouse_ID
Lager oder Ort für Dienstleistung
*/
@Override
public void setM_Warehouse_ID (int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID));
}
/** Get Lager.
@return Lager oder Ort für Dienstleistung
*/
@Override
public int getM_Warehouse_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set ResetBufferInterval.
@param ResetBufferInterval ResetBufferInterval */
@Override | public void setResetBufferInterval (java.math.BigDecimal ResetBufferInterval)
{
set_Value (COLUMNNAME_ResetBufferInterval, ResetBufferInterval);
}
/** Get ResetBufferInterval.
@return ResetBufferInterval */
@Override
public java.math.BigDecimal getResetBufferInterval ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ResetBufferInterval);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inout\model\X_M_Material_Balance_Config.java | 1 |
请完成以下Java代码 | public MemoryUsageInfo getHeap() {
return this.heap;
}
public MemoryUsageInfo getNonHeap() {
return this.nonHeap;
}
/**
* Garbage Collector information for the process. This list provides details about
* the currently used GC algorithms selected by the user or JVM ergonomics. It
* might not be trivial to know the used GC algorithms since that usually depends
* on the {@link Runtime#availableProcessors()} (see:
* {@link ProcessInfo#getCpus()}) and the available memory (see:
* {@link MemoryUsageInfo}).
* @return {@link List} of {@link GarbageCollectorInfo}.
* @since 3.5.0
*/
public List<GarbageCollectorInfo> getGarbageCollectors() {
return this.garbageCollectors;
}
public static class MemoryUsageInfo {
private final MemoryUsage memoryUsage;
MemoryUsageInfo(MemoryUsage memoryUsage) {
this.memoryUsage = memoryUsage;
}
public long getInit() {
return this.memoryUsage.getInit();
}
public long getUsed() {
return this.memoryUsage.getUsed();
}
public long getCommitted() {
return this.memoryUsage.getCommitted();
}
public long getMax() { | return this.memoryUsage.getMax();
}
}
/**
* Garbage collection information.
*
* @since 3.5.0
*/
public static class GarbageCollectorInfo {
private final String name;
private final long collectionCount;
GarbageCollectorInfo(GarbageCollectorMXBean garbageCollectorMXBean) {
this.name = garbageCollectorMXBean.getName();
this.collectionCount = garbageCollectorMXBean.getCollectionCount();
}
public String getName() {
return this.name;
}
public long getCollectionCount() {
return this.collectionCount;
}
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\ProcessInfo.java | 1 |
请完成以下Java代码 | public StringBuilder createBuilder(String field, String str, boolean not, boolean addQuot) {
StringBuilder sb = new StringBuilder(field).append(":(");
if (not) {
sb.append(" NOT ");
}
this.addQuotEffect(sb, str, addQuot);
return sb;
}
public QueryStringBuilder and(String str) {
return this.and(str, true);
}
public QueryStringBuilder and(String str, boolean addQuot) {
builder.append(" AND ");
this.addQuot(str, addQuot);
return this;
}
public QueryStringBuilder or(String str) {
return this.or(str, true);
}
public QueryStringBuilder or(String str, boolean addQuot) {
builder.append(" OR ");
this.addQuot(str, addQuot);
return this;
}
public QueryStringBuilder not(String str) {
return this.not(str, true);
}
public QueryStringBuilder not(String str, boolean addQuot) {
builder.append(" NOT ");
this.addQuot(str, addQuot);
return this; | }
/**
* 添加双引号(模糊查询,不能加双引号)
*/
private QueryStringBuilder addQuot(String str, boolean addQuot) {
return this.addQuotEffect(this.builder, str, addQuot);
}
/**
* 是否在两边加上双引号
* @param builder
* @param str
* @param addQuot
* @return
*/
private QueryStringBuilder addQuotEffect(StringBuilder builder, String str, boolean addQuot) {
if (addQuot) {
builder.append('"');
}
builder.append(str);
if (addQuot) {
builder.append('"');
}
return this;
}
@Override
public String toString() {
return builder.append(")").toString();
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\es\QueryStringBuilder.java | 1 |
请完成以下Java代码 | private static INamePairPredicate computePostQueryPredicate(@NonNull final ImmutableList<SqlLookupFilter> filters)
{
if (filters.isEmpty())
{
return NamePairPredicates.ACCEPT_ALL;
}
final NamePairPredicates.Composer builder = NamePairPredicates.compose();
for (SqlLookupFilter filter : filters)
{
final INamePairPredicate postQueryPredicate = filter.getPostQueryPredicate();
if (postQueryPredicate != null)
{
builder.add(postQueryPredicate);
}
}
return builder.build();
}
private static ImmutableSet<String> computeDependsOnTableNames(final ImmutableList<SqlLookupFilter> filters)
{
return filters.stream()
.flatMap(filter -> filter.getDependsOnTableNames().stream())
.collect(ImmutableSet.toImmutableSet());
}
private static ImmutableSet<String> computeDependsOnFieldNames(final ImmutableList<SqlLookupFilter> filters)
{
return filters.stream()
.flatMap(filter -> filter.getDependsOnFieldNames().stream())
.collect(ImmutableSet.toImmutableSet());
} | public CompositeSqlLookupFilter withOnlyScope(@Nullable LookupDescriptorProvider.LookupScope onlyScope)
{
return !Objects.equals(this.onlyScope, onlyScope)
? new CompositeSqlLookupFilter(this.allFilters, onlyScope, this.onlyForAvailableParameterNames)
: this;
}
public CompositeSqlLookupFilter withOnlyForAvailableParameterNames(@Nullable Set<String> onlyForAvailableParameterNames)
{
return !Objects.equals(this.onlyForAvailableParameterNames, onlyForAvailableParameterNames)
? new CompositeSqlLookupFilter(this.allFilters, this.onlyScope, onlyForAvailableParameterNames)
: this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\CompositeSqlLookupFilter.java | 1 |
请完成以下Java代码 | public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
return false;
}
@Override
public int hashCode()
{
// NOTE: we implemented this method only to get rid of "implemented equals() but not hashCode() warning"
return super.hashCode();
}
@Override
public String toString()
{
if (!isAvailable())
{
return DEBUG ? "<GARBAGED: " + valueStr + ">" : "<GARBAGED>";
}
else
{
return String.valueOf(this.get()); | }
}
}
/**
* Gets internal lock used by this weak list.
*
* NOTE: use it only if you know what are you doing.
*
* @return internal lock used by this weak list.
*/
public final ReentrantLock getReentrantLock()
{
return lock;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\WeakList.java | 1 |
请完成以下Java代码 | class EnableConfigurationPropertiesRegistrar implements ImportBeanDefinitionRegistrar {
private static final String METHOD_VALIDATION_EXCLUDE_FILTER_BEAN_NAME = Conventions
.getQualifiedAttributeName(EnableConfigurationPropertiesRegistrar.class, "methodValidationExcludeFilter");
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
registerInfrastructureBeans(registry);
registerMethodValidationExcludeFilter(registry);
ConfigurationPropertiesBeanRegistrar beanRegistrar = new ConfigurationPropertiesBeanRegistrar(registry);
getTypes(metadata).forEach(beanRegistrar::register);
}
private Set<Class<?>> getTypes(AnnotationMetadata metadata) {
return metadata.getAnnotations()
.stream(EnableConfigurationProperties.class)
.flatMap((annotation) -> Arrays.stream(annotation.getClassArray(MergedAnnotation.VALUE)))
.filter((type) -> void.class != type)
.collect(Collectors.toSet());
} | static void registerInfrastructureBeans(BeanDefinitionRegistry registry) {
ConfigurationPropertiesBindingPostProcessor.register(registry);
BoundConfigurationProperties.register(registry);
}
static void registerMethodValidationExcludeFilter(BeanDefinitionRegistry registry) {
if (!registry.containsBeanDefinition(METHOD_VALIDATION_EXCLUDE_FILTER_BEAN_NAME)) {
BeanDefinition definition = BeanDefinitionBuilder
.rootBeanDefinition(MethodValidationExcludeFilter.class, "byAnnotation")
.addConstructorArgValue(ConfigurationProperties.class)
.setRole(BeanDefinition.ROLE_INFRASTRUCTURE)
.getBeanDefinition();
registry.registerBeanDefinition(METHOD_VALIDATION_EXCLUDE_FILTER_BEAN_NAME, definition);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\EnableConfigurationPropertiesRegistrar.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.