text
stringlengths
7
1.01M
package com.redhat.labs.lodestar.activity.rest.client; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.eclipse.microprofile.rest.client.ext.ClientHeadersFactory; import org.jboss.resteasy.specimpl.MultivaluedMapImpl; import javax.enterprise.context.ApplicationScoped; import javax.ws.rs.core.MultivaluedMap; @ApplicationScoped public class GitlabTokenFactory implements ClientHeadersFactory { @ConfigProperty(name = "gitlab.personal.access.token") String gitLabToken; @Override public MultivaluedMap<String, String> update(MultivaluedMap<String, String> incomingHeaders, MultivaluedMap<String, String> clientOutgoingHeaders) { MultivaluedMap<String, String> result = new MultivaluedMapImpl<>(); result.add("Private-Token", gitLabToken); return result; } }
/* * Copyright 1999-2011 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.registry.integration; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.common.utils.UrlUtils; import com.alibaba.dubbo.registry.NotifyListener; import com.alibaba.dubbo.registry.Registry; import com.alibaba.dubbo.registry.RegistryFactory; import com.alibaba.dubbo.registry.RegistryService; import com.alibaba.dubbo.rpc.Exporter; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.Protocol; import com.alibaba.dubbo.rpc.ProxyFactory; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.cluster.Cluster; import com.alibaba.dubbo.rpc.cluster.Configurator; import com.alibaba.dubbo.rpc.protocol.InvokerWrapper; /** * RegistryProtocol * * @author william.liangf * @author chao.liuc */ public class RegistryProtocol implements Protocol { private Cluster cluster; public void setCluster(Cluster cluster) { this.cluster = cluster; } private Protocol protocol; public void setProtocol(Protocol protocol) { this.protocol = protocol; } private RegistryFactory registryFactory; public void setRegistryFactory(RegistryFactory registryFactory) { this.registryFactory = registryFactory; } private ProxyFactory proxyFactory; public void setProxyFactory(ProxyFactory proxyFactory) { this.proxyFactory = proxyFactory; } public int getDefaultPort() { return 9090; } private static RegistryProtocol INSTANCE; public RegistryProtocol() { INSTANCE = this; } public static RegistryProtocol getRegistryProtocol() { if (INSTANCE == null) { ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(Constants.REGISTRY_PROTOCOL); // load } return INSTANCE; } private final Map<URL, NotifyListener> overrideListeners = new ConcurrentHashMap<URL, NotifyListener>(); public Map<URL, NotifyListener> getOverrideListeners() { return overrideListeners; } //用于解决rmi重复暴露端口冲突的问题,已经暴露过的服务不再重新暴露 //providerurl <--> exporter private final Map<String, ExporterChangeableWrapper<?>> bounds = new ConcurrentHashMap<String, ExporterChangeableWrapper<?>>(); private final static Logger logger = LoggerFactory.getLogger(RegistryProtocol.class); public <T> Exporter<T> export(final Invoker<T> originInvoker) throws RpcException { //add by 暴露服务 export invoker final ExporterChangeableWrapper<T> exporter = doLocalExport(originInvoker); //add by wanggen registry provider 添加定时任务 final Registry registry = getRegistry(originInvoker); final URL registedProviderUrl = getRegistedProviderUrl(originInvoker); registry.register(registedProviderUrl); // 订阅override数据 // FIXME 提供者订阅时,会影响同一JVM即暴露服务,又引用同一服务的的场景,因为subscribed以服务名为缓存的key,导致订阅信息覆盖。 final URL overrideSubscribeUrl = getSubscribedOverrideUrl(registedProviderUrl); final OverrideListener overrideSubscribeListener = new OverrideListener(overrideSubscribeUrl); overrideListeners.put(overrideSubscribeUrl, overrideSubscribeListener); registry.subscribe(overrideSubscribeUrl, overrideSubscribeListener); //保证每次export都返回一个新的exporter实例 return new Exporter<T>() { public Invoker<T> getInvoker() { return exporter.getInvoker(); } public void unexport() { try { exporter.unexport(); } catch (Throwable t) { logger.warn(t.getMessage(), t); } try { registry.unregister(registedProviderUrl); } catch (Throwable t) { logger.warn(t.getMessage(), t); } try { overrideListeners.remove(overrideSubscribeUrl); registry.unsubscribe(overrideSubscribeUrl, overrideSubscribeListener); } catch (Throwable t) { logger.warn(t.getMessage(), t); } } }; } @SuppressWarnings("unchecked") private <T> ExporterChangeableWrapper<T> doLocalExport(final Invoker<T> originInvoker) { String key = getCacheKey(originInvoker); ExporterChangeableWrapper<T> exporter = (ExporterChangeableWrapper<T>) bounds.get(key); if (exporter == null) { synchronized (bounds) { exporter = (ExporterChangeableWrapper<T>) bounds.get(key); if (exporter == null) { final Invoker<?> invokerDelegete = new InvokerDelegete<T>(originInvoker, getProviderUrl(originInvoker)); exporter = new ExporterChangeableWrapper<T>((Exporter<T>) protocol.export(invokerDelegete), originInvoker); bounds.put(key, exporter); } } } return (ExporterChangeableWrapper<T>) exporter; } /** * 对修改了url的invoker重新export * * @param originInvoker * @param newInvokerUrl */ @SuppressWarnings("unchecked") private <T> void doChangeLocalExport(final Invoker<T> originInvoker, URL newInvokerUrl) { String key = getCacheKey(originInvoker); final ExporterChangeableWrapper<T> exporter = (ExporterChangeableWrapper<T>) bounds.get(key); if (exporter == null) { logger.warn(new IllegalStateException("error state, exporter should not be null")); return;//不存在是异常场景 直接返回 } else { final Invoker<T> invokerDelegete = new InvokerDelegete<T>(originInvoker, newInvokerUrl); exporter.setExporter(protocol.export(invokerDelegete)); } } /** * 根据invoker的地址获取registry实例 * * @param originInvoker * @return */ private Registry getRegistry(final Invoker<?> originInvoker) { URL registryUrl = originInvoker.getUrl(); if (Constants.REGISTRY_PROTOCOL.equals(registryUrl.getProtocol())) { String protocol = registryUrl.getParameter(Constants.REGISTRY_KEY, Constants.DEFAULT_DIRECTORY); registryUrl = registryUrl.setProtocol(protocol).removeParameter(Constants.REGISTRY_KEY); } return registryFactory.getRegistry(registryUrl); } /** * 返回注册到注册中心的URL,对URL参数进行一次过滤 * * @param originInvoker * @return */ private URL getRegistedProviderUrl(final Invoker<?> originInvoker) { URL providerUrl = getProviderUrl(originInvoker); //注册中心看到的地址 final URL registedProviderUrl = providerUrl.removeParameters(getFilteredKeys(providerUrl)).removeParameter(Constants.MONITOR_KEY); return registedProviderUrl; } private URL getSubscribedOverrideUrl(URL registedProviderUrl) { return registedProviderUrl.setProtocol(Constants.PROVIDER_PROTOCOL) .addParameters(Constants.CATEGORY_KEY, Constants.CONFIGURATORS_CATEGORY, Constants.CHECK_KEY, String.valueOf(false)); } /** * 通过invoker的url 获取 providerUrl的地址 * * @param origininvoker * @return */ private URL getProviderUrl(final Invoker<?> origininvoker) { String export = origininvoker.getUrl().getParameterAndDecoded(Constants.EXPORT_KEY); if (export == null || export.length() == 0) { throw new IllegalArgumentException("The registry export url is null! registry: " + origininvoker.getUrl()); } URL providerUrl = URL.valueOf(export); return providerUrl; } /** * 获取invoker在bounds中缓存的key * * @param originInvoker * @return */ private String getCacheKey(final Invoker<?> originInvoker) { URL providerUrl = getProviderUrl(originInvoker); String key = providerUrl.removeParameters("dynamic", "enabled").toFullString(); return key; } @SuppressWarnings("unchecked") public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { url = url.setProtocol(url.getParameter(Constants.REGISTRY_KEY, Constants.DEFAULT_REGISTRY)).removeParameter(Constants.REGISTRY_KEY); Registry registry = registryFactory.getRegistry(url); if (RegistryService.class.equals(type)) { return proxyFactory.getInvoker((T) registry, type, url); } // group="a,b" or group="*" Map<String, String> qs = StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY)); String group = qs.get(Constants.GROUP_KEY); if (group != null && group.length() > 0) { if ((Constants.COMMA_SPLIT_PATTERN.split(group)).length > 1 || "*".equals(group)) { return doRefer(getMergeableCluster(), registry, type, url); } } return doRefer(cluster, registry, type, url); } private Cluster getMergeableCluster() { return ExtensionLoader.getExtensionLoader(Cluster.class).getExtension("mergeable"); } private <T> Invoker<T> doRefer(Cluster cluster, Registry registry, Class<T> type, URL url) { RegistryDirectory<T> directory = new RegistryDirectory<T>(type, url); directory.setRegistry(registry); directory.setProtocol(protocol); URL subscribeUrl = new URL(Constants.CONSUMER_PROTOCOL, NetUtils.getLocalHost(), 0, type.getName(), directory.getUrl().getParameters()); if (!Constants.ANY_VALUE.equals(url.getServiceInterface()) && url.getParameter(Constants.REGISTER_KEY, true)) { registry.register(subscribeUrl.addParameters(Constants.CATEGORY_KEY, Constants.CONSUMERS_CATEGORY, Constants.CHECK_KEY, String.valueOf(false))); } directory.subscribe(subscribeUrl.addParameter(Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY + "," + Constants.CONFIGURATORS_CATEGORY + "," + Constants.ROUTERS_CATEGORY)); return cluster.join(directory); } //过滤URL中不需要输出的参数(以点号开头的) private static String[] getFilteredKeys(URL url) { Map<String, String> params = url.getParameters(); if (params != null && !params.isEmpty()) { List<String> filteredKeys = new ArrayList<String>(); for (Map.Entry<String, String> entry : params.entrySet()) { if (entry != null && entry.getKey() != null && entry.getKey().startsWith(Constants.HIDE_KEY_PREFIX)) { filteredKeys.add(entry.getKey()); } } return filteredKeys.toArray(new String[filteredKeys.size()]); } else { return new String[]{}; } } public void destroy() { List<Exporter<?>> exporters = new ArrayList<Exporter<?>>(bounds.values()); for (Exporter<?> exporter : exporters) { exporter.unexport(); } bounds.clear(); } /*重新export 1.protocol中的exporter destory问题 *1.要求registryprotocol返回的exporter可以正常destroy *2.notify后不需要重新向注册中心注册 *3.export 方法传入的invoker最好能一直作为exporter的invoker. */ private class OverrideListener implements NotifyListener { private volatile List<Configurator> configurators; private final URL subscribeUrl; public OverrideListener(URL subscribeUrl) { this.subscribeUrl = subscribeUrl; } /* * provider 端可识别的override url只有这两种. * override://0.0.0.0/serviceName?timeout=10 * override://0.0.0.0/?timeout=10 */ public void notify(List<URL> urls) { List<URL> result = null; for (URL url : urls) { URL overrideUrl = url; if (url.getParameter(Constants.CATEGORY_KEY) == null && Constants.OVERRIDE_PROTOCOL.equals(url.getProtocol())) { // 兼容旧版本 overrideUrl = url.addParameter(Constants.CATEGORY_KEY, Constants.CONFIGURATORS_CATEGORY); } if (!UrlUtils.isMatch(subscribeUrl, overrideUrl)) { if (result == null) { result = new ArrayList<URL>(urls); } result.remove(url); logger.warn("Subsribe category=configurator, but notifed non-configurator urls. may be registry bug. unexcepted url: " + url); } } if (result != null) { urls = result; } this.configurators = RegistryDirectory.toConfigurators(urls); List<ExporterChangeableWrapper<?>> exporters = new ArrayList<ExporterChangeableWrapper<?>>(bounds.values()); for (ExporterChangeableWrapper<?> exporter : exporters) { Invoker<?> invoker = exporter.getOriginInvoker(); final Invoker<?> originInvoker; if (invoker instanceof InvokerDelegete) { originInvoker = ((InvokerDelegete<?>) invoker).getInvoker(); } else { originInvoker = invoker; } URL originUrl = RegistryProtocol.this.getProviderUrl(originInvoker); URL newUrl = getNewInvokerUrl(originUrl, urls); if (!originUrl.equals(newUrl)) { RegistryProtocol.this.doChangeLocalExport(originInvoker, newUrl); } } } private URL getNewInvokerUrl(URL url, List<URL> urls) { List<Configurator> localConfigurators = this.configurators; // local reference // 合并override参数 if (localConfigurators != null && localConfigurators.size() > 0) { for (Configurator configurator : localConfigurators) { url = configurator.configure(url); } } return url; } } public static class InvokerDelegete<T> extends InvokerWrapper<T> { private final Invoker<T> invoker; /** * @param invoker * @param url invoker.getUrl返回此值 */ public InvokerDelegete(Invoker<T> invoker, URL url) { super(invoker, url); this.invoker = invoker; } public Invoker<T> getInvoker() { if (invoker instanceof InvokerDelegete) { return ((InvokerDelegete<T>) invoker).getInvoker(); } else { return invoker; } } } /** * exporter代理,建立返回的exporter与protocol export出的exporter的对应关系,在override时可以进行关系修改. * * @param <T> * @author chao.liuc */ private class ExporterChangeableWrapper<T> implements Exporter<T> { private Exporter<T> exporter; private final Invoker<T> originInvoker; public ExporterChangeableWrapper(Exporter<T> exporter, Invoker<T> originInvoker) { this.exporter = exporter; this.originInvoker = originInvoker; } public Invoker<T> getOriginInvoker() { return originInvoker; } public Invoker<T> getInvoker() { return exporter.getInvoker(); } public void setExporter(Exporter<T> exporter) { this.exporter = exporter; } public void unexport() { String key = getCacheKey(this.originInvoker); bounds.remove(key); exporter.unexport(); } } }
package org.pp.controller; import com.jfinal.config.Routes; public class DefaultRoutes extends Routes{ @Override public void config() { setBaseViewPath("/view/"); // 公共页面和接口 add("/public", PublicController.class); // 配合HtmlHandler进行模板渲染 add("/html", HtmlController.class); // 后台首页 add("/admin", IndexController.class); // 文件上传 add("/upload", UploadController.class); } }
package leetcode.oo.strings; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; //https://leetcode.com/problems/group-anagrams/ final class GroupAnagrams { List<List<String>> groupAnagrams(final String[] strs) { final Map<Map<Character, Integer>, Integer> cache = new HashMap<>(); final List<List<String>> solution = new ArrayList<>(strs.length); int index = 0; for (final String str : strs) { final Map<Character, Integer> cnt = new HashMap<>(); for (int i = 0; i < str.length(); i++) { cnt.merge(str.charAt(i), 1, Integer::sum); } final Integer position = cache.getOrDefault(cnt, -1); if (position == -1) { solution.add(new ArrayList<>()); solution.get(index).add(str); cache.put(cnt, index); index++; } else { solution.get(position).add(str); } } return solution; } }
package com.kevin.scepter.client.resolve; /** * @author: kevin * @description: double类型处理器 * @updateRemark: 修改内容(每次大改都要写修改内容) * @date: 2019-07-30 11:00 */ public class DoubleResolve implements IResolve<Double> { @Override public Class<Double> getResolveClass() { return Double.class; } @Override public Double resolve(String res) { return Double.valueOf(res); } }
package io.github.greyp9.arwo.core.expr; public abstract class Node { public abstract String render(); }
/* * Copyright (C) 2016 Andrey Mogilev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gilecode.yagson.types; import java.lang.reflect.Field; import java.util.Collections; import java.util.concurrent.CopyOnWriteArrayList; /** * A {@link PostReadProcessor} for sublists of {@link CopyOnWriteArrayList}. Sets the 'expectedArray' * field to match the corresponding 'array' list in the backing full list. * * @author Andrey Mogilev */ public class COWSubListPostReadProcessor implements PostReadProcessor { public void apply(Object instance) { Class c = instance.getClass(); try { // synchronize 'array' (used for CoModification checks) with the current state of the backing list Field fBackingList = TypeUtils.findOneFieldByType(c, CopyOnWriteArrayList.class); Field fExpectedArray = TypeUtils.getDeclaredField(c, "expectedArray"); Field fArray = TypeUtils.getDeclaredField(CopyOnWriteArrayList.class, "array", "elements"); CopyOnWriteArrayList backingList = (CopyOnWriteArrayList) fBackingList.get(instance); Object[] array = (Object[]) fArray.get(backingList); fExpectedArray.set(instance, array); } catch (Exception e) { throw new IllegalStateException("COWSubListPostReadProcessor failed", e); } } public Iterable<String> getNamesOfProcessedClasses() { return Collections.singleton("java.util.concurrent.CopyOnWriteArrayList$COWSubList"); } }
package frc.robot.subsystems; import java.util.List; import edu.wpi.first.wpilibj.TimedRobot; import frc.pathrecognizer.VisionFieldLayoutRecognizer; import frc.pathrecognizer.VisionPathName; //import sun.awt.www.content.image.png; import frc.pathrecognizer.AutonomousPath; import frc.pathrecognizer.PixyCameraConnector; import frc.pathrecognizer.FieldVisionInput; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class PathRecognizerSubsystem extends EntechSubsystem { private VisionFieldLayoutRecognizer visionFieldLayoutRecognizer = new VisionFieldLayoutRecognizer(); private PixyCameraConnector pixyCameraConnector; private List<FieldVisionInput> fieldVisionInputList; @Override public void initialize() { pixyCameraConnector = new PixyCameraConnector(); } public AutonomousPath getAutonomousPath(){ AutonomousPath autonomousPath = new AutonomousPath(VisionPathName.CouldNotDeterminePath); if (pixyCameraConnector.getPixyConnectionStatus()){ fieldVisionInputList = pixyCameraConnector.getFieldVisionInput(); autonomousPath = visionFieldLayoutRecognizer.detectPose(fieldVisionInputList); } SmartDashboard.putString("Pixy Detected Path ", autonomousPath.getPathName().toString()); SmartDashboard.putBoolean("Pixy Camera Connection Status", pixyCameraConnector.getPixyConnectionStatus()); return autonomousPath; } }
package com.mtx.system.rpc.api; import com.baomidou.mybatisplus.plugins.Page; import com.mtx.common.base.BaseServiceMock; import com.mtx.system.dao.mapper.SystemLogMapper; import com.mtx.system.dao.model.SystemLog; import com.mtx.system.dao.model.SystemLogExample; import com.mtx.system.dao.vo.SystemLogVo; import java.util.List; /** * 降级实现SystemLogService接口 * Created by yu on 2018/12/9. */ public class SystemLogServiceMock extends BaseServiceMock<SystemLogMapper, SystemLog, SystemLogExample> implements SystemLogService { @Override public List<SystemLogVo> list(Page<SystemLog> page, String search) { return null; } }
/* * Copyright 2018 dc-square and the HiveMQ MQTT Client Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.hivemq.client.mqtt.mqtt5.exceptions; import com.hivemq.client.mqtt.mqtt5.message.disconnect.Mqtt5Disconnect; import org.jetbrains.annotations.NotNull; /** * @author Silvio Giebl * @since 1.0 */ public class Mqtt5DisconnectException extends Mqtt5MessageException { private final @NotNull Mqtt5Disconnect disconnect; public Mqtt5DisconnectException(final @NotNull Mqtt5Disconnect disconnect, final @NotNull String message) { super(message); this.disconnect = disconnect; } public Mqtt5DisconnectException(final @NotNull Mqtt5Disconnect disconnect, final @NotNull Throwable cause) { super(cause); this.disconnect = disconnect; } @Override public @NotNull Mqtt5Disconnect getMqttMessage() { return disconnect; } }
// OrthogonalSearch.java // // (c) 2006- JEBL development team // // based on LGPL code from the Phylogenetic Analysis Library (PAL), // http://www.cebl.auckland.ac.nz/pal-project/ // which is (c) 1999-2001 PAL Development Core Team // // This package may be distributed under the // terms of the Lesser GNU General Public License (LGPL) package jebl.math; /** * minimization of a real-valued function of * several variables without using derivatives, using the simple * strategy of optimizing variables one by one. * * @author Korbinian Strimmer * @author Matthew Goode */ public class OrthogonalSearch extends MultivariateMinimum { // // Public stuff // // // Private stuff // private OrderEnumerator.OEFactory orthogonalOrderingFactory_; /** Use the current value of dimension in univariate minimisation, or ignore (original method) */ private boolean useCurrentInUnivariateMinimisation_ = false; /** Sometimes the minimum gained through the single variate minimisation is * worse than the minimum currently found (in that it has found another minimum * which is not the original, and is not as minimumal). * This can cause convergence problems, if this is true than the original minima * will be kept if it is more minimal than the new minimuma. This ensures convergence. * In the future a possible strategy might be SimulatedAnealing with regard to accepting, * or rejecting new minima. */ private boolean ignoreNonMinimalUnivariateMinimisations_ = true; /** * If true, print out debug info... */ private boolean debug_ = false; /** * If true calls MinimiserMonitor methods after each orthogonal update, otherwise after each round */ private boolean frequentMonitoring_ = true; /** * Initialization */ public OrthogonalSearch() { //this(OrderUtils.getBiasAlternatingFactory( OrderUtils.getOrderedFactory(), OrderUtils.getZeroFactory())); this(OrderEnumerator.Utils.getOrderedFactory()); } /** * Initialization * @param shuffle If true uses shuffling, else uses ascending order, when choosing next parameter to optimse * (true means equivalent to old StochasticOSearch) */ public OrthogonalSearch(boolean shuffle) { //this(OrderUtils.getBiasAlternatingFactory( OrderUtils.getOrderedFactory(), OrderUtils.getZeroFactory())); this(shuffle? OrderEnumerator.Utils.getShuffledFactory() : OrderEnumerator.Utils.getOrderedFactory()); } /** * Initialization */ public OrthogonalSearch(OrderEnumerator.OEFactory orderingFactory) { this.orthogonalOrderingFactory_ = orderingFactory; } /** * */ public void setUseCurrentInUnivariateMinimisation(boolean value) { this.useCurrentInUnivariateMinimisation_ = value; } /** * Should we ignore new minisations that are not as minimal as the current one? */ public void setIgnoreNonMinimalUnivariateMinimisations(boolean value) { this.ignoreNonMinimalUnivariateMinimisations_ = value; } // implementation of abstract method public void optimize(MultivariateFunction f, double[] xvec, double tolfx, double tolx) { optimize(f,xvec,tolfx,tolx,null); } public void optimize(MultivariateFunction f, double[] xvec, double tolfx, double tolx, MinimiserMonitor monitor) { int numArgs = f.getNumArguments(); numFun = 1; double fx = f.evaluate(xvec); stopCondition(fx, xvec, tolfx, tolx, true); RoundOptimiser od = generateOrthogonalRoundOptimiser(f); UnivariateMinimum um = generateUnivariateMinimum(); double lastFX; while (true) { lastFX = fx; fx = od.doRound(xvec,um,tolx,fx, (frequentMonitoring_ ? monitor : null)); if(monitor!=null) { monitor.newMinimum(fx,xvec,f); if (maxFun > 0) { monitor.updateProgress((double) numFun / maxFun); } } debug("Round fx:"+fx); if (stopCondition(fx, xvec, tolfx, tolx, false) || (maxFun > 0 && numFun > maxFun) || numArgs == 1) { break; } } } //============ Static Methods ==================== /** * Generate a MultivariateMinimum.Factory for an OrthogonalSearch * @param shuffle if true shuffles order for each round (see OrthogonalSearch constructors) */ public static final Factory generateFactory(boolean shuffle) { return new SearchFactory(shuffle); } //============ For sub classes =================== protected UnivariateMinimum generateUnivariateMinimum() { return new UnivariateMinimum(); } protected boolean isFrequentMonitoring() { return frequentMonitoring_; } protected RoundOptimiser generateOrthogonalRoundOptimiser(MultivariateFunction mf) { OrthogonalHints hints = mf.getOrthogonalHints(); if(hints!=null) { return new OrthogonalHintsDirection(mf,hints,orthogonalOrderingFactory_); } return new OrthogonalDirection(mf,orthogonalOrderingFactory_); } protected interface RoundOptimiser { /** * @param monitor - may be null; */ public double doRound(double[] xvec, UnivariateMinimum um, double tolx,double fx, MinimiserMonitor monitor); } protected final boolean isUseCurrentInUnivariateMinimisation() { return this.useCurrentInUnivariateMinimisation_; } /** * Should we ignore new minisations that are not as minimal as the current one? */ protected final boolean isIgnoreNonMinimalUnivariateMinimisations() { return this.ignoreNonMinimalUnivariateMinimisations_; } protected void debug(Object output) { if(debug_) { System.out.println(output); } } protected boolean isDebug() { return debug_; } // ============ The Factory Class for Orthogonal Searches =================== private static final class SearchFactory implements Factory { boolean shuffle_; private SearchFactory(boolean shuffle) { this.shuffle_ = shuffle; } public MultivariateMinimum generateNewMinimiser() { return new OrthogonalSearch(shuffle_); } } //============== A means for doing Orthogonal optimisation ================== private class OrthogonalDirection implements RoundOptimiser { OrderEnumerator order_; OrthogonalLineFunction olf_; MultivariateFunction base_; public OrthogonalDirection(MultivariateFunction mf, OrderEnumerator.OEFactory orderFactory) { base_ = mf; olf_ = new OrthogonalLineFunction(base_); this.order_ = orthogonalOrderingFactory_.createOrderEnumerator(base_.getNumArguments()); } public double doRound(double[] xvec, UnivariateMinimum um, double tolx,double fx, MinimiserMonitor monitor) { olf_.setAllArguments(xvec); order_.reset(); while(order_.hasMore()) { int argument = order_.getNext(); olf_.selectArgument(argument); double newArgValue = ( useCurrentInUnivariateMinimisation_ ? um.optimize(xvec[argument], olf_, tolx) : um.optimize(olf_, tolx) ); //If we actually found a better minimum... if(um.fminx<=fx) { xvec[argument] = newArgValue; olf_.setArgument(newArgValue); fx = um.fminx; } if(monitor!=null) { monitor.newMinimum(fx,xvec,base_); } debug(argument+":"+um.fminx+" "+fx); numFun += um.numFun; } return fx; } } //============== A means for doing Orthogonal optimisation ================== private class OrthogonalHintsDirection implements RoundOptimiser { OrderEnumerator order_; OrthogonalLineFunction olf_; OrthogonalHints hints_; double[] store_ = new double[100]; MultivariateFunction base_; public OrthogonalHintsDirection(MultivariateFunction mf, OrthogonalHints hints, OrderEnumerator.OEFactory orderFactory) { base_ = mf; olf_ = new OrthogonalLineFunction(base_); this.hints_ = hints; this.order_ = orthogonalOrderingFactory_.createOrderEnumerator(base_.getNumArguments()); } private final double getNormalMin(UnivariateMinimum um, double argumentValue, double tolx) { return ( useCurrentInUnivariateMinimisation_ ? um.optimize(argumentValue, olf_, tolx) : um.optimize(olf_, tolx) ); } private final double getBoundedMin(UnivariateMinimum um, double argumentValue, double tolx,double min, double max) { if(useCurrentInUnivariateMinimisation_ && (min<=argumentValue&&max>=argumentValue)) { return um.optimize(argumentValue, olf_, tolx,min,max); } return um.optimize(olf_, tolx,min,max); } public double doRound(double[] xvec, UnivariateMinimum um, double tolx,double fx, MinimiserMonitor monitor) { olf_.setAllArguments(xvec); order_.reset(); while(order_.hasMore()) { int argument = order_.getNext(); olf_.selectArgument(argument); int numberOfHints= hints_.getInternalParameterBoundaries(argument,store_); //Yes this expensive, but will not happen very often (and only at beging of optimisation) while(numberOfHints<0) { store_ = new double[store_.length+10]; numberOfHints= hints_.getInternalParameterBoundaries(argument,store_); } double newArgValue; double newFX; if(numberOfHints==0) { newArgValue= getNormalMin(um,xvec[argument],tolx); newFX = um.fminx; } else { debug("Number of hints:"+numberOfHints); //System.out.println("Store:"+pal.misc.Utils.toString(store_,numberOfHints)); double min = olf_.getLowerBound(); double x = xvec[argument]; newArgValue = xvec[argument]; newFX = Double.POSITIVE_INFINITY; for(int i = 0 ; i < numberOfHints ; i++) { x =getBoundedMin(um, xvec[argument], tolx, min,store_[i]); if(um.fminx<newFX) { newArgValue=x; newFX = um.fminx; } min = store_[i]; } double max = olf_.getUpperBound(); if(min!=max) { x =getBoundedMin(um, xvec[argument], tolx, min,max); if(um.fminx<newFX) { newArgValue=x; newFX = um.fminx; } } } //If we actually found a better minimum... if(newFX<=fx) { if(debug_&&numberOfHints>0) { //Do it old school! getNormalMin(um,xvec[argument],tolx); } xvec[argument] = newArgValue; olf_.setArgument(newArgValue); if(monitor!=null) { monitor.newMinimum(newFX,xvec,base_); } fx = newFX; } if(debug_) { System.out.println(argument+":"+newFX+" "+fx+" "+um.fminx+" "+(um.fminx-newFX)+" "+((um.fminx<newFX) ? "Bad" : "Good!")); } numFun += um.numFun; } return fx; } } }
/* * This file is part of ComputerCraft - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ package dan200.computercraft.core.apis.handles; import com.google.common.base.Preconditions; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.NonWritableChannelException; import java.nio.channels.SeekableByteChannel; /** * A seekable, readable byte channel which is backed by a simple byte array. */ public class ArrayByteChannel implements SeekableByteChannel { private boolean closed = false; private int position = 0; private final byte[] backing; public ArrayByteChannel( byte[] backing ) { this.backing = backing; } @Override public int read( ByteBuffer destination ) throws IOException { if( closed ) throw new ClosedChannelException(); Preconditions.checkNotNull( destination, "destination" ); if( position >= backing.length ) return -1; int remaining = Math.min( backing.length - position, destination.remaining() ); destination.put( backing, position, remaining ); position += remaining; return remaining; } @Override public int write( ByteBuffer src ) throws IOException { if( closed ) throw new ClosedChannelException(); throw new NonWritableChannelException(); } @Override public long position() throws IOException { if( closed ) throw new ClosedChannelException(); return position; } @Override public SeekableByteChannel position( long newPosition ) throws IOException { if( closed ) throw new ClosedChannelException(); if( newPosition < 0 || newPosition > Integer.MAX_VALUE ) { throw new IllegalArgumentException( "Position out of bounds" ); } position = (int) newPosition; return this; } @Override public long size() throws IOException { if( closed ) throw new ClosedChannelException(); return backing.length; } @Override public SeekableByteChannel truncate( long size ) throws IOException { if( closed ) throw new ClosedChannelException(); throw new NonWritableChannelException(); } @Override public boolean isOpen() { return !closed; } @Override public void close() { closed = true; } }
/** * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.internal.operators.maybe; import java.util.concurrent.atomic.AtomicReference; import org.reactivestreams.*; import io.reactivex.*; import io.reactivex.disposables.Disposable; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.plugins.RxJavaPlugins; /** * Relays the main source's event unless the other Publisher signals an item first or just completes * at which point the resulting Maybe is completed. * * @param <T> the value type * @param <U> the other's value type */ public final class MaybeTakeUntilPublisher<T, U> extends AbstractMaybeWithUpstream<T, T> { final Publisher<U> other; public MaybeTakeUntilPublisher(MaybeSource<T> source, Publisher<U> other) { super(source); this.other = other; } @Override protected void subscribeActual(MaybeObserver<? super T> observer) { TakeUntilMainMaybeObserver<T, U> parent = new TakeUntilMainMaybeObserver<T, U>(observer); observer.onSubscribe(parent); other.subscribe(parent.other); source.subscribe(parent); } static final class TakeUntilMainMaybeObserver<T, U> extends AtomicReference<Disposable> implements MaybeObserver<T>, Disposable { private static final long serialVersionUID = -2187421758664251153L; final MaybeObserver<? super T> actual; final TakeUntilOtherMaybeObserver<U> other; TakeUntilMainMaybeObserver(MaybeObserver<? super T> actual) { this.actual = actual; this.other = new TakeUntilOtherMaybeObserver<U>(this); } @Override public void dispose() { DisposableHelper.dispose(this); SubscriptionHelper.cancel(other); } @Override public boolean isDisposed() { return DisposableHelper.isDisposed(get()); } @Override public void onSubscribe(Disposable d) { DisposableHelper.setOnce(this, d); } @Override public void onSuccess(T value) { SubscriptionHelper.cancel(other); if (getAndSet(DisposableHelper.DISPOSED) != DisposableHelper.DISPOSED) { actual.onSuccess(value); } } @Override public void onError(Throwable e) { SubscriptionHelper.cancel(other); if (getAndSet(DisposableHelper.DISPOSED) != DisposableHelper.DISPOSED) { actual.onError(e); } else { RxJavaPlugins.onError(e); } } @Override public void onComplete() { SubscriptionHelper.cancel(other); if (getAndSet(DisposableHelper.DISPOSED) != DisposableHelper.DISPOSED) { actual.onComplete(); } } void otherError(Throwable e) { if (DisposableHelper.dispose(this)) { actual.onError(e); } else { RxJavaPlugins.onError(e); } } void otherComplete() { if (DisposableHelper.dispose(this)) { actual.onComplete(); } } static final class TakeUntilOtherMaybeObserver<U> extends AtomicReference<Subscription> implements FlowableSubscriber<U> { private static final long serialVersionUID = -1266041316834525931L; final TakeUntilMainMaybeObserver<?, U> parent; TakeUntilOtherMaybeObserver(TakeUntilMainMaybeObserver<?, U> parent) { this.parent = parent; } @Override public void onSubscribe(Subscription s) { SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override public void onNext(Object value) { SubscriptionHelper.cancel(this); parent.otherComplete(); } @Override public void onError(Throwable e) { parent.otherError(e); } @Override public void onComplete() { parent.otherComplete(); } } } }
/* * Created by LuaView. * Copyright (c) 2017, Alibaba Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.taobao.luaview.view.viewpager; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import com.taobao.luaview.util.LogUtil; import com.taobao.luaview.view.adapter.LVLoopPagerAdapter; /** * A ViewPager subclass enabling infinte scrolling of the viewPager elements * <p/> * When used for paginating views (in opposite to fragments), no code changes * should be needed only change xml's from <android.support.v4.view.ViewPager> * to <com.imbryk.viewPager.LoopViewPager> * <p/> * If "blinking" can be seen when paginating to first or last view, simply call * seBoundaryCaching( true ), or change DEFAULT_BOUNDARY_CASHING to true * <p/> * When using a FragmentPagerAdapter or FragmentStatePagerAdapter, * additional changes in the adapter must be done. * The adapter must be prepared to create 2 extra items e.g.: * <p/> * The original adapter creates 4 items: [0,1,2,3] * The modified adapter will have to create 6 items [0,1,2,3,4,5] * with mapping realPosition=(position-1)%count * [0->3, 1->0, 2->1, 3->2, 4->3, 5->0] */ public class LoopViewPager extends ViewPager { private OnPageChangeListener mOuterPageChangeListener; private LVLoopPagerAdapter mAdapter; private float mPreviousOffset = -1; private float mPreviousRealPosition = -1; public LoopViewPager(Context context) { super(context); init(); } @Override public void setAdapter(PagerAdapter adapter) { mAdapter = (LVLoopPagerAdapter) adapter; super.setAdapter(mAdapter); setCurrentItem(0, false); } @Override public PagerAdapter getAdapter() { return mAdapter; } public int getRealCount() { return mAdapter != null ? mAdapter.getRealCount() : 0; } public int getCount() { return mAdapter != null ? mAdapter.getCount() : 0; } public void setLooping(boolean looping) { if (mAdapter != null && mAdapter.isLooping() != looping) { final int currentPosition = super.getCurrentItem(); super.setAdapter(null); mAdapter.setLooping(looping); super.setAdapter(mAdapter); if (looping) { super.setCurrentItem(mAdapter.toFakePosition(currentPosition), false); } mPreviousRealPosition = -1; mPreviousOffset = -1; } } public boolean isLooping() { return mAdapter != null && mAdapter.isLooping(); } @Override public int getCurrentItem() { return mAdapter != null ? mAdapter.toRealPosition(super.getCurrentItem()) : super.getCurrentItem(); } @Override public void setCurrentItem(int item) { setCurrentItem(item, false); } public void setCurrentItem(int realItem, boolean smoothScroll) { final int fakeItem = mAdapter.toFakePosition(realItem); final int currentFakeItem = super.getCurrentItem(); // LogUtil.d("yesong", "setCurrentItem", fakeItem, currentFakeItem); if (fakeItem != currentFakeItem) { super.setCurrentItem(fakeItem, smoothScroll); } } @Override public void setOnPageChangeListener(OnPageChangeListener listener) { mOuterPageChangeListener = listener; } private boolean isBoundaryPosition(int position) { return position == 0 || (position == getCount() - 1); } private void init() { super.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int position) { // LogUtil.d("yesong", "onPageSelected", position); if (mAdapter != null && mAdapter.shouldLooping()) { int fakePosition = position; int realPosition = mAdapter.toRealPosition(fakePosition); if (mPreviousRealPosition != realPosition) { mPreviousRealPosition = realPosition; if (mOuterPageChangeListener != null) { mOuterPageChangeListener.onPageSelected(realPosition); } } } else { mPreviousRealPosition = position; if (mOuterPageChangeListener != null) { mOuterPageChangeListener.onPageSelected(position); } } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // LogUtil.d("yesong", "onPageScrolled-offset", position, positionOffset, positionOffsetPixels); if (mAdapter != null && mAdapter.shouldLooping()) { final int fakePosition = position; final int realPosition = mAdapter.toRealPosition(fakePosition); if (positionOffset == 0 && mPreviousOffset == 0 && isBoundaryPosition(fakePosition)) { // LogUtil.d("yesong", "onPageScrolled", fakePosition, realPosition); setCurrentItem(realPosition, false); } mPreviousOffset = positionOffset; if (mOuterPageChangeListener != null) { if (realPosition == mAdapter.getRealCount() - 1) { if (positionOffset > 0.5) { mOuterPageChangeListener.onPageScrolled(0, 0, 0); } else { mOuterPageChangeListener.onPageScrolled(realPosition, 0, 0); } } else { mOuterPageChangeListener.onPageScrolled(realPosition, positionOffset, positionOffsetPixels); } } } else { if (mOuterPageChangeListener != null) { mOuterPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } } } @Override public void onPageScrollStateChanged(int state) { // LogUtil.d("yesong", "onPageScrollStateChanged", state); if (mAdapter != null && mAdapter.shouldLooping()) { int fakePosition = LoopViewPager.super.getCurrentItem(); int realPosition = mAdapter.toRealPosition(fakePosition); if (state == ViewPager.SCROLL_STATE_IDLE && isBoundaryPosition(fakePosition)) { // LogUtil.d("yesong", "onPageScrollStateChanged", fakePosition, realPosition); setCurrentItem(realPosition, false); } } if (mOuterPageChangeListener != null) { mOuterPageChangeListener.onPageScrollStateChanged(state); } } }); } }
package com.material.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.*; import androidx.annotation.NonNull; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewParent; /** * Created by IntelliJ IDEA. * User: keith. * Date: 14-10-10. * Time: 14:47. */ public class Slider extends View { private static final String TAG = Slider.class.getSimpleName(); private static final int MAX = 4; private static final int MIN = 0; private static final int StateNormal = 0; private static final int StateDragging = 1; public static interface OnValueChangeListener { void onValueChanged(Slider slider, int value, boolean fromUser); } private Paint mPaint; private int mColor; private int mTintColor; private int mThumbRadius; private int mRippleRadius; private int mBarHeight; private int mMax; private int mProgress; private int mThumbBorderWidth; private RectF mUncoveredBarRectF = new RectF(); private RectF mCoveredBarRectF = new RectF(); private Point mThumbCenter = new Point(); private Canvas mMinCanvas; private Paint mClearPaint; private PorterDuffXfermode mPorterDuffXFerMode; private float mCoordinateX; private int mState = StateNormal; private OnValueChangeListener mOnValueChangeListener; public void setOnValueChangeListener(OnValueChangeListener listener) { this.mOnValueChangeListener = listener; } public Slider(Context context) { this(context, null); } public Slider(Context context, AttributeSet attrs) { this(context, attrs, 0); } public Slider(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.Slider); mColor = attributes.getColor(R.styleable.Slider_slider_color, getResources().getColor(R.color.slider_color)); mTintColor = attributes.getColor(R.styleable.Slider_slider_tint_color, getResources().getColor(R.color.slider_tint_color)); mThumbRadius = attributes.getDimensionPixelSize(R.styleable.Slider_slider_thumb_radius, getResources().getDimensionPixelSize(R.dimen.slider_thumb_radius)); mRippleRadius = attributes.getDimensionPixelSize(R.styleable.Slider_slider_ripple_radius, getResources().getDimensionPixelSize(R.dimen.slider_thumb_ripple_radius)); mBarHeight = attributes.getDimensionPixelSize(R.styleable.Slider_slider_bar_height, getResources().getDimensionPixelSize(R.dimen.slider_bar_height)); mThumbBorderWidth = attributes.getDimensionPixelSize(R.styleable.TrackSlider_slider_thumb_border_width, getResources().getDimensionPixelSize(R.dimen.slider_thumb_border_width)); mMax = attributes.getInteger(R.styleable.Slider_slider_max, MAX); mProgress = attributes.getInteger(R.styleable.Slider_slider_progress, MIN); mCoordinateX = 0.f; mPaint = new Paint(); mPaint.setAntiAlias(true); mClearPaint = new Paint(); mClearPaint.setAntiAlias(true); mMinCanvas = new Canvas(); mPorterDuffXFerMode = new PorterDuffXfermode(PorterDuff.Mode.CLEAR); } @Override protected int getSuggestedMinimumWidth() { return mRippleRadius * 4; } @Override protected int getSuggestedMinimumHeight() { return mRippleRadius * 2; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(measure(widthMeasureSpec, true), measure(heightMeasureSpec, false)); } private int measure(int measureSpec, boolean isWidth) { int result; int mode = MeasureSpec.getMode(measureSpec); int size = MeasureSpec.getSize(measureSpec); int padding = isWidth ? getPaddingLeft() + getPaddingRight() : getPaddingTop() + getPaddingBottom(); if (mode == MeasureSpec.EXACTLY) { result = size; } else { result = isWidth ? getSuggestedMinimumWidth() : getSuggestedMinimumHeight(); result += padding; if (mode == MeasureSpec.AT_MOST) { if (isWidth) { result = Math.max(result, size); } else { result = Math.min(result, size); } } } return result; } @Override public boolean onTouchEvent(@NonNull MotionEvent event) { super.onTouchEvent(event); ViewParent parent = getParent(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } if (event.getX() >= 0 && event.getX() <= getWidth() && event.getY() >= 0 && event.getY() <= getHeight()) { mCoordinateX = getCoordinateX(event); } } break; case MotionEvent.ACTION_MOVE: { if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } mState = StateDragging; if (event.getX() >= 0 && event.getX() <= getWidth() && event.getY() >= 0 && event.getY() <= getHeight()) { mCoordinateX = getCoordinateX(event); Log.v("EventX", event.getX() + ":" + mCoordinateX); invalidate(); } } break; case MotionEvent.ACTION_UP: { if (parent != null) { parent.requestDisallowInterceptTouchEvent(false); } calculateProgress(); mState = StateNormal; invalidate(); } break; case MotionEvent.ACTION_CANCEL: { if (parent != null) { parent.requestDisallowInterceptTouchEvent(false); } calculateProgress(); mState = StateNormal; invalidate(); } break; } return true; } private float getCoordinateX(MotionEvent event) { return ((getWidth() - getPaddingLeft() - getPaddingRight()) * event.getX()) / getWidth(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); RectF barRectF = getBarRect(); switch (mState) { case StateNormal: { calculateThumbCenterPoint(); if (mProgress == MIN) { Bitmap bitmap = getMinBitmap(canvas); mMinCanvas.setBitmap(bitmap); mPaint.setColor(mColor); mMinCanvas.drawRect(barRectF, mPaint); mPaint.setColor(mTintColor); mMinCanvas.drawCircle(mThumbCenter.x, mThumbCenter.y, mThumbRadius, mPaint); mClearPaint.setColor(Color.TRANSPARENT); mClearPaint.setXfermode(mPorterDuffXFerMode); mMinCanvas.drawCircle(mThumbCenter.x, mThumbCenter.y, mThumbRadius - mThumbBorderWidth, mClearPaint); canvas.drawBitmap(bitmap, 0, 0, null); bitmap.recycle(); } else if (mProgress == MAX) { mPaint.setColor(mColor); canvas.drawRect(barRectF, mPaint); mPaint.setColor(mTintColor); canvas.drawRect(getMaxCoveredBarRect(), mPaint); mPaint.setColor(mTintColor); canvas.drawCircle(mThumbCenter.x, mThumbCenter.y, mThumbRadius, mPaint); } else { mPaint.setColor(mColor); canvas.drawRect(barRectF, mPaint); mPaint.setColor(mTintColor); canvas.drawRect(getCoveredRectF(mProgress), mPaint); mThumbCenter.set(getThumbCenterX(mProgress), getHeight() / 2); mPaint.setColor(mTintColor); canvas.drawCircle(mThumbCenter.x, mThumbCenter.y, mThumbRadius, mPaint); } } break; case StateDragging: { mUncoveredBarRectF.left = getPaddingLeft() + mThumbRadius; mUncoveredBarRectF.right = getWidth() - getPaddingRight() - mThumbRadius; mUncoveredBarRectF.top = getHeight() / 2.0f + -mBarHeight / 2.0f; mUncoveredBarRectF.bottom = getHeight() / 2.0f + mBarHeight / 2.0f; float realX = getThumbCenterX(mCoordinateX); mPaint.setColor(mColor); canvas.drawRect(barRectF, mPaint); mPaint.setColor(mTintColor); canvas.drawRect(getCoveredRectF(realX), mPaint); mPaint.setColor(mTintColor); mThumbCenter.set((int) realX, getHeight() / 2); canvas.drawCircle(mThumbCenter.x, mThumbCenter.y, mThumbRadius, mPaint); } break; } /* canvas.save(); canvas.getClipBounds(mCanvasRect); mCanvasRect.inset(-mRippleRadius, -mRippleRadius); canvas.clipRect(mCanvasRect, Region.Op.REPLACE); canvas.restore(); calculateBarDrawRect(); calculateThumbCenterPoint(); if (mProgress == MIN) { mMinBitmap = getMinBitmap(canvas); mMinCanvas.setBitmap(mMinBitmap); mPaint.setColor(mColor); mMinCanvas.drawRect(mUncoveredBarRectF, mPaint); mPaint.setColor(mTintColor); mMinCanvas.drawRect(mCoveredBarRectF, mPaint); mPaint.setColor(mTintColor); mMinCanvas.drawCircle(mThumbCenter.x, mThumbCenter.y, mThumbRadius, mPaint); mClearPaint.setColor(Color.TRANSPARENT); mClearPaint.setXfermode(mPorterDuffXFerMode); mMinCanvas.drawCircle(mThumbCenter.x, mThumbCenter.y, mThumbRadius - mThumbBorderWidth, mClearPaint); canvas.drawBitmap(mMinBitmap, 0, 0, null); } else if (mProgress == MAX) { mPaint.setColor(mColor); canvas.drawRect(mUncoveredBarRectF, mPaint); mPaint.setColor(mTintColor); canvas.drawRect(mCoveredBarRectF, mPaint); mPaint.setColor(mTintColor); canvas.drawCircle(mThumbCenter.x, mThumbCenter.y, mThumbRadius, mPaint); } else { } */ } private void calculateProgress() { float width = getMaxThumbCenterX() - getMinThumbCenterX(); float passed = getThumbCenterX(mCoordinateX) - getMinThumbCenterX(); mProgress = Math.round(passed * mMax / width); Log.v("Progress", mProgress + ":" + width + ":" + passed); } private float getThumbCenterX(float x) { if (x < getPaddingLeft() + mThumbRadius) { return getMinThumbCenterX(); } else if (x > getWidth() - getPaddingRight() - mThumbRadius) { return getMaxThumbCenterX(); } else { int width = getWidth() - getPaddingLeft() - getPaddingRight() - mThumbRadius * 2; return mThumbRadius + getPaddingLeft() + x * width / getWidth(); } } private int getThumbCenterX(int progress) { if (progress == MIN) { return getPaddingLeft() + mThumbRadius; } else if (progress == MAX) { return getWidth() - getPaddingRight() - mThumbRadius; } else { float width = getMaxThumbCenterX() - getMinThumbCenterX(); float passed = mProgress * width / mMax; return Math.round(getPaddingLeft() + mThumbRadius + passed); } } private Bitmap getMinBitmap(Canvas canvas) { return Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888); } private float getMinThumbCenterX() { return getPaddingLeft() + mThumbRadius; } private float getMaxThumbCenterX() { return getWidth() - getPaddingRight() - mThumbRadius; } private RectF getMinCoveredBarRect() { if (mCoveredBarRectF == null) { mCoveredBarRectF = new RectF(); } mCoveredBarRectF.left = getPaddingLeft() + mThumbRadius; mCoveredBarRectF.right = getPaddingLeft() + mThumbRadius; mCoveredBarRectF.top = getHeight() / 2.0f + -mBarHeight / 2.0f; mCoveredBarRectF.bottom = getHeight() / 2.0f + mBarHeight / 2.0f; return mCoveredBarRectF; } private RectF getMaxCoveredBarRect() { if (mCoveredBarRectF == null) { mCoveredBarRectF = new RectF(); } mCoveredBarRectF.left = getPaddingLeft() + mThumbRadius; mCoveredBarRectF.right = getWidth() - getPaddingRight() - mThumbRadius; mCoveredBarRectF.top = getHeight() / 2.0f + -mBarHeight / 2.0f; mCoveredBarRectF.bottom = getHeight() / 2.0f + mBarHeight / 2.0f; return mCoveredBarRectF; } private RectF getBarRect() { if (mUncoveredBarRectF == null) { mUncoveredBarRectF = new RectF(); } mUncoveredBarRectF.left = getPaddingLeft() + mThumbRadius; mUncoveredBarRectF.right = getWidth() - getPaddingRight() - mThumbRadius; mUncoveredBarRectF.top = getHeight() / 2.0f + -mBarHeight / 2.0f; mUncoveredBarRectF.bottom = getHeight() / 2.0f + mBarHeight / 2.0f; return mUncoveredBarRectF; } private RectF getCoveredRectF(float x) { if (mCoveredBarRectF == null) { mCoveredBarRectF = new RectF(); } mCoveredBarRectF.left = getPaddingLeft() + mThumbRadius; mCoveredBarRectF.right = x; mCoveredBarRectF.top = getHeight() / 2.0f + -mBarHeight / 2.0f; mCoveredBarRectF.bottom = getHeight() / 2.0f + mBarHeight / 2.0f; return mCoveredBarRectF; } private RectF getCoveredRectF(int progress) { if (mCoveredBarRectF == null) { mCoveredBarRectF = new RectF(); } mCoveredBarRectF.left = getPaddingLeft() + mThumbRadius; mCoveredBarRectF.right = getThumbCenterX(progress); mCoveredBarRectF.top = getHeight() / 2.0f + -mBarHeight / 2.0f; mCoveredBarRectF.bottom = getHeight() / 2.0f + mBarHeight / 2.0f; return mCoveredBarRectF; } private void calculateThumbCenterPoint() { if (mProgress == MIN) { mThumbCenter.set(mThumbRadius, getHeight() / 2); } else if (mProgress == mMax) { mThumbCenter.set(getWidth() - getPaddingRight() - mThumbRadius, getHeight() / 2); } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javafxapplication3; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.stage.Stage; /** * * @author Nimbert */ public class FXMLDocumentController implements Initializable { @FXML private Label label; @FXML private void handleButtonAction(ActionEvent event) { label.setText("*You have to register first."); } @FXML private void Hyperlink_button(ActionEvent event) throws IOException{ Stage stage = (Stage)((Node) event.getSource()).getScene().getWindow(); Parent root = FXMLLoader.load(getClass().getResource("Register.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } @FXML private void forget_Pass(ActionEvent event) throws IOException{ Stage stage = (Stage)((Node) event.getSource()).getScene().getWindow(); Parent root = FXMLLoader.load(getClass().getResource("forget_Password.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } @FXML private void Sign_in(ActionEvent event)throws IOException{ Stage stage = (Stage)((Node) event.getSource()).getScene().getWindow(); Parent root = FXMLLoader.load(getClass().getResource("logged_in.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } @Override public void initialize(URL url, ResourceBundle rb) { // TODO } }
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ /** * Do not modify this class. It was generated. * Instead modify LeafRegionEntry.cpp and then run * bin/generateRegionEntryClasses.sh from the directory * that contains your build.xml. */ package com.gemstone.gemfire.internal.cache; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import com.gemstone.gemfire.internal.cache.Token; import com.gemstone.gemfire.internal.concurrent.AtomicUpdaterFactory; import com.gemstone.gemfire.internal.offheap.OffHeapRegionEntryHelper; import com.gemstone.gemfire.internal.offheap.annotations.Released; import com.gemstone.gemfire.internal.offheap.annotations.Retained; import com.gemstone.gemfire.internal.offheap.annotations.Unretained; import com.gemstone.gemfire.cache.EntryEvent; import com.gemstone.gemfire.internal.cache.lru.EnableLRU; import com.gemstone.gemfire.internal.InternalStatisticsDisabledException; import com.gemstone.gemfire.internal.cache.lru.LRUClockNode; import com.gemstone.gemfire.internal.cache.lru.NewLRUClockHand; import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember; import com.gemstone.gemfire.internal.cache.versions.VersionSource; import com.gemstone.gemfire.internal.cache.versions.VersionStamp; import com.gemstone.gemfire.internal.cache.versions.VersionTag; import com.gemstone.gemfire.internal.concurrent.CustomEntryConcurrentHashMap.HashEntry; @SuppressWarnings("serial") public class VersionedStatsLRURegionEntryOffHeap extends VMStatsLRURegionEntry implements OffHeapRegionEntry, VersionStamp { public VersionedStatsLRURegionEntryOffHeap (RegionEntryContext context, Object key, @Retained Object value ) { super(context, value ); this.key = key; } protected int hash; private HashEntry<Object, Object> next; @SuppressWarnings("unused") private volatile long lastModified; private static final AtomicLongFieldUpdater<VersionedStatsLRURegionEntryOffHeap> lastModifiedUpdater = AtomicUpdaterFactory.newLongFieldUpdater(VersionedStatsLRURegionEntryOffHeap.class, "lastModified"); protected long getlastModifiedField() { return lastModifiedUpdater.get(this); } protected final boolean compareAndSetLastModifiedField(long expectedValue, long newValue) { return lastModifiedUpdater.compareAndSet(this, expectedValue, newValue); } @Override public final int getEntryHash() { return this.hash; } @Override protected final void setEntryHash(int v) { this.hash = v; } @Override public final HashEntry<Object, Object> getNextEntry() { return this.next; } @Override public final void setNextEntry(final HashEntry<Object, Object> n) { this.next = n; } @Override public final void setDelayedDiskId(LocalRegion r) { } public final synchronized int updateEntrySize(EnableLRU capacityController) { return updateEntrySize(capacityController, _getValue()); } public final synchronized int updateEntrySize(EnableLRU capacityController, Object value) { int oldSize = getEntrySize(); int newSize = capacityController.entrySize(getRawKey(), value); setEntrySize(newSize); int delta = newSize - oldSize; return delta; } private LRUClockNode nextLRU; private LRUClockNode prevLRU; private int size; public final void setNextLRUNode( LRUClockNode next ) { this.nextLRU = next; } public final LRUClockNode nextLRUNode() { return this.nextLRU; } public final void setPrevLRUNode( LRUClockNode prev ) { this.prevLRU = prev; } public final LRUClockNode prevLRUNode() { return this.prevLRU; } public final int getEntrySize() { return this.size; } protected final void setEntrySize(int size) { this.size = size; } @Override public final void updateStatsForGet(boolean hit, long time) { setLastAccessed(time); if (hit) { incrementHitCount(); } else { incrementMissCount(); } } @Override public final void setLastModified(long lastModified) { _setLastModified(lastModified); if (!DISABLE_ACCESS_TIME_UPDATE_ON_PUT) { setLastAccessed(lastModified); } } private volatile long lastAccessed; private volatile int hitCount; private volatile int missCount; private static final AtomicIntegerFieldUpdater<VersionedStatsLRURegionEntryOffHeap> hitCountUpdater = AtomicUpdaterFactory.newIntegerFieldUpdater(VersionedStatsLRURegionEntryOffHeap.class, "hitCount"); private static final AtomicIntegerFieldUpdater<VersionedStatsLRURegionEntryOffHeap> missCountUpdater = AtomicUpdaterFactory.newIntegerFieldUpdater(VersionedStatsLRURegionEntryOffHeap.class, "missCount"); @Override public final long getLastAccessed() throws InternalStatisticsDisabledException { return this.lastAccessed; } private void setLastAccessed(long lastAccessed) { this.lastAccessed = lastAccessed; } @Override public final long getHitCount() throws InternalStatisticsDisabledException { return this.hitCount & 0xFFFFFFFFL; } @Override public final long getMissCount() throws InternalStatisticsDisabledException { return this.missCount & 0xFFFFFFFFL; } private void incrementHitCount() { hitCountUpdater.incrementAndGet(this); } private void incrementMissCount() { missCountUpdater.incrementAndGet(this); } @Override public final void resetCounts() throws InternalStatisticsDisabledException { hitCountUpdater.set(this,0); missCountUpdater.set(this,0); } @Override public final void txDidDestroy(long currTime) { setLastModified(currTime); setLastAccessed(currTime); this.hitCount = 0; this.missCount = 0; } @Override public final boolean hasStats() { return true; } private VersionSource memberID; private short entryVersionLowBytes; private short regionVersionHighBytes; private int regionVersionLowBytes; private byte entryVersionHighByte; private byte distributedSystemId; public final int getEntryVersion() { return ((entryVersionHighByte << 16) & 0xFF0000) | (entryVersionLowBytes & 0xFFFF); } public final long getRegionVersion() { return (((long)regionVersionHighBytes) << 32) | (regionVersionLowBytes & 0x00000000FFFFFFFFL); } public final long getVersionTimeStamp() { return getLastModified(); } public final void setVersionTimeStamp(long time) { setLastModified(time); } public final VersionSource getMemberID() { return this.memberID; } public final int getDistributedSystemId() { return this.distributedSystemId; } public final void setVersions(VersionTag tag) { this.memberID = tag.getMemberID(); int eVersion = tag.getEntryVersion(); this.entryVersionLowBytes = (short)(eVersion & 0xffff); this.entryVersionHighByte = (byte)((eVersion & 0xff0000) >> 16); this.regionVersionHighBytes = tag.getRegionVersionHighBytes(); this.regionVersionLowBytes = tag.getRegionVersionLowBytes(); if (!(tag.isGatewayTag()) && this.distributedSystemId == tag.getDistributedSystemId()) { if (getVersionTimeStamp() <= tag.getVersionTimeStamp()) { setVersionTimeStamp(tag.getVersionTimeStamp()); } else { tag.setVersionTimeStamp(getVersionTimeStamp()); } } else { setVersionTimeStamp(tag.getVersionTimeStamp()); } this.distributedSystemId = (byte)(tag.getDistributedSystemId() & 0xff); } public final void setMemberID(VersionSource memberID) { this.memberID = memberID; } @Override public final VersionStamp getVersionStamp() { return this; } public final VersionTag asVersionTag() { VersionTag tag = VersionTag.create(memberID); tag.setEntryVersion(getEntryVersion()); tag.setRegionVersion(this.regionVersionHighBytes, this.regionVersionLowBytes); tag.setVersionTimeStamp(getVersionTimeStamp()); tag.setDistributedSystemId(this.distributedSystemId); return tag; } public final void processVersionTag(LocalRegion r, VersionTag tag, boolean isTombstoneFromGII, boolean hasDelta, VersionSource thisVM, InternalDistributedMember sender, boolean checkForConflicts) { basicProcessVersionTag(r, tag, isTombstoneFromGII, hasDelta, thisVM, sender, checkForConflicts); } @Override public final void processVersionTag(EntryEvent cacheEvent) { super.processVersionTag(cacheEvent); } public final short getRegionVersionHighBytes() { return this.regionVersionHighBytes; } public final int getRegionVersionLowBytes() { return this.regionVersionLowBytes; } private Object key; @Override public final Object getRawKey() { return this.key; } @Override protected final void _setRawKey(Object key) { this.key = key; } @Retained @Released private volatile long ohAddress; private final static AtomicLongFieldUpdater<VersionedStatsLRURegionEntryOffHeap> ohAddrUpdater = AtomicUpdaterFactory.newLongFieldUpdater(VersionedStatsLRURegionEntryOffHeap.class, "ohAddress"); @Override public final boolean isOffHeap() { return true; } @Override public final Token getValueAsToken() { return OffHeapRegionEntryHelper.getValueAsToken(this); } @Override @Unretained protected final Object getValueField() { return OffHeapRegionEntryHelper._getValue(this); } @Override protected final void setValueField(@Unretained Object v) { OffHeapRegionEntryHelper.setValue(this, v); } @Override @Retained public final Object _getValueRetain(RegionEntryContext context, boolean decompress) { return OffHeapRegionEntryHelper._getValueRetain(this, decompress); } @Override public final long getAddress() { return ohAddrUpdater.get(this); } @Override public final boolean setAddress(long expectedAddr, long newAddr) { return ohAddrUpdater.compareAndSet(this, expectedAddr, newAddr); } @Override @Released public final void release() { OffHeapRegionEntryHelper.releaseEntry(this); } private static RegionEntryFactory factory = new RegionEntryFactory() { public final RegionEntry createEntry(RegionEntryContext context, Object key, Object value) { return new VersionedStatsLRURegionEntryOffHeap(context, key, value); } public final Class<?> getEntryClass() { return VersionedStatsLRURegionEntryOffHeap.class; } public RegionEntryFactory makeVersioned() { return this; } @Override public RegionEntryFactory makeOnHeap() { return VersionedStatsLRURegionEntryHeap.getEntryFactory(); } }; public static RegionEntryFactory getEntryFactory() { return factory; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: SimpleService.proto package io.rsocket.rpc.testing.protobuf; public interface SimpleRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:io.rsocket.rpc.testing.SimpleRequest) com.google.protobuf.MessageOrBuilder { /** * <code>string requestMessage = 1;</code> */ java.lang.String getRequestMessage(); /** * <code>string requestMessage = 1;</code> */ com.google.protobuf.ByteString getRequestMessageBytes(); }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.storage; import java.math.BigDecimal; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import org.apache.cloudstack.api.command.admin.storage.CancelPrimaryStorageMaintenanceCmd; import org.apache.cloudstack.api.command.admin.storage.CreateSecondaryStagingStoreCmd; import org.apache.cloudstack.api.command.admin.storage.CreateStoragePoolCmd; import org.apache.cloudstack.api.command.admin.storage.DeleteImageStoreCmd; import org.apache.cloudstack.api.command.admin.storage.DeletePoolCmd; import org.apache.cloudstack.api.command.admin.storage.DeleteSecondaryStagingStoreCmd; import org.apache.cloudstack.api.command.admin.storage.UpdateStoragePoolCmd; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreDriver; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreLifeCycle; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProviderManager; import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; import org.apache.cloudstack.engine.subsystem.api.storage.ImageStoreProvider; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreLifeCycle; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotService; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService.TemplateApiResult; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult; import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; import org.apache.cloudstack.framework.async.AsyncCallFuture; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.Configurable; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.managed.context.ManagedContextRunnable; import org.apache.cloudstack.management.ManagementServerHost; import org.apache.cloudstack.storage.command.DettachCommand; import org.apache.cloudstack.storage.datastore.db.ImageStoreDao; import org.apache.cloudstack.storage.datastore.db.ImageStoreDetailsDao; import org.apache.cloudstack.storage.datastore.db.ImageStoreVO; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao; import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO; import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity; import org.apache.cloudstack.storage.to.VolumeObjectTO; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; import com.cloud.agent.api.DeleteStoragePoolCommand; import com.cloud.agent.api.StoragePoolInfo; import com.cloud.agent.api.to.DataTO; import com.cloud.agent.api.to.DiskTO; import com.cloud.agent.manager.Commands; import com.cloud.api.ApiDBUtils; import com.cloud.api.query.dao.TemplateJoinDao; import com.cloud.api.query.vo.TemplateJoinVO; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityManager; import com.cloud.capacity.CapacityState; import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDao; import com.cloud.cluster.ClusterManagerListener; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationManagerImpl; import com.cloud.configuration.Resource.ResourceType; import com.cloud.dc.ClusterVO; import com.cloud.dc.DataCenterVO; import com.cloud.dc.dao.ClusterDao; import com.cloud.dc.dao.DataCenterDao; import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.ConnectionException; import com.cloud.exception.DiscoveryException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.OperationTimedoutException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceInUseException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.StorageConflictException; import com.cloud.exception.StorageUnavailableException; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.Status; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.HypervisorGuruManager; import com.cloud.offering.DiskOffering; import com.cloud.offering.ServiceOffering; import com.cloud.org.Grouping; import com.cloud.org.Grouping.AllocationState; import com.cloud.resource.ResourceState; import com.cloud.server.ConfigurationServer; import com.cloud.server.ManagementServer; import com.cloud.server.StatsCollector; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Volume.Type; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.storage.dao.StoragePoolTagsDao; import com.cloud.storage.dao.StoragePoolWorkDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplatePoolDao; import com.cloud.storage.dao.VMTemplateZoneDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.listener.StoragePoolMonitor; import com.cloud.storage.listener.VolumeStateListener; import com.cloud.template.TemplateManager; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.ResourceLimitService; import com.cloud.user.dao.UserDao; import com.cloud.utils.DateUtil; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; import com.cloud.utils.UriUtils; import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.EntityManager; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.JoinBuilder.JoinType; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.Transaction; import com.cloud.utils.db.TransactionCallbackNoReturn; import com.cloud.utils.db.TransactionLegacy; import com.cloud.utils.db.TransactionStatus; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.DiskProfile; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.dao.VMInstanceDao; @Component public class StorageManagerImpl extends ManagerBase implements StorageManager, ClusterManagerListener, Configurable { private static final Logger s_logger = Logger.getLogger(StorageManagerImpl.class); protected String _name; @Inject protected AgentManager _agentMgr; @Inject protected TemplateManager _tmpltMgr; @Inject protected AccountManager _accountMgr; @Inject protected ConfigurationManager _configMgr; @Inject protected VolumeDao _volsDao; @Inject private VolumeDataStoreDao _volumeDataStoreDao; @Inject protected HostDao _hostDao; @Inject protected SnapshotDao _snapshotDao; @Inject protected StoragePoolHostDao _storagePoolHostDao; @Inject protected VMTemplatePoolDao _vmTemplatePoolDao = null; @Inject protected VMTemplateZoneDao _vmTemplateZoneDao; @Inject protected VMTemplateDao _vmTemplateDao = null; @Inject protected VMInstanceDao _vmInstanceDao; @Inject protected PrimaryDataStoreDao _storagePoolDao = null; @Inject protected StoragePoolDetailsDao _storagePoolDetailsDao; @Inject protected ImageStoreDao _imageStoreDao = null; @Inject protected ImageStoreDetailsDao _imageStoreDetailsDao = null; @Inject protected SnapshotDataStoreDao _snapshotStoreDao = null; @Inject protected TemplateDataStoreDao _templateStoreDao = null; @Inject protected TemplateJoinDao _templateViewDao = null; @Inject protected VolumeDataStoreDao _volumeStoreDao = null; @Inject protected CapacityDao _capacityDao; @Inject protected CapacityManager _capacityMgr; @Inject protected DataCenterDao _dcDao = null; @Inject protected VMTemplateDao _templateDao; @Inject protected UserDao _userDao; @Inject protected ClusterDao _clusterDao; @Inject protected StoragePoolWorkDao _storagePoolWorkDao; @Inject protected HypervisorGuruManager _hvGuruMgr; @Inject protected VolumeDao _volumeDao; @Inject ConfigurationDao _configDao; @Inject ManagementServer _msServer; @Inject VolumeService volService; @Inject VolumeDataFactory volFactory; @Inject TemplateDataFactory tmplFactory; @Inject SnapshotDataFactory snapshotFactory; @Inject ConfigurationServer _configServer; @Inject DataStoreManager _dataStoreMgr; @Inject DataStoreProviderManager _dataStoreProviderMgr; @Inject private TemplateService _imageSrv; @Inject EndPointSelector _epSelector; @Inject private DiskOfferingDao _diskOfferingDao; @Inject ResourceLimitService _resourceLimitMgr; @Inject EntityManager _entityMgr; @Inject SnapshotService _snapshotService; @Inject StoragePoolTagsDao _storagePoolTagsDao; protected List<StoragePoolDiscoverer> _discoverers; public List<StoragePoolDiscoverer> getDiscoverers() { return _discoverers; } public void setDiscoverers(List<StoragePoolDiscoverer> discoverers) { _discoverers = discoverers; } protected SearchBuilder<VMTemplateHostVO> HostTemplateStatesSearch; protected GenericSearchBuilder<StoragePoolHostVO, Long> UpHostsInPoolSearch; protected SearchBuilder<VMInstanceVO> StoragePoolSearch; protected SearchBuilder<StoragePoolVO> LocalStorageSearch; ScheduledExecutorService _executor = null; int _storagePoolAcquisitionWaitSeconds = 1800; // 30 minutes int _downloadUrlCleanupInterval; int _downloadUrlExpirationInterval; // protected BigDecimal _overProvisioningFactor = new BigDecimal(1); private long _serverId; private final Map<String, HypervisorHostListener> hostListeners = new HashMap<String, HypervisorHostListener>(); public boolean share(VMInstanceVO vm, List<VolumeVO> vols, HostVO host, boolean cancelPreviousShare) throws StorageUnavailableException { // if pool is in maintenance and it is the ONLY pool available; reject List<VolumeVO> rootVolForGivenVm = _volsDao.findByInstanceAndType(vm.getId(), Type.ROOT); if (rootVolForGivenVm != null && rootVolForGivenVm.size() > 0) { boolean isPoolAvailable = isPoolAvailable(rootVolForGivenVm.get(0).getPoolId()); if (!isPoolAvailable) { throw new StorageUnavailableException("Can not share " + vm, rootVolForGivenVm.get(0).getPoolId()); } } // this check is done for maintenance mode for primary storage // if any one of the volume is unusable, we return false // if we return false, the allocator will try to switch to another PS if // available for (VolumeVO vol : vols) { if (vol.getRemoved() != null) { s_logger.warn("Volume id:" + vol.getId() + " is removed, cannot share on this instance"); // not ok to share return false; } } // ok to share return true; } private boolean isPoolAvailable(Long poolId) { // get list of all pools List<StoragePoolVO> pools = _storagePoolDao.listAll(); // if no pools or 1 pool which is in maintenance if (pools == null || pools.size() == 0 || (pools.size() == 1 && pools.get(0).getStatus().equals(StoragePoolStatus.Maintenance))) { return false; } else { return true; } } @Override public List<StoragePoolVO> ListByDataCenterHypervisor(long datacenterId, HypervisorType type) { List<StoragePoolVO> pools = _storagePoolDao.listByDataCenterId(datacenterId); List<StoragePoolVO> retPools = new ArrayList<StoragePoolVO>(); for (StoragePoolVO pool : pools) { if (pool.getStatus() != StoragePoolStatus.Up) { continue; } if (pool.getScope() == ScopeType.ZONE) { if (pool.getHypervisor() != null && pool.getHypervisor() == type) { retPools.add(pool); } } else { ClusterVO cluster = _clusterDao.findById(pool.getClusterId()); if (type == cluster.getHypervisorType()) { retPools.add(pool); } } } Collections.shuffle(retPools); return retPools; } @Override public boolean isLocalStorageActiveOnHost(Long hostId) { List<StoragePoolHostVO> storagePoolHostRefs = _storagePoolHostDao.listByHostId(hostId); for (StoragePoolHostVO storagePoolHostRef : storagePoolHostRefs) { StoragePoolVO PrimaryDataStoreVO = _storagePoolDao.findById(storagePoolHostRef.getPoolId()); if (PrimaryDataStoreVO.getPoolType() == StoragePoolType.LVM || PrimaryDataStoreVO.getPoolType() == StoragePoolType.EXT) { SearchBuilder<VolumeVO> volumeSB = _volsDao.createSearchBuilder(); volumeSB.and("poolId", volumeSB.entity().getPoolId(), SearchCriteria.Op.EQ); volumeSB.and("removed", volumeSB.entity().getRemoved(), SearchCriteria.Op.NULL); volumeSB.and("state", volumeSB.entity().getState(), SearchCriteria.Op.NIN); SearchBuilder<VMInstanceVO> activeVmSB = _vmInstanceDao.createSearchBuilder(); activeVmSB.and("state", activeVmSB.entity().getState(), SearchCriteria.Op.IN); volumeSB.join("activeVmSB", activeVmSB, volumeSB.entity().getInstanceId(), activeVmSB.entity().getId(), JoinBuilder.JoinType.INNER); SearchCriteria<VolumeVO> volumeSC = volumeSB.create(); volumeSC.setParameters("poolId", PrimaryDataStoreVO.getId()); volumeSC.setParameters("state", Volume.State.Expunging, Volume.State.Destroy); volumeSC.setJoinParameters("activeVmSB", "state", State.Starting, State.Running, State.Stopping, State.Migrating); List<VolumeVO> volumes = _volsDao.search(volumeSC, null); if (volumes.size() > 0) { return true; } } } return false; } @Override public Answer[] sendToPool(StoragePool pool, Commands cmds) throws StorageUnavailableException { return sendToPool(pool, null, null, cmds).second(); } @Override public Answer sendToPool(StoragePool pool, long[] hostIdsToTryFirst, Command cmd) throws StorageUnavailableException { Answer[] answers = sendToPool(pool, hostIdsToTryFirst, null, new Commands(cmd)).second(); if (answers == null) { return null; } return answers[0]; } @Override public Answer sendToPool(StoragePool pool, Command cmd) throws StorageUnavailableException { Answer[] answers = sendToPool(pool, new Commands(cmd)); if (answers == null) { return null; } return answers[0]; } public Long chooseHostForStoragePool(StoragePoolVO poolVO, List<Long> avoidHosts, boolean sendToVmResidesOn, Long vmId) { if (sendToVmResidesOn) { if (vmId != null) { VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId); if (vmInstance != null) { Long hostId = vmInstance.getHostId(); if (hostId != null && !avoidHosts.contains(vmInstance.getHostId())) { return hostId; } } } /* * Can't find the vm where host resides on(vm is destroyed? or * volume is detached from vm), randomly choose a host to send the * cmd */ } List<StoragePoolHostVO> poolHosts = _storagePoolHostDao.listByHostStatus(poolVO.getId(), Status.Up); Collections.shuffle(poolHosts); if (poolHosts != null && poolHosts.size() > 0) { for (StoragePoolHostVO sphvo : poolHosts) { if (!avoidHosts.contains(sphvo.getHostId())) { return sphvo.getHostId(); } } } return null; } @Override public boolean configure(String name, Map<String, Object> params) { Map<String, String> configs = _configDao.getConfiguration("management-server", params); _storagePoolAcquisitionWaitSeconds = NumbersUtil.parseInt(configs.get("pool.acquisition.wait.seconds"), 1800); s_logger.info("pool.acquisition.wait.seconds is configured as " + _storagePoolAcquisitionWaitSeconds + " seconds"); _agentMgr.registerForHostEvents(new StoragePoolMonitor(this, _storagePoolDao, _dataStoreProviderMgr), true, false, true); s_logger.info("Storage cleanup enabled: " + StorageCleanupEnabled.value() + ", interval: " + StorageCleanupInterval.value() + ", delay: " + StorageCleanupDelay.value() + ", template cleanup enabled: " + TemplateCleanupEnabled.value()); String cleanupInterval = configs.get("extract.url.cleanup.interval"); _downloadUrlCleanupInterval = NumbersUtil.parseInt(cleanupInterval, 7200); String urlExpirationInterval = configs.get("extract.url.expiration.interval"); _downloadUrlExpirationInterval = NumbersUtil.parseInt(urlExpirationInterval, 14400); String workers = configs.get("expunge.workers"); int wrks = NumbersUtil.parseInt(workers, 10); _executor = Executors.newScheduledThreadPool(wrks, new NamedThreadFactory("StorageManager-Scavenger")); _agentMgr.registerForHostEvents(ComponentContext.inject(LocalStoragePoolListener.class), true, false, false); _serverId = _msServer.getId(); UpHostsInPoolSearch = _storagePoolHostDao.createSearchBuilder(Long.class); UpHostsInPoolSearch.selectFields(UpHostsInPoolSearch.entity().getHostId()); SearchBuilder<HostVO> hostSearch = _hostDao.createSearchBuilder(); hostSearch.and("status", hostSearch.entity().getStatus(), Op.EQ); hostSearch.and("resourceState", hostSearch.entity().getResourceState(), Op.EQ); UpHostsInPoolSearch.join("hosts", hostSearch, hostSearch.entity().getId(), UpHostsInPoolSearch.entity().getHostId(), JoinType.INNER); UpHostsInPoolSearch.and("pool", UpHostsInPoolSearch.entity().getPoolId(), Op.EQ); UpHostsInPoolSearch.done(); StoragePoolSearch = _vmInstanceDao.createSearchBuilder(); SearchBuilder<VolumeVO> volumeSearch = _volumeDao.createSearchBuilder(); volumeSearch.and("volumeType", volumeSearch.entity().getVolumeType(), SearchCriteria.Op.EQ); volumeSearch.and("poolId", volumeSearch.entity().getPoolId(), SearchCriteria.Op.EQ); volumeSearch.and("state", volumeSearch.entity().getState(), SearchCriteria.Op.EQ); StoragePoolSearch.join("vmVolume", volumeSearch, volumeSearch.entity().getInstanceId(), StoragePoolSearch.entity().getId(), JoinBuilder.JoinType.INNER); StoragePoolSearch.done(); LocalStorageSearch = _storagePoolDao.createSearchBuilder(); SearchBuilder<StoragePoolHostVO> storageHostSearch = _storagePoolHostDao.createSearchBuilder(); storageHostSearch.and("hostId", storageHostSearch.entity().getHostId(), SearchCriteria.Op.EQ); LocalStorageSearch.join("poolHost", storageHostSearch, storageHostSearch.entity().getPoolId(), LocalStorageSearch.entity().getId(), JoinBuilder.JoinType.INNER); LocalStorageSearch.and("type", LocalStorageSearch.entity().getPoolType(), SearchCriteria.Op.IN); LocalStorageSearch.done(); Volume.State.getStateMachine().registerListener(new VolumeStateListener(_configDao, _vmInstanceDao)); return true; } @Override public String getStoragePoolTags(long poolId) { return StringUtils.listToCsvTags(getStoragePoolTagList(poolId)); } @Override public List<String> getStoragePoolTagList(long poolId) { return _storagePoolDao.searchForStoragePoolTags(poolId); } @Override public boolean start() { if (StorageCleanupEnabled.value()) { Random generator = new Random(); int initialDelay = generator.nextInt(StorageCleanupInterval.value()); _executor.scheduleWithFixedDelay(new StorageGarbageCollector(), initialDelay, StorageCleanupInterval.value(), TimeUnit.SECONDS); } else { s_logger.debug("Storage cleanup is not enabled, so the storage cleanup thread is not being scheduled."); } _executor.scheduleWithFixedDelay(new DownloadURLGarbageCollector(), _downloadUrlCleanupInterval, _downloadUrlCleanupInterval, TimeUnit.SECONDS); return true; } @Override public boolean stop() { if (StorageCleanupEnabled.value()) { _executor.shutdown(); } return true; } @DB @Override public DataStore createLocalStorage(Host host, StoragePoolInfo pInfo) throws ConnectionException { DataCenterVO dc = _dcDao.findById(host.getDataCenterId()); if (dc == null) { return null; } boolean useLocalStorageForSystemVM = false; Boolean isLocal = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dc.getId()); if (isLocal != null) { useLocalStorageForSystemVM = isLocal.booleanValue(); } if (!(dc.isLocalStorageEnabled() || useLocalStorageForSystemVM)) { return null; } DataStore store; try { String hostAddress = pInfo.getHost(); if (host.getHypervisorType() == Hypervisor.HypervisorType.VMware) { hostAddress = "VMFS datastore: " + pInfo.getHostPath(); } StoragePoolVO pool = _storagePoolDao.findPoolByHostPath(host.getDataCenterId(), host.getPodId(), hostAddress, pInfo.getHostPath(), pInfo.getUuid()); if (pool == null && host.getHypervisorType() == HypervisorType.VMware) { // perform run-time upgrade. In versions prior to 2.2.12, there // is a bug that we don't save local datastore info (host path // is empty), this will cause us // not able to distinguish multiple local datastores that may be // available on the host, to support smooth migration, we // need to perform runtime upgrade here if (pInfo.getHostPath().length() > 0) { pool = _storagePoolDao.findPoolByHostPath(host.getDataCenterId(), host.getPodId(), hostAddress, "", pInfo.getUuid()); } } if (pool == null) { //the path can be different, but if they have the same uuid, assume they are the same storage pool = _storagePoolDao.findPoolByHostPath(host.getDataCenterId(), host.getPodId(), hostAddress, null, pInfo.getUuid()); if (pool != null) { s_logger.debug("Found a storage pool: " + pInfo.getUuid() + ", but with different hostpath " + pInfo.getHostPath() + ", still treat it as the same pool"); } } DataStoreProvider provider = _dataStoreProviderMgr.getDefaultPrimaryDataStoreProvider(); DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); if (pool == null) { Map<String, Object> params = new HashMap<String, Object>(); String name = createLocalStoragePoolName(host, pInfo); params.put("zoneId", host.getDataCenterId()); params.put("clusterId", host.getClusterId()); params.put("podId", host.getPodId()); params.put("url", pInfo.getPoolType().toString() + "://" + pInfo.getHost() + "/" + pInfo.getHostPath()); params.put("name", name); params.put("localStorage", true); params.put("details", pInfo.getDetails()); params.put("uuid", pInfo.getUuid()); params.put("providerName", provider.getName()); store = lifeCycle.initialize(params); } else { store = _dataStoreMgr.getDataStore(pool.getId(), DataStoreRole.Primary); } pool = _storagePoolDao.findById(store.getId()); if (pool.getStatus() != StoragePoolStatus.Maintenance && pool.getStatus() != StoragePoolStatus.Removed) { HostScope scope = new HostScope(host.getId(), host.getClusterId(), host.getDataCenterId()); lifeCycle.attachHost(store, scope, pInfo); } } catch (Exception e) { s_logger.warn("Unable to setup the local storage pool for " + host, e); throw new ConnectionException(true, "Unable to setup the local storage pool for " + host, e); } return _dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Primary); } /** * Creates the local storage pool name. * The name will follow the pattern: <hostname>-local-<firstBlockOfUuid> */ protected String createLocalStoragePoolName(Host host, StoragePoolInfo storagePoolInformation) { return String.format("%s-%s-%s", org.apache.commons.lang3.StringUtils.trim(host.getName()), "local", storagePoolInformation.getUuid().split("-")[0]); } @Override public PrimaryDataStoreInfo createPool(CreateStoragePoolCmd cmd) throws ResourceInUseException, IllegalArgumentException, UnknownHostException, ResourceUnavailableException { String providerName = cmd.getStorageProviderName(); DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(providerName); if (storeProvider == null) { storeProvider = _dataStoreProviderMgr.getDefaultPrimaryDataStoreProvider(); if (storeProvider == null) { throw new InvalidParameterValueException("can't find storage provider: " + providerName); } } Long clusterId = cmd.getClusterId(); Long podId = cmd.getPodId(); Long zoneId = cmd.getZoneId(); ScopeType scopeType = ScopeType.CLUSTER; String scope = cmd.getScope(); if (scope != null) { try { scopeType = Enum.valueOf(ScopeType.class, scope.toUpperCase()); } catch (Exception e) { throw new InvalidParameterValueException("invalid scope for pool " + scope); } } if (scopeType == ScopeType.CLUSTER && clusterId == null) { throw new InvalidParameterValueException("cluster id can't be null, if scope is cluster"); } else if (scopeType == ScopeType.ZONE && zoneId == null) { throw new InvalidParameterValueException("zone id can't be null, if scope is zone"); } HypervisorType hypervisorType = HypervisorType.KVM; if (scopeType == ScopeType.ZONE) { // ignore passed clusterId and podId clusterId = null; podId = null; String hypervisor = cmd.getHypervisor(); if (hypervisor != null) { try { hypervisorType = HypervisorType.getType(hypervisor); } catch (Exception e) { throw new InvalidParameterValueException("invalid hypervisor type " + hypervisor); } } else { throw new InvalidParameterValueException("Missing parameter hypervisor. Hypervisor type is required to create zone wide primary storage."); } if (hypervisorType != HypervisorType.KVM && hypervisorType != HypervisorType.VMware && hypervisorType != HypervisorType.Hyperv && hypervisorType != HypervisorType.LXC && hypervisorType != HypervisorType.Any) { throw new InvalidParameterValueException("zone wide storage pool is not supported for hypervisor type " + hypervisor); } } Map<String, String> details = extractApiParamAsMap(cmd.getDetails()); DataCenterVO zone = _dcDao.findById(cmd.getZoneId()); if (zone == null) { throw new InvalidParameterValueException("unable to find zone by id " + zoneId); } // Check if zone is disabled Account account = CallContext.current().getCallingAccount(); if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getId())) { throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId); } Map<String, Object> params = new HashMap<String, Object>(); params.put("zoneId", zone.getId()); params.put("clusterId", clusterId); params.put("podId", podId); params.put("url", cmd.getUrl()); params.put("tags", cmd.getTags()); params.put("name", cmd.getStoragePoolName()); params.put("details", details); params.put("providerName", storeProvider.getName()); params.put("managed", cmd.isManaged()); params.put("capacityBytes", cmd.getCapacityBytes()); params.put("capacityIops", cmd.getCapacityIops()); DataStoreLifeCycle lifeCycle = storeProvider.getDataStoreLifeCycle(); DataStore store = null; try { store = lifeCycle.initialize(params); if (scopeType == ScopeType.CLUSTER) { ClusterScope clusterScope = new ClusterScope(clusterId, podId, zoneId); lifeCycle.attachCluster(store, clusterScope); } else if (scopeType == ScopeType.ZONE) { ZoneScope zoneScope = new ZoneScope(zoneId); lifeCycle.attachZone(store, zoneScope, hypervisorType); } } catch (Exception e) { s_logger.debug("Failed to add data store: " + e.getMessage(), e); try { // clean up the db, just absorb the exception thrown in deletion with error logged, so that user can get error for adding data store // not deleting data store. if (store != null) { lifeCycle.deleteDataStore(store); } } catch (Exception ex) { s_logger.debug("Failed to clean up storage pool: " + ex.getMessage()); } throw new CloudRuntimeException("Failed to add data store: " + e.getMessage(), e); } return (PrimaryDataStoreInfo)_dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Primary); } private Map<String, String> extractApiParamAsMap(Map ds) { Map<String, String> details = new HashMap<String, String>(); if (ds != null) { Collection detailsCollection = ds.values(); Iterator it = detailsCollection.iterator(); while (it.hasNext()) { HashMap d = (HashMap)it.next(); Iterator it2 = d.entrySet().iterator(); while (it2.hasNext()) { Map.Entry entry = (Map.Entry)it2.next(); details.put((String)entry.getKey(), (String)entry.getValue()); } } } return details; } @ActionEvent(eventType = EventTypes.EVENT_DISABLE_PRIMARY_STORAGE, eventDescription = "disable storage pool") private void disablePrimaryStoragePool(StoragePoolVO primaryStorage) { if (!primaryStorage.getStatus().equals(StoragePoolStatus.Up)) { throw new InvalidParameterValueException("Primary storage with id " + primaryStorage.getId() + " cannot be disabled. Storage pool state : " + primaryStorage.getStatus().toString()); } DataStoreProvider provider = _dataStoreProviderMgr.getDataStoreProvider(primaryStorage.getStorageProviderName()); DataStoreLifeCycle dataStoreLifeCycle = provider.getDataStoreLifeCycle(); DataStore store = _dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary); ((PrimaryDataStoreLifeCycle)dataStoreLifeCycle).disableStoragePool(store); } @ActionEvent(eventType = EventTypes.EVENT_ENABLE_PRIMARY_STORAGE, eventDescription = "enable storage pool") private void enablePrimaryStoragePool(StoragePoolVO primaryStorage) { if (!primaryStorage.getStatus().equals(StoragePoolStatus.Disabled)) { throw new InvalidParameterValueException("Primary storage with id " + primaryStorage.getId() + " cannot be enabled. Storage pool state : " + primaryStorage.getStatus().toString()); } DataStoreProvider provider = _dataStoreProviderMgr.getDataStoreProvider(primaryStorage.getStorageProviderName()); DataStoreLifeCycle dataStoreLifeCycle = provider.getDataStoreLifeCycle(); DataStore store = _dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary); ((PrimaryDataStoreLifeCycle)dataStoreLifeCycle).enableStoragePool(store); } @Override public PrimaryDataStoreInfo updateStoragePool(UpdateStoragePoolCmd cmd) throws IllegalArgumentException { // Input validation Long id = cmd.getId(); StoragePoolVO pool = _storagePoolDao.findById(id); if (pool == null) { throw new IllegalArgumentException("Unable to find storage pool with ID: " + id); } final List<String> storagePoolTags = cmd.getTags(); if (storagePoolTags != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Updating Storage Pool Tags to :" + storagePoolTags); } _storagePoolTagsDao.persist(pool.getId(), storagePoolTags); } Long updatedCapacityBytes = null; Long capacityBytes = cmd.getCapacityBytes(); if (capacityBytes != null) { if (capacityBytes != pool.getCapacityBytes()) { updatedCapacityBytes = capacityBytes; } } Long updatedCapacityIops = null; Long capacityIops = cmd.getCapacityIops(); if (capacityIops != null) { if (!capacityIops.equals(pool.getCapacityIops())) { updatedCapacityIops = capacityIops; } } if (updatedCapacityBytes != null || updatedCapacityIops != null) { StoragePoolVO storagePool = _storagePoolDao.findById(id); DataStoreProvider dataStoreProvider = _dataStoreProviderMgr.getDataStoreProvider(storagePool.getStorageProviderName()); DataStoreLifeCycle dataStoreLifeCycle = dataStoreProvider.getDataStoreLifeCycle(); if (dataStoreLifeCycle instanceof PrimaryDataStoreLifeCycle) { Map<String, String> details = new HashMap<String, String>(); details.put(PrimaryDataStoreLifeCycle.CAPACITY_BYTES, updatedCapacityBytes != null ? String.valueOf(updatedCapacityBytes) : null); details.put(PrimaryDataStoreLifeCycle.CAPACITY_IOPS, updatedCapacityIops != null ? String.valueOf(updatedCapacityIops) : null); ((PrimaryDataStoreLifeCycle)dataStoreLifeCycle).updateStoragePool(storagePool, details); } } Boolean enabled = cmd.getEnabled(); if (enabled != null) { if (enabled) { enablePrimaryStoragePool(pool); } else { disablePrimaryStoragePool(pool); } } if (updatedCapacityBytes != null) { _storagePoolDao.updateCapacityBytes(id, capacityBytes); } if (updatedCapacityIops != null) { _storagePoolDao.updateCapacityIops(id, capacityIops); } return (PrimaryDataStoreInfo)_dataStoreMgr.getDataStore(pool.getId(), DataStoreRole.Primary); } @Override public void removeStoragePoolFromCluster(long hostId, String iScsiName, StoragePool storagePool) { final Map<String, String> details = new HashMap<>(); details.put(DeleteStoragePoolCommand.DATASTORE_NAME, iScsiName); details.put(DeleteStoragePoolCommand.IQN, iScsiName); details.put(DeleteStoragePoolCommand.STORAGE_HOST, storagePool.getHostAddress()); details.put(DeleteStoragePoolCommand.STORAGE_PORT, String.valueOf(storagePool.getPort())); final DeleteStoragePoolCommand cmd = new DeleteStoragePoolCommand(); cmd.setDetails(details); cmd.setRemoveDatastore(true); final Answer answer = _agentMgr.easySend(hostId, cmd); if (answer == null || !answer.getResult()) { String errMsg = "Error interacting with host (related to DeleteStoragePoolCommand)" + (StringUtils.isNotBlank(answer.getDetails()) ? ": " + answer.getDetails() : ""); s_logger.error(errMsg); throw new CloudRuntimeException(errMsg); } } @Override @DB public boolean deletePool(DeletePoolCmd cmd) { Long id = cmd.getId(); boolean forced = cmd.isForced(); StoragePoolVO sPool = _storagePoolDao.findById(id); if (sPool == null) { s_logger.warn("Unable to find pool:" + id); throw new InvalidParameterValueException("Unable to find pool by id " + id); } if (sPool.getStatus() != StoragePoolStatus.Maintenance) { s_logger.warn("Unable to delete storage id: " + id + " due to it is not in Maintenance state"); throw new InvalidParameterValueException("Unable to delete storage due to it is not in Maintenance state, id: " + id); } Pair<Long, Long> vlms = _volsDao.getCountAndTotalByPool(id); if (forced) { if (vlms.first() > 0) { Pair<Long, Long> nonDstrdVlms = _volsDao.getNonDestroyedCountAndTotalByPool(id); if (nonDstrdVlms.first() > 0) { throw new CloudRuntimeException("Cannot delete pool " + sPool.getName() + " as there are associated " + "non-destroyed vols for this pool"); } // force expunge non-destroyed volumes List<VolumeVO> vols = _volsDao.listVolumesToBeDestroyed(); for (VolumeVO vol : vols) { AsyncCallFuture<VolumeApiResult> future = volService.expungeVolumeAsync(volFactory.getVolume(vol.getId())); try { future.get(); } catch (InterruptedException e) { s_logger.debug("expunge volume failed:" + vol.getId(), e); } catch (ExecutionException e) { s_logger.debug("expunge volume failed:" + vol.getId(), e); } } } } else { // Check if the pool has associated volumes in the volumes table // If it does , then you cannot delete the pool if (vlms.first() > 0) { throw new CloudRuntimeException("Cannot delete pool " + sPool.getName() + " as there are associated volumes for this pool"); } } // First get the host_id from storage_pool_host_ref for given pool id StoragePoolVO lock = _storagePoolDao.acquireInLockTable(sPool.getId()); if (lock == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Failed to acquire lock when deleting PrimaryDataStoreVO with ID: " + sPool.getId()); } return false; } _storagePoolDao.releaseFromLockTable(lock.getId()); s_logger.trace("Released lock for storage pool " + id); DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(sPool.getStorageProviderName()); DataStoreLifeCycle lifeCycle = storeProvider.getDataStoreLifeCycle(); DataStore store = _dataStoreMgr.getDataStore(sPool.getId(), DataStoreRole.Primary); return lifeCycle.deleteDataStore(store); } @Override public void connectHostToSharedPool(long hostId, long poolId) throws StorageUnavailableException, StorageConflictException { StoragePool pool = (StoragePool)_dataStoreMgr.getDataStore(poolId, DataStoreRole.Primary); assert (pool.isShared()) : "Now, did you actually read the name of this method?"; s_logger.debug("Adding pool " + pool.getName() + " to host " + hostId); DataStoreProvider provider = _dataStoreProviderMgr.getDataStoreProvider(pool.getStorageProviderName()); HypervisorHostListener listener = hostListeners.get(provider.getName()); listener.hostConnect(hostId, pool.getId()); } @Override public BigDecimal getStorageOverProvisioningFactor(Long poolId) { return new BigDecimal(CapacityManager.StorageOverprovisioningFactor.valueIn(poolId)); } @Override public void createCapacityEntry(StoragePoolVO storagePool, short capacityType, long allocated) { SearchCriteria<CapacityVO> capacitySC = _capacityDao.createSearchCriteria(); capacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, storagePool.getId()); capacitySC.addAnd("dataCenterId", SearchCriteria.Op.EQ, storagePool.getDataCenterId()); capacitySC.addAnd("capacityType", SearchCriteria.Op.EQ, capacityType); List<CapacityVO> capacities = _capacityDao.search(capacitySC, null); long totalOverProvCapacity; if (storagePool.getPoolType().supportsOverProvisioning()) { // All this is for the inaccuracy of floats for big number multiplication. BigDecimal overProvFactor = getStorageOverProvisioningFactor(storagePool.getId()); totalOverProvCapacity = overProvFactor.multiply(new BigDecimal(storagePool.getCapacityBytes())).longValue(); s_logger.debug("Found storage pool " + storagePool.getName() + " of type " + storagePool.getPoolType().toString() + " with overprovisioning factor " + overProvFactor.toString()); s_logger.debug("Total over provisioned capacity calculated is " + overProvFactor + " * " + storagePool.getCapacityBytes()); } else { s_logger.debug("Found storage pool " + storagePool.getName() + " of type " + storagePool.getPoolType().toString()); totalOverProvCapacity = storagePool.getCapacityBytes(); } s_logger.debug("Total over provisioned capacity of the pool " + storagePool.getName() + " id: " + storagePool.getId() + " is " + totalOverProvCapacity); CapacityState capacityState = CapacityState.Enabled; if (storagePool.getScope() == ScopeType.ZONE) { DataCenterVO dc = ApiDBUtils.findZoneById(storagePool.getDataCenterId()); AllocationState allocationState = dc.getAllocationState(); capacityState = (allocationState == AllocationState.Disabled) ? CapacityState.Disabled : CapacityState.Enabled; } else { if (storagePool.getClusterId() != null) { ClusterVO cluster = ApiDBUtils.findClusterById(storagePool.getClusterId()); if (cluster != null) { AllocationState allocationState = _configMgr.findClusterAllocationState(cluster); capacityState = (allocationState == AllocationState.Disabled) ? CapacityState.Disabled : CapacityState.Enabled; } } } if (storagePool.getScope() == ScopeType.HOST) { List<StoragePoolHostVO> stoargePoolHostVO = _storagePoolHostDao.listByPoolId(storagePool.getId()); if (stoargePoolHostVO != null && !stoargePoolHostVO.isEmpty()) { HostVO host = _hostDao.findById(stoargePoolHostVO.get(0).getHostId()); if (host != null) { capacityState = (host.getResourceState() == ResourceState.Disabled) ? CapacityState.Disabled : CapacityState.Enabled; } } } if (capacities.size() == 0) { CapacityVO capacity = new CapacityVO(storagePool.getId(), storagePool.getDataCenterId(), storagePool.getPodId(), storagePool.getClusterId(), allocated, totalOverProvCapacity, capacityType); capacity.setCapacityState(capacityState); _capacityDao.persist(capacity); } else { CapacityVO capacity = capacities.get(0); if (capacity.getTotalCapacity() != totalOverProvCapacity || allocated != capacity.getUsedCapacity() || capacity.getCapacityState() != capacityState) { capacity.setTotalCapacity(totalOverProvCapacity); capacity.setUsedCapacity(allocated); capacity.setCapacityState(capacityState); _capacityDao.update(capacity.getId(), capacity); } } s_logger.debug("Successfully set Capacity - " + totalOverProvCapacity + " for capacity type - " + capacityType + " , DataCenterId - " + storagePool.getDataCenterId() + ", HostOrPoolId - " + storagePool.getId() + ", PodId " + storagePool.getPodId()); } @Override public List<Long> getUpHostsInPool(long poolId) { SearchCriteria<Long> sc = UpHostsInPoolSearch.create(); sc.setParameters("pool", poolId); sc.setJoinParameters("hosts", "status", Status.Up); sc.setJoinParameters("hosts", "resourceState", ResourceState.Enabled); return _storagePoolHostDao.customSearch(sc, null); } @Override public Pair<Long, Answer[]> sendToPool(StoragePool pool, long[] hostIdsToTryFirst, List<Long> hostIdsToAvoid, Commands cmds) throws StorageUnavailableException { List<Long> hostIds = getUpHostsInPool(pool.getId()); Collections.shuffle(hostIds); if (hostIdsToTryFirst != null) { for (int i = hostIdsToTryFirst.length - 1; i >= 0; i--) { if (hostIds.remove(hostIdsToTryFirst[i])) { hostIds.add(0, hostIdsToTryFirst[i]); } } } if (hostIdsToAvoid != null) { hostIds.removeAll(hostIdsToAvoid); } if (hostIds == null || hostIds.isEmpty()) { throw new StorageUnavailableException("Unable to send command to the pool " + pool.getId() + " due to there is no enabled hosts up in this cluster", pool.getId()); } for (Long hostId : hostIds) { try { List<Answer> answers = new ArrayList<Answer>(); Command[] cmdArray = cmds.toCommands(); for (Command cmd : cmdArray) { long targetHostId = _hvGuruMgr.getGuruProcessedCommandTargetHost(hostId, cmd); answers.add(_agentMgr.send(targetHostId, cmd)); } return new Pair<Long, Answer[]>(hostId, answers.toArray(new Answer[answers.size()])); } catch (AgentUnavailableException e) { s_logger.debug("Unable to send storage pool command to " + pool + " via " + hostId, e); } catch (OperationTimedoutException e) { s_logger.debug("Unable to send storage pool command to " + pool + " via " + hostId, e); } } throw new StorageUnavailableException("Unable to send command to the pool ", pool.getId()); } @Override public Pair<Long, Answer> sendToPool(StoragePool pool, long[] hostIdsToTryFirst, List<Long> hostIdsToAvoid, Command cmd) throws StorageUnavailableException { Commands cmds = new Commands(cmd); Pair<Long, Answer[]> result = sendToPool(pool, hostIdsToTryFirst, hostIdsToAvoid, cmds); return new Pair<Long, Answer>(result.first(), result.second()[0]); } @Override public void cleanupStorage(boolean recurring) { GlobalLock scanLock = GlobalLock.getInternLock("storagemgr.cleanup"); try { if (scanLock.lock(3)) { try { // Cleanup primary storage pools if (TemplateCleanupEnabled.value()) { List<StoragePoolVO> storagePools = _storagePoolDao.listAll(); for (StoragePoolVO pool : storagePools) { try { List<VMTemplateStoragePoolVO> unusedTemplatesInPool = _tmpltMgr.getUnusedTemplatesInPool(pool); s_logger.debug("Storage pool garbage collector found " + unusedTemplatesInPool.size() + " templates to clean up in storage pool: " + pool.getName()); for (VMTemplateStoragePoolVO templatePoolVO : unusedTemplatesInPool) { if (templatePoolVO.getDownloadState() != VMTemplateStorageResourceAssoc.Status.DOWNLOADED) { s_logger.debug("Storage pool garbage collector is skipping template with ID: " + templatePoolVO.getTemplateId() + " on pool " + templatePoolVO.getPoolId() + " because it is not completely downloaded."); continue; } if (!templatePoolVO.getMarkedForGC()) { templatePoolVO.setMarkedForGC(true); _vmTemplatePoolDao.update(templatePoolVO.getId(), templatePoolVO); s_logger.debug("Storage pool garbage collector has marked template with ID: " + templatePoolVO.getTemplateId() + " on pool " + templatePoolVO.getPoolId() + " for garbage collection."); continue; } _tmpltMgr.evictTemplateFromStoragePool(templatePoolVO); } } catch (Exception e) { s_logger.warn("Problem cleaning up primary storage pool " + pool, e); } } } //destroy snapshots in destroying state in snapshot_store_ref List<SnapshotDataStoreVO> ssSnapshots = _snapshotStoreDao.listByState(ObjectInDataStoreStateMachine.State.Destroying); for (SnapshotDataStoreVO ssSnapshotVO : ssSnapshots) { try { _snapshotService.deleteSnapshot(snapshotFactory.getSnapshot(ssSnapshotVO.getSnapshotId(), DataStoreRole.Image)); } catch (Exception e) { s_logger.debug("Failed to delete snapshot: " + ssSnapshotVO.getId() + " from storage"); } } cleanupSecondaryStorage(recurring); List<VolumeVO> vols = _volsDao.listVolumesToBeDestroyed(new Date(System.currentTimeMillis() - ((long)StorageCleanupDelay.value() << 10))); for (VolumeVO vol : vols) { try { // If this fails, just log a warning. It's ideal if we clean up the host-side clustered file // system, but not necessary. handleManagedStorage(vol); } catch (Exception e) { s_logger.warn("Unable to destroy host-side clustered file system " + vol.getUuid(), e); } try { VolumeInfo volumeInfo = volFactory.getVolume(vol.getId()); if (volumeInfo != null) { volService.expungeVolumeAsync(volumeInfo); } else { s_logger.debug("Volume " + vol.getUuid() + " is already destroyed"); } } catch (Exception e) { s_logger.warn("Unable to destroy volume " + vol.getUuid(), e); } } // remove snapshots in Error state List<SnapshotVO> snapshots = _snapshotDao.listAllByStatus(Snapshot.State.Error); for (SnapshotVO snapshotVO : snapshots) { try { List<SnapshotDataStoreVO> storeRefs = _snapshotStoreDao.findBySnapshotId(snapshotVO.getId()); for (SnapshotDataStoreVO ref : storeRefs) { _snapshotStoreDao.expunge(ref.getId()); } _snapshotDao.expunge(snapshotVO.getId()); } catch (Exception e) { s_logger.warn("Unable to destroy snapshot " + snapshotVO.getUuid(), e); } } // destroy uploaded volumes in abandoned/error state List<VolumeDataStoreVO> volumeDataStores = _volumeDataStoreDao.listByVolumeState(Volume.State.UploadError, Volume.State.UploadAbandoned); for (VolumeDataStoreVO volumeDataStore : volumeDataStores) { VolumeVO volume = _volumeDao.findById(volumeDataStore.getVolumeId()); if (volume == null) { s_logger.warn("Uploaded volume with id " + volumeDataStore.getVolumeId() + " not found, so cannot be destroyed"); continue; } try { DataStore dataStore = _dataStoreMgr.getDataStore(volumeDataStore.getDataStoreId(), DataStoreRole.Image); EndPoint ep = _epSelector.select(dataStore, volumeDataStore.getExtractUrl()); if (ep == null) { s_logger.warn("There is no secondary storage VM for image store " + dataStore.getName() + ", cannot destroy uploaded volume " + volume.getUuid()); continue; } Host host = _hostDao.findById(ep.getId()); if (host != null && host.getManagementServerId() != null) { if (_serverId == host.getManagementServerId().longValue()) { volService.destroyVolume(volume.getId()); // decrement volume resource count _resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.volume, volume.isDisplayVolume()); // expunge volume from secondary if volume is on image store VolumeInfo volOnSecondary = volFactory.getVolume(volume.getId(), DataStoreRole.Image); if (volOnSecondary != null) { s_logger.info("Expunging volume " + volume.getUuid() + " uploaded using HTTP POST from secondary data store"); AsyncCallFuture<VolumeApiResult> future = volService.expungeVolumeAsync(volOnSecondary); VolumeApiResult result = future.get(); if (!result.isSuccess()) { s_logger.warn("Failed to expunge volume " + volume.getUuid() + " from the image store " + dataStore.getName() + " due to: " + result.getResult()); } } } } } catch (Throwable th) { s_logger.warn("Unable to destroy uploaded volume " + volume.getUuid() + ". Error details: " + th.getMessage()); } } // destroy uploaded templates in abandoned/error state List<TemplateDataStoreVO> templateDataStores = _templateStoreDao.listByTemplateState(VirtualMachineTemplate.State.UploadError, VirtualMachineTemplate.State.UploadAbandoned); for (TemplateDataStoreVO templateDataStore : templateDataStores) { VMTemplateVO template = _templateDao.findById(templateDataStore.getTemplateId()); if (template == null) { s_logger.warn("Uploaded template with id " + templateDataStore.getTemplateId() + " not found, so cannot be destroyed"); continue; } try { DataStore dataStore = _dataStoreMgr.getDataStore(templateDataStore.getDataStoreId(), DataStoreRole.Image); EndPoint ep = _epSelector.select(dataStore, templateDataStore.getExtractUrl()); if (ep == null) { s_logger.warn("There is no secondary storage VM for image store " + dataStore.getName() + ", cannot destroy uploaded template " + template.getUuid()); continue; } Host host = _hostDao.findById(ep.getId()); if (host != null && host.getManagementServerId() != null) { if (_serverId == host.getManagementServerId().longValue()) { AsyncCallFuture<TemplateApiResult> future = _imageSrv.deleteTemplateAsync(tmplFactory.getTemplate(template.getId(), dataStore)); TemplateApiResult result = future.get(); if (!result.isSuccess()) { s_logger.warn("Failed to delete template " + template.getUuid() + " from the image store " + dataStore.getName() + " due to: " + result.getResult()); continue; } // remove from template_zone_ref List<VMTemplateZoneVO> templateZones = _vmTemplateZoneDao.listByZoneTemplate(((ImageStoreEntity)dataStore).getDataCenterId(), template.getId()); if (templateZones != null) { for (VMTemplateZoneVO templateZone : templateZones) { _vmTemplateZoneDao.remove(templateZone.getId()); } } // mark all the occurrences of this template in the given store as destroyed _templateStoreDao.removeByTemplateStore(template.getId(), dataStore.getId()); // find all eligible image stores for this template List<DataStore> imageStores = _tmpltMgr.getImageStoreByTemplate(template.getId(), null); if (imageStores == null || imageStores.size() == 0) { template.setState(VirtualMachineTemplate.State.Inactive); _templateDao.update(template.getId(), template); // decrement template resource count _resourceLimitMgr.decrementResourceCount(template.getAccountId(), ResourceType.template); } } } } catch (Throwable th) { s_logger.warn("Unable to destroy uploaded template " + template.getUuid() + ". Error details: " + th.getMessage()); } } } finally { scanLock.unlock(); } } } finally { scanLock.releaseRef(); } } /** * This method only applies for managed storage. * * For XenServer and vSphere, see if we need to remove an SR or a datastore, then remove the underlying volume * from any applicable access control list (before other code attempts to delete the volume that supports it). * * For KVM, just tell the underlying storage plug-in to remove the volume from any applicable access control list * (before other code attempts to delete the volume that supports it). */ private void handleManagedStorage(Volume volume) { Long instanceId = volume.getInstanceId(); if (instanceId != null) { StoragePoolVO storagePool = _storagePoolDao.findById(volume.getPoolId()); if (storagePool != null && storagePool.isManaged()) { VMInstanceVO vmInstanceVO = _vmInstanceDao.findById(instanceId); Long lastHostId = vmInstanceVO.getLastHostId(); if (lastHostId != null) { HostVO host = _hostDao.findById(lastHostId); ClusterVO cluster = _clusterDao.findById(host.getClusterId()); VolumeInfo volumeInfo = volFactory.getVolume(volume.getId()); if (cluster.getHypervisorType() == HypervisorType.KVM) { volService.revokeAccess(volumeInfo, host, volumeInfo.getDataStore()); } else { DataTO volTO = volFactory.getVolume(volume.getId()).getTO(); DiskTO disk = new DiskTO(volTO, volume.getDeviceId(), volume.getPath(), volume.getVolumeType()); DettachCommand cmd = new DettachCommand(disk, null); cmd.setManaged(true); cmd.setStorageHost(storagePool.getHostAddress()); cmd.setStoragePort(storagePool.getPort()); cmd.set_iScsiName(volume.get_iScsiName()); Answer answer = _agentMgr.easySend(lastHostId, cmd); if (answer != null && answer.getResult()) { volService.revokeAccess(volumeInfo, host, volumeInfo.getDataStore()); } else { s_logger.warn("Unable to remove host-side clustered file system for the following volume: " + volume.getUuid()); } } } } } } @DB List<Long> findAllVolumeIdInSnapshotTable(Long storeId) { String sql = "SELECT volume_id from snapshots, snapshot_store_ref WHERE snapshots.id = snapshot_store_ref.snapshot_id and store_id=? GROUP BY volume_id"; List<Long> list = new ArrayList<Long>(); try { TransactionLegacy txn = TransactionLegacy.currentTxn(); ResultSet rs = null; PreparedStatement pstmt = null; pstmt = txn.prepareAutoCloseStatement(sql); pstmt.setLong(1, storeId); rs = pstmt.executeQuery(); while (rs.next()) { list.add(rs.getLong(1)); } return list; } catch (Exception e) { s_logger.debug("failed to get all volumes who has snapshots in secondary storage " + storeId + " due to " + e.getMessage()); return null; } } List<String> findAllSnapshotForVolume(Long volumeId) { String sql = "SELECT backup_snap_id FROM snapshots WHERE volume_id=? and backup_snap_id is not NULL"; try { TransactionLegacy txn = TransactionLegacy.currentTxn(); ResultSet rs = null; PreparedStatement pstmt = null; pstmt = txn.prepareAutoCloseStatement(sql); pstmt.setLong(1, volumeId); rs = pstmt.executeQuery(); List<String> list = new ArrayList<String>(); while (rs.next()) { list.add(rs.getString(1)); } return list; } catch (Exception e) { s_logger.debug("failed to get all snapshots for a volume " + volumeId + " due to " + e.getMessage()); return null; } } @Override @DB public void cleanupSecondaryStorage(boolean recurring) { // NOTE that object_store refactor will immediately delete the object from secondary storage when deleteTemplate etc api is issued. // so here we don't need to issue DeleteCommand to resource anymore, only need to remove db entry. try { // Cleanup templates in template_store_ref List<DataStore> imageStores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(null)); for (DataStore store : imageStores) { try { long storeId = store.getId(); List<TemplateDataStoreVO> destroyedTemplateStoreVOs = _templateStoreDao.listDestroyed(storeId); s_logger.debug("Secondary storage garbage collector found " + destroyedTemplateStoreVOs.size() + " templates to cleanup on template_store_ref for store: " + store.getName()); for (TemplateDataStoreVO destroyedTemplateStoreVO : destroyedTemplateStoreVOs) { if (s_logger.isDebugEnabled()) { s_logger.debug("Deleting template store DB entry: " + destroyedTemplateStoreVO); } _templateStoreDao.remove(destroyedTemplateStoreVO.getId()); } } catch (Exception e) { s_logger.warn("problem cleaning up templates in template_store_ref for store: " + store.getName(), e); } } // CleanUp snapshots on snapshot_store_ref for (DataStore store : imageStores) { try { List<SnapshotDataStoreVO> destroyedSnapshotStoreVOs = _snapshotStoreDao.listDestroyed(store.getId()); s_logger.debug("Secondary storage garbage collector found " + destroyedSnapshotStoreVOs.size() + " snapshots to cleanup on snapshot_store_ref for store: " + store.getName()); for (SnapshotDataStoreVO destroyedSnapshotStoreVO : destroyedSnapshotStoreVOs) { // check if this snapshot has child SnapshotInfo snap = snapshotFactory.getSnapshot(destroyedSnapshotStoreVO.getSnapshotId(), store); if (snap.getChild() != null) { s_logger.debug("Skip snapshot on store: " + destroyedSnapshotStoreVO + " , because it has child"); continue; } if (s_logger.isDebugEnabled()) { s_logger.debug("Deleting snapshot store DB entry: " + destroyedSnapshotStoreVO); } _snapshotDao.remove(destroyedSnapshotStoreVO.getSnapshotId()); SnapshotDataStoreVO snapshotOnPrimary = _snapshotStoreDao.findBySnapshot(destroyedSnapshotStoreVO.getSnapshotId(), DataStoreRole.Primary); if (snapshotOnPrimary != null) { _snapshotStoreDao.remove(snapshotOnPrimary.getId()); } _snapshotStoreDao.remove(destroyedSnapshotStoreVO.getId()); } } catch (Exception e2) { s_logger.warn("problem cleaning up snapshots in snapshot_store_ref for store: " + store.getName(), e2); } } // CleanUp volumes on volume_store_ref for (DataStore store : imageStores) { try { List<VolumeDataStoreVO> destroyedStoreVOs = _volumeStoreDao.listDestroyed(store.getId()); s_logger.debug("Secondary storage garbage collector found " + destroyedStoreVOs.size() + " volumes to cleanup on volume_store_ref for store: " + store.getName()); for (VolumeDataStoreVO destroyedStoreVO : destroyedStoreVOs) { if (s_logger.isDebugEnabled()) { s_logger.debug("Deleting volume store DB entry: " + destroyedStoreVO); } _volumeStoreDao.remove(destroyedStoreVO.getId()); } } catch (Exception e2) { s_logger.warn("problem cleaning up volumes in volume_store_ref for store: " + store.getName(), e2); } } } catch (Exception e3) { s_logger.warn("problem cleaning up secondary storage DB entries. ", e3); } } @Override public String getPrimaryStorageNameLabel(VolumeVO volume) { Long poolId = volume.getPoolId(); // poolId is null only if volume is destroyed, which has been checked // before. assert poolId != null; StoragePoolVO PrimaryDataStoreVO = _storagePoolDao.findById(poolId); assert PrimaryDataStoreVO != null; return PrimaryDataStoreVO.getUuid(); } @Override @DB public PrimaryDataStoreInfo preparePrimaryStorageForMaintenance(Long primaryStorageId) throws ResourceUnavailableException, InsufficientCapacityException { StoragePoolVO primaryStorage = null; primaryStorage = _storagePoolDao.findById(primaryStorageId); if (primaryStorage == null) { String msg = "Unable to obtain lock on the storage pool record in preparePrimaryStorageForMaintenance()"; s_logger.error(msg); throw new InvalidParameterValueException(msg); } if (!primaryStorage.getStatus().equals(StoragePoolStatus.Up) && !primaryStorage.getStatus().equals(StoragePoolStatus.ErrorInMaintenance)) { throw new InvalidParameterValueException("Primary storage with id " + primaryStorageId + " is not ready for migration, as the status is:" + primaryStorage.getStatus().toString()); } DataStoreProvider provider = _dataStoreProviderMgr.getDataStoreProvider(primaryStorage.getStorageProviderName()); DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); DataStore store = _dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary); lifeCycle.maintain(store); return (PrimaryDataStoreInfo)_dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary); } @Override @DB public PrimaryDataStoreInfo cancelPrimaryStorageForMaintenance(CancelPrimaryStorageMaintenanceCmd cmd) throws ResourceUnavailableException { Long primaryStorageId = cmd.getId(); StoragePoolVO primaryStorage = null; primaryStorage = _storagePoolDao.findById(primaryStorageId); if (primaryStorage == null) { String msg = "Unable to obtain lock on the storage pool in cancelPrimaryStorageForMaintenance()"; s_logger.error(msg); throw new InvalidParameterValueException(msg); } if (primaryStorage.getStatus().equals(StoragePoolStatus.Up) || primaryStorage.getStatus().equals(StoragePoolStatus.PrepareForMaintenance)) { throw new StorageUnavailableException("Primary storage with id " + primaryStorageId + " is not ready to complete migration, as the status is:" + primaryStorage.getStatus().toString(), primaryStorageId); } DataStoreProvider provider = _dataStoreProviderMgr.getDataStoreProvider(primaryStorage.getStorageProviderName()); DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); DataStore store = _dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary); lifeCycle.cancelMaintain(store); return (PrimaryDataStoreInfo)_dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary); } protected class StorageGarbageCollector extends ManagedContextRunnable { public StorageGarbageCollector() { } @Override protected void runInContext() { try { s_logger.trace("Storage Garbage Collection Thread is running."); cleanupStorage(true); } catch (Exception e) { s_logger.error("Caught the following Exception", e); } } } @Override public void onManagementNodeJoined(List<? extends ManagementServerHost> nodeList, long selfNodeId) { } @Override public void onManagementNodeLeft(List<? extends ManagementServerHost> nodeList, long selfNodeId) { for (ManagementServerHost vo : nodeList) { if (vo.getMsid() == _serverId) { s_logger.info("Cleaning up storage maintenance jobs associated with Management server: " + vo.getMsid()); List<Long> poolIds = _storagePoolWorkDao.searchForPoolIdsForPendingWorkJobs(vo.getMsid()); if (poolIds.size() > 0) { for (Long poolId : poolIds) { StoragePoolVO pool = _storagePoolDao.findById(poolId); // check if pool is in an inconsistent state if (pool != null && (pool.getStatus().equals(StoragePoolStatus.ErrorInMaintenance) || pool.getStatus().equals(StoragePoolStatus.PrepareForMaintenance) || pool.getStatus().equals(StoragePoolStatus.CancelMaintenance))) { _storagePoolWorkDao.removePendingJobsOnMsRestart(vo.getMsid(), poolId); pool.setStatus(StoragePoolStatus.ErrorInMaintenance); _storagePoolDao.update(poolId, pool); } } } } } } @Override public void onManagementNodeIsolated() { } @Override public CapacityVO getSecondaryStorageUsedStats(Long hostId, Long zoneId) { SearchCriteria<HostVO> sc = _hostDao.createSearchCriteria(); if (zoneId != null) { sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); } List<Long> hosts = new ArrayList<Long>(); if (hostId != null) { hosts.add(hostId); } else { List<DataStore> stores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(zoneId)); if (stores != null) { for (DataStore store : stores) { hosts.add(store.getId()); } } } CapacityVO capacity = new CapacityVO(hostId, zoneId, null, null, 0, 0, Capacity.CAPACITY_TYPE_SECONDARY_STORAGE); for (Long id : hosts) { StorageStats stats = ApiDBUtils.getSecondaryStorageStatistics(id); if (stats == null) { continue; } capacity.setUsedCapacity(stats.getByteUsed() + capacity.getUsedCapacity()); capacity.setTotalCapacity(stats.getCapacityBytes() + capacity.getTotalCapacity()); } return capacity; } @Override public CapacityVO getStoragePoolUsedStats(Long poolId, Long clusterId, Long podId, Long zoneId) { SearchCriteria<StoragePoolVO> sc = _storagePoolDao.createSearchCriteria(); List<StoragePoolVO> pools = new ArrayList<StoragePoolVO>(); if (zoneId != null) { sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); } if (podId != null) { sc.addAnd("podId", SearchCriteria.Op.EQ, podId); } if (clusterId != null) { sc.addAnd("clusterId", SearchCriteria.Op.EQ, clusterId); } if (poolId != null) { sc.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, poolId); } if (poolId != null) { pools.add(_storagePoolDao.findById(poolId)); } else { pools = _storagePoolDao.search(sc, null); } CapacityVO capacity = new CapacityVO(poolId, zoneId, podId, clusterId, 0, 0, Capacity.CAPACITY_TYPE_STORAGE); for (StoragePoolVO PrimaryDataStoreVO : pools) { StorageStats stats = ApiDBUtils.getStoragePoolStatistics(PrimaryDataStoreVO.getId()); if (stats == null) { continue; } capacity.setUsedCapacity(stats.getByteUsed() + capacity.getUsedCapacity()); capacity.setTotalCapacity(stats.getCapacityBytes() + capacity.getTotalCapacity()); } return capacity; } @Override public PrimaryDataStoreInfo getStoragePool(long id) { return (PrimaryDataStoreInfo)_dataStoreMgr.getDataStore(id, DataStoreRole.Primary); } @Override @DB public List<VMInstanceVO> listByStoragePool(long storagePoolId) { SearchCriteria<VMInstanceVO> sc = StoragePoolSearch.create(); sc.setJoinParameters("vmVolume", "volumeType", Volume.Type.ROOT); sc.setJoinParameters("vmVolume", "poolId", storagePoolId); sc.setJoinParameters("vmVolume", "state", Volume.State.Ready); return _vmInstanceDao.search(sc, null); } @Override @DB public StoragePoolVO findLocalStorageOnHost(long hostId) { SearchCriteria<StoragePoolVO> sc = LocalStorageSearch.create(); sc.setParameters("type", new Object[] {StoragePoolType.Filesystem, StoragePoolType.LVM}); sc.setJoinParameters("poolHost", "hostId", hostId); List<StoragePoolVO> storagePools = _storagePoolDao.search(sc, null); if (!storagePools.isEmpty()) { return storagePools.get(0); } else { return null; } } @Override public Host updateSecondaryStorage(long secStorageId, String newUrl) { HostVO secHost = _hostDao.findById(secStorageId); if (secHost == null) { throw new InvalidParameterValueException("Can not find out the secondary storage id: " + secStorageId); } if (secHost.getType() != Host.Type.SecondaryStorage) { throw new InvalidParameterValueException("host: " + secStorageId + " is not a secondary storage"); } URI uri = null; try { uri = new URI(UriUtils.encodeURIComponent(newUrl)); if (uri.getScheme() == null) { throw new InvalidParameterValueException("uri.scheme is null " + newUrl + ", add nfs:// (or cifs://) as a prefix"); } else if (uri.getScheme().equalsIgnoreCase("nfs")) { if (uri.getHost() == null || uri.getHost().equalsIgnoreCase("") || uri.getPath() == null || uri.getPath().equalsIgnoreCase("")) { throw new InvalidParameterValueException("Your host and/or path is wrong. Make sure it's of the format nfs://hostname/path"); } } else if (uri.getScheme().equalsIgnoreCase("cifs")) { // Don't validate against a URI encoded URI. URI cifsUri = new URI(newUrl); String warnMsg = UriUtils.getCifsUriParametersProblems(cifsUri); if (warnMsg != null) { throw new InvalidParameterValueException(warnMsg); } } } catch (URISyntaxException e) { throw new InvalidParameterValueException(newUrl + " is not a valid uri"); } String oldUrl = secHost.getStorageUrl(); URI oldUri = null; try { oldUri = new URI(UriUtils.encodeURIComponent(oldUrl)); if (!oldUri.getScheme().equalsIgnoreCase(uri.getScheme())) { throw new InvalidParameterValueException("can not change old scheme:" + oldUri.getScheme() + " to " + uri.getScheme()); } } catch (URISyntaxException e) { s_logger.debug("Failed to get uri from " + oldUrl); } secHost.setStorageUrl(newUrl); secHost.setGuid(newUrl); secHost.setName(newUrl); _hostDao.update(secHost.getId(), secHost); return secHost; } @Override public HypervisorType getHypervisorTypeFromFormat(ImageFormat format) { if (format == null) { return HypervisorType.None; } if (format == ImageFormat.VHD) { return HypervisorType.XenServer; } else if (format == ImageFormat.OVA) { return HypervisorType.VMware; } else if (format == ImageFormat.QCOW2) { return HypervisorType.KVM; } else if (format == ImageFormat.RAW) { return HypervisorType.Ovm; } else if (format == ImageFormat.VHDX) { return HypervisorType.Hyperv; } else { return HypervisorType.None; } } private boolean checkUsagedSpace(StoragePool pool) { // Managed storage does not currently deal with accounting for physically used space (only provisioned space). Just return true if "pool" is managed. if (pool.isManaged()) { return true; } StatsCollector sc = StatsCollector.getInstance(); double storageUsedThreshold = CapacityManager.StorageCapacityDisableThreshold.valueIn(pool.getDataCenterId()); if (sc != null) { long totalSize = pool.getCapacityBytes(); StorageStats stats = sc.getStoragePoolStats(pool.getId()); if (stats == null) { stats = sc.getStorageStats(pool.getId()); } if (stats != null) { double usedPercentage = ((double)stats.getByteUsed() / (double)totalSize); if (s_logger.isDebugEnabled()) { s_logger.debug("Checking pool " + pool.getId() + " for storage, totalSize: " + pool.getCapacityBytes() + ", usedBytes: " + stats.getByteUsed() + ", usedPct: " + usedPercentage + ", disable threshold: " + storageUsedThreshold); } if (usedPercentage >= storageUsedThreshold) { if (s_logger.isDebugEnabled()) { s_logger.debug("Insufficient space on pool: " + pool.getId() + " since its usage percentage: " + usedPercentage + " has crossed the pool.storage.capacity.disablethreshold: " + storageUsedThreshold); } return false; } } return true; } return false; } @Override public boolean storagePoolHasEnoughIops(List<Volume> requestedVolumes, StoragePool pool) { if (requestedVolumes == null || requestedVolumes.isEmpty() || pool == null) { return false; } // Only IOPS-guaranteed primary storage like SolidFire is using/setting IOPS. // This check returns true for storage that does not specify IOPS. if (pool.getCapacityIops() == null) { s_logger.info("Storage pool " + pool.getName() + " (" + pool.getId() + ") does not supply IOPS capacity, assuming enough capacity"); return true; } StoragePoolVO storagePoolVo = _storagePoolDao.findById(pool.getId()); long currentIops = _capacityMgr.getUsedIops(storagePoolVo); long requestedIops = 0; for (Volume requestedVolume : requestedVolumes) { Long minIops = requestedVolume.getMinIops(); if (minIops != null && minIops > 0) { requestedIops += minIops; } } long futureIops = currentIops + requestedIops; return futureIops <= pool.getCapacityIops(); } @Override public boolean storagePoolHasEnoughSpace(List<Volume> volumes, StoragePool pool) { return storagePoolHasEnoughSpace(volumes, pool, null); } @Override public boolean storagePoolHasEnoughSpace(List<Volume> volumes, StoragePool pool, Long clusterId) { if (volumes == null || volumes.isEmpty()) { return false; } if (!checkUsagedSpace(pool)) { return false; } // allocated space includes templates if (s_logger.isDebugEnabled()) { s_logger.debug("Destination pool id: " + pool.getId()); } // allocated space includes templates final StoragePoolVO poolVO = _storagePoolDao.findById(pool.getId()); long allocatedSizeWithTemplate = _capacityMgr.getAllocatedPoolCapacity(poolVO, null); long totalAskingSize = 0; for (Volume volume : volumes) { // refreshing the volume from the DB to get latest hv_ss_reserve (hypervisor snapshot reserve) field // I could have just assigned this to "volume", but decided to make a new variable for it so that it // might be clearer that this "volume" in "volumes" still might have an old value for hv_ss_reverse. VolumeVO volumeVO = _volumeDao.findById(volume.getId()); if (volumeVO.getHypervisorSnapshotReserve() == null) { // update the volume's hv_ss_reserve (hypervisor snapshot reserve) from a disk offering (used for managed storage) volService.updateHypervisorSnapshotReserveForVolume(getDiskOfferingVO(volumeVO), volumeVO.getId(), getHypervisorType(volumeVO)); // hv_ss_reserve field might have been updated; refresh from DB to make use of it in getDataObjectSizeIncludingHypervisorSnapshotReserve volumeVO = _volumeDao.findById(volume.getId()); } // this if statement should resolve to true at most once per execution of the for loop its contained within (for a root disk that is // to leverage a template) if (volume.getTemplateId() != null) { VMTemplateVO tmpl = _templateDao.findByIdIncludingRemoved(volume.getTemplateId()); if (tmpl != null && !ImageFormat.ISO.equals(tmpl.getFormat())) { allocatedSizeWithTemplate = _capacityMgr.getAllocatedPoolCapacity(poolVO, tmpl); } } if (s_logger.isDebugEnabled()) { s_logger.debug("Pool ID for the volume with ID " + volumeVO.getId() + " is " + volumeVO.getPoolId()); } // A ready-state volume is already allocated in a pool, so the asking size is zero for it. // In case the volume is moving across pools or is not ready yet, the asking size has to be computed. if ((volumeVO.getState() != Volume.State.Ready) || (volumeVO.getPoolId() != pool.getId())) { totalAskingSize += getDataObjectSizeIncludingHypervisorSnapshotReserve(volumeVO, poolVO); totalAskingSize += getAskingSizeForTemplateBasedOnClusterAndStoragePool(volumeVO.getTemplateId(), clusterId, poolVO); } } return checkPoolforSpace(pool, allocatedSizeWithTemplate, totalAskingSize); } @Override public boolean storagePoolHasEnoughSpaceForResize(StoragePool pool, long currentSize, long newSiz) { if (!checkUsagedSpace(pool)) { return false; } if (s_logger.isDebugEnabled()) { s_logger.debug("Destination pool id: " + pool.getId()); } long totalAskingSize = newSiz - currentSize; if (totalAskingSize <= 0) { return true; } else { final StoragePoolVO poolVO = _storagePoolDao.findById(pool.getId()); final long allocatedSizeWithTemplate = _capacityMgr.getAllocatedPoolCapacity(poolVO, null); return checkPoolforSpace(pool, allocatedSizeWithTemplate, totalAskingSize); } } private boolean checkPoolforSpace(StoragePool pool, long allocatedSizeWithTemplate, long totalAskingSize) { // allocated space includes templates StoragePoolVO poolVO = _storagePoolDao.findById(pool.getId()); long totalOverProvCapacity; if (pool.getPoolType().supportsOverProvisioning()) { BigDecimal overProvFactor = getStorageOverProvisioningFactor(pool.getId()); totalOverProvCapacity = overProvFactor.multiply(new BigDecimal(pool.getCapacityBytes())).longValue(); s_logger.debug("Found storage pool " + poolVO.getName() + " of type " + pool.getPoolType().toString() + " with over-provisioning factor " + overProvFactor.toString()); s_logger.debug("Total over-provisioned capacity calculated is " + overProvFactor + " * " + pool.getCapacityBytes()); } else { totalOverProvCapacity = pool.getCapacityBytes(); s_logger.debug("Found storage pool " + poolVO.getName() + " of type " + pool.getPoolType().toString()); } s_logger.debug("Total capacity of the pool " + poolVO.getName() + " with ID " + pool.getId() + " is " + totalOverProvCapacity); double storageAllocatedThreshold = CapacityManager.StorageAllocatedCapacityDisableThreshold.valueIn(pool.getDataCenterId()); if (s_logger.isDebugEnabled()) { s_logger.debug("Checking pool: " + pool.getId() + " for storage allocation , maxSize : " + totalOverProvCapacity + ", totalAllocatedSize : " + allocatedSizeWithTemplate + ", askingSize : " + totalAskingSize + ", allocated disable threshold: " + storageAllocatedThreshold); } double usedPercentage = (allocatedSizeWithTemplate + totalAskingSize) / (double)(totalOverProvCapacity); if (usedPercentage > storageAllocatedThreshold) { if (s_logger.isDebugEnabled()) { s_logger.debug("Insufficient un-allocated capacity on: " + pool.getId() + " for storage allocation since its allocated percentage: " + usedPercentage + " has crossed the allocated pool.storage.allocated.capacity.disablethreshold: " + storageAllocatedThreshold + ", skipping this pool"); } return false; } if (totalOverProvCapacity < (allocatedSizeWithTemplate + totalAskingSize)) { if (s_logger.isDebugEnabled()) { s_logger.debug("Insufficient un-allocated capacity on: " + pool.getId() + " for storage allocation, not enough storage, maxSize : " + totalOverProvCapacity + ", totalAllocatedSize : " + allocatedSizeWithTemplate + ", askingSize : " + totalAskingSize); } return false; } return true; } /** * Storage plug-ins for managed storage can be designed in such a way as to store a template on the primary storage once and * make use of it via storage-side cloning. * * This method determines how many more bytes it will need for the template (if the template is already stored on the primary storage, * then the answer is 0). */ private long getAskingSizeForTemplateBasedOnClusterAndStoragePool(Long templateId, Long clusterId, StoragePoolVO storagePoolVO) { if (templateId == null || clusterId == null || storagePoolVO == null || !storagePoolVO.isManaged()) { return 0; } VMTemplateVO tmpl = _templateDao.findByIdIncludingRemoved(templateId); if (tmpl == null || ImageFormat.ISO.equals(tmpl.getFormat())) { return 0; } HypervisorType hypervisorType = tmpl.getHypervisorType(); // The getSupportsResigning method is applicable for XenServer as a UUID-resigning patch may or may not be installed on those hypervisor hosts. if (_clusterDao.getSupportsResigning(clusterId) || HypervisorType.VMware.equals(hypervisorType) || HypervisorType.KVM.equals(hypervisorType)) { return getBytesRequiredForTemplate(tmpl, storagePoolVO); } return 0; } private long getDataObjectSizeIncludingHypervisorSnapshotReserve(Volume volume, StoragePool pool) { DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(pool.getStorageProviderName()); DataStoreDriver storeDriver = storeProvider.getDataStoreDriver(); if (storeDriver instanceof PrimaryDataStoreDriver) { PrimaryDataStoreDriver primaryStoreDriver = (PrimaryDataStoreDriver)storeDriver; VolumeInfo volumeInfo = volFactory.getVolume(volume.getId()); return primaryStoreDriver.getDataObjectSizeIncludingHypervisorSnapshotReserve(volumeInfo, pool); } return volume.getSize(); } private DiskOfferingVO getDiskOfferingVO(Volume volume) { Long diskOfferingId = volume.getDiskOfferingId(); return _diskOfferingDao.findById(diskOfferingId); } private HypervisorType getHypervisorType(Volume volume) { Long instanceId = volume.getInstanceId(); VMInstanceVO vmInstance = _vmInstanceDao.findById(instanceId); if (vmInstance != null) { return vmInstance.getHypervisorType(); } return null; } private long getBytesRequiredForTemplate(VMTemplateVO tmpl, StoragePool pool) { DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(pool.getStorageProviderName()); DataStoreDriver storeDriver = storeProvider.getDataStoreDriver(); if (storeDriver instanceof PrimaryDataStoreDriver) { PrimaryDataStoreDriver primaryStoreDriver = (PrimaryDataStoreDriver)storeDriver; TemplateInfo templateInfo = tmplFactory.getReadyTemplateOnImageStore(tmpl.getId(), pool.getDataCenterId()); return primaryStoreDriver.getBytesRequiredForTemplate(templateInfo, pool); } return tmpl.getSize(); } @Override public void createCapacityEntry(long poolId) { StoragePoolVO storage = _storagePoolDao.findById(poolId); createCapacityEntry(storage, Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED, 0); } @Override public synchronized boolean registerHostListener(String providerName, HypervisorHostListener listener) { hostListeners.put(providerName, listener); return true; } @Override public Answer sendToPool(long poolId, Command cmd) throws StorageUnavailableException { return null; } @Override public Answer[] sendToPool(long poolId, Commands cmd) throws StorageUnavailableException { return null; } @Override public String getName() { return null; } @Override public ImageStore discoverImageStore(String name, String url, String providerName, Long zoneId, Map details) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(providerName); if (storeProvider == null) { storeProvider = _dataStoreProviderMgr.getDefaultImageDataStoreProvider(); if (storeProvider == null) { throw new InvalidParameterValueException("can't find image store provider: " + providerName); } providerName = storeProvider.getName(); // ignored passed provider name and use default image store provider name } ScopeType scopeType = ScopeType.ZONE; if (zoneId == null) { scopeType = ScopeType.REGION; } if (name == null) { name = url; } ImageStoreVO imageStore = _imageStoreDao.findByName(name); if (imageStore != null) { throw new InvalidParameterValueException("The image store with name " + name + " already exists, try creating with another name"); } // check if scope is supported by store provider if (!((ImageStoreProvider)storeProvider).isScopeSupported(scopeType)) { throw new InvalidParameterValueException("Image store provider " + providerName + " does not support scope " + scopeType); } // check if we have already image stores from other different providers, // we currently are not supporting image stores from different // providers co-existing List<ImageStoreVO> imageStores = _imageStoreDao.listImageStores(); for (ImageStoreVO store : imageStores) { if (!store.getProviderName().equalsIgnoreCase(providerName)) { throw new InvalidParameterValueException("You can only add new image stores from the same provider " + store.getProviderName() + " already added"); } } if (zoneId != null) { // Check if the zone exists in the system DataCenterVO zone = _dcDao.findById(zoneId); if (zone == null) { throw new InvalidParameterValueException("Can't find zone by id " + zoneId); } Account account = CallContext.current().getCallingAccount(); if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getId())) { PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, Zone with specified id is currently disabled"); ex.addProxyObject(zone.getUuid(), "dcId"); throw ex; } } Map<String, Object> params = new HashMap<>(); params.put("zoneId", zoneId); params.put("url", url); params.put("name", name); params.put("details", details); params.put("scope", scopeType); params.put("providerName", storeProvider.getName()); params.put("role", DataStoreRole.Image); DataStoreLifeCycle lifeCycle = storeProvider.getDataStoreLifeCycle(); DataStore store; try { store = lifeCycle.initialize(params); } catch (Exception e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Failed to add data store: " + e.getMessage(), e); } throw new CloudRuntimeException("Failed to add data store: " + e.getMessage(), e); } if (((ImageStoreProvider)storeProvider).needDownloadSysTemplate()) { // trigger system vm template download _imageSrv.downloadBootstrapSysTemplate(store); } else { // populate template_store_ref table _imageSrv.addSystemVMTemplatesToSecondary(store); _imageSrv.handleTemplateSync(store); } // associate builtin template with zones associated with this image store associateCrosszoneTemplatesToZone(zoneId); // duplicate cache store records to region wide storage if (scopeType == ScopeType.REGION) { duplicateCacheStoreRecordsToRegionStore(store.getId()); } return (ImageStore)_dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Image); } @Override public ImageStore migrateToObjectStore(String name, String url, String providerName, Map<String, String> details) throws DiscoveryException, InvalidParameterValueException { // check if current cloud is ready to migrate, we only support cloud with only NFS secondary storages List<ImageStoreVO> imgStores = _imageStoreDao.listImageStores(); List<ImageStoreVO> nfsStores = new ArrayList<ImageStoreVO>(); if (imgStores != null && imgStores.size() > 0) { for (ImageStoreVO store : imgStores) { if (!store.getProviderName().equals(DataStoreProvider.NFS_IMAGE)) { throw new InvalidParameterValueException("We only support migrate NFS secondary storage to use object store!"); } else { nfsStores.add(store); } } } // convert all NFS secondary storage to staging store if (nfsStores != null && nfsStores.size() > 0) { for (ImageStoreVO store : nfsStores) { long storeId = store.getId(); _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), store.getDataCenterId()); DataStoreProvider provider = _dataStoreProviderMgr.getDataStoreProvider(store.getProviderName()); DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); DataStore secStore = _dataStoreMgr.getDataStore(storeId, DataStoreRole.Image); lifeCycle.migrateToObjectStore(secStore); // update store_role in template_store_ref and snapshot_store_ref to ImageCache _templateStoreDao.updateStoreRoleToCachce(storeId); _snapshotStoreDao.updateStoreRoleToCache(storeId); } } // add object store return discoverImageStore(name, url, providerName, null, details); } private void duplicateCacheStoreRecordsToRegionStore(long storeId) { _templateStoreDao.duplicateCacheRecordsOnRegionStore(storeId); _snapshotStoreDao.duplicateCacheRecordsOnRegionStore(storeId); _volumeStoreDao.duplicateCacheRecordsOnRegionStore(storeId); } private void associateCrosszoneTemplatesToZone(Long zoneId) { VMTemplateZoneVO tmpltZone; List<VMTemplateVO> allTemplates = _vmTemplateDao.listAll(); List<Long> dcIds = new ArrayList<Long>(); if (zoneId != null) { dcIds.add(zoneId); } else { List<DataCenterVO> dcs = _dcDao.listAll(); if (dcs != null) { for (DataCenterVO dc : dcs) { dcIds.add(dc.getId()); } } } for (VMTemplateVO vt : allTemplates) { if (vt.isCrossZones()) { for (Long dcId : dcIds) { tmpltZone = _vmTemplateZoneDao.findByZoneTemplate(dcId, vt.getId()); if (tmpltZone == null) { VMTemplateZoneVO vmTemplateZone = new VMTemplateZoneVO(dcId, vt.getId(), new Date()); _vmTemplateZoneDao.persist(vmTemplateZone); } } } } } @Override public boolean deleteImageStore(DeleteImageStoreCmd cmd) { final long storeId = cmd.getId(); // Verify that image store exists ImageStoreVO store = _imageStoreDao.findById(storeId); if (store == null) { throw new InvalidParameterValueException("Image store with id " + storeId + " doesn't exist"); } _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), store.getDataCenterId()); // Verify that there are no live snapshot, template, volume on the image // store to be deleted List<SnapshotDataStoreVO> snapshots = _snapshotStoreDao.listByStoreId(storeId, DataStoreRole.Image); if (snapshots != null && snapshots.size() > 0) { throw new InvalidParameterValueException("Cannot delete image store with active snapshots backup!"); } List<VolumeDataStoreVO> volumes = _volumeStoreDao.listByStoreId(storeId); if (volumes != null && volumes.size() > 0) { throw new InvalidParameterValueException("Cannot delete image store with active volumes backup!"); } // search if there are user templates stored on this image store, excluding system, builtin templates List<TemplateJoinVO> templates = _templateViewDao.listActiveTemplates(storeId); if (templates != null && templates.size() > 0) { throw new InvalidParameterValueException("Cannot delete image store with active templates backup!"); } // ready to delete Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { // first delete from image_store_details table, we need to do that since // we are not actually deleting record from main // image_data_store table, so delete cascade will not work _imageStoreDetailsDao.deleteDetails(storeId); _snapshotStoreDao.deletePrimaryRecordsForStore(storeId, DataStoreRole.Image); _volumeStoreDao.deletePrimaryRecordsForStore(storeId); _templateStoreDao.deletePrimaryRecordsForStore(storeId); _imageStoreDao.remove(storeId); } }); return true; } @Override public ImageStore createSecondaryStagingStore(CreateSecondaryStagingStoreCmd cmd) { String providerName = cmd.getProviderName(); DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(providerName); if (storeProvider == null) { storeProvider = _dataStoreProviderMgr.getDefaultCacheDataStoreProvider(); if (storeProvider == null) { throw new InvalidParameterValueException("can't find cache store provider: " + providerName); } } Long dcId = cmd.getZoneId(); ScopeType scopeType = null; String scope = cmd.getScope(); if (scope != null) { try { scopeType = Enum.valueOf(ScopeType.class, scope.toUpperCase()); } catch (Exception e) { throw new InvalidParameterValueException("invalid scope for cache store " + scope); } if (scopeType != ScopeType.ZONE) { throw new InvalidParameterValueException("Only zone wide cache storage is supported"); } } if (scopeType == ScopeType.ZONE && dcId == null) { throw new InvalidParameterValueException("zone id can't be null, if scope is zone"); } // Check if the zone exists in the system DataCenterVO zone = _dcDao.findById(dcId); if (zone == null) { throw new InvalidParameterValueException("Can't find zone by id " + dcId); } Account account = CallContext.current().getCallingAccount(); if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getId())) { PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, Zone with specified id is currently disabled"); ex.addProxyObject(zone.getUuid(), "dcId"); throw ex; } Map<String, Object> params = new HashMap<String, Object>(); params.put("zoneId", dcId); params.put("url", cmd.getUrl()); params.put("name", cmd.getUrl()); params.put("details", cmd.getDetails()); params.put("scope", scopeType); params.put("providerName", storeProvider.getName()); params.put("role", DataStoreRole.ImageCache); DataStoreLifeCycle lifeCycle = storeProvider.getDataStoreLifeCycle(); DataStore store = null; try { store = lifeCycle.initialize(params); } catch (Exception e) { s_logger.debug("Failed to add data store: " + e.getMessage(), e); throw new CloudRuntimeException("Failed to add data store: " + e.getMessage(), e); } return (ImageStore)_dataStoreMgr.getDataStore(store.getId(), DataStoreRole.ImageCache); } @Override public boolean deleteSecondaryStagingStore(DeleteSecondaryStagingStoreCmd cmd) { final long storeId = cmd.getId(); // Verify that cache store exists ImageStoreVO store = _imageStoreDao.findById(storeId); if (store == null) { throw new InvalidParameterValueException("Cache store with id " + storeId + " doesn't exist"); } _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), store.getDataCenterId()); // Verify that there are no live snapshot, template, volume on the cache // store that is currently referenced List<SnapshotDataStoreVO> snapshots = _snapshotStoreDao.listActiveOnCache(storeId); if (snapshots != null && snapshots.size() > 0) { throw new InvalidParameterValueException("Cannot delete cache store with staging snapshots currently in use!"); } List<VolumeDataStoreVO> volumes = _volumeStoreDao.listActiveOnCache(storeId); if (volumes != null && volumes.size() > 0) { throw new InvalidParameterValueException("Cannot delete cache store with staging volumes currently in use!"); } List<TemplateDataStoreVO> templates = _templateStoreDao.listActiveOnCache(storeId); if (templates != null && templates.size() > 0) { throw new InvalidParameterValueException("Cannot delete cache store with staging templates currently in use!"); } // ready to delete Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { // first delete from image_store_details table, we need to do that since // we are not actually deleting record from main // image_data_store table, so delete cascade will not work _imageStoreDetailsDao.deleteDetails(storeId); _snapshotStoreDao.deletePrimaryRecordsForStore(storeId, DataStoreRole.ImageCache); _volumeStoreDao.deletePrimaryRecordsForStore(storeId); _templateStoreDao.deletePrimaryRecordsForStore(storeId); _imageStoreDao.remove(storeId); } }); return true; } protected class DownloadURLGarbageCollector implements Runnable { public DownloadURLGarbageCollector() { } @Override public void run() { try { s_logger.trace("Download URL Garbage Collection Thread is running."); cleanupDownloadUrls(); } catch (Exception e) { s_logger.error("Caught the following Exception", e); } } } @Override public void cleanupDownloadUrls() { // Cleanup expired volume URLs List<VolumeDataStoreVO> volumesOnImageStoreList = _volumeStoreDao.listVolumeDownloadUrls(); HashSet<Long> expiredVolumeIds = new HashSet<Long>(); HashSet<Long> activeVolumeIds = new HashSet<Long>(); for (VolumeDataStoreVO volumeOnImageStore : volumesOnImageStoreList) { long volumeId = volumeOnImageStore.getVolumeId(); try { long downloadUrlCurrentAgeInSecs = DateUtil.getTimeDifference(DateUtil.now(), volumeOnImageStore.getExtractUrlCreated()); if (downloadUrlCurrentAgeInSecs < _downloadUrlExpirationInterval) { // URL hasnt expired yet activeVolumeIds.add(volumeId); continue; } expiredVolumeIds.add(volumeId); s_logger.debug("Removing download url " + volumeOnImageStore.getExtractUrl() + " for volume id " + volumeId); // Remove it from image store ImageStoreEntity secStore = (ImageStoreEntity)_dataStoreMgr.getDataStore(volumeOnImageStore.getDataStoreId(), DataStoreRole.Image); secStore.deleteExtractUrl(volumeOnImageStore.getInstallPath(), volumeOnImageStore.getExtractUrl(), Upload.Type.VOLUME); // Now expunge it from DB since this entry was created only for download purpose _volumeStoreDao.expunge(volumeOnImageStore.getId()); } catch (Throwable th) { s_logger.warn("Caught exception while deleting download url " + volumeOnImageStore.getExtractUrl() + " for volume id " + volumeOnImageStore.getVolumeId(), th); } } for (Long volumeId : expiredVolumeIds) { if (activeVolumeIds.contains(volumeId)) { continue; } Volume volume = _volumeDao.findById(volumeId); if (volume != null && volume.getState() == Volume.State.Expunged) { _volumeDao.remove(volumeId); } } // Cleanup expired template URLs List<TemplateDataStoreVO> templatesOnImageStoreList = _templateStoreDao.listTemplateDownloadUrls(); for (TemplateDataStoreVO templateOnImageStore : templatesOnImageStoreList) { try { long downloadUrlCurrentAgeInSecs = DateUtil.getTimeDifference(DateUtil.now(), templateOnImageStore.getExtractUrlCreated()); if (downloadUrlCurrentAgeInSecs < _downloadUrlExpirationInterval) { // URL hasnt expired yet continue; } s_logger.debug("Removing download url " + templateOnImageStore.getExtractUrl() + " for template id " + templateOnImageStore.getTemplateId()); // Remove it from image store ImageStoreEntity secStore = (ImageStoreEntity)_dataStoreMgr.getDataStore(templateOnImageStore.getDataStoreId(), DataStoreRole.Image); secStore.deleteExtractUrl(templateOnImageStore.getInstallPath(), templateOnImageStore.getExtractUrl(), Upload.Type.TEMPLATE); // Now remove download details from DB. templateOnImageStore.setExtractUrl(null); templateOnImageStore.setExtractUrlCreated(null); _templateStoreDao.update(templateOnImageStore.getId(), templateOnImageStore); } catch (Throwable th) { s_logger.warn("caught exception while deleting download url " + templateOnImageStore.getExtractUrl() + " for template id " + templateOnImageStore.getTemplateId(), th); } } } // get bytesReadRate from service_offering, disk_offering and vm.disk.throttling.bytes_read_rate @Override public Long getDiskBytesReadRate(final ServiceOffering offering, final DiskOffering diskOffering) { if ((offering != null) && (offering.getBytesReadRate() != null) && (offering.getBytesReadRate() > 0)) { return offering.getBytesReadRate(); } else if ((diskOffering != null) && (diskOffering.getBytesReadRate() != null) && (diskOffering.getBytesReadRate() > 0)) { return diskOffering.getBytesReadRate(); } else { Long bytesReadRate = Long.parseLong(_configDao.getValue(Config.VmDiskThrottlingBytesReadRate.key())); if ((bytesReadRate > 0) && ((offering == null) || (!offering.isSystemUse()))) { return bytesReadRate; } } return 0L; } // get bytesWriteRate from service_offering, disk_offering and vm.disk.throttling.bytes_write_rate @Override public Long getDiskBytesWriteRate(final ServiceOffering offering, final DiskOffering diskOffering) { if ((offering != null) && (offering.getBytesWriteRate() != null) && (offering.getBytesWriteRate() > 0)) { return offering.getBytesWriteRate(); } else if ((diskOffering != null) && (diskOffering.getBytesWriteRate() != null) && (diskOffering.getBytesWriteRate() > 0)) { return diskOffering.getBytesWriteRate(); } else { Long bytesWriteRate = Long.parseLong(_configDao.getValue(Config.VmDiskThrottlingBytesWriteRate.key())); if ((bytesWriteRate > 0) && ((offering == null) || (!offering.isSystemUse()))) { return bytesWriteRate; } } return 0L; } // get iopsReadRate from service_offering, disk_offering and vm.disk.throttling.iops_read_rate @Override public Long getDiskIopsReadRate(final ServiceOffering offering, final DiskOffering diskOffering) { if ((offering != null) && (offering.getIopsReadRate() != null) && (offering.getIopsReadRate() > 0)) { return offering.getIopsReadRate(); } else if ((diskOffering != null) && (diskOffering.getIopsReadRate() != null) && (diskOffering.getIopsReadRate() > 0)) { return diskOffering.getIopsReadRate(); } else { Long iopsReadRate = Long.parseLong(_configDao.getValue(Config.VmDiskThrottlingIopsReadRate.key())); if ((iopsReadRate > 0) && ((offering == null) || (!offering.isSystemUse()))) { return iopsReadRate; } } return 0L; } // get iopsWriteRate from service_offering, disk_offering and vm.disk.throttling.iops_write_rate @Override public Long getDiskIopsWriteRate(final ServiceOffering offering, final DiskOffering diskOffering) { if ((offering != null) && (offering.getIopsWriteRate() != null) && (offering.getIopsWriteRate() > 0)) { return offering.getIopsWriteRate(); } else if ((diskOffering != null) && (diskOffering.getIopsWriteRate() != null) && (diskOffering.getIopsWriteRate() > 0)) { return diskOffering.getIopsWriteRate(); } else { Long iopsWriteRate = Long.parseLong(_configDao.getValue(Config.VmDiskThrottlingIopsWriteRate.key())); if ((iopsWriteRate > 0) && ((offering == null) || (!offering.isSystemUse()))) { return iopsWriteRate; } } return 0L; } @Override public String getConfigComponentName() { return StorageManager.class.getSimpleName(); } @Override public ConfigKey<?>[] getConfigKeys() { return new ConfigKey<?>[]{ StorageCleanupInterval, StorageCleanupDelay, StorageCleanupEnabled, TemplateCleanupEnabled, KvmStorageOfflineMigrationWait, KvmStorageOnlineMigrationWait, KvmAutoConvergence, MaxNumberOfManagedClusteredFileSystems, PRIMARY_STORAGE_DOWNLOAD_WAIT }; } @Override public void setDiskProfileThrottling(DiskProfile dskCh, final ServiceOffering offering, final DiskOffering diskOffering) { dskCh.setBytesReadRate(getDiskBytesReadRate(offering, diskOffering)); dskCh.setBytesWriteRate(getDiskBytesWriteRate(offering, diskOffering)); dskCh.setIopsReadRate(getDiskIopsReadRate(offering, diskOffering)); dskCh.setIopsWriteRate(getDiskIopsWriteRate(offering, diskOffering)); } @Override public DiskTO getDiskWithThrottling(final DataTO volTO, final Volume.Type volumeType, final long deviceId, final String path, final long offeringId, final long diskOfferingId) { DiskTO disk = null; if (volTO != null && volTO instanceof VolumeObjectTO) { VolumeObjectTO volumeTO = (VolumeObjectTO)volTO; ServiceOffering offering = _entityMgr.findById(ServiceOffering.class, offeringId); DiskOffering diskOffering = _entityMgr.findById(DiskOffering.class, diskOfferingId); if (volumeType == Volume.Type.ROOT) { setVolumeObjectTOThrottling(volumeTO, offering, diskOffering); } else { setVolumeObjectTOThrottling(volumeTO, null, diskOffering); } disk = new DiskTO(volumeTO, deviceId, path, volumeType); } else { disk = new DiskTO(volTO, deviceId, path, volumeType); } return disk; } private void setVolumeObjectTOThrottling(VolumeObjectTO volumeTO, final ServiceOffering offering, final DiskOffering diskOffering) { volumeTO.setBytesReadRate(getDiskBytesReadRate(offering, diskOffering)); volumeTO.setBytesWriteRate(getDiskBytesWriteRate(offering, diskOffering)); volumeTO.setIopsReadRate(getDiskIopsReadRate(offering, diskOffering)); volumeTO.setIopsWriteRate(getDiskIopsWriteRate(offering, diskOffering)); } }
package io.antmedia.licence; import io.antmedia.datastore.db.types.Licence; import io.antmedia.settings.ServerSettings; public interface ILicenceService { public enum BeanName { LICENCE_SERVICE("ant.media.licence.service"); private String licenceBeanName; BeanName(String name) { this.licenceBeanName = name; } @Override public String toString() { return this.licenceBeanName; } } /** * Starts License operations */ public void start(); /** * Check License Status * @param key of the license * @return result of the operation and message */ public Licence checkLicence (String key); /** * Sets Server Settings * @param serverSettings */ public void setServerSettings(ServerSettings serverSettings); /** * Returns the last license status checked * @return */ public Licence getLastLicenseStatus(); /** * Returns if license is blocked * * @return true if license is blocked * false if license can be used */ public boolean isLicenceSuspended(); }
package net.ssehub.exercisesubmitter.protocol.backend; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import net.ssehub.exercisesubmitter.protocol.TestUtils; import net.ssehub.studentmgmt.backend_api.ApiClient; import net.ssehub.studentmgmt.backend_api.ApiException; import net.ssehub.studentmgmt.backend_api.api.UserApi; /** * This class declares <b>integration</b> tests for the {@link LoginComponent} class. * These tests communicates with the REST test server. * * @author El-Sharkawy * */ public class LoginComponentIntegrationTests { /** * Create a {@link LoginComponent}, which may be used during testing. * If no credentials are provided, test will be skipped (and marked yellow in Jenkins). * Required properties are: * <ul> * <li>test_user</li> * <li>test_password</li> * </ul> * * @return A logged in user. */ public static LoginComponent createLoginForTests() { String[] credentials = TestUtils.retreiveCredentialsFormVmArgs(); LoginComponent login = new LoginComponent(TestUtils.TEST_AUTH_SERVER, TestUtils.TEST_MANAGEMENT_SERVER); try { login.login(credentials[0], credentials[1]); } catch (UnknownCredentialsException e) { Assertions.fail(e); } catch (ServerNotFoundException e) { Assertions.fail(e); } return login; } /** * Tests precondition if credentials have been provided via external properties (to avoid placing valid credentials * inside the repository). If no credentials are provided, test will be skipped (and marked yellow in Jenkins). * Required properties are: * <ul> * <li>test_user</li> * <li>test_password</li> * </ul> * * @param variable The variable containing the properties value * @param propertyName the name of the properties (one from above) * @param typeName The name of the properties (human readable name) */ public static void assumeSpecified(String variable, String propertyName, String typeName) { Assumptions.assumeTrue(variable != null && !variable.isEmpty(), "No " + typeName + " specified, please specify " + "a test " + typeName + " via the property \"" + propertyName + "\", either on the command line via " + "-D" + propertyName + "= or on in maven/Eclipse via specifying system properties."); } /** * Tests the integration of three systems to login a user. * The involved systems are: * <ul> * <li>Authentication System (aka. Sparky Service)</li> * <li>Student Management System</li> * <li>Submitter Protocol</li> * </ul> * @throws UnknownCredentialsException If non valid credentials have been used (not tested here) * @throws ServerNotFoundException If one of the 2 other servers are not found, this may happen if hard coded * URLs change */ @Test public void testLogin() throws UnknownCredentialsException, ServerNotFoundException { String userName = System.getProperty("test_user"); String pw = System.getProperty("test_password"); // Check if credentials have been specified via system properties assumeSpecified(userName, "test_user", "user name"); assumeSpecified(pw, "test_password", "password"); // Perform login LoginComponent loginComp = new LoginComponent(TestUtils.TEST_AUTH_SERVER, TestUtils.TEST_MANAGEMENT_SERVER); boolean success = loginComp.login(userName, pw); // Test if login was successful Assertions.assertTrue(success, "Could not login. Check if valid credentials are used, otherwise " + LoginComponent.class.getSimpleName() + " is defect."); String id = loginComp.getUserID(); Assertions.assertNotNull(id, "No userID retrieved: " + LoginComponent.class.getSimpleName() + " is defect."); Assertions.assertFalse(id.isEmpty(), "No userID retrieved: " + LoginComponent.class.getSimpleName() + " is defect."); } /** * Tests that generated Token can be used to query for protected services. * @throws UnknownCredentialsException If non valid credentials have been used (not tested here) * @throws ServerNotFoundException If one of the 2 other servers are not found, this may happen if hard coded * URLs change */ @Test public void testRetrievelOfValidAccessToken() throws UnknownCredentialsException, ServerNotFoundException { String testUserID = "abc6e1c0-6db0-4c35-8d97-07cc7173c34c"; String userName = System.getProperty("test_user"); String pw = System.getProperty("test_password"); // Precondition: Check if credentials have been specified via system properties assumeSpecified(userName, "test_user", "user name"); assumeSpecified(pw, "test_password", "password"); // Precondition: Check that tested services requires valid token ApiClient client = new ApiClient(); client.setBasePath(TestUtils.TEST_MANAGEMENT_SERVER); UserApi userApi = new UserApi(client); boolean exceptionOccured = false; try { userApi.getUserById(testUserID); Assertions.fail("Expected to fail if no Token is used. Possibly an unprotected sevices was queried."); } catch (ApiException e) { exceptionOccured = true; } Assertions.assertTrue(exceptionOccured, "Expected to fail if no Token is used. Possibly an unprotected sevices " + "was queried."); // Perform login LoginComponent loginComp = new LoginComponent(TestUtils.TEST_AUTH_SERVER, TestUtils.TEST_MANAGEMENT_SERVER); loginComp.login(userName, pw); //Query a service that requires valid token client.setAccessToken(loginComp.getManagementToken()); try { userApi.getUserById(testUserID); } catch (ApiException e) { Assertions.fail("Service should not fail when used with valid token. reason: " + e.getMessage(), e); } } }
/* * Copyright (c) 2016, grossmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the jo-widgets.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL jo-widgets.org BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.jowidgets.addons.logging.slf4j161; import org.jowidgets.logging.api.ILogger; import org.jowidgets.util.Assert; import org.slf4j.spi.LocationAwareLogger; final class Slf4JLocationAwareLoggerAdapter extends AbstractSlf4JLoggerAdapter implements ILogger { private final LocationAwareLogger original; Slf4JLocationAwareLoggerAdapter(final LocationAwareLogger original, final String wrapperFQCN) { super(original, wrapperFQCN); Assert.paramNotNull(original, "original"); this.original = original; } @Override public void error(final String wrapperFQCN, final String message, final Throwable throwable) { original.log(null, wrapperFQCN, LocationAwareLogger.ERROR_INT, message, null, throwable); } @Override public void warn(final String wrapperFQCN, final String message, final Throwable throwable) { original.log(null, wrapperFQCN, LocationAwareLogger.WARN_INT, message, null, throwable); } @Override public void info(final String wrapperFQCN, final String message, final Throwable throwable) { original.log(null, wrapperFQCN, LocationAwareLogger.INFO_INT, message, null, throwable); } @Override public void debug(final String wrapperFQCN, final String message, final Throwable throwable) { original.log(null, wrapperFQCN, LocationAwareLogger.DEBUG_INT, message, null, throwable); } @Override public void trace(final String wrapperFQCN, final String message, final Throwable throwable) { original.log(null, wrapperFQCN, LocationAwareLogger.TRACE_INT, message, null, throwable); } }
package com.cn.springflowable.service; import org.flowable.engine.delegate.DelegateExecution; import org.flowable.engine.delegate.JavaDelegate; /** * @author chenning */ public class CallExternalSystemDelegate implements JavaDelegate { @Override public void execute(DelegateExecution execution) { System.out.println("All variable: "+execution.getVariables()); System.out.println("Calling the external system for employee " + execution.getVariable("employee")); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sling.testing.mock.sling.junit; import org.apache.sling.testing.mock.osgi.context.ContextCallback; import org.osgi.annotation.versioning.ConsumerType; /** * Callback interface for application-specific setup and teardown operations to * customize the {@link SlingContext} JUnit rule. */ @ConsumerType public interface SlingContextCallback extends ContextCallback<SlingContext> { // specialized version of ContextCallback }
package io.github.ololx.cranberry.data.modifier.annotation; import java.lang.annotation.*; /** * The interface Final. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target({ ElementType.PARAMETER, ElementType.LOCAL_VARIABLE }) public @interface Final { }
package de.bitbrain.jpersis.util; public class ConnectionData { ConnectionData() { } public String username; public String password; public String db; public String host; public String port; }
package com.k_beta.android.app.mvp; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import com.k_beta.android.app.mvp.base.MvpPresenter; import com.k_beta.android.app.mvp.base.MvpView; import com.k_beta.android.app.mvp.delegate.ActivityMvpDelegate; import com.k_beta.android.app.mvp.delegate.ActivityMvpDelegateImpl; import com.k_beta.android.app.mvp.delegate.MvpDelegateCallback; /** * Created by Kevin Dong on 2017/7/20. */ public abstract class MvpActivity<V extends MvpView, P extends MvpPresenter<V>> extends AppCompatActivity implements MvpView, MvpDelegateCallback<V,P> { protected ActivityMvpDelegate mvpDelegate; protected P presenter; protected boolean retainInstance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getMvpDelegate().onCreate(savedInstanceState); } @Override protected void onDestroy() { super.onDestroy(); getMvpDelegate().onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); getMvpDelegate().onSaveInstanceState(outState); } @Override protected void onPause() { super.onPause(); getMvpDelegate().onPause(); } @Override protected void onResume() { super.onResume(); getMvpDelegate().onResume(); } @Override protected void onStart() { super.onStart(); getMvpDelegate().onStart(); } @Override protected void onStop() { super.onStop(); getMvpDelegate().onStop(); } @Override protected void onRestart() { super.onRestart(); getMvpDelegate().onRestart(); } @Override public void onContentChanged() { super.onContentChanged(); getMvpDelegate().onContentChanged(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getMvpDelegate().onPostCreate(savedInstanceState); } /** * Instantiate a presenter instance * * @return The {@link MvpPresenter} for this view */ @NonNull public abstract P createPresenter(); /** * Get the mvp delegate. This is internally used for creating presenter, attaching and detaching * view from presenter. * * <p><b>Please note that only one instance of mvp delegate should be used per Activity * instance</b>. * </p> * * <p> * Only override this method if you really know what you are doing. * </p> * * @return {@link ActivityMvpDelegateImpl} */ @NonNull protected ActivityMvpDelegate<V, P> getMvpDelegate() { if (mvpDelegate == null) { mvpDelegate = new ActivityMvpDelegateImpl(this, this, true); } return mvpDelegate; } @NonNull @Override public P getPresenter() { return presenter; } @Override public void setPresenter(@NonNull P presenter) { this.presenter = presenter; } @NonNull @Override public V getMvpView() { return (V) this; } }
package io.ebean.docker.commands; import java.util.Properties; public class ElasticConfig extends BaseConfig { public ElasticConfig(String version, Properties properties) { super("elastic", 9201, 9200, version); this.image = "docker.elastic.co/elasticsearch/elasticsearch:" + version; setProperties(properties); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.qyouti.data; import java.util.Vector; import javax.swing.table.AbstractTableModel; /** * * @author jon */ public class PageListModel extends AbstractTableModel { ExaminationData exam; private static final String[] column_headings = { "Page No.", "Barcode", "Paper Name", "Paper ID", "Scanned", "Error" }; Vector<PrintedPageData> pages = new Vector<PrintedPageData>(); //Vector<PageData> unprocessedpages = new Vector<PageData>(); //Hashtable<String,Vector<PageData>> candidatelookup = new Hashtable<String,Vector<PageData>>(); public PageListModel( ExaminationData exam, Vector<PrintedPageData> data ) { this.exam = exam; this.pages = data; } @Override public int getRowCount() { return pages.size(); } @Override public int getColumnCount() { return column_headings.length; } @Override public String getColumnName( int columnIndex ) { return column_headings[columnIndex]; } @Override public Class<?> getColumnClass( int columnIndex ) { //if ( columnIndex == 0 ) return Integer.class; return String.class; } @Override public boolean isCellEditable( int rowIndex, int columnIndex ) { return false; } @Override public Object getValueAt( int rowIndex, int columnIndex ) { PrintedPageData page = pages.elementAt( rowIndex ); switch( columnIndex ) { case 0: return page.pageid; case 1: return page.code; case 2: return page.candidate_name; case 3: return page.candidate_number; case 4: return (exam.getScannedPageData(page.pageid) != null)?"yes":"no"; case 5: return page.error; } return null; } @Override public void setValueAt( Object aValue, int rowIndex, int columnIndex ) { throw new UnsupportedOperationException( "Not supported." ); } }
// Java implementation of iterative Binary Search class BinarySearch { // Returns index of x if it is present in arr[], // else return -1 int binarySearch(int arr[], int x) { int l = 0, r = arr.length - 1; while (l <= r) { int m = l + (r-l)/2; // Check if x is present at mid if (arr[m] == x) return m; // If x greater, ignore left half if (arr[m] < x) l = m + 1; // If x is smaller, ignore right half else r = m - 1; } // if we reach here, then element was // not present return -1; } // Driver method to test above public static void main(String args[]) { BinarySearch ob = new BinarySearch(); int arr[] = {2, 3, 4, 10, 40}; int n = arr.length; int x = 10; int result = ob.binarySearch(arr, x); if (result == -1) System.out.println("Element not present"); else System.out.println("Element found at " + "index " + result); } }
package com.exadel.frs.core.trainservice; import com.exadel.frs.core.trainservice.config.IntegrationTest; import io.zonky.test.db.AutoConfigureEmbeddedDatabase; import liquibase.Contexts; import liquibase.LabelExpression; import liquibase.Liquibase; import liquibase.database.DatabaseFactory; import liquibase.database.jvm.JdbcConnection; import liquibase.integration.spring.SpringResourceAccessor; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ResourceLoader; import org.springframework.test.context.junit.jupiter.SpringExtension; import javax.annotation.PostConstruct; import javax.sql.DataSource; @IntegrationTest @ExtendWith(SpringExtension.class) @AutoConfigureEmbeddedDatabase(beanName = "dsPg") public class EmbeddedPostgreSQLTest { @Autowired DataSource dataSource; @Autowired ResourceLoader resourceLoader; @PostConstruct public void initDatabase() { try { Liquibase liquibase = new Liquibase( "db/changelog/db.changelog-master.yaml", new SpringResourceAccessor(resourceLoader), DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(dataSource.getConnection())) ); liquibase.update(new Contexts(), new LabelExpression()); } catch (Exception e) { //manage exception e.printStackTrace(); } } }
/* * Copyright 2020 LINE Corporation * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.centraldogma.server.internal.storage.repository; import static com.linecorp.centraldogma.server.internal.storage.repository.DefaultMetaRepository.PATH_CREDENTIALS; import static com.linecorp.centraldogma.server.internal.storage.repository.DefaultMetaRepository.PATH_MIRRORS; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.File; import java.util.Comparator; import java.util.List; import java.util.concurrent.ForkJoinPool; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.io.TempDir; import com.cronutils.model.CronType; import com.cronutils.model.definition.CronDefinitionBuilder; import com.cronutils.parser.CronParser; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.util.concurrent.MoreExecutors; import com.linecorp.armeria.common.metric.NoopMeterRegistry; import com.linecorp.centraldogma.common.Author; import com.linecorp.centraldogma.common.Change; import com.linecorp.centraldogma.common.Revision; import com.linecorp.centraldogma.common.ShuttingDownException; import com.linecorp.centraldogma.server.internal.mirror.credential.NoneMirrorCredential; import com.linecorp.centraldogma.server.internal.mirror.credential.PasswordMirrorCredential; import com.linecorp.centraldogma.server.internal.storage.project.DefaultProjectManager; import com.linecorp.centraldogma.server.mirror.Mirror; import com.linecorp.centraldogma.server.mirror.MirrorCredential; import com.linecorp.centraldogma.server.mirror.MirrorDirection; import com.linecorp.centraldogma.server.storage.project.Project; import com.linecorp.centraldogma.server.storage.project.ProjectManager; import com.linecorp.centraldogma.server.storage.repository.MetaRepository; import com.linecorp.centraldogma.testing.internal.TestUtil; class DefaultMetaRepositoryTest { private static final Change<JsonNode> UPSERT_CREDENTIALS = Change.ofJsonUpsert( PATH_CREDENTIALS, "[{" + " \"type\": \"password\"," + " \"id\": \"alice\"," + " \"hostnamePatterns\": [ \"^foo\\\\.com$\" ]," + " \"username\": \"alice\"," + " \"password\": \"secret_a\"" + "},{" + " \"type\": \"password\"," + " \"hostnamePatterns\": [ \"^.*\\\\.com$\" ]," + " \"username\": \"bob\"," + " \"password\": \"secret_b\"" + "}]"); private static final CronParser cronParser = new CronParser( CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ)); @TempDir static File rootDir; private static ProjectManager pm; private Project project; private MetaRepository metaRepo; @BeforeAll static void init() { pm = new DefaultProjectManager(rootDir, ForkJoinPool.commonPool(), MoreExecutors.directExecutor(), NoopMeterRegistry.get(), null); } @AfterAll static void destroy() { pm.close(ShuttingDownException::new); } @BeforeEach void setUp(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); project = pm.create(name, Author.SYSTEM); metaRepo = project.metaRepo(); } @Test void testEmptyMirrors() { // should return an empty result when both /credentials.json and /mirrors.json are non-existent. assertThat(metaRepo.mirrors()).isEmpty(); // should return an empty result when /credentials.json exists and /mirrors.json does not. metaRepo.commit(Revision.HEAD, 0, Author.SYSTEM, "", Change.ofJsonUpsert("/credentials.json", "[]")); assertThat(metaRepo.mirrors()).isEmpty(); // should return an empty result when both /credentials.json and /mirrors.json exist. metaRepo.commit(Revision.HEAD, 0, Author.SYSTEM, "", Change.ofJsonUpsert("/mirrors.json", "[]")); assertThat(metaRepo.mirrors()).isEmpty(); } /** * Ensures a {@link RepositoryMetadataException} is raised when the mirror configuration is not valid. */ @Test void testInvalidMirrors() { // not an array but an object metaRepo.commit(Revision.HEAD, 0, Author.SYSTEM, "", Change.ofJsonUpsert(PATH_MIRRORS, "{}")).join(); assertThatThrownBy(() -> metaRepo.mirrors()).isInstanceOf(RepositoryMetadataException.class); // not an array but a value metaRepo.commit(Revision.HEAD, 0, Author.SYSTEM, "", Change.ofJsonUpsert(PATH_MIRRORS, "\"oops\"")).join(); assertThatThrownBy(() -> metaRepo.mirrors()).isInstanceOf(RepositoryMetadataException.class); // an array that contains null. metaRepo.commit(Revision.HEAD, 0, Author.SYSTEM, "", Change.ofJsonUpsert(PATH_MIRRORS, "[ null ]")).join(); assertThatThrownBy(() -> metaRepo.mirrors()).isInstanceOf(RepositoryMetadataException.class); } @Test void testSingleTypeMirror() { metaRepo.commit(Revision.HEAD, 0, Author.SYSTEM, "", Change.ofJsonUpsert( PATH_MIRRORS, "[{" + " \"enabled\": true," + " \"type\": \"single\"," + " \"direction\": \"LOCAL_TO_REMOTE\"," + " \"localRepo\": \"foo\"," + " \"localPath\": \"/mirrors/foo\"," + " \"remoteUri\": \"git+ssh://foo.com/foo.git\"" + "},{" + " \"enabled\": true," + " \"type\": \"single\"," + " \"schedule\": \"*/10 * * * * ?\"," + " \"direction\": \"REMOTE_TO_LOCAL\"," + " \"localRepo\": \"bar\"," + " \"remoteUri\": \"git+ssh://bar.com/bar.git/some-path\"" + "}, {" + " \"type\": \"single\"," + // Enabled implicitly " \"direction\": \"LOCAL_TO_REMOTE\"," + " \"localRepo\": \"qux\"," + " \"remoteUri\": \"git+ssh://qux.net/qux.git#develop\"" + "}, {" + " \"enabled\": false," + // Disabled " \"type\": \"single\"," + " \"direction\": \"LOCAL_TO_REMOTE\"," + " \"localRepo\": \"foo\"," + " \"localPath\": \"/mirrors/bar\"," + " \"remoteUri\": \"git+ssh://bar.com/bar.git\"" + "}]"), UPSERT_CREDENTIALS).join(); // When the mentioned repositories (foo and bar) do not exist, assertThat(metaRepo.mirrors()).isEmpty(); project.repos().create("foo", Author.SYSTEM); project.repos().create("bar", Author.SYSTEM); project.repos().create("qux", Author.SYSTEM); final List<Mirror> mirrors = findMirrors(); assertThat(mirrors.stream() .map(m -> m.localRepo().name()) .collect(Collectors.toList())).containsExactly("bar", "foo", "qux"); final Mirror foo = mirrors.get(1); final Mirror bar = mirrors.get(0); final Mirror qux = mirrors.get(2); assertThat(foo.direction()).isEqualTo(MirrorDirection.LOCAL_TO_REMOTE); assertThat(bar.direction()).isEqualTo(MirrorDirection.REMOTE_TO_LOCAL); assertThat(qux.direction()).isEqualTo(MirrorDirection.LOCAL_TO_REMOTE); assertThat(foo.schedule().equivalent(cronParser.parse("0 * * * * ?"))).isTrue(); assertThat(bar.schedule().equivalent(cronParser.parse("*/10 * * * * ?"))).isTrue(); assertThat(qux.schedule().equivalent(cronParser.parse("0 * * * * ?"))).isTrue(); assertThat(foo.localPath()).isEqualTo("/mirrors/foo/"); assertThat(bar.localPath()).isEqualTo("/"); assertThat(qux.localPath()).isEqualTo("/"); assertThat(foo.remoteRepoUri().toString()).isEqualTo("git+ssh://foo.com/foo.git"); assertThat(bar.remoteRepoUri().toString()).isEqualTo("git+ssh://bar.com/bar.git"); assertThat(qux.remoteRepoUri().toString()).isEqualTo("git+ssh://qux.net/qux.git"); assertThat(foo.remotePath()).isEqualTo("/"); assertThat(bar.remotePath()).isEqualTo("/some-path/"); assertThat(qux.remotePath()).isEqualTo("/"); assertThat(foo.remoteBranch()).isEqualTo("master"); assertThat(bar.remoteBranch()).isEqualTo("master"); assertThat(qux.remoteBranch()).isEqualTo("develop"); // Ensure the credentials are loaded correctly. //// Should be matched by 'alice' credential. assertThat(foo.credential()).isInstanceOf(PasswordMirrorCredential.class); //// Should be matched by 'bob' credential. assertThat(bar.credential()).isInstanceOf(PasswordMirrorCredential.class); //// Should be matched by no credential. assertThat(qux.credential()).isInstanceOf(NoneMirrorCredential.class); final PasswordMirrorCredential fooCredential = (PasswordMirrorCredential) foo.credential(); final PasswordMirrorCredential barCredential = (PasswordMirrorCredential) bar.credential(); assertThat(fooCredential.username()).isEqualTo("alice"); assertThat(fooCredential.password()).isEqualTo("secret_a"); assertThat(barCredential.username()).isEqualTo("bob"); assertThat(barCredential.password()).isEqualTo("secret_b"); } @Test void testSingleTypeMirrorWithCredentialId() { metaRepo.commit(Revision.HEAD, 0, Author.SYSTEM, "", Change.ofJsonUpsert( PATH_MIRRORS, "[{" + " \"type\": \"single\"," + " \"direction\": \"LOCAL_TO_REMOTE\"," + " \"localRepo\": \"qux\"," + " \"remoteUri\": \"git+ssh://qux.net/qux.git\"," + " \"credentialId\": \"alice\"" + "}]"), UPSERT_CREDENTIALS).join(); project.repos().create("qux", Author.SYSTEM); final List<Mirror> mirrors = findMirrors(); assertThat(mirrors).hasSize(1); final Mirror m = mirrors.get(0); assertThat(m.localRepo().name()).isEqualTo("qux"); assertThat(m.credential()).isInstanceOf(PasswordMirrorCredential.class); assertThat(((PasswordMirrorCredential) m.credential()).username()).isEqualTo("alice"); } @Test void testMultipleTypeMirror() { metaRepo.commit(Revision.HEAD, 0, Author.SYSTEM, "", Change.ofJsonUpsert( PATH_MIRRORS, "[{" + " \"enabled\": true," + " \"type\": \"multiple\"," + " \"defaultDirection\": \"LOCAL_TO_REMOTE\"," + " \"defaultLocalPath\": \"/source\"," + " \"includes\": [{" + " \"pattern\": \"^([^.]+)(\\\\.[^.]+)$\"," + " \"replacement\": \"git+ssh://$1$2/$1.git#develop-$1\"" + " }]," + " \"excludes\": [ \"^qux\\\\.net$\" ]" + "}, {" + " \"type\": \"multiple\"," + // Enabled implicitly. " \"defaultDirection\": \"LOCAL_TO_REMOTE\"," + " \"defaultLocalPath\": \"/source\"," + " \"defaultSchedule\": \"* * * * * ?\"," + " \"includes\": [{" + " \"pattern\": \"^qux\\\\.net$\"," + " \"replacement\": \"dogma://qux.net/origin/qux.dogma/some-path\"," + " \"schedule\": \"0 0 * * * ?\"," + // Override the defaultSchedule. " \"direction\": \"REMOTE_TO_LOCAL\"," + // Override the defaultDirection. " \"localPath\": \"/mirrored/qux\"" + // Override the defaultLocalPath. " }]" + "}, {" + " \"enabled\": false," + // Disabled " \"type\": \"multiple\"," + " \"defaultDirection\": \"REMOTE_TO_LOCAL\"," + " \"defaultLocalPath\": \"/otherSource\"," + " \"includes\": [{" + " \"pattern\": \"^([^.]+)(\\\\.[^.]+)$\"," + " \"replacement\": \"git+ssh://$1$2/$1.git#others-$1\"" + " }]" + "}]"), UPSERT_CREDENTIALS).join(); // When no matching repositories exist. assertThat(metaRepo.mirrors()).isEmpty(); project.repos().create("foo.com", Author.SYSTEM); project.repos().create("bar.org", Author.SYSTEM); project.repos().create("qux.net", Author.SYSTEM); final List<Mirror> mirrors = findMirrors(); assertThat(mirrors.stream() .map(m -> m.localRepo().name()) .collect(Collectors.toList())).containsExactly("bar.org", "foo.com", "qux.net"); final Mirror foo = mirrors.get(1); final Mirror bar = mirrors.get(0); final Mirror qux = mirrors.get(2); // Ensure the directions are generated correctly. assertThat(foo.direction()).isEqualTo(MirrorDirection.LOCAL_TO_REMOTE); assertThat(bar.direction()).isEqualTo(MirrorDirection.LOCAL_TO_REMOTE); assertThat(qux.direction()).isEqualTo(MirrorDirection.REMOTE_TO_LOCAL); // Ensure the schedules are generated correctly. assertThat(foo.schedule().equivalent(cronParser.parse("0 * * * * ?"))).isTrue(); assertThat(bar.schedule().equivalent(cronParser.parse("0 * * * * ?"))).isTrue(); assertThat(qux.schedule().equivalent(cronParser.parse("0 0 * * * ?"))).isTrue(); // Ensure the localPaths are generated correctly. assertThat(foo.localPath()).isEqualTo("/source/"); assertThat(bar.localPath()).isEqualTo("/source/"); assertThat(qux.localPath()).isEqualTo("/mirrored/qux/"); // Ensure the remoteUris are generated correctly. assertThat(foo.remoteRepoUri().toASCIIString()).isEqualTo("git+ssh://foo.com/foo.git"); assertThat(bar.remoteRepoUri().toASCIIString()).isEqualTo("git+ssh://bar.org/bar.git"); assertThat(qux.remoteRepoUri().toASCIIString()).isEqualTo("dogma://qux.net/origin/qux.dogma"); // Ensure the remotePaths are generated correctly. assertThat(foo.remotePath()).isEqualTo("/"); assertThat(bar.remotePath()).isEqualTo("/"); assertThat(qux.remotePath()).isEqualTo("/some-path/"); // Ensure the remoteBranches are generated correctly. assertThat(foo.remoteBranch()).isEqualTo("develop-foo"); assertThat(bar.remoteBranch()).isEqualTo("develop-bar"); assertThat(qux.remoteBranch()).isNull(); // Central Dogma has no notion of branch. // Ensure the direction is set correctly. assertThat(foo.direction()).isEqualTo(MirrorDirection.LOCAL_TO_REMOTE); assertThat(bar.direction()).isEqualTo(MirrorDirection.LOCAL_TO_REMOTE); assertThat(qux.direction()).isEqualTo(MirrorDirection.REMOTE_TO_LOCAL); } @Test void testMultipleTypeMirrorWithCredentialId() { metaRepo.commit(Revision.HEAD, 0, Author.SYSTEM, "", Change.ofJsonUpsert( PATH_MIRRORS, "[{" + // foo and bar will use 'credentialId' under 'includes'. " \"type\": \"multiple\"," + " \"defaultDirection\": \"REMOTE_TO_LOCAL\"," + " \"includes\": [{" + " \"pattern\": \"^(foo|bar)$\"," + " \"replacement\": \"git+ssh://$1.net/repo.git\"," + " \"credentialId\": \"alice\"" + " }]" + "}, {" + // qux will use 'defaultCredentialId'. " \"type\": \"multiple\"," + " \"defaultDirection\": \"REMOTE_TO_LOCAL\"," + " \"defaultCredentialId\": \"alice\"," + " \"includes\": [{" + " \"pattern\": \"^(qux)$\"," + " \"replacement\": \"git+ssh://$1.net/repo.git\"" + " }]" + "}]"), UPSERT_CREDENTIALS).join(); // When no matching repositories exist. assertThat(metaRepo.mirrors()).isEmpty(); project.repos().create("foo", Author.SYSTEM); project.repos().create("bar", Author.SYSTEM); project.repos().create("qux", Author.SYSTEM); final List<Mirror> mirrors = findMirrors(); assertThat(mirrors.stream() .map(m -> m.localRepo().name()) .collect(Collectors.toList())).containsExactly("bar", "foo", "qux"); // Ensure that the three mirrors use the same correct credential. final MirrorCredential fooCredential = mirrors.get(1).credential(); assertThat(fooCredential).isInstanceOf(PasswordMirrorCredential.class); assertThat(((PasswordMirrorCredential) fooCredential).username()).isEqualTo("alice"); assertThat(mirrors.get(0).credential()).isSameAs(fooCredential); assertThat(mirrors.get(2).credential()).isSameAs(fooCredential); } private List<Mirror> findMirrors() { // Get the mirror list and sort it by localRepo name alphabetically for easier testing. return metaRepo.mirrors().stream() .sorted(Comparator.comparing(m -> m.localRepo().name())) .collect(Collectors.toList()); } }
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.pets.data; import android.content.ContentResolver; import android.net.Uri; import android.provider.BaseColumns; /** * API Contract for the Pets app. */ public final class PetContract { // To prevent someone from accidentally instantiating the contract class, // give it an empty constructor. private PetContract() {} // Constant for Uri preparation public static final String CONTENT_AUTHORITY = "com.example.android.pets"; public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); public static final String PATH_PETS = "pets"; /** * Inner class that defines constant values for the pets database table. * Each entry in the table represents a single pet. */ public static final class PetEntry implements BaseColumns { /** Name of database table for pets */ public final static String TABLE_NAME = "pets"; public final static String _ID = BaseColumns._ID; public final static String COLUMN_PET_NAME ="name"; public final static String COLUMN_PET_BREED = "breed"; public final static String COLUMN_PET_GENDER = "gender"; public final static String COLUMN_PET_WEIGHT = "weight"; /** * Possible values for the gender of the pet. */ public static final int GENDER_UNKNOWN = 0; public static final int GENDER_MALE = 1; public static final int GENDER_FEMALE = 2; //Constant for content uri public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_PETS); /** * The MIME type of the {@link #CONTENT_URI} for a list of pets. */ public static final String CONTENT_LIST_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_PETS; /** * The MIME type of the {@link #CONTENT_URI} for a single pet. */ public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_PETS; /** * Returns whether or not the given gender is {@link #GENDER_UNKNOWN}, {@link #GENDER_MALE}, * or {@link #GENDER_FEMALE}. */ public static boolean isValidGender(int gender) { if (gender == GENDER_UNKNOWN || gender == GENDER_MALE || gender == GENDER_FEMALE) { return true; } return false; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * <p>http://www.apache.org/licenses/LICENSE-2.0 * <p> * <p>Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.apache.hadoop.hdds.scm.container; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import org.apache.hadoop.hdds.conf.ConfigurationSource; import org.apache.hadoop.hdds.protocol.proto.HddsProtos; import org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState; import org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationFactor; import org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationType; import org.apache.hadoop.hdds.scm.ScmConfigKeys; import org.apache.hadoop.hdds.scm.container.metrics.SCMContainerManagerMetrics; import org.apache.hadoop.hdds.scm.exceptions.SCMException; import org.apache.hadoop.hdds.scm.pipeline.Pipeline; import org.apache.hadoop.hdds.scm.pipeline.PipelineManager; import org.apache.hadoop.hdds.scm.pipeline.PipelineNotFoundException; import org.apache.hadoop.hdds.utils.db.BatchOperation; import org.apache.hadoop.hdds.utils.db.BatchOperationHandler; import org.apache.hadoop.hdds.utils.db.Table; import org.apache.hadoop.hdds.utils.db.Table.KeyValue; import org.apache.hadoop.hdds.utils.db.TableIterator; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.hadoop.hdds.scm.exceptions.SCMException.ResultCodes.FAILED_TO_FIND_CONTAINER; /** * ContainerManager class contains the mapping from a name to a pipeline * mapping. This is used by SCM when allocating new locations and when * looking up a key. */ public class SCMContainerManager implements ContainerManager { private static final Logger LOG = LoggerFactory.getLogger( SCMContainerManager.class); private final Lock lock; private final PipelineManager pipelineManager; private final ContainerStateManager containerStateManager; private final int numContainerPerVolume; private final SCMContainerManagerMetrics scmContainerManagerMetrics; private Table<ContainerID, ContainerInfo> containerStore; private BatchOperationHandler batchHandler; /** * Constructs a mapping class that creates mapping between container names * and pipelines. * <p> * passed to LevelDB and this memory is allocated in Native code space. * CacheSize is specified * in MB. * * @param conf - {@link ConfigurationSource} * @param pipelineManager - {@link PipelineManager} * @throws IOException on Failure. */ public SCMContainerManager( final ConfigurationSource conf, Table<ContainerID, ContainerInfo> containerStore, BatchOperationHandler batchHandler, PipelineManager pipelineManager) throws IOException { this.batchHandler = batchHandler; this.containerStore = containerStore; this.lock = new ReentrantLock(); this.pipelineManager = pipelineManager; this.containerStateManager = new ContainerStateManager(conf); this.numContainerPerVolume = conf .getInt(ScmConfigKeys.OZONE_SCM_PIPELINE_OWNER_CONTAINER_COUNT, ScmConfigKeys.OZONE_SCM_PIPELINE_OWNER_CONTAINER_COUNT_DEFAULT); loadExistingContainers(); scmContainerManagerMetrics = SCMContainerManagerMetrics.create(); } private int getOpenContainerCountPerPipeline(Pipeline pipeline) { int minContainerCountPerDn = numContainerPerVolume * pipelineManager.minHealthyVolumeNum(pipeline); int minPipelineCountPerDn = pipelineManager.minPipelineLimit(pipeline); return (int) Math.ceil( ((double) minContainerCountPerDn / minPipelineCountPerDn)); } private void loadExistingContainers() throws IOException { TableIterator<ContainerID, ? extends KeyValue<ContainerID, ContainerInfo>> iterator = containerStore.iterator(); while (iterator.hasNext()) { ContainerInfo container = iterator.next().getValue(); Preconditions.checkNotNull(container); containerStateManager.loadContainer(container); try { if (container.getState() == LifeCycleState.OPEN) { pipelineManager.addContainerToPipeline(container.getPipelineID(), ContainerID.valueof(container.getContainerID())); } } catch (PipelineNotFoundException ex) { LOG.warn("Found a Container {} which is in {} state with pipeline {} " + "that does not exist. Closing Container.", container, container.getState(), container.getPipelineID()); updateContainerState(container.containerID(), HddsProtos.LifeCycleEvent.FINALIZE, true); } } } @VisibleForTesting // TODO: remove this later. public ContainerStateManager getContainerStateManager() { return containerStateManager; } @Override public Set<ContainerID> getContainerIDs() { lock.lock(); try { return containerStateManager.getAllContainerIDs(); } finally { lock.unlock(); } } @Override public List<ContainerInfo> getContainers() { lock.lock(); try { return containerStateManager.getAllContainerIDs().stream().map(id -> { try { return containerStateManager.getContainer(id); } catch (ContainerNotFoundException e) { // How can this happen? return null; } }).filter(Objects::nonNull).collect(Collectors.toList()); } finally { lock.unlock(); } } @Override public List<ContainerInfo> getContainers(LifeCycleState state) { lock.lock(); try { return containerStateManager.getContainerIDsByState(state).stream() .map(id -> { try { return containerStateManager.getContainer(id); } catch (ContainerNotFoundException e) { // How can this happen? return null; } }).filter(Objects::nonNull).collect(Collectors.toList()); } finally { lock.unlock(); } } /** * Get number of containers in the given state. * * @param state {@link LifeCycleState} * @return Count */ public Integer getContainerCountByState(LifeCycleState state) { return containerStateManager.getContainerCountByState(state); } /** * {@inheritDoc} */ @Override public ContainerInfo getContainer(final ContainerID containerID) throws ContainerNotFoundException { return containerStateManager.getContainer(containerID); } @Override public boolean exists(ContainerID containerID) { lock.lock(); try { return (containerStateManager.getContainer(containerID) != null); } catch (ContainerNotFoundException e) { return false; } finally { lock.unlock(); } } /** * {@inheritDoc} */ @Override public List<ContainerInfo> listContainer(ContainerID startContainerID, int count) { lock.lock(); try { scmContainerManagerMetrics.incNumListContainersOps(); final long startId = startContainerID == null ? 0 : startContainerID.getId(); final List<ContainerID> containersIds = new ArrayList<>(containerStateManager.getAllContainerIDs()); Collections.sort(containersIds); return containersIds.stream() .filter(id -> id.getId() > startId) .limit(count) .map(id -> { try { return containerStateManager.getContainer(id); } catch (ContainerNotFoundException ex) { // This can never happen, as we hold lock no one else can remove // the container after we got the container ids. LOG.warn("Container Missing.", ex); return null; } }).collect(Collectors.toList()); } finally { lock.unlock(); } } /** * Allocates a new container. * * @param replicationFactor - replication factor of the container. * @param owner - The string name of the Service that owns this container. * @return - Pipeline that makes up this container. * @throws IOException - Exception */ @Override public ContainerInfo allocateContainer(final ReplicationType type, final ReplicationFactor replicationFactor, final String owner) throws IOException { try { lock.lock(); ContainerInfo containerInfo = null; try { containerInfo = containerStateManager.allocateContainer(pipelineManager, type, replicationFactor, owner); } catch (IOException ex) { scmContainerManagerMetrics.incNumFailureCreateContainers(); throw ex; } // Add container to DB. try { addContainerToDB(containerInfo); } catch (IOException ex) { // When adding to DB failed, we are removing from containerStateMap. // We should also remove from pipeline2Container Map in // PipelineStateManager. pipelineManager.removeContainerFromPipeline( containerInfo.getPipelineID(), new ContainerID(containerInfo.getContainerID())); throw ex; } return containerInfo; } finally { lock.unlock(); } } /** * Deletes a container from SCM. * * @param containerID - Container ID * @throws IOException if container doesn't exist or container store failed * to delete the * specified key. */ @Override public void deleteContainer(ContainerID containerID) throws IOException { lock.lock(); try { containerStateManager.removeContainer(containerID); if (containerStore.get(containerID) != null) { containerStore.delete(containerID); } else { // Where did the container go? o_O LOG.warn("Unable to remove the container {} from container store," + " it's missing!", containerID); } scmContainerManagerMetrics.incNumSuccessfulDeleteContainers(); } catch (ContainerNotFoundException cnfe) { scmContainerManagerMetrics.incNumFailureDeleteContainers(); throw new SCMException( "Failed to delete container " + containerID + ", reason : " + "container doesn't exist.", FAILED_TO_FIND_CONTAINER); } finally { lock.unlock(); } } /** * {@inheritDoc} Used by client to update container state on SCM. */ @Override public HddsProtos.LifeCycleState updateContainerState( ContainerID containerID, HddsProtos.LifeCycleEvent event) throws IOException { // Should we return the updated ContainerInfo instead of LifeCycleState? return updateContainerState(containerID, event, false); } private HddsProtos.LifeCycleState updateContainerState( ContainerID containerID, HddsProtos.LifeCycleEvent event, boolean skipPipelineToContainerRemove) throws IOException { // Should we return the updated ContainerInfo instead of LifeCycleState? lock.lock(); try { final ContainerInfo container = containerStateManager .getContainer(containerID); final LifeCycleState oldState = container.getState(); containerStateManager.updateContainerState(containerID, event); final LifeCycleState newState = container.getState(); if (!skipPipelineToContainerRemove) { if (oldState == LifeCycleState.OPEN && newState != LifeCycleState.OPEN) { try { pipelineManager .removeContainerFromPipeline(container.getPipelineID(), containerID); } catch (PipelineNotFoundException e) { LOG.warn("Unable to remove container {} from pipeline {} " + " as the pipeline no longer exists", containerID, container.getPipelineID()); } } } if (newState == LifeCycleState.DELETED) { containerStore.delete(containerID); } else { containerStore.put(containerID, container); } return newState; } catch (ContainerNotFoundException cnfe) { throw new SCMException( "Failed to update container state" + containerID + ", reason : container doesn't exist.", FAILED_TO_FIND_CONTAINER); } finally { lock.unlock(); } } /** * Update deleteTransactionId according to deleteTransactionMap. * * @param deleteTransactionMap Maps the containerId to latest delete * transaction id for the container. * @throws IOException */ public void updateDeleteTransactionId(Map<Long, Long> deleteTransactionMap) throws IOException { if (deleteTransactionMap == null) { return; } lock.lock(); try(BatchOperation batchOperation = batchHandler.initBatchOperation()) { for (Map.Entry< Long, Long > entry : deleteTransactionMap.entrySet()) { long containerID = entry.getKey(); ContainerID containerIdObject = new ContainerID(containerID); ContainerInfo containerInfo = containerStore.get(containerIdObject); try { ContainerInfo containerInfoInMem = containerStateManager .getContainer(containerIdObject); if (containerInfo == null || containerInfoInMem == null) { throw new SCMException("Failed to increment number of deleted " + "blocks for container " + containerID + ", reason : " + "container doesn't exist.", FAILED_TO_FIND_CONTAINER); } containerInfo.updateDeleteTransactionId(entry.getValue()); containerInfo.setNumberOfKeys(containerInfoInMem.getNumberOfKeys()); containerInfo.setUsedBytes(containerInfoInMem.getUsedBytes()); containerStore.putWithBatch(batchOperation, containerIdObject, containerInfo); } catch (ContainerNotFoundException ex) { // Container is not present therefore we don't need to update // transaction id for this container. LOG.warn( "Failed to update the transaction Id as container: " + containerID + " for transaction: " + entry.getValue() + " does not exists"); } } batchHandler.commitBatchOperation(batchOperation); containerStateManager.updateDeleteTransactionId(deleteTransactionMap); } finally { lock.unlock(); } } /** * Return a container matching the attributes specified. * * @param sizeRequired - Space needed in the Container. * @param owner - Owner of the container - A specific nameservice. * @param pipeline - Pipeline to which the container should belong. * @return ContainerInfo, null if there is no match found. */ public ContainerInfo getMatchingContainer(final long sizeRequired, String owner, Pipeline pipeline) { return getMatchingContainer(sizeRequired, owner, pipeline, Collections.emptySet()); } @SuppressWarnings("squid:S2445") public ContainerInfo getMatchingContainer(final long sizeRequired, String owner, Pipeline pipeline, Collection<ContainerID> excludedContainers) { NavigableSet<ContainerID> containerIDs; ContainerInfo containerInfo; try { synchronized (pipeline) { containerIDs = getContainersForOwner(pipeline, owner); if (containerIDs.size() < getOpenContainerCountPerPipeline(pipeline)) { containerInfo = containerStateManager.allocateContainer( pipelineManager, owner, pipeline); // Add to DB addContainerToDB(containerInfo); } else { containerIDs.removeAll(excludedContainers); containerInfo = containerStateManager.getMatchingContainer( sizeRequired, owner, pipeline.getId(), containerIDs); if (containerInfo == null) { containerInfo = containerStateManager. allocateContainer(pipelineManager, owner, pipeline); // Add to DB addContainerToDB(containerInfo); } } containerStateManager.updateLastUsedMap(pipeline.getId(), containerInfo.containerID(), owner); // TODO: #CLUTIL cleanup entries in lastUsedMap return containerInfo; } } catch (Exception e) { LOG.warn("Container allocation failed for pipeline={} requiredSize={}.", pipeline, sizeRequired, e); return null; } } /** * Add newly allocated container to container DB. * @param containerInfo * @throws IOException */ protected void addContainerToDB(ContainerInfo containerInfo) throws IOException { try { containerStore .put(new ContainerID(containerInfo.getContainerID()), containerInfo); // Incrementing here, as allocateBlock to create a container calls // getMatchingContainer() and finally calls this API to add newly // created container to DB. // Even allocateContainer calls this API to add newly allocated // container to DB. So we need to increment metrics here. scmContainerManagerMetrics.incNumSuccessfulCreateContainers(); } catch (IOException ex) { // If adding to containerStore fails, we should remove the container // from in-memory map. scmContainerManagerMetrics.incNumFailureCreateContainers(); LOG.error("Add Container to DB failed for ContainerID #{}", containerInfo.getContainerID()); try { containerStateManager.removeContainer(containerInfo.containerID()); } catch (ContainerNotFoundException cnfe) { // This should not happen, as we are removing after adding in to // container state cmap. } throw ex; } } /** * Returns the container ID's matching with specified owner. * @param pipeline * @param owner * @return NavigableSet<ContainerID> */ private NavigableSet<ContainerID> getContainersForOwner( Pipeline pipeline, String owner) throws IOException { NavigableSet<ContainerID> containerIDs = pipelineManager.getContainersInPipeline(pipeline.getId()); Iterator<ContainerID> containerIDIterator = containerIDs.iterator(); while (containerIDIterator.hasNext()) { ContainerID cid = containerIDIterator.next(); try { if (!getContainer(cid).getOwner().equals(owner)) { containerIDIterator.remove(); } } catch (ContainerNotFoundException e) { LOG.error("Could not find container info for container id={}.", cid, e); containerIDIterator.remove(); } } return containerIDs; } /** * Returns the latest list of DataNodes where replica for given containerId * exist. Throws an SCMException if no entry is found for given containerId. * * @param containerID * @return Set<DatanodeDetails> */ public Set<ContainerReplica> getContainerReplicas( final ContainerID containerID) throws ContainerNotFoundException { return containerStateManager.getContainerReplicas(containerID); } /** * Add a container Replica for given DataNode. * * @param containerID * @param replica */ public void updateContainerReplica(final ContainerID containerID, final ContainerReplica replica) throws ContainerNotFoundException { containerStateManager.updateContainerReplica(containerID, replica); } /** * Remove a container Replica for given DataNode. * * @param containerID * @param replica * @return True of dataNode is removed successfully else false. */ public void removeContainerReplica(final ContainerID containerID, final ContainerReplica replica) throws ContainerNotFoundException, ContainerReplicaNotFoundException { containerStateManager.removeContainerReplica(containerID, replica); } /** * Closes this stream and releases any system resources associated with it. * If the stream is * already closed then invoking this method has no effect. * <p> * <p>As noted in {@link AutoCloseable#close()}, cases where the close may * fail require careful * attention. It is strongly advised to relinquish the underlying resources * and to internally * <em>mark</em> the {@code Closeable} as closed, prior to throwing the * {@code IOException}. * * @throws IOException if an I/O error occurs */ @Override public void close() throws IOException { if (containerStateManager != null) { containerStateManager.close(); } if (scmContainerManagerMetrics != null) { this.scmContainerManagerMetrics.unRegister(); } } public void notifyContainerReportProcessing(boolean isFullReport, boolean success) { if (isFullReport) { if (success) { scmContainerManagerMetrics.incNumContainerReportsProcessedSuccessful(); } else { scmContainerManagerMetrics.incNumContainerReportsProcessedFailed(); } } else { if (success) { scmContainerManagerMetrics.incNumICRReportsProcessedSuccessful(); } else { scmContainerManagerMetrics.incNumICRReportsProcessedFailed(); } } } protected PipelineManager getPipelineManager() { return pipelineManager; } public Lock getLock() { return lock; } }
import java.util.*; public class Solution { HashMap<Integer, List<List<Integer>>> sumMap; public List<List<Integer>> pathSum(TreeNode root, int sum) { if (root == null) { return new LinkedList<List<Integer>>(); } sumMap = new HashMap<Integer, List<List<Integer>>>(); List<Integer> path = new LinkedList<Integer>(); sumMap.put(sum, new LinkedList<List<Integer>>()); generatePaths(root, sum, path); return sumMap.get(sum); } private void generatePaths(TreeNode root, int sum, List<Integer> path) { path.add(root.val); if (root.left == null && root.right == null) { int r = 0; for (Integer e : path) { r += e; } if (r == sum) { List<List<Integer>> current = sumMap.get(sum); List<Integer> p = new LinkedList<Integer>(); p.addAll(path); current.add(p); } } if (root.left != null) { generatePaths(root.left, sum, path); } if (root.right != null) { generatePaths(root.right, sum, path); } path.remove(path.size()-1); } }
/* * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.developerstudio.eclipse.capp.core.ui.utils; import java.io.File; import java.io.IOException; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.dialogs.DialogSettings; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Text; import org.wso2.developerstudio.eclipse.capp.core.Activator; import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog; import org.wso2.developerstudio.eclipse.logging.core.Logger; public class WizardInfoPersister { private static IDeveloperStudioLog log=Logger.getLog(Activator.PLUGIN_ID); private DialogSettings settings; private String filename; public void addControl(final Control control, final String ID) throws IOException{ IPath path = Activator.getDefault().getStateLocation(); filename = path.append("settings.txt").toOSString(); File file = new File(filename); if(!file.exists()){ file.createNewFile(); } if(settings == null){ settings = new DialogSettings("Top"); } settings.load(filename); if(control instanceof Text){ ((Text) control).addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent arg0) { if (settings != null) { settings.put(ID, ((Text) control).getText()); try { settings.save(filename); } catch (IOException e) { log.error(e); } } } }); String temp=""; if(settings != null){ try { settings.load(filename); } catch (IOException e1) { e1.printStackTrace(); } temp = settings.get(ID); } if(temp != null){ ((Text) control).setText(temp); } } /* if(control instanceof Composite){ } if(control instanceof Combo){ } */ } }
package de.uni_stuttgart.vis.vowl.owl2vowl.parser.vowl.property; import de.uni_stuttgart.vis.vowl.owl2vowl.model.data.VowlData; import de.uni_stuttgart.vis.vowl.owl2vowl.model.entities.AbstractEntity; import de.uni_stuttgart.vis.vowl.owl2vowl.model.entities.nodes.classes.VowlClass; import de.uni_stuttgart.vis.vowl.owl2vowl.model.entities.nodes.classes.VowlThing; import de.uni_stuttgart.vis.vowl.owl2vowl.model.entities.nodes.datatypes.VowlDatatype; import de.uni_stuttgart.vis.vowl.owl2vowl.model.entities.nodes.datatypes.VowlLiteral; import de.uni_stuttgart.vis.vowl.owl2vowl.model.entities.properties.TypeOfProperty; import de.uni_stuttgart.vis.vowl.owl2vowl.model.entities.properties.VowlDatatypeProperty; import de.uni_stuttgart.vis.vowl.owl2vowl.model.entities.properties.VowlObjectProperty; import de.uni_stuttgart.vis.vowl.owl2vowl.model.individuals.VowlIndividual; import de.uni_stuttgart.vis.vowl.owl2vowl.model.visitor.VowlElementVisitor; import org.semanticweb.owlapi.model.IRI; import java.util.HashSet; import java.util.Set; /** * @author Eduard */ public class VowlSubclassPropertyGenerator implements VowlElementVisitor { private VowlData vowlData; public VowlSubclassPropertyGenerator(VowlData vowlData) { this.vowlData = vowlData; } public void execute() { Set<AbstractEntity> entities = new HashSet<>(vowlData.getEntityMap().values()); for (AbstractEntity abstractEntity : entities) { abstractEntity.accept(this); } } @Override public void visit(VowlThing vowlThing) { } @Override public void visit(VowlClass vowlClass) { if (vowlClass.getSubEntities().size() != 0) { for (IRI iri : vowlClass.getSubEntities()) { vowlData.getGenerator().generateSubclassProperty(iri, vowlClass.getIri()); } } } @Override public void visit(VowlLiteral vowlLiteral) { } @Override public void visit(VowlDatatype vowlDatatype) { } @Override public void visit(VowlObjectProperty vowlObjectProperty) { } @Override public void visit(VowlDatatypeProperty vowlDatatypeProperty) { } @Override public void visit(VowlIndividual vowlIndividual) { } @Override public void visit(TypeOfProperty typeOfProperty) { } }
/* * Copyright (c) 2015, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.nrfbeacon.nearby.update; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.view.View; import no.nordicsemi.android.nrfbeacon.nearby.R; /** * Created by rora on 16.03.2016. */ public class ErrorDialogFragment extends DialogFragment{ private static final String MESSAGE = "MESSAGE"; private String mMessage; public static ErrorDialogFragment newInstance(final String message){ ErrorDialogFragment fragment = new ErrorDialogFragment(); final Bundle args = new Bundle(); args.putString(MESSAGE, message); fragment.setArguments(args); return fragment; } public ErrorDialogFragment(){ } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(getArguments() != null){ mMessage = getArguments().getString(MESSAGE); } } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity()); alertDialogBuilder.setTitle(getString(R.string.error_generic)); alertDialogBuilder.setMessage(mMessage); final AlertDialog alertDialog = alertDialogBuilder.setPositiveButton(getString(R.string.ok), null).show(); alertDialog.setCanceledOnTouchOutside(false); alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); return alertDialog; } }
package com.example.howes.myapplication; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Provider; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public class NaiveSSLContext { private NaiveSSLContext() { } public static SSLContext getInstance(String protocol) throws NoSuchAlgorithmException { return init(SSLContext.getInstance(protocol)); } public static SSLContext getInstance(String protocol, Provider provider) throws NoSuchAlgorithmException { return init(SSLContext.getInstance(protocol, provider)); } public static SSLContext getInstance(String protocol, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { return init(SSLContext.getInstance(protocol, provider)); } private static SSLContext init(SSLContext context) { try { // Set NaiveTrustManager. context.init(null, new TrustManager[]{new NaiveTrustManager()}, null); } catch (KeyManagementException e) { throw new RuntimeException("Failed to initialize an SSLContext.", e); } return context; } private static class NaiveTrustManager implements X509TrustManager { @Override public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.run.deployment; import com.android.ddmlib.IDevice; import com.android.tools.idea.adb.AdbService; import com.google.common.util.concurrent.FluentFuture; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.intellij.openapi.diagnostic.Logger; import com.intellij.util.concurrency.AppExecutorUtil; import java.io.File; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.jetbrains.annotations.NotNull; final class DdmlibAndroidDebugBridge implements AndroidDebugBridge { @NotNull private final File myAdb; @NotNull private final ListeningExecutorService myListeningExecutorService; DdmlibAndroidDebugBridge(@NotNull File adb) { myAdb = adb; myListeningExecutorService = MoreExecutors.listeningDecorator(AppExecutorUtil.getAppExecutorService()); } @Override public boolean isConnected() { Future<com.android.ddmlib.AndroidDebugBridge> future = AdbService.getInstance().getDebugBridge(myAdb); if (future.isCancelled()) { return false; } if (!future.isDone()) { return false; } try { return future.get().isConnected(); } catch (InterruptedException exception) { Thread.currentThread().interrupt(); return false; } catch (ExecutionException exception) { Logger.getInstance(DdmlibAndroidDebugBridge.class).warn(exception); return false; } } @NotNull @Override public ListenableFuture<Collection<IDevice>> getConnectedDevices() { // noinspection UnstableApiUsage return FluentFuture.from(AdbService.getInstance().getDebugBridge(myAdb)) .transform(com.android.ddmlib.AndroidDebugBridge::getDevices, myListeningExecutorService) .transform(Arrays::asList, myListeningExecutorService); } @NotNull @Override public ListenableFuture<String> getVirtualDeviceId(@NotNull IDevice virtualDevice) { return com.android.ddmlib.AndroidDebugBridge.getVirtualDeviceId(myListeningExecutorService, myAdb, virtualDevice); } }
package com.jbm.framework.usage.form; import com.jbm.framework.usage.paging.PageForm; import java.io.Serializable; /** * 前端请求封装类 * * @author wesley.zhang */ public class JsonRequestBody extends BaseRequsetBody { /** * 分页封装类 */ private PageForm pageForm; public PageForm getPageForm() { if (this.pageForm == null) { this.pageForm = this.tryGet(PageForm.class); } return this.pageForm; } }
/* * (c) Copyright 2018 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.atlasdb.cas; import java.util.Optional; import com.palantir.atlasdb.transaction.api.TransactionManager; public class CheckAndSetClient { private final TransactionManager transactionManager; public CheckAndSetClient(TransactionManager transactionManager) { this.transactionManager = transactionManager; } public Optional<Long> get() { return transactionManager.runTaskReadOnly((transaction) -> new CheckAndSetPersistentValue(transaction).get()); } public void set(Optional<Long> value) { transactionManager.runTaskWithRetry((transaction) -> { new CheckAndSetPersistentValue(transaction).set(value); return null; }); } public boolean checkAndSet(Optional<Long> oldValue, Optional<Long> newValue) { return transactionManager.runTaskWithRetry( (transaction) -> new CheckAndSetPersistentValue(transaction).checkAndSet(oldValue, newValue)); } }
/* * Copyright 1999-2011 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.remoting.transport.dispather; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.ChannelHandler; /** * @author chao.liuc * */ public class ChannelEventRunnable implements Runnable { private static final Logger logger = LoggerFactory.getLogger(ChannelEventRunnable.class); private final ChannelHandler handler; private final Channel channel; private final ChannelState state; private final Throwable exception; private final Object message; public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelState state) { this(channel, handler, state, null); } public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelState state, Object message) { this(channel, handler, state, message, null); } public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelState state, Throwable t) { this(channel, handler, state, null , t); } public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelState state, Object message, Throwable exception) { this.channel = channel; this.handler = handler; this.state = state; this.message = message; this.exception = exception; } public void run() { switch (state) { case CONNECTED: try{ handler.connected(channel); }catch (Exception e) { logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel, e); } break; case DISCONNECTED: try{ handler.disconnected(channel); }catch (Exception e) { logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel, e); } break; case SENT: try{ handler.sent(channel,message); }catch (Exception e) { logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel + ", message is "+ message,e); } break; case RECEIVED: try{ handler.received(channel, message); }catch (Exception e) { logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel + ", message is "+ message,e); } break; case CAUGHT: try{ handler.caught(channel, exception); }catch (Exception e) { logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is "+ channel + ", message is: " + message + ", exception is " + exception,e); } break; default: logger.warn("unknown state: " + state + ", message is " + message); } } /** * ChannelState * * @author william.liangf */ public enum ChannelState{ /** * CONNECTED */ CONNECTED, /** * DISCONNECTED */ DISCONNECTED, /** * SENT */ SENT, /** * RECEIVED */ RECEIVED, /** * CAUGHT */ CAUGHT } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.requests.generated.IBaseWorkbookFunctionsPercentRank_ExcRequestBuilder; // This file is available for extending, afterwards please submit a pull request. /** * The interface for the Workbook Functions Percent Rank_Exc Request Builder. */ public interface IWorkbookFunctionsPercentRank_ExcRequestBuilder extends IBaseWorkbookFunctionsPercentRank_ExcRequestBuilder { }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bluenimble.platform.servers.broker.server; public class BrokerException extends Exception { private static final long serialVersionUID = 1165308892883189037L; public BrokerException () { super (); } public BrokerException (String message, Throwable cause) { super (message, cause); } public BrokerException (String message) { super (message); } public BrokerException (Throwable cause) { super (cause); } }
/* * Copyright (c) 2016-present The Limitart Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.limitart.base; /** * 二参过程函数接口 * * @param <T1> * @param <T2> * @author hank */ @FunctionalInterface public interface Proc2<T1, T2> { void run(T1 t1, T2 t2); }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.job.entries.checkdbconnection; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import org.junit.ClassRule; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.job.entry.loadSave.JobEntryLoadSaveTestSupport; import org.pentaho.di.junit.rules.RestorePDIEngineEnvironment; import org.pentaho.di.trans.steps.loadsave.validator.ArrayLoadSaveValidator; import org.pentaho.di.trans.steps.loadsave.validator.DatabaseMetaLoadSaveValidator; import org.pentaho.di.trans.steps.loadsave.validator.FieldLoadSaveValidator; import org.pentaho.di.trans.steps.loadsave.validator.IntLoadSaveValidator; import org.pentaho.di.trans.steps.loadsave.validator.PrimitiveIntArrayLoadSaveValidator; import org.pentaho.di.trans.steps.loadsave.validator.StringLoadSaveValidator; public class JobEntryCheckDbConnectionsLoadSaveTest extends JobEntryLoadSaveTestSupport<JobEntryCheckDbConnections> { @ClassRule public static RestorePDIEngineEnvironment env = new RestorePDIEngineEnvironment(); @Override protected Class<JobEntryCheckDbConnections> getJobEntryClass() { return JobEntryCheckDbConnections.class; } @Override protected List<String> listCommonAttributes() { return Arrays.asList( new String[] { "connections", "waitfors", "waittimes" } ); } @Override protected Map<String, FieldLoadSaveValidator<?>> createAttributeValidatorsMap() { Map<String, FieldLoadSaveValidator<?>> validators = new HashMap<String, FieldLoadSaveValidator<?>>(); int entries = new Random().nextInt( 10 ) + 1; validators.put( "connections", new ArrayLoadSaveValidator<DatabaseMeta>( new DatabaseMetaLoadSaveValidator(), entries ) ); validators.put( "waitfors", new ArrayLoadSaveValidator<String>( new StringLoadSaveValidator(), entries ) ); validators.put( "waittimes", new PrimitiveIntArrayLoadSaveValidator( new IntLoadSaveValidator( JobEntryCheckDbConnections.unitTimeCode.length ), entries ) ); return validators; } }
/* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.android; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.facebook.buck.android.toolchain.AndroidPlatformTarget; import com.facebook.buck.core.build.execution.context.ExecutionContext; import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder; import com.facebook.buck.core.toolchain.tool.impl.testutil.SimpleTool; import com.facebook.buck.core.toolchain.toolprovider.impl.ConstantToolProvider; import com.facebook.buck.io.file.MorePaths; import com.facebook.buck.rules.coercer.ManifestEntries; import com.facebook.buck.step.TestExecutionContext; import com.facebook.buck.testutil.TestConsole; import com.facebook.buck.util.Verbosity; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedSet; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import org.junit.Test; /** Test generation of command line flags based on creation parameters */ public class AaptStepTest { private Path basePath = Paths.get("/java/com/facebook/buck/example"); private Path proguardConfig = basePath.resolve("mock_proguard.txt"); private AaptStep buildAaptStep( Path pathToGeneratedProguardConfig, boolean isCrunchFiles, boolean includesVectorDrawables, ManifestEntries manifestEntries) { return buildAaptStep( pathToGeneratedProguardConfig, isCrunchFiles, includesVectorDrawables, manifestEntries, ImmutableList.of()); } /** * Build an AaptStep that can be used to generate a shell command. Should only be used for * checking the generated command, since it does not refer to useful directories (so it can't be * executed). */ private AaptStep buildAaptStep( Path pathToGeneratedProguardConfig, boolean isCrunchFiles, boolean includesVectorDrawables, ManifestEntries manifestEntries, ImmutableList<String> additionalAaptParams) { return new AaptStep( new TestActionGraphBuilder().getSourcePathResolver(), AndroidPlatformTarget.of( "android", basePath.resolve("mock_android.jar"), Collections.emptyList(), () -> new SimpleTool("mock_aapt_bin"), new ConstantToolProvider(new SimpleTool("")), Paths.get(""), Paths.get(""), Paths.get(""), Paths.get(""), Paths.get(""), Paths.get(""), Paths.get(""), Paths.get("")), /* workingDirectory */ basePath, /* manifestDirectory */ basePath.resolve("AndroidManifest.xml"), /* resDirectories */ ImmutableList.of(), /* assetsDirectories */ ImmutableSortedSet.of(), /* pathToOutputApk */ basePath.resolve("build").resolve("out.apk"), /* pathToRDotDText */ basePath.resolve("r"), pathToGeneratedProguardConfig, ImmutableList.of(), isCrunchFiles, includesVectorDrawables, manifestEntries, additionalAaptParams); } /** * Create an execution context with the given verbosity level. The execution context will yield * fake values relative to the base path for all target queries. The mock context returned has not * been replayed, so the calling code may add additional expectations, and is responsible for * calling replay(). */ private ExecutionContext createTestExecutionContext(Verbosity verbosity) { return TestExecutionContext.newBuilder().setConsole(new TestConsole(verbosity)).build(); } @Test public void shouldEmitVerbosityFlagWithVerboseContext() { AaptStep aaptStep = buildAaptStep(proguardConfig, false, false, ManifestEntries.empty()); ExecutionContext executionContext = createTestExecutionContext(Verbosity.ALL); ImmutableList<String> command = aaptStep.getShellCommandInternal(executionContext); assertTrue(command.contains("-v")); } @Test public void shouldNotEmitVerbosityFlagWithQuietContext() { AaptStep aaptStep = buildAaptStep(proguardConfig, false, false, ManifestEntries.empty()); ExecutionContext executionContext = createTestExecutionContext(Verbosity.SILENT); ImmutableList<String> command = aaptStep.getShellCommandInternal(executionContext); assertFalse(command.contains("-v")); } @Test public void shouldEmitGFlagIfProguardConfigPresent() { AaptStep aaptStep = buildAaptStep(proguardConfig, false, false, ManifestEntries.empty()); ExecutionContext executionContext = createTestExecutionContext(Verbosity.ALL); ImmutableList<String> command = aaptStep.getShellCommandInternal(executionContext); assertTrue(command.contains("-G")); String proguardConfigPath = MorePaths.pathWithPlatformSeparators("/java/com/facebook/buck/example/mock_proguard.txt"); assertTrue(command.contains(proguardConfigPath)); } @Test public void shouldEmitNoCrunchFlagIfNotCrunch() { AaptStep aaptStep = buildAaptStep(proguardConfig, false, false, ManifestEntries.empty()); ExecutionContext executionContext = createTestExecutionContext(Verbosity.ALL); ImmutableList<String> command = aaptStep.getShellCommandInternal(executionContext); assertTrue(command.contains("--no-crunch")); } @Test public void shouldNotEmitNoCrunchFlagIfCrunch() { AaptStep aaptStep = buildAaptStep(proguardConfig, true, false, ManifestEntries.empty()); ExecutionContext executionContext = createTestExecutionContext(Verbosity.ALL); ImmutableList<String> command = aaptStep.getShellCommandInternal(executionContext); assertFalse(command.contains("--no-crunch")); } @Test public void shouldEmitNoVersionVectorsFlagIfRequested() { AaptStep aaptStep = buildAaptStep(proguardConfig, false, true, ManifestEntries.empty()); ExecutionContext executionContext = createTestExecutionContext(Verbosity.ALL); ImmutableList<String> command = aaptStep.getShellCommandInternal(executionContext); assertTrue(command.contains("--no-version-vectors")); } @Test public void shouldNotEmitNoVersionVectorsFlagIfNotRequested() { AaptStep aaptStep = buildAaptStep(proguardConfig, false, false, ManifestEntries.empty()); ExecutionContext executionContext = createTestExecutionContext(Verbosity.ALL); ImmutableList<String> command = aaptStep.getShellCommandInternal(executionContext); assertFalse(command.contains("--no-version-vectors")); } @Test public void shouldEmitFlagsForManifestEntries() { ManifestEntries entries = ManifestEntries.builder() .setMinSdkVersion(3) .setTargetSdkVersion(5) .setVersionCode(7) .setVersionName("eleven") .setDebugMode(true) .build(); AaptStep aaptStep = buildAaptStep(proguardConfig, true, false, entries); ExecutionContext executionContext = createTestExecutionContext(Verbosity.ALL); ImmutableList<String> command = aaptStep.getShellCommandInternal(executionContext); assertTrue(command.contains("--min-sdk-version")); assertEquals("3", command.get(command.indexOf("--min-sdk-version") + 1)); assertTrue(command.contains("--target-sdk-version")); assertEquals("5", command.get(command.indexOf("--target-sdk-version") + 1)); assertTrue(command.contains("--version-code")); assertEquals("7", command.get(command.indexOf("--version-code") + 1)); assertTrue(command.contains("--version-name")); assertEquals("eleven", command.get(command.indexOf("--version-name") + 1)); assertTrue(command.contains("--debug-mode")); // This should be present because we've emitted > 0 manifest-changing flags. assertTrue(command.contains("--error-on-failed-insert")); } @Test public void shouldNotEmitFailOnInsertWithoutManifestEntries() { AaptStep aaptStep = buildAaptStep(proguardConfig, true, false, ManifestEntries.empty()); ExecutionContext executionContext = createTestExecutionContext(Verbosity.ALL); ImmutableList<String> command = aaptStep.getShellCommandInternal(executionContext); assertFalse(command.contains("--error-on-failed-insert")); } @Test public void shouldEmitAdditionalAaptParams() { AaptStep aaptStep = buildAaptStep( proguardConfig, false, false, ManifestEntries.empty(), ImmutableList.of("--shared-lib")); ExecutionContext executionContext = createTestExecutionContext(Verbosity.ALL); ImmutableList<String> command = aaptStep.getShellCommandInternal(executionContext); assertTrue(command.contains("--shared-lib")); } }
package com.example.procare.data; import java.io.Serializable; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Task implements Serializable, Comparable<Task> { public static final int FREQUENCY_NONE = 0; public static final int FREQUENCY_DAILY = 1; public static final int FREQUENCY_WEEKLY = 2; public static final int FREQUENCY_MONTHLY = 3; public static final int FREQUENCY_YEARLY = 4; private Integer mId; private Integer mPetId; private String mTaskName; private Date mScheduleDatetime; private Date mTaskDoneDatetime; private String mDescription; private Integer mFreq; private String[] mFreqNames; public Task(Integer mId, Integer mPetId, String mTaskName, String mScheduleDatetime, String mTaskDoneDatetime, String mDescription, Integer mFreq, String[] mFreqNames) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); Date schedDate = null; Date doneDate = null; try { schedDate = dateFormat.parse(mScheduleDatetime); if(mTaskDoneDatetime != null) doneDate = dateFormat.parse(mTaskDoneDatetime); } catch (ParseException e) { e.printStackTrace(); } this.mId = mId; this.mPetId = mPetId; this.mTaskName = mTaskName; this.mScheduleDatetime = schedDate; this.mTaskDoneDatetime = doneDate; this.mDescription = mDescription; this.mFreq = mFreq; this.mFreqNames = mFreqNames; } public String getmTaskName() { return mTaskName; } public void setmTaskName(String mTaskName) { this.mTaskName = mTaskName; } public Integer getmId() { return mId; } public void setmId(Integer mId) { this.mId = mId; } public Integer getmPetId() { return mPetId; } public void setmPetId(Integer mPetId) { this.mPetId = mPetId; } public Date getmScheduleDatetime() { return mScheduleDatetime; } public void setmScheduleDatetime(Date mScheduleDatetime) { this.mScheduleDatetime = mScheduleDatetime; } public Date getmTaskDoneDatetime() { return mTaskDoneDatetime; } public void setmTaskDoneDatetime(Date mTaskDoneDatetime) { this.mTaskDoneDatetime = mTaskDoneDatetime; } public String getmDescription() { return mDescription; } public void setmDescription(String mDescription) { this.mDescription = mDescription; } public String getmFreqName(){ return mFreqNames[mFreq]; } public void setmFreqNames(String[] mFreqNames){ this.mFreqNames = mFreqNames; } public String[] getmFreqNames(){ return this.mFreqNames; } public Integer getmFreq() { return mFreq; } public void setmFreq(Integer mFreq) { this.mFreq = mFreq; } @Override public int compareTo(Task task) { return getmScheduleDatetime().compareTo(task.getmScheduleDatetime()); } }
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =======================================================================*/ // This class has been generated, DO NOT EDIT! package org.tensorflow.op.image; import org.tensorflow.Operand; import org.tensorflow.Operation; import org.tensorflow.OperationBuilder; import org.tensorflow.Output; import org.tensorflow.op.RawOp; import org.tensorflow.op.Scope; import org.tensorflow.op.annotation.Endpoint; import org.tensorflow.op.annotation.Operator; import org.tensorflow.types.family.TNumber; /** * Convert one or more images from HSV to RGB. * <p> * Outputs a tensor of the same shape as the `images` tensor, containing the RGB * value of the pixels. The output is only well defined if the value in `images` * are in `[0,1]`. * <p> * See `rgb_to_hsv` for a description of the HSV encoding. * * @param <T> data type for {@code output()} output */ @Operator(group = "image") public final class HsvToRgb<T extends TNumber> extends RawOp implements Operand<T> { /** * Factory method to create a class wrapping a new HsvToRgb operation. * * @param scope current scope * @param images 1-D or higher rank. HSV data to convert. Last dimension must be size 3. * @return a new instance of HsvToRgb */ @Endpoint(describeByClass = true) public static <T extends TNumber> HsvToRgb<T> create(Scope scope, Operand<T> images) { OperationBuilder opBuilder = scope.env().opBuilder("HSVToRGB", scope.makeOpName("HsvToRgb")); opBuilder.addInput(images.asOutput()); opBuilder = scope.apply(opBuilder); return new HsvToRgb<T>(opBuilder.build()); } /** * `images` converted to RGB. */ public Output<T> output() { return output; } @Override public Output<T> asOutput() { return output; } /** The name of this op, as known by TensorFlow core engine */ public static final String OP_NAME = "HSVToRGB"; private Output<T> output; private HsvToRgb(Operation operation) { super(operation); int outputIdx = 0; output = operation.output(outputIdx++); } }
/* * Copyright 2015 Johannes Donath <johannesd@torchmind.com> * and other copyright owners as documented in the project's IP log. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.torchmind.candle.node; import com.torchmind.candle.api.*; import com.torchmind.candle.node.property.*; import com.torchmind.candle.node.property.array.*; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author Johannes Donath */ public class ObjectNode extends AbstractNamedNode implements IObjectNode { private final LinkedList<INode> children = new LinkedList<> (); protected ObjectNode () { super (); } public ObjectNode (@Nonnull IDocumentNode documentNode, @Nonnull String name) { super (documentNode, name); } /** * {@inheritDoc} */ @Nonnull @Override public IObjectNode append (@Nonnull INode node) { if (node instanceof INamedNode && this.isPresent (((INamedNode) node).name ())) { this.replace (((INamedNode) node).name (), node); return this; } this.children.add (node); return this; } /** * {@inheritDoc} */ @Nonnull @Override public List<INode> children () { return Collections.unmodifiableList (this.children); } /** * {@inheritDoc} */ @Nonnull @Override public <T extends INode> List<T> children (@Nonnull Class<T> nodeType) { return this.stream (nodeType).collect (Collectors.toList ()); } /** * {@inheritDoc} */ @Nonnull @Override public IObjectNode clear () { this.children.clear (); return this; } /** * {@inheritDoc} */ @Nonnull @Override public INode get (@Nonnull String name) throws NoSuchElementException { final String closestNode = (name.indexOf ('.') == -1 ? name : name.substring (0, name.indexOf ('.'))); // @formatter:off INode node = this.stream () .filter (n -> { if (!(n instanceof INamedNode)) return false; return closestNode.equalsIgnoreCase (((INamedNode) n).name ()); }) .findFirst () .orElseThrow (() -> new NoSuchElementException ("Could not locate element with name \"" + name + "\"" + (!closestNode.equals (name) ? " (failed to locate closest node \"" + closestNode + "\")" : ""))); // @formatter:on if (name.indexOf ('.') == -1) { return node; } if (!(node instanceof IObjectNode)) { throw new NoSuchElementException ("Node with name \"" + closestNode + "\" is not a container node"); } return ((IObjectNode) node).get (name.substring ((closestNode.length () + 1))); } /** * {@inheritDoc} */ @Nonnull @Override @SuppressWarnings ("unchecked") public <T extends INode> T get (@Nonnull String name, @Nonnull Class<T> nodeType) throws IllegalStateException, NoSuchElementException { INode node = this.get (name); if (!nodeType.isAssignableFrom (node.getClass ())) { throw new IllegalStateException ("Expected node of type " + nodeType.getCanonicalName () + " but got " + node.getClass ().getName ()); } return ((T) node); } /** * {@inheritDoc} */ @Override public boolean getBoolean (@Nonnull String name) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, BooleanPropertyNode.class, BooleanPropertyNode::value, () -> false); } /** * {@inheritDoc} */ @Override public boolean getBoolean (@Nonnull String name, boolean defaultValue) throws IllegalStateException { if (this.isDefault (name)) { return defaultValue; } return this.getBoolean (name); } /** * {@inheritDoc} */ @Nullable @Override public boolean[] getBooleanArray (@Nonnull String name) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, BooleanArrayPropertyNode.class, BooleanArrayPropertyNode::array); } /** * {@inheritDoc} */ @Nullable @Override public boolean[] getBooleanArray (@Nonnull String name, @Nullable boolean[] defaultValue) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getBooleanArray (name); } /** * {@inheritDoc} */ @Nullable @Override public String getEnum (@Nonnull String name) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, EnumPropertyNode.class, EnumPropertyNode::value); } /** * {@inheritDoc} */ @Nullable @Override public String getEnum (@Nonnull String name, @Nullable String defaultValue) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getEnum (name); } /** * {@inheritDoc} */ @Nullable @Override public <T extends Enum> T getEnum (@Nonnull String name, @Nonnull Class<T> enumType) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, EnumPropertyNode.class, (n) -> n.value (enumType)); } /** * {@inheritDoc} */ @Nullable @Override @SuppressWarnings ("unchecked") // Indeed very unchecked. However Java does not allow us to extend Enums so this is perfectly fine ... public <T extends Enum> T getEnum (@Nonnull String name, @Nonnull T defaultValue) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getEnum (name, ((Class<T>) defaultValue.getClass ())); } /** * {@inheritDoc} */ @Nullable @Override public <T extends Enum> T getEnum (@Nonnull String name, @Nullable T defaultValue, @Nonnull Class<T> enumType) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getEnum (name, enumType); } /** * {@inheritDoc} */ @Nullable @Override public String[] getEnumArray (@Nonnull String name) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, EnumArrayPropertyNode.class, EnumArrayPropertyNode::array); } /** * {@inheritDoc} */ @Nullable @Override public String[] getEnumArray (@Nonnull String name, @Nullable String[] defaultValue) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getEnumArray (name); } /** * {@inheritDoc} */ @Nullable @Override public <T extends Enum> T[] getEnumArray (@Nonnull String name, @Nullable Class<T> enumType) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, EnumArrayPropertyNode.class, (n) -> n.array (enumType)); } /** * {@inheritDoc} */ @Nullable @Override public <T extends Enum> T[] getEnumArray (@Nonnull String name, @Nullable T[] defaultValue, @Nonnull Class<T> enumType) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getEnumArray (name, enumType); } /** * {@inheritDoc} */ @Override public float getFloat (@Nonnull String name) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, FloatPropertyNode.class, FloatPropertyNode::value, () -> 0.0f); } /** * {@inheritDoc} */ @Override public float getFloat (@Nonnull String name, float defaultValue) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getFloat (name); } /** * {@inheritDoc} */ @Nullable @Override public float[] getFloatArray (@Nonnull String name) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, FloatArrayPropertyNode.class, FloatArrayPropertyNode::array); } /** * {@inheritDoc} */ @Nullable @Override public float[] getFloatArray (@Nonnegative String name, @Nullable float[] defaultValue) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getFloatArray (name); } /** * {@inheritDoc} */ @Override public int getInteger (@Nonnull String name) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, IntegerPropertyNode.class, IntegerPropertyNode::value, () -> 0); } /** * {@inheritDoc} */ @Override public int getInteger (@Nonnull String name, int defaultValue) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getInteger (name); } /** * {@inheritDoc} */ @Nullable @Override public int[] getIntegerArray (@Nonnull String name) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, IntegerArrayPropertyNode.class, IntegerArrayPropertyNode::array); } /** * {@inheritDoc} */ @Nullable @Override public int[] getIntegerArray (@Nonnull String name, @Nullable int[] defaultValue) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getIntegerArray (name); } /** * {@inheritDoc} */ @Nonnull @Override public IPropertyNode getProperty (@Nonnull String name) throws IllegalStateException, NoSuchElementException { return this.get (name, IPropertyNode.class); } /** * {@inheritDoc} */ @Nullable @Override public <T extends IPropertyNode, R> R getPropertyValue (@Nonnull String name, @Nonnull Class<T> nodeType, @Nonnull Function<T, R> ifPresent) { return this.getPropertyValue (name, nodeType, ifPresent, () -> null); } /** * {@inheritDoc} */ @Nonnull @Override public <T extends IPropertyNode, R> R getPropertyValue (@Nonnull String name, @Nonnull Class<T> nodeType, @Nonnull Function<T, R> ifPresent, @Nonnull Supplier<R> ifNull) { if (this.isNull (name) || this.isDefault (name)) { return ifNull.get (); } return ifPresent.apply (this.get (name, nodeType)); } /** * {@inheritDoc} */ @Nullable @Override public String getString (@Nonnull String name) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, StringPropertyNode.class, StringPropertyNode::value); } /** * {@inheritDoc} */ @Nullable @Override public String getString (@Nonnegative String name, @Nullable String defaultValue) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getString (name); } /** * {@inheritDoc} */ @Nullable @Override public String[] getStringArray (@Nonnull String name) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, StringArrayPropertyNode.class, StringArrayPropertyNode::array); } /** * {@inheritDoc} */ @Nullable @Override public String[] getStringArray (@Nonnull String name, @Nullable String[] defaultValue) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getStringArray (name); } /** * {@inheritDoc} */ @Override public float getUnsignedFloat (@Nonnull String name) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, FloatPropertyNode.class, FloatPropertyNode::valueUnsigned, () -> 0.0f); } /** * {@inheritDoc} */ @Override public float getUnsignedFloat (@Nonnull String name, @Nonnegative float defaultValue) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getUnsignedFloat (name); } /** * {@inheritDoc} */ @Nullable @Override public float[] getUnsignedFloatArray (@Nonnull String name) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, FloatArrayPropertyNode.class, FloatArrayPropertyNode::arrayUnsigned); } /** * {@inheritDoc} */ @Nullable @Override public float[] getUnsignedFloatArray (@Nonnull String name, @Nullable @Nonnegative float[] defaultValue) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getUnsignedFloatArray (name); } /** * {@inheritDoc} */ @Override public int getUnsignedInteger (@Nonnull String name) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, IntegerPropertyNode.class, IntegerPropertyNode::valueUnsigned, () -> 0); } /** * {@inheritDoc} */ @Override public int getUnsignedInteger (@Nonnegative String name, @Nonnegative int defaultValue) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getUnsignedInteger (name); } /** * {@inheritDoc} */ @Nullable @Override public int[] getUnsignedIntegerArray (@Nonnull String name) throws IllegalStateException, NoSuchElementException { return this.getPropertyValue (name, IntegerArrayPropertyNode.class, IntegerArrayPropertyNode::arrayUnsigned); } /** * {@inheritDoc} */ @Nullable @Override public int[] getUnsignedIntegerArray (@Nonnull String name, @Nullable @Nonnegative int[] defaultValue) throws IllegalStateException, NoSuchElementException { if (this.isDefault (name)) { return defaultValue; } return this.getUnsignedIntegerArray (name); } /** * {@inheritDoc} */ @Nonnull @Override public IObjectNode insertAfter (@Nonnull String after, @Nonnull INode node) throws NoSuchElementException { int index = after.indexOf ('.'); if (index != -1) { IObjectNode closestNode = this.get (after.substring (0, index), IObjectNode.class); closestNode.insertAfter (after.substring ((index + 1)), node); return this; } return this.insertAfter (this.get (after), node); } /** * {@inheritDoc} */ @Nonnull @Override public IObjectNode insertAfter (@Nonnull INode after, @Nonnull INode node) throws NoSuchElementException { int index = (this.children.indexOf (after) + 1); if (index == 0) { throw new NoSuchElementException ("Cannot locate element to insert after within tree"); } this.children.add (index, node); return this; } /** * {@inheritDoc} */ @Nonnull @Override public IObjectNode insertBefore (@Nonnull String before, @Nonnull INode node) throws NoSuchElementException { int index = before.indexOf ('.'); if (index != -1) { IObjectNode closestNode = this.get (before.substring (0, index), IObjectNode.class); closestNode.insertBefore (before.substring ((index + 1)), node); return this; } return this.insertBefore (this.get (before), node); } /** * {@inheritDoc} */ @Nonnull @Override public IObjectNode insertBefore (@Nonnull INode before, @Nonnull INode node) throws NoSuchElementException { int index = this.children.indexOf (before); if (index == -1) { throw new NoSuchElementException ("Cannot locate element to insert before within tree"); } this.children.add (index, node); return this; } /** * {@inheritDoc} */ @Override public boolean isDefault (@Nonnull String name) throws IllegalStateException, NoSuchElementException { INode node = this.get (name); node.ensureType (NodeType.PROPERTY); return ((IPropertyNode) node).valueType () == NodeValueType.DEFAULT; } /** * {@inheritDoc} */ @Override public boolean isNull (@Nonnull String name) throws IllegalStateException, NoSuchElementException { INode node = this.get (name); node.ensureType (NodeType.PROPERTY); return ((IPropertyNode) node).valueType () == NodeValueType.NULL; } /** * {@inheritDoc} */ @Override public boolean isPresent (@Nonnull String name) { try { int index = name.indexOf ('.'); if (index != -1) { IObjectNode closestNode = this.get (name.substring (0, index), IObjectNode.class); return closestNode.isPresent (name.substring ((index + 1))); } // @formatter:off return this.stream () .parallel () .filter (n -> { if (!(n instanceof INamedNode)) return false; return name.equalsIgnoreCase (((INamedNode) n).name ()); }) .findAny () .isPresent (); // @formatter:on } catch (IllegalStateException | NoSuchElementException ex) { return false; } } /** * {@inheritDoc} */ @Override public boolean isPresent (@Nonnull String name, @Nonnull Class<? extends INode> nodeType) { try { int index = name.indexOf ('.'); if (index != -1) { IObjectNode closestNode = this.get (name.substring (0, index), IObjectNode.class); return closestNode.isPresent (name.substring ((index + 1)), nodeType); } // @formatter:off return this.stream (nodeType) .parallel () .filter (n -> { if (!(n instanceof INamedNode)) return false; return name.equalsIgnoreCase (((INamedNode) n).name ()); }) .findAny () .isPresent (); // @formatter:on } catch (IllegalStateException | NoSuchElementException ex) { return false; } } /** * {@inheritDoc} */ @Nonnull @Override public <T extends INode> Iterator<T> iterator (@Nonnull Class<T> nodeType) { return this.stream (nodeType).iterator (); } /** * {@inheritDoc} */ @Override public Iterator<INode> iterator () { return this.children ().iterator (); } /** * {@inheritDoc} */ @Nonnull @Override public IObjectNode remove (@Nonnull String name) throws NoSuchElementException { int index = name.indexOf ('.'); if (index != -1) { IObjectNode node = this.get (name.substring (0, index), IObjectNode.class); node.remove (name.substring ((index + 1))); return this; } return this.remove (this.get (name)); } /** * {@inheritDoc} */ @Nonnull @Override public IObjectNode remove (@Nonnull INode node) throws NoSuchElementException { if (!this.children.remove (node)) { throw new NoSuchElementException ("Cannot locate element to remove within tree"); } return this; } /** * {@inheritDoc} */ @Nonnull @Override public IObjectNode replace (@Nonnull String name, @Nonnull INode replacement) throws NoSuchElementException { int index = name.indexOf ('.'); if (index != -1) { IObjectNode closestNode = this.get (name.substring (0, index), IObjectNode.class); closestNode.replace (name.substring ((index + 1)), replacement); return this; } return this.replace (this.get (name), replacement); } /** * {@inheritDoc} */ @Nonnull @Override public IObjectNode replace (@Nonnull INode node, @Nonnull INode replacement) throws NoSuchElementException { int index = this.children.indexOf (node); if (index == -1) { throw new NoSuchElementException ("Cannot locate element to replace within tree"); } this.children.remove (node); this.children.add (index, replacement); return this; } /** * {@inheritDoc} */ @Override public int size () { return this.children.size (); } /** * {@inheritDoc} */ @Nonnull @Override public Stream<INode> stream () { return this.children.stream (); } /** * {@inheritDoc} */ @Nonnull @Override @SuppressWarnings ("unchecked") public <T extends INode> Stream<T> stream (@Nonnull Class<T> nodeType) { return ((Stream<T>) this.stream ().parallel () .filter (n -> nodeType.isAssignableFrom (n.getClass ())) .sequential ()); } /** * {@inheritDoc} */ @Override public String toString () { return String.format ("ObjectNode{%s,children=[%s]}", super.toString (), this.children ()); } }
package com.anybbo; import com.anybbo.filter.AccessFilter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapper; import org.springframework.context.annotation.Bean; @EnableZuulProxy @SpringBootApplication public class AnybboApiGatewayApplication { public static void main(String[] args) { SpringApplication.run(AnybboApiGatewayApplication.class, args); } @Bean public AccessFilter accessFilter() { return new AccessFilter(); } // @Bean // public PatternServiceRouteMapper serviceRouteMapper() { // return new PatternServiceRouteMapper( // "(?<name>^.+)-(?<version>v.+$)", // "${version}/${name}" // ); // } }
package com.lvcoding.mq.header; import com.rabbitmq.client.*; import java.io.IOException; import java.util.*; public class Consumer2 { public static final String EXCHANGE_NAME = "header"; public static void main(String[] args) throws Exception { // 获取mq连接 ConnectionFactory factory = new ConnectionFactory(); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // 创建交换机 channel.exchangeDeclare(EXCHANGE_NAME, "headers"); // 创建队列 (名称随机生成,断开连接后队列自动删除) String queue = channel.queueDeclare().getQueue(); // 绑定交换机和队列 Map<String, Object> headers_sms = new Hashtable<>(); headers_sms.put("info_sms", "sms"); channel.queueBind(queue, EXCHANGE_NAME, "", headers_sms); System.out.println("等待消息中...,退出请 CTRL+C"); // 消费消息 boolean autoAck = true; // 自动确认消息 channel.basicConsume(queue, autoAck, new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("消费了消息 " + new String(body, "UTF-8")); } }); } }
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ui.controls.resultset.panel; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IContributionManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.DBeaverPreferences; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.core.DBeaverCore; import org.jkiss.dbeaver.model.DBPImage; import org.jkiss.dbeaver.model.data.DBDAttributeBinding; import org.jkiss.dbeaver.model.data.DBDValue; import org.jkiss.dbeaver.runtime.ui.DBUserInterface; import org.jkiss.dbeaver.ui.ActionUtils; import org.jkiss.dbeaver.ui.DBeaverIcons; import org.jkiss.dbeaver.ui.UIIcon; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.dbeaver.ui.controls.resultset.*; import org.jkiss.dbeaver.ui.data.IValueController; import org.jkiss.dbeaver.ui.data.IValueEditor; import org.jkiss.dbeaver.ui.data.IValueManager; import org.jkiss.dbeaver.ui.data.editors.BaseValueEditor; import org.jkiss.dbeaver.ui.data.editors.ReferenceValueEditor; import org.jkiss.utils.CommonUtils; /** * RSV value view panel */ public class ViewValuePanel implements IResultSetPanel, IAdaptable { private static final Log log = Log.getLog(ViewValuePanel.class); public static final String PANEL_ID = "value-view"; public static final String SETTINGS_SECTION = "panel-" + PANEL_ID; private static final String VALUE_VIEW_CONTROL_ID = "org.jkiss.dbeaver.ui.resultset.panel.valueView"; private IResultSetPresentation presentation; private Composite viewPlaceholder; private ResultSetValueController previewController; private IValueEditor valueEditor; private ReferenceValueEditor referenceValueEditor; private volatile boolean valueSaving; private IValueManager valueManager; public static IDialogSettings getPanelSettings() { return ResultSetUtils.getViewerSettings(SETTINGS_SECTION); } public ViewValuePanel() { } @Override public String getPanelTitle() { return "Value"; } @Override public DBPImage getPanelImage() { return UIIcon.PANEL_VALUE; } @Override public String getPanelDescription() { return "Value view/edit"; } @Override public Control createContents(IResultSetPresentation presentation, Composite parent) { this.presentation = presentation; viewPlaceholder = new Composite(parent, SWT.NONE); viewPlaceholder.setLayout(new FillLayout()); viewPlaceholder.addPaintListener(e -> { if (viewPlaceholder.getChildren().length == 0) { String hidePanelCmd = ActionUtils.findCommandDescription( ResultSetCommandHandler.CMD_TOGGLE_PANELS, ViewValuePanel.this.presentation.getController().getSite(), true); UIUtils.drawMessageOverControl(viewPlaceholder, e, "Select a cell to view/edit value", 0); UIUtils.drawMessageOverControl(viewPlaceholder, e, "Press " + hidePanelCmd + " to hide this panel", 20); } }); /* addTraverseListener(new TraverseListener() { @Override public void keyTraversed(TraverseEvent e) { if (e.detail == SWT.TRAVERSE_ESCAPE) { hidePanel(); e.doit = false; } } }); */ if (this.presentation instanceof ISelectionProvider) { final ISelectionProvider selectionProvider = (ISelectionProvider) this.presentation; final ISelectionChangedListener selectionListener = event -> { if (ViewValuePanel.this.presentation.getController().getVisiblePanel() == ViewValuePanel.this) { refreshValue(false); } }; selectionProvider.addSelectionChangedListener(selectionListener); viewPlaceholder.addDisposeListener(e -> selectionProvider.removeSelectionChangedListener(selectionListener)); } return viewPlaceholder; } @Override public void activatePanel() { refreshValue(false); } @Override public void deactivatePanel() { // Dispose panel control if (viewPlaceholder != null && !viewPlaceholder.isDisposed()) { viewPlaceholder.dispose(); viewPlaceholder = null; } } @Override public void refresh(boolean force) { refreshValue(force); } @Override public void contributeActions(ToolBarManager manager) { fillToolBar(manager); } private void refreshValue(boolean force) { DBDAttributeBinding attr = presentation.getCurrentAttribute(); ResultSetRow row = presentation.getController().getCurrentRow(); if (attr == null || row == null) { clearValue(); return; } boolean updateActions; if (previewController == null) { previewController = new ResultSetValueController( presentation.getController(), attr, row, IValueController.EditType.PANEL, viewPlaceholder) { @Override public void updateValue(@Nullable Object value, boolean updatePresentation) { valueSaving = true; try { super.updateValue(value, updatePresentation); } finally { valueSaving = false; } presentation.updateValueView(); } }; updateActions = true; force = true; } else { updateActions = force = (force || previewController.getBinding() != attr); previewController.setCurRow(row); previewController.setBinding(attr); } viewValue(force); if (updateActions) { presentation.getController().updatePanelActions(); } } private void viewValue(boolean forceRefresh) { if (valueSaving) { return; } if (valueManager == null || valueEditor == null) { forceRefresh = true; } if (forceRefresh) { cleanupPanel(); // Create a new one valueManager = previewController.getValueManager(); try { valueEditor = valueManager.createEditor(previewController); } catch (Throwable e) { DBUserInterface.getInstance().showError("Value preview", "Can't create value viewer", e); return; } if (valueEditor != null) { try { valueEditor.createControl(); } catch (Exception e) { log.error(e); } Control control = valueEditor.getControl(); if (control != null) { UIUtils.addFocusTracker(presentation.getController().getSite(), VALUE_VIEW_CONTROL_ID, control); presentation.getController().lockActionsByFocus(control); } referenceValueEditor = new ReferenceValueEditor(previewController, valueEditor); if (referenceValueEditor.isReferenceValue()) { GridLayout gl = new GridLayout(1, false); viewPlaceholder.setLayout(gl); valueEditor.getControl().setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); referenceValueEditor.createEditorSelector(viewPlaceholder); } else { viewPlaceholder.setLayout(new FillLayout()); } } else { final Composite placeholder = UIUtils.createPlaceholder(viewPlaceholder, 1); placeholder.setBackground(placeholder.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); placeholder.addPaintListener(e -> { Rectangle bounds = placeholder.getBounds(); String message = "No editor for [" + previewController.getValueType().getTypeName() + "]"; Point ext = e.gc.textExtent(message); e.gc.drawText(message, (bounds.width - ext.x) / 2, bounds.height / 3 + 20); }); referenceValueEditor = null; } viewPlaceholder.layout(); } if (valueEditor instanceof BaseValueEditor) { ((BaseValueEditor) valueEditor).setAutoSaveEnabled(false); } if (valueEditor != null) { try { Object newValue = previewController.getValue(); if (newValue instanceof DBDValue) { // Do not check for difference valueEditor.primeEditorValue(newValue); } else { Object oldValue = null; try { if (previewController.getExecutionContext() != null) { oldValue = valueEditor.extractEditorValue(); } } catch (Throwable e) { // Some error extracting current value // This may happen if we were disconnected } if (forceRefresh || !CommonUtils.equalObjects(oldValue, newValue)) { valueEditor.primeEditorValue(newValue); } } } catch (DBException e) { log.error(e); } valueEditor.setDirty(false); } if (valueEditor instanceof BaseValueEditor) { ((BaseValueEditor) valueEditor).setAutoSaveEnabled(true); } } public void saveValue() { if (valueEditor == null) { return; } try { valueSaving = true; Object newValue = valueEditor.extractEditorValue(); previewController.updateValue(newValue, true); presentation.updateValueView(); } catch (Exception e) { DBUserInterface.getInstance().showError("Value apply", "Can't apply edited value", e); } finally { valueSaving = false; } } public void clearValue() { cleanupPanel(); valueManager = null; valueEditor = null; presentation.getController().updateEditControls(); viewPlaceholder.layout(); } private void cleanupPanel() { // Cleanup previous viewer for (Control child : viewPlaceholder.getChildren()) { child.dispose(); } } private void fillToolBar(final IContributionManager contributionManager) { contributionManager.add(new Separator()); //contributionManager.add(new Separator()); if (valueManager != null) { try { valueManager.contributeActions(contributionManager, previewController, valueEditor); } catch (Exception e) { log.error("Can't contribute value manager actions", e); } } contributionManager.add( ActionUtils.makeCommandContribution(presentation.getController().getSite(), ValueViewCommandHandler.CMD_SAVE_VALUE)); contributionManager.add( new Action("Auto-apply value", Action.AS_CHECK_BOX) { { setImageDescriptor(DBeaverIcons.getImageDescriptor(UIIcon.LINK_TO_EDITOR)); } @Override public boolean isChecked() { return DBeaverCore.getGlobalPreferenceStore().getBoolean(DBeaverPreferences.RS_EDIT_AUTO_UPDATE_VALUE); } @Override public void run() { boolean newValue = !isChecked(); DBeaverCore.getGlobalPreferenceStore().setValue(DBeaverPreferences.RS_EDIT_AUTO_UPDATE_VALUE, newValue); presentation.getController().updatePanelActions(); } }); } @Override public <T> T getAdapter(Class<T> adapter) { if (valueEditor != null) { if (adapter.isAssignableFrom(valueEditor.getClass())) { return adapter.cast(valueEditor); } if (valueEditor instanceof IAdaptable) { return ((IAdaptable) valueEditor).getAdapter(adapter); } } return null; } }
package jopenvr; import com.sun.jna.Pointer; import com.sun.jna.Structure; import java.util.Arrays; import java.util.List; /** * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class VRControllerState_t extends AlignedStructure { public int unPacketNum; public long ulButtonPressed; public long ulButtonTouched; /** struct vr::VRControllerAxis_t[5] */ public VRControllerAxis_t[] rAxis = new VRControllerAxis_t[5]; public VRControllerState_t() { super(); } protected List<? > getFieldOrder() { return Arrays.asList("unPacketNum", "ulButtonPressed", "ulButtonTouched", "rAxis"); } public VRControllerState_t(int unPacketNum, long ulButtonPressed, long ulButtonTouched, VRControllerAxis_t rAxis[]) { super(); this.unPacketNum = unPacketNum; this.ulButtonPressed = ulButtonPressed; this.ulButtonTouched = ulButtonTouched; if ((rAxis.length != this.rAxis.length)) throw new IllegalArgumentException("Wrong array size !"); this.rAxis = rAxis; } public VRControllerState_t(Pointer peer) { super(peer); } public static class ByReference extends VRControllerState_t implements Structure.ByReference { }; public static class ByValue extends VRControllerState_t implements Structure.ByValue { }; }
package love.wangqi.handler.front; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; import io.netty.handler.stream.ChunkedWriteHandler; import love.wangqi.config.GatewayConfig; import love.wangqi.handler.ExceptionHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author: wangqi * @description: * @date: Created in 2018/5/26 21:57 */ public class FrontFilter extends ChannelInitializer<SocketChannel> { private Logger logger = LoggerFactory.getLogger(FrontFilter.class); private GatewayConfig config = GatewayConfig.getInstance(); @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); config.getChannelInboundHandlerList().forEach(pipeline::addLast); config.getChannelOutboundHandlerList().forEach(pipeline::addLast); pipeline.addLast(new HttpResponseEncoder()); config.getHttpResponseHandlerList().forEach(pipeline::addLast); pipeline.addLast(new HttpRequestDecoder()); pipeline.addLast(new ChunkedWriteHandler()); pipeline.addLast(new HttpObjectAggregator(10 * 1024 * 1024)); pipeline.addLast(new FrontHandler()); pipeline.addLast(new ExceptionHandler()); ch.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { logger.debug("channel close"); } }); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.gpdb.model.v20160503; import java.util.List; import com.aliyuncs.AcsResponse; import com.aliyuncs.gpdb.transform.v20160503.DescribeSQLLogByQueryIdResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class DescribeSQLLogByQueryIdResponse extends AcsResponse { private String requestId; private List<SQLLog> items; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public List<SQLLog> getItems() { return this.items; } public void setItems(List<SQLLog> items) { this.items = items; } public static class SQLLog { private String operationClass; private String executeState; private Float executeCost; private String sQLText; private Integer sourcePort; private String dBRole; private String operationType; private String sourceIP; private String sQLPlan; private Long returnRowCounts; private String dBName; private String operationExecuteTime; private Long scanRowCounts; private String accountName; private String queryId; private List<String> sliceIds; public String getOperationClass() { return this.operationClass; } public void setOperationClass(String operationClass) { this.operationClass = operationClass; } public String getExecuteState() { return this.executeState; } public void setExecuteState(String executeState) { this.executeState = executeState; } public Float getExecuteCost() { return this.executeCost; } public void setExecuteCost(Float executeCost) { this.executeCost = executeCost; } public String getSQLText() { return this.sQLText; } public void setSQLText(String sQLText) { this.sQLText = sQLText; } public Integer getSourcePort() { return this.sourcePort; } public void setSourcePort(Integer sourcePort) { this.sourcePort = sourcePort; } public String getDBRole() { return this.dBRole; } public void setDBRole(String dBRole) { this.dBRole = dBRole; } public String getOperationType() { return this.operationType; } public void setOperationType(String operationType) { this.operationType = operationType; } public String getSourceIP() { return this.sourceIP; } public void setSourceIP(String sourceIP) { this.sourceIP = sourceIP; } public String getSQLPlan() { return this.sQLPlan; } public void setSQLPlan(String sQLPlan) { this.sQLPlan = sQLPlan; } public Long getReturnRowCounts() { return this.returnRowCounts; } public void setReturnRowCounts(Long returnRowCounts) { this.returnRowCounts = returnRowCounts; } public String getDBName() { return this.dBName; } public void setDBName(String dBName) { this.dBName = dBName; } public String getOperationExecuteTime() { return this.operationExecuteTime; } public void setOperationExecuteTime(String operationExecuteTime) { this.operationExecuteTime = operationExecuteTime; } public Long getScanRowCounts() { return this.scanRowCounts; } public void setScanRowCounts(Long scanRowCounts) { this.scanRowCounts = scanRowCounts; } public String getAccountName() { return this.accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public String getQueryId() { return this.queryId; } public void setQueryId(String queryId) { this.queryId = queryId; } public List<String> getSliceIds() { return this.sliceIds; } public void setSliceIds(List<String> sliceIds) { this.sliceIds = sliceIds; } } @Override public DescribeSQLLogByQueryIdResponse getInstance(UnmarshallerContext context) { return DescribeSQLLogByQueryIdResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wdullaer.materialdatetimepicker.date; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v7.widget.AppCompatTextView; import android.util.AttributeSet; import com.wdullaer.materialdatetimepicker.R; /** * A text view which, when pressed or activated, displays a colored circle around the text. */ public class TextViewWithCircularIndicator extends AppCompatTextView { private static final int SELECTED_CIRCLE_ALPHA = 255; Paint mCirclePaint = new Paint(); private int mCircleColor; private final String mItemIsSelectedText; private boolean mDrawCircle; public TextViewWithCircularIndicator(Context context, AttributeSet attrs) { super(context, attrs); mCircleColor = ContextCompat.getColor(context, R.color.mdtp_accent_color); mItemIsSelectedText = context.getResources().getString(R.string.mdtp_item_is_selected); init(); } private void init() { mCirclePaint.setFakeBoldText(true); mCirclePaint.setAntiAlias(true); mCirclePaint.setColor(mCircleColor); mCirclePaint.setTextAlign(Align.CENTER); mCirclePaint.setStyle(Style.FILL); mCirclePaint.setAlpha(SELECTED_CIRCLE_ALPHA); } public void setAccentColor(int color, boolean darkMode) { mCircleColor = color; mCirclePaint.setColor(mCircleColor); setTextColor(createTextColor(color, darkMode)); } /** * Programmatically set the color state list (see mdtp_date_picker_year_selector) * @param accentColor pressed state text color * @param darkMode current theme mode * @return ColorStateList with pressed state */ private ColorStateList createTextColor(int accentColor, boolean darkMode) { int[][] states = new int[][]{ new int[]{android.R.attr.state_pressed}, // pressed new int[]{android.R.attr.state_selected}, // selected new int[]{} }; int[] colors = new int[]{ accentColor, Color.WHITE, darkMode ? Color.WHITE : Color.BLACK }; return new ColorStateList(states, colors); } public void drawIndicator(boolean drawCircle) { mDrawCircle = drawCircle; } @Override public void onDraw(@NonNull Canvas canvas) { if (mDrawCircle) { final int width = getWidth(); final int height = getHeight(); int radius = Math.min(width, height) / 2; canvas.drawCircle(width / 2, height / 2, radius, mCirclePaint); } setSelected(mDrawCircle); super.onDraw(canvas); } @SuppressLint("GetContentDescriptionOverride") @Override public CharSequence getContentDescription() { CharSequence itemText = getText(); if (mDrawCircle) { return String.format(mItemIsSelectedText, itemText); } else { return itemText; } } }
package Kurama.ComponentSystem.components.constraintGUI; public interface IVRequestPackGenerator { public abstract BoundInteractionMessage getValidificationRequestPack(Boundary parent, Boundary boundary, float deltaMoveX, float deltaMoveY); }
package com.x.cms.core.entity.query; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import com.x.base.core.bean.NameIdPair; import com.x.base.core.entity.JpaObject; import com.x.base.core.utils.ListTools; import com.x.cms.core.entity.content.DataItem; import com.x.cms.core.entity.content.DataItem_; public class WhereEntryTools { public static Predicate toPredicate(CriteriaBuilder cb, Root<DataItem> root, WhereEntry whereEntry) throws Exception { if ((null == whereEntry) || (!whereEntry.available())) { return cb.conjunction(); } return cb.or( predicateAppInfo(cb, root, whereEntry.getAppInfoList()), predicateCategory(cb, root, whereEntry.getCategoryList()), predicateCompany(cb, root, whereEntry.getCompanyList()), predicateDepartment(cb, root, whereEntry.getDepartmentList()), predicatePerson(cb, root, whereEntry.getPersonList()), predicateIdentity(cb, root, whereEntry.getIdentityList())); } private static Predicate predicateAppInfo(CriteriaBuilder cb, Root<DataItem> root, List<NameIdPair> appInfoList ) throws Exception { if (ListTools.isEmpty(appInfoList)) { return cb.disjunction(); } return root.get( DataItem_.appId ).in(ListTools.extractProperty( appInfoList, JpaObject.ID, String.class, true, true)); } private static Predicate predicateCategory(CriteriaBuilder cb, Root<DataItem> root, List<NameIdPair> categoryList ) throws Exception { if (ListTools.isEmpty(categoryList)) { return cb.disjunction(); } return root.get(DataItem_.categoryId ).in(ListTools.extractProperty( categoryList, JpaObject.ID, String.class, true, true)); } private static Predicate predicateCompany(CriteriaBuilder cb, Root<DataItem> root, List<NameIdPair> companies) throws Exception { if (ListTools.isEmpty(companies)) { return cb.disjunction(); } return root.get(DataItem_.creatorCompany).in(ListTools.extractProperty(companies, "name", String.class, true, true)); } private static Predicate predicateDepartment(CriteriaBuilder cb, Root<DataItem> root, List<NameIdPair> departments) throws Exception { if (ListTools.isEmpty(departments)) { return cb.disjunction(); } return root.get(DataItem_.creatorDepartment).in(ListTools.extractProperty(departments, "name", String.class, true, true)); } private static Predicate predicatePerson(CriteriaBuilder cb, Root<DataItem> root, List<NameIdPair> people) throws Exception { if (ListTools.isEmpty(people)) { return cb.disjunction(); } return root.get(DataItem_.creatorPerson).in(ListTools.extractProperty(people, "name", String.class, true, true)); } private static Predicate predicateIdentity(CriteriaBuilder cb, Root<DataItem> root, List<NameIdPair> identities) throws Exception { if (ListTools.isEmpty(identities)) { return cb.disjunction(); } return root.get(DataItem_.creatorIdentity).in(ListTools.extractProperty(identities, "name", String.class, true, true)); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.appcontainers.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; /** Configuration properties that define the mutable settings of a Container App SourceControl. */ @Fluent public final class GithubActionConfiguration { /* * Registry configurations. */ @JsonProperty(value = "registryInfo") private RegistryInfo registryInfo; /* * AzureCredentials configurations. */ @JsonProperty(value = "azureCredentials") private AzureCredentials azureCredentials; /* * Context path */ @JsonProperty(value = "contextPath") private String contextPath; /* * Image name */ @JsonProperty(value = "image") private String image; /* * Code or Image */ @JsonProperty(value = "publishType") private String publishType; /* * Operation system */ @JsonProperty(value = "os") private String os; /* * Runtime stack */ @JsonProperty(value = "runtimeStack") private String runtimeStack; /* * Runtime version */ @JsonProperty(value = "runtimeVersion") private String runtimeVersion; /** * Get the registryInfo property: Registry configurations. * * @return the registryInfo value. */ public RegistryInfo registryInfo() { return this.registryInfo; } /** * Set the registryInfo property: Registry configurations. * * @param registryInfo the registryInfo value to set. * @return the GithubActionConfiguration object itself. */ public GithubActionConfiguration withRegistryInfo(RegistryInfo registryInfo) { this.registryInfo = registryInfo; return this; } /** * Get the azureCredentials property: AzureCredentials configurations. * * @return the azureCredentials value. */ public AzureCredentials azureCredentials() { return this.azureCredentials; } /** * Set the azureCredentials property: AzureCredentials configurations. * * @param azureCredentials the azureCredentials value to set. * @return the GithubActionConfiguration object itself. */ public GithubActionConfiguration withAzureCredentials(AzureCredentials azureCredentials) { this.azureCredentials = azureCredentials; return this; } /** * Get the contextPath property: Context path. * * @return the contextPath value. */ public String contextPath() { return this.contextPath; } /** * Set the contextPath property: Context path. * * @param contextPath the contextPath value to set. * @return the GithubActionConfiguration object itself. */ public GithubActionConfiguration withContextPath(String contextPath) { this.contextPath = contextPath; return this; } /** * Get the image property: Image name. * * @return the image value. */ public String image() { return this.image; } /** * Set the image property: Image name. * * @param image the image value to set. * @return the GithubActionConfiguration object itself. */ public GithubActionConfiguration withImage(String image) { this.image = image; return this; } /** * Get the publishType property: Code or Image. * * @return the publishType value. */ public String publishType() { return this.publishType; } /** * Set the publishType property: Code or Image. * * @param publishType the publishType value to set. * @return the GithubActionConfiguration object itself. */ public GithubActionConfiguration withPublishType(String publishType) { this.publishType = publishType; return this; } /** * Get the os property: Operation system. * * @return the os value. */ public String os() { return this.os; } /** * Set the os property: Operation system. * * @param os the os value to set. * @return the GithubActionConfiguration object itself. */ public GithubActionConfiguration withOs(String os) { this.os = os; return this; } /** * Get the runtimeStack property: Runtime stack. * * @return the runtimeStack value. */ public String runtimeStack() { return this.runtimeStack; } /** * Set the runtimeStack property: Runtime stack. * * @param runtimeStack the runtimeStack value to set. * @return the GithubActionConfiguration object itself. */ public GithubActionConfiguration withRuntimeStack(String runtimeStack) { this.runtimeStack = runtimeStack; return this; } /** * Get the runtimeVersion property: Runtime version. * * @return the runtimeVersion value. */ public String runtimeVersion() { return this.runtimeVersion; } /** * Set the runtimeVersion property: Runtime version. * * @param runtimeVersion the runtimeVersion value to set. * @return the GithubActionConfiguration object itself. */ public GithubActionConfiguration withRuntimeVersion(String runtimeVersion) { this.runtimeVersion = runtimeVersion; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (registryInfo() != null) { registryInfo().validate(); } if (azureCredentials() != null) { azureCredentials().validate(); } } }
package it.imperato.test.ms.app; import lombok.Getter; import lombok.Setter; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Component @ConfigurationProperties @PropertySource("application.properties") public class GlobalProperties { @Value("${oauth2.provider.facebook.active}") @Getter @Setter private String serverPort; @Value("${oauth2.provider.facebook.active}") @Getter @Setter private Boolean oauth2ProviderFacebookActive; @Value("${oauth2.provider.google.active}") @Getter @Setter private Boolean oauth2ProviderGoogleActive; }
/* * Copyright (c) 2018, hiwepy (https://github.com/hiwepy). * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.apache.mybatis.dbperms.parser.def; import org.apache.ibatis.exception.MybatisException; import org.apache.ibatis.plugin.meta.MetaStatementHandler; import org.apache.mybatis.dbperms.parser.ITablePermissionAutowireHandler; import org.apache.mybatis.dbperms.parser.ITablePermissionParser; import lombok.Data; import lombok.experimental.Accessors; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.parser.CCJSqlParserUtil; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.select.Select; import net.sf.jsqlparser.util.SelectAutowirePermissionParser; @Data @Accessors(chain = true) public class TablePermissionAutowireParser implements ITablePermissionParser { private ITablePermissionAutowireHandler tablePermissionHandler; private volatile boolean initialized = false; /* * Initialize the object. */ public void init() { if (!this.initialized) { synchronized (this) { if (!this.initialized) { internalInit(); this.initialized = true; } } } } /* * Internal initialization of the object. */ protected void internalInit() {}; public String parser(MetaStatementHandler metaHandler, String sql) { if (!this.doFilter(metaHandler, sql)) { return sql; } this.init(); String parsedSQL = sql; try { Statement statement = CCJSqlParserUtil.parse(sql); if (null != statement && statement instanceof Select) { Select select = (Select) statement; // 动态修改SQL select.accept(new SelectAutowirePermissionParser(this.getTablePermissionHandler(), metaHandler)); // 获取处理后的SQL parsedSQL = select.getSelectBody().toString(); } } catch (JSQLParserException e) { throw new MybatisException(String.format("Failed to process, please exclude the tableName or statementId.\n Error SQL: %s", e, sql), e); } return parsedSQL; } }
/* * Copyright 2004-2010 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.seasar.doma.internal.jdbc.command; import java.util.List; import junit.framework.TestCase; import org.seasar.doma.internal.jdbc.mock.MockConfig; import org.seasar.doma.internal.jdbc.query.AutoFunctionQuery; import org.seasar.doma.internal.jdbc.sql.BasicInOutParameter; import org.seasar.doma.internal.jdbc.sql.BasicInParameter; import org.seasar.doma.internal.jdbc.sql.BasicOutParameter; import org.seasar.doma.internal.jdbc.sql.BasicResultParameter; import org.seasar.doma.jdbc.Reference; import org.seasar.doma.wrapper.IntegerWrapper; /** * @author taedium * */ public class FunctionCommandTest extends TestCase { private final MockConfig runtimeConfig = new MockConfig(); public void testExecute() throws Exception { List<Object> outParameters = runtimeConfig.dataSource.connection.callableStatement.outParameters; outParameters.add(10); outParameters.add(null); outParameters.add(20); outParameters.add(30); IntegerWrapper aaa = new IntegerWrapper(40); IntegerWrapper bbb = new IntegerWrapper(50); IntegerWrapper ccc = new IntegerWrapper(60); AutoFunctionQuery<Integer> query = new AutoFunctionQuery<Integer>(); query.setConfig(runtimeConfig); query.setFunctionName("aaa"); query.setResultParameter(new BasicResultParameter<Integer>( new IntegerWrapper(), false)); query.addParameter(new BasicInParameter(aaa)); query.addParameter(new BasicOutParameter<Integer>(bbb, new Reference<Integer>())); query.addParameter(new BasicInOutParameter<Integer>(ccc, new Reference<Integer>())); query.setCallerClassName("aaa"); query.setCallerMethodName("bbb"); query.prepare(); Integer result = new FunctionCommand<Integer>(query).execute(); query.complete(); assertNotNull(result); assertEquals(new Integer(10), result); assertEquals(new Integer(40), aaa.get()); assertEquals(new Integer(20), bbb.get()); assertEquals(new Integer(30), ccc.get()); String sql = runtimeConfig.dataSource.connection.callableStatement.sql; assertEquals("{? = call aaa(?, ?, ?)}", sql); } }
package com.hipay.fullservice.core.requests.payment; import com.hipay.fullservice.core.models.Transaction; import com.hipay.fullservice.core.requests.AbstractRequest; import com.hipay.fullservice.core.serialization.AbstractSerializationMapper; import java.util.Map; /** * Created by HiPay on 03/02/16. */ public class CardTokenPaymentMethodRequest extends AbstractPaymentMethodRequest { protected String cardToken; protected Transaction.ECI eci; protected AuthenticationIndicator authenticationIndicator; public CardTokenPaymentMethodRequest() { this.setEci(Transaction.ECI.Undefined); } public CardTokenPaymentMethodRequest(String cardToken, Transaction.ECI eci, AuthenticationIndicator authenticationIndicator) { this.cardToken = cardToken; this.eci = eci; this.authenticationIndicator = authenticationIndicator; } public Map<String, String> getSerializedObject() { CardTokenPaymentMethodRequest.CardTokenPaymentMethodRequestSerializationMapper mapper = new CardTokenPaymentMethodRequest.CardTokenPaymentMethodRequestSerializationMapper(this); return mapper.getSerializedObject(); } public enum AuthenticationIndicator { //Undefined (-1), Bypass(0), IfAvailable(1), Mandatory(2); protected final Integer indicator; AuthenticationIndicator(Integer indicator) { this.indicator = indicator; } public static AuthenticationIndicator fromIntegerValue(Integer value) { if (value == null) return null; if (value.equals(Bypass.getIntegerValue())) { return Bypass; } if (value.equals(IfAvailable.getIntegerValue())) { return IfAvailable; } if (value.equals(Mandatory.getIntegerValue())) { return Mandatory; } return null; } public Integer getIntegerValue() { return this.indicator; } } public String getCardToken() { return cardToken; } public void setCardToken(String cardToken) { this.cardToken = cardToken; } public Transaction.ECI getEci() { return eci; } public void setEci(Transaction.ECI eci) { this.eci = eci; } public AuthenticationIndicator getAuthenticationIndicator() { return authenticationIndicator; } public void setAuthenticationIndicator(AuthenticationIndicator authenticationIndicator) { this.authenticationIndicator = authenticationIndicator; } public static class CardTokenPaymentMethodRequestSerializationMapper extends AbstractSerializationMapper { public CardTokenPaymentMethodRequestSerializationMapper(AbstractRequest request) { super(request); } @Override public Map<String, String> getSerializedObject() { return super.getSerializedObject(); } } }
package javax0.geci.jamal.util; import javax0.geci.tools.GeciReflectionTools; import javax0.jamal.api.BadSyntax; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Arrays; import java.util.stream.Collectors; /** * Entity is a field or a method. Stringer is something that converts to and from string. This class can convert a field * (not the value of the field, but the field as in reflection) or a method to string and it can also do the conversion * the other way. * * <p> Methods in this class convert fields or methods to string and back. The Jamal macros that list fields or methods * return comma separated list of fields, or methods. When other macros in a loop work with these strings they need to * get the actual methods and fields to work with during code generation. * * <p> The string format was designed so that this is also human readable, easy to parse, unique for each field and * method and do not interfere with the comma separated macro list handling. */ public class EntityStringer { /** * Creates a proprietary string representation of a method. This representation is passed back as a string by * macros that search methods. Later this string can be passed to other macros that work with methods. * <p> * The representation is * <pre> * class canonical name|method name| arg1 type | arg2 type | ... | argN type * </pre> * <p> * The class is the declaring class. * * <p> * The representation was created so that this is easy to parse (just split along the | characters), does not * contain comma, so it can be used as a member of comma separated list in a "for" macro and can also be readable * and last but not least have all information needed to look up the method via reflection. * <p> * Important that there are at least two {@code |} characters in the representation even if there are no arguments * of the method. In that case the last character of the fingerprint is {@code |}. This helps the method * {@link #isFingerPrintAField(String)} tell a field fingerprint from a method fingerprint. * * @param method to convert to a fingerprint * @return the fingerprint */ public static String method2Fingerprint(Method method) { final var className = method.getDeclaringClass().getCanonicalName(); final var argList = Arrays.stream(method.getGenericParameterTypes()) .map(Type::getTypeName) .collect(Collectors.joining("|")); return className + "|" + method.getName() + "|" + argList; } /** * Creates a proprietary string representation of a field. This representation is passed back as a string by * macros that search fields. Later this string can be passed to other macros that work with fields. * <p> * The representation is * <pre> * class canonical name|field name * </pre> * <p> * The class is the declaring class. * * <p> * Important that there is exactly one {@code |} character in the representation. * This helps the method {@link #isFingerPrintAField(String)} tell a field fingerprint from a method fingerprint. * <p> * Read the explanation at {@link #method2Fingerprint(Method)} * * @param field to convert to a fingerprint * @return the fingerprint */ public static String field2Fingerprint(Field field) { final var className = field.getDeclaringClass().getCanonicalName(); return className + "|" + field.getName(); } private static Class<?> forName(String klassName) { try { return GeciReflectionTools.classForName(klassName); } catch (ClassNotFoundException e) { return null; } } /** * Search for the method, which is represented by the fingerprint that was presumably created by the method * {@link #method2Fingerprint(Method)}. If the method can be found using reflection then return the method. * * @param fingerprint the string fingerprint of the method. * @return the method * @throws BadSyntax if the method cannot be found */ public static Method fingerprint2Method(String fingerprint) throws BadSyntax { final var parts = fingerprint.split("\\|", -1); if (parts.length < 2) { throw new BadSyntax("Method fingerprint '" + fingerprint + "' is badly formatted, does not have 'class|name' parts."); } try { final var klass = GeciReflectionTools.classForName(parts[0]); final var name = parts[1]; if (parts.length > 2) { final var argClasses = Arrays.stream(parts).skip(2).map(EntityStringer::forName).toArray(Class[]::new); return GeciReflectionTools.getMethod(klass, name, argClasses); } else { return GeciReflectionTools.getMethod(klass, name); } } catch (ClassNotFoundException e) { throw new BadSyntax("Class in fingerprint '" + fingerprint + "' cannot be found.", e); } catch (NoSuchMethodException e) { throw new BadSyntax("Method in fingerprint '" + fingerprint + "' cannot be found.", e); } } /** * Decides if a fingerprint string represents a method or a field. * <p> * The decision is fairly simple, as field fingerprints have two | separated parts, the class and the name of the * field. Methods have more: class, name of the method, arguments and if there is no argument even then the end * of the fingerprint is a | character. * * @param fingerPrint a method or field fingerprint string * @return {@code true} if the fingerprint represents a method, and false otherwise */ public static boolean isFingerPrintAField(String fingerPrint) { return fingerPrint.split("\\|", -1).length < 3; } /** * Search for the field, which is represented by the fingerprint that was presumably created by the method * {@link #field2Fingerprint(Field)} . If the field can be found using reflection then return the method. * * @param fingerprint is the string representation of the field that was created * by {@link #field2Fingerprint(Field)}. * @return the field * @throws BadSyntax if the argument has no | in it or uses a class or field that is not available */ public static Field fingerprint2Field(String fingerprint) throws BadSyntax { final var parts = fingerprint.split("\\|", -1); if (parts.length < 2) { throw new BadSyntax("Fields fingerprint '" + fingerprint + "' is badly formatted, does not have 'class|name' parts."); } try { final var klass = GeciReflectionTools.classForName(parts[0]); final var name = parts[1]; return GeciReflectionTools.getField(klass, name); } catch (ClassNotFoundException e) { throw new BadSyntax("Class in fingerprint '" + fingerprint + "' cannot be found.", e); } catch (NoSuchFieldException e) { throw new BadSyntax("Field in fingerprint '" + fingerprint + "' cannot be found.", e); } } }
package za.co.entelect.challenge.entities; import com.google.gson.annotations.SerializedName; public class BotArguments { @SerializedName("coreCount") private int coreCount; public BotArguments(int coreCount) { this.coreCount = coreCount; } public int getCoreCount() { return this.coreCount; } }
/* * Copyright 1999-2011 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.remoting.p2p.exchange.support; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.p2p.exchange.ExchangeGroup; import com.alibaba.dubbo.remoting.p2p.exchange.ExchangeNetworker; /** * FileNetworker * * @author william.liangf */ public class FileExchangeNetworker implements ExchangeNetworker { public ExchangeGroup lookup(URL url) throws RemotingException { return new FileExchangeGroup(url); } }
package com.vod.common.v5; import java.util.List; public class BasePageDetail<T> { private int total; private int rowsPerPage; private int offset; private List<T> datas; @Override public String toString() { return "BasePageDetail [total=" + total + ", rowsPerPage=" + rowsPerPage + ", offset=" + offset + ", datas=" + datas + "]"; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public int getRowsPerPage() { return rowsPerPage; } public void setRowsPerPage(int rowsPerPage) { this.rowsPerPage = rowsPerPage; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public List<T> getDatas() { return datas; } public void setDatas(List<T> datas) { this.datas = datas; } }
package com.morgan.test.attr; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import com.morgan.lib.util.Logger; import com.morgan.main.R; /** * 用于属性测试的View,因为是使用xml来声明,系统来创建的View, <br/> * 所以系统会调用第一个构造函数,第一个构造函数会调用第二个构造函数, <br/> * 最后打印出这个View使用的属性值 * * @author Morgan.Ji * @version 1.0 * @date 2015-11-12 */ public class AttributeTestView extends View { private static final String TAG = "AttributeTest"; public AttributeTestView(Context context, AttributeSet attrs) { // this(context, attrs, 0);// defStyle为0时obtainStyledAttributes第四个参数才会有效 this(context, attrs, R.attr.CustomizeThemeStyle); } public AttributeTestView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Customize, defStyle, R.style.DefaultCustomizeStyle); String one = a.getString(R.styleable.Customize_attr_one); String two = a.getString(R.styleable.Customize_attr_two); String three = a.getString(R.styleable.Customize_attr_three); String four = a.getString(R.styleable.Customize_attr_four); String five = a.getString(R.styleable.Customize_attr_five); Logger.i(TAG, "one:" + one); Logger.i(TAG, "two:" + two); Logger.i(TAG, "three:" + three); Logger.i(TAG, "four:" + four); Logger.i(TAG, "five:" + five); a.recycle(); } }
package main.tut04; import com.jogamp.newt.event.KeyEvent; import com.jogamp.opengl.GL3; import com.jogamp.opengl.util.GLBuffers; import main.framework.Framework; import main.framework.Semantic; import glm.vec._4.Vec4; import java.nio.FloatBuffer; import java.nio.IntBuffer; import static com.jogamp.opengl.GL.*; import static com.jogamp.opengl.GL2ES3.GL_COLOR; import static uno.buffer.UtilKt.destroyBuffer; import static uno.buffer.UtilKt.destroyBuffers; import static uno.glsl.UtilKt.programOf; /** * * @author gbarbieri */ public class OrthoCube extends Framework { public static void main(String[] args) { new OrthoCube().setup("Tutorial 04 - Ortho Cube"); } private int theProgram, offsetUniform; private IntBuffer vertexBufferObject = GLBuffers.newDirectIntBuffer(1), vao = GLBuffers.newDirectIntBuffer(1); @Override public void init(GL3 gl) { initializeProgram(gl); initializeVertexBuffer(gl); gl.glGenVertexArrays(1, vao); gl.glBindVertexArray(vao.get(0)); gl.glEnable(GL_CULL_FACE); gl.glCullFace(GL_BACK); gl.glFrontFace(GL_CW); } private void initializeProgram(GL3 gl) { theProgram = programOf(gl, getClass(), "tut04", "ortho-with-offset.vert", "standard-colors.frag"); offsetUniform = gl.glGetUniformLocation(theProgram, "offset"); } private void initializeVertexBuffer(GL3 gl) { FloatBuffer vertexBuffer = GLBuffers.newDirectFloatBuffer(vertexData); gl.glGenBuffers(1, vertexBufferObject); gl.glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject.get(0)); gl.glBufferData(GL_ARRAY_BUFFER, vertexBuffer.capacity() * Float.BYTES, vertexBuffer, GL_STATIC_DRAW); gl.glBindBuffer(GL_ARRAY_BUFFER, 0); destroyBuffer(vertexBuffer); } @Override public void display(GL3 gl) { gl.glClearBufferfv(GL_COLOR, 0, clearColor.put(0, 0.0f).put(1, 0.0f).put(2, 0.0f).put(3, 0.0f)); gl.glUseProgram(theProgram); gl.glUniform2f(offsetUniform, 0.5f, 0.25f); int colorData = vertexData.length * Float.BYTES / 2; gl.glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject.get(0)); gl.glEnableVertexAttribArray(Semantic.Attr.POSITION); gl.glEnableVertexAttribArray(Semantic.Attr.COLOR); gl.glVertexAttribPointer(Semantic.Attr.POSITION, Vec4.length, GL_FLOAT, false, Vec4.SIZE, 0); gl.glVertexAttribPointer(Semantic.Attr.COLOR, Vec4.length, GL_FLOAT, false, Vec4.SIZE, colorData); gl.glDrawArrays(GL_TRIANGLES, 0, 36); gl.glDisableVertexAttribArray(Semantic.Attr.POSITION); gl.glDisableVertexAttribArray(Semantic.Attr.COLOR); gl.glUseProgram(0); } @Override public void reshape(GL3 gl, int w, int h) { gl.glViewport(0, 0, w, h); } @Override public void end(GL3 gl) { gl.glDeleteProgram(theProgram); gl.glDeleteBuffers(1, vertexBufferObject); gl.glDeleteVertexArrays(1, vao); destroyBuffers(vao, vertexBufferObject); } @Override public void keyPressed(KeyEvent keyEvent) { switch (keyEvent.getKeyCode()) { case KeyEvent.VK_ESCAPE: quit(); break; } } private float[] vertexData = { +0.25f, +0.25f, +0.75f, 1.0f, +0.25f, -0.25f, +0.75f, 1.0f, -0.25f, +0.25f, +0.75f, 1.0f, +0.25f, -0.25f, +0.75f, 1.0f, -0.25f, -0.25f, +0.75f, 1.0f, -0.25f, +0.25f, +0.75f, 1.0f, +0.25f, +0.25f, -0.75f, 1.0f, -0.25f, +0.25f, -0.75f, 1.0f, +0.25f, -0.25f, -0.75f, 1.0f, +0.25f, -0.25f, -0.75f, 1.0f, -0.25f, +0.25f, -0.75f, 1.0f, -0.25f, -0.25f, -0.75f, 1.0f, -0.25f, +0.25f, +0.75f, 1.0f, -0.25f, -0.25f, +0.75f, 1.0f, -0.25f, -0.25f, -0.75f, 1.0f, -0.25f, +0.25f, +0.75f, 1.0f, -0.25f, -0.25f, -0.75f, 1.0f, -0.25f, +0.25f, -0.75f, 1.0f, +0.25f, +0.25f, +0.75f, 1.0f, +0.25f, -0.25f, -0.75f, 1.0f, +0.25f, -0.25f, +0.75f, 1.0f, +0.25f, +0.25f, +0.75f, 1.0f, +0.25f, +0.25f, -0.75f, 1.0f, +0.25f, -0.25f, -0.75f, 1.0f, +0.25f, +0.25f, -0.75f, 1.0f, +0.25f, +0.25f, +0.75f, 1.0f, -0.25f, +0.25f, +0.75f, 1.0f, +0.25f, +0.25f, -0.75f, 1.0f, -0.25f, +0.25f, +0.75f, 1.0f, -0.25f, +0.25f, -0.75f, 1.0f, +0.25f, -0.25f, -0.75f, 1.0f, -0.25f, -0.25f, +0.75f, 1.0f, +0.25f, -0.25f, +0.75f, 1.0f, +0.25f, -0.25f, -0.75f, 1.0f, -0.25f, -0.25f, -0.75f, 1.0f, -0.25f, -0.25f, +0.75f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f}; }
/** * Copyright(C) 2020 Hangzhou zhaoyunxing92 Technology Co., Ltd. All rights reserved. */ package io.github.sunny.cloud.file.controller; import io.github.sunny.cloud.file.controller.form.AccountForm; import io.github.sunny.cloud.file.service.AccountService; import io.github.sunny.cloud.file.service.WechatService; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; /** * 微信模块控制器 * * @author zhaoyunxing92 * @date: 2020-04-05 17:21 */ @RestController @RequestMapping("/wechat") public class WechatController { private final WechatService wechatService; private final AccountService accountService; public WechatController(WechatService wechatService, AccountService accountService) { this.wechatService = wechatService; this.accountService = accountService; } /** * 通过小程序code获取用户信息 * * @param code 小程序生成的code * @return openid */ @GetMapping("/code") public ResponseEntity<Object> getAccountByCode(String code) { return ResponseEntity.ok(wechatService.getAccountByCode(code)); } /** * 注册活登录小程序用户 * * @param form 表单数据 * @return openid */ @PostMapping("/register") public ResponseEntity<Object> registerOrLogin(@RequestBody @Validated AccountForm form) { return ResponseEntity.ok(accountService.registerOrLogin(form)); } }
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jdbc; import org.springframework.dao.DataRetrievalFailureException; import java.io.IOException; /** * Exception to be thrown when a LOB could not be retrieved. * * @author Juergen Hoeller * @since 1.0.2 */ @SuppressWarnings("serial") public class LobRetrievalFailureException extends DataRetrievalFailureException { /** * Constructor for LobRetrievalFailureException. * * @param msg the detail message */ public LobRetrievalFailureException(String msg) { super(msg); } /** * Constructor for LobRetrievalFailureException. * * @param msg the detail message * @param ex the root cause IOException */ public LobRetrievalFailureException(String msg, IOException ex) { super(msg, ex); } }
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.dingtalkproject_integration_1_0.models; import com.aliyun.tea.*; public class CreateEventGroupHeaders extends TeaModel { @NameInMap("commonHeaders") public java.util.Map<String, String> commonHeaders; @NameInMap("x-acs-dingtalk-access-token") public String xAcsDingtalkAccessToken; public static CreateEventGroupHeaders build(java.util.Map<String, ?> map) throws Exception { CreateEventGroupHeaders self = new CreateEventGroupHeaders(); return TeaModel.build(map, self); } public CreateEventGroupHeaders setCommonHeaders(java.util.Map<String, String> commonHeaders) { this.commonHeaders = commonHeaders; return this; } public java.util.Map<String, String> getCommonHeaders() { return this.commonHeaders; } public CreateEventGroupHeaders setXAcsDingtalkAccessToken(String xAcsDingtalkAccessToken) { this.xAcsDingtalkAccessToken = xAcsDingtalkAccessToken; return this; } public String getXAcsDingtalkAccessToken() { return this.xAcsDingtalkAccessToken; } }
package com.github.wxiaoqi.security.movie.service; import com.baomidou.mybatisplus.extension.service.IService; import com.github.wxiaoqi.security.movie.entity.User; /** * <p> * 服务类 * </p> * * @author lxr * @since 2019-06-14 */ public interface IUserService extends IService<User> { User verifyUser(User user); void registerUser(User user); User getByAccount(String account); }
package ParkTicket; public class CustomerInfo { private String date = ""; private int ticketType; private int ageType; }
package com.niliv.entity; import java.util.Date; /** * 考勤类 * @author Administrator * */ public class Duty { private int dtID; private Date dtDate; private String signinTime; private String signoutTime; private String empId; //可以同时提供id和对象属性 private Employee emp;//员工的信息 public Duty() { super(); } public Duty(Date dtDate, String signinTime, String signoutTime, String empId) { super(); this.dtDate = dtDate; this.signinTime = signinTime; this.signoutTime = signoutTime; this.empId = empId; } public Duty(int dtID, Date dtDate, String signinTime, String signoutTime, Employee emp) { super(); this.dtID = dtID; this.dtDate = dtDate; this.signinTime = signinTime; this.signoutTime = signoutTime; this.emp = emp; } public int getDtID() { return dtID; } public void setDtID(int dtID) { this.dtID = dtID; } public Date getDtDate() { return dtDate; } public void setDtDate(Date dtDate) { this.dtDate = dtDate; } public String getSigninTime() { return signinTime; } public void setSigninTime(String signinTime) { this.signinTime = signinTime; } public String getSignoutTime() { return signoutTime; } public void setSignoutTime(String signoutTime) { this.signoutTime = signoutTime; } public String getEmpId() { return empId; } public void setEmpId(String empId) { this.empId = empId; } public Employee getEmp() { return emp; } public void setEmp(Employee emp) { this.emp = emp; } @Override public String toString() { return "Duty [dtID=" + dtID + ", dtDate=" + dtDate + ", signinTime=" + signinTime + ", signoutTime=" + signoutTime + ", empId=" + empId + ", emp=" + emp + "]"; } }
package ui; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SpringLayout; import dtos.ArchivePathsDTO; import exceptions.SortParamException; public class ArchiveSelectionPage extends GUIPage { /** * */ private static final long serialVersionUID = -5559164918960750910L; private JTextField boxArchivePath; private JTextField fileMasterArchivePath; private JTextField excelSheetPath; @Override public void prepareGUI() { SpringLayout layout = new SpringLayout(); this.setLayout(layout); // Place header JLabel pageHeader = new JLabel("Archive folders and files to sort or make edits to"); this.add(pageHeader); layout.putConstraint(SpringLayout.NORTH, pageHeader, 5, SpringLayout.NORTH, this); layout.putConstraint(SpringLayout.WEST, pageHeader, 5, SpringLayout.WEST, this); layout.putConstraint(SpringLayout.EAST, pageHeader, 5, SpringLayout.EAST, this); // Construct box archive selection line boxArchivePath = new JTextField(); boxArchivePath.setEditable(false); JFileChooser dirChooser = new JFileChooser(); dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); JPanel boxArchivePathSelector = constructSelectFilePanel("Box archive:", boxArchivePath, dirChooser); this.add(boxArchivePathSelector); layout.putConstraint(SpringLayout.NORTH, boxArchivePathSelector, 5, SpringLayout.SOUTH, pageHeader); layout.putConstraint(SpringLayout.WEST, boxArchivePathSelector, 5, SpringLayout.WEST, this); layout.putConstraint(SpringLayout.EAST, boxArchivePathSelector, -5, SpringLayout.EAST, this); // Construct file archive selection line fileMasterArchivePath = new JTextField(); fileMasterArchivePath.setEditable(false); JPanel fileArchivePathSelector = constructSelectFilePanel("File archive:", fileMasterArchivePath, dirChooser); this.add(fileArchivePathSelector); layout.putConstraint(SpringLayout.NORTH, fileArchivePathSelector, 5, SpringLayout.SOUTH, boxArchivePathSelector); layout.putConstraint(SpringLayout.WEST, fileArchivePathSelector, 5, SpringLayout.WEST, this); layout.putConstraint(SpringLayout.EAST, fileArchivePathSelector, -5, SpringLayout.EAST, this); // Construct excel selection line excelSheetPath = new JTextField(); excelSheetPath.setEditable(false); JFileChooser excelSheetChooser = new JFileChooser(); excelSheetChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); JPanel excelSheetPathSelector = constructSelectFilePanel("Excel list:", excelSheetPath, excelSheetChooser); // this.add(excelSheetPathSelector); // TODO: Implement excel editation layout.putConstraint(SpringLayout.NORTH, excelSheetPathSelector, 5, SpringLayout.SOUTH, fileArchivePathSelector); layout.putConstraint(SpringLayout.WEST, excelSheetPathSelector, 5, SpringLayout.WEST, this); layout.putConstraint(SpringLayout.EAST, excelSheetPathSelector, -5, SpringLayout.EAST, this); } public ArchivePathsDTO getArchivePathsDTO() throws SortParamException { validateInput(); return new ArchivePathsDTO ( boxArchivePath.getText(), fileMasterArchivePath.getText(), excelSheetPath.getText() ); } private JPanel constructSelectFilePanel(String label, JTextField pathTextField, JFileChooser fc) { // Create components JLabel selectionLabel = new JLabel(label); JButton selectionBtn = new JButton("Open folder"); JPanel container = new JPanel(new GridBagLayout()); // Initiate file chooser selectionBtn.addActionListener(linkTextInputAndFileChooser(pathTextField, fc)); // Position components GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; container.add(selectionLabel, gbc); gbc.gridx++; gbc.weightx = 1; gbc.fill = GridBagConstraints.BOTH; gbc.insets = new Insets(0, 5, 0, 0); container.add(pathTextField, gbc); gbc.gridx++; gbc.weightx = 0; gbc.fill = GridBagConstraints.NONE; gbc.insets = new Insets(0, 0, 0, 0); container.add(selectionBtn, gbc); return container; } private ActionListener linkTextInputAndFileChooser(JTextField input, JFileChooser fc) { return new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int returnFlag = fc.showDialog(input, "Select"); if (returnFlag == JFileChooser.APPROVE_OPTION) { input.setText(fc.getSelectedFile().toString()); } } }; } /** * Checks to see if the sort parameters are valid * */ private void validateInput() throws SortParamException { // Added function stub, didn't end up using but could be used if inputs changes are needed later on } }
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.engine.impl.cmd; import org.activiti.engine.ActivitiIllegalArgumentException; import org.activiti.engine.ActivitiObjectNotFoundException; import org.activiti.engine.impl.context.Context; import org.activiti.engine.impl.interceptor.Command; import org.activiti.engine.impl.interceptor.CommandContext; import org.activiti.engine.impl.persistence.entity.DeploymentEntity; import org.activiti.engine.repository.Deployment; /** * @author Tijs Rademakers */ public class SetDeploymentCategoryCmd implements Command<Void> { protected String deploymentId; protected String category; public SetDeploymentCategoryCmd(String deploymentId, String category) { this.deploymentId = deploymentId; this.category = category; } public Void execute(CommandContext commandContext) { if (deploymentId == null) { throw new ActivitiIllegalArgumentException("Deployment id is null"); } DeploymentEntity deployment = Context .getCommandContext() .getDeploymentEntityManager() .findDeploymentById(deploymentId); if (deployment == null) { throw new ActivitiObjectNotFoundException("No deployment found for id = '" + deploymentId + "'", Deployment.class); } // Update category deployment.setCategory(category); return null; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.core.management.impl; import javax.json.JsonArray; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.management.ListenerNotFoundException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; import javax.management.NotificationEmitter; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.transaction.xa.Xid; import java.net.URL; import java.text.DateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.api.core.ActiveMQAddressDoesNotExistException; import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.JsonUtil; import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; import org.apache.activemq.artemis.api.core.management.ActiveMQServerControl; import org.apache.activemq.artemis.api.core.management.AddressControl; import org.apache.activemq.artemis.api.core.management.BridgeControl; import org.apache.activemq.artemis.api.core.management.CoreNotificationType; import org.apache.activemq.artemis.api.core.management.DivertControl; import org.apache.activemq.artemis.api.core.management.ManagementHelper; import org.apache.activemq.artemis.api.core.management.Parameter; import org.apache.activemq.artemis.api.core.management.QueueControl; import org.apache.activemq.artemis.core.client.impl.Topology; import org.apache.activemq.artemis.core.client.impl.TopologyMemberImpl; import org.apache.activemq.artemis.core.config.BridgeConfiguration; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.config.ConnectorServiceConfiguration; import org.apache.activemq.artemis.core.config.DivertConfiguration; import org.apache.activemq.artemis.core.config.TransformerConfiguration; import org.apache.activemq.artemis.core.filter.Filter; import org.apache.activemq.artemis.core.management.impl.view.AddressView; import org.apache.activemq.artemis.core.management.impl.view.ConnectionView; import org.apache.activemq.artemis.core.management.impl.view.ConsumerView; import org.apache.activemq.artemis.core.management.impl.view.ProducerView; import org.apache.activemq.artemis.core.management.impl.view.QueueView; import org.apache.activemq.artemis.core.management.impl.view.SessionView; import org.apache.activemq.artemis.core.messagecounter.MessageCounterManager; import org.apache.activemq.artemis.core.messagecounter.impl.MessageCounterManagerImpl; import org.apache.activemq.artemis.core.persistence.StorageManager; import org.apache.activemq.artemis.core.persistence.config.PersistedAddressSetting; import org.apache.activemq.artemis.core.persistence.config.PersistedRoles; import org.apache.activemq.artemis.core.postoffice.Binding; import org.apache.activemq.artemis.core.postoffice.Bindings; import org.apache.activemq.artemis.core.postoffice.DuplicateIDCache; import org.apache.activemq.artemis.core.postoffice.PostOffice; import org.apache.activemq.artemis.core.postoffice.impl.LocalQueueBinding; import org.apache.activemq.artemis.core.remoting.server.RemotingService; import org.apache.activemq.artemis.core.security.CheckType; import org.apache.activemq.artemis.core.security.Role; import org.apache.activemq.artemis.core.server.ActiveMQMessageBundle; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import org.apache.activemq.artemis.core.server.ConnectorServiceFactory; import org.apache.activemq.artemis.core.server.Consumer; import org.apache.activemq.artemis.core.server.ComponentConfigurationRoutingType; import org.apache.activemq.artemis.core.server.JournalType; import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.core.server.ServerConsumer; import org.apache.activemq.artemis.core.server.ServerProducer; import org.apache.activemq.artemis.core.server.ServerSession; import org.apache.activemq.artemis.core.server.cluster.ClusterConnection; import org.apache.activemq.artemis.core.server.cluster.ClusterManager; import org.apache.activemq.artemis.core.server.cluster.ha.HAPolicy; import org.apache.activemq.artemis.core.server.cluster.ha.LiveOnlyPolicy; import org.apache.activemq.artemis.core.server.cluster.ha.ScaleDownPolicy; import org.apache.activemq.artemis.core.server.cluster.ha.SharedStoreSlavePolicy; import org.apache.activemq.artemis.core.server.group.GroupingHandler; import org.apache.activemq.artemis.core.server.impl.Activation; import org.apache.activemq.artemis.core.server.impl.AddressInfo; import org.apache.activemq.artemis.core.server.impl.SharedNothingLiveActivation; import org.apache.activemq.artemis.core.settings.impl.AddressFullMessagePolicy; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.core.settings.impl.DeletionPolicy; import org.apache.activemq.artemis.core.settings.impl.SlowConsumerPolicy; import org.apache.activemq.artemis.core.transaction.ResourceManager; import org.apache.activemq.artemis.core.transaction.Transaction; import org.apache.activemq.artemis.core.transaction.TransactionDetail; import org.apache.activemq.artemis.core.transaction.TransactionDetailFactory; import org.apache.activemq.artemis.core.transaction.impl.CoreTransactionDetail; import org.apache.activemq.artemis.core.transaction.impl.XidImpl; import org.apache.activemq.artemis.logs.AuditLogger; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.spi.core.security.jaas.PropertiesLoginModuleConfigurator; import org.apache.activemq.artemis.utils.JsonLoader; import org.apache.activemq.artemis.utils.ListUtil; import org.apache.activemq.artemis.utils.PasswordMaskingUtil; import org.apache.activemq.artemis.utils.SecurityFormatter; import org.apache.activemq.artemis.utils.collections.TypedProperties; import org.jboss.logging.Logger; public class ActiveMQServerControlImpl extends AbstractControl implements ActiveMQServerControl, NotificationEmitter, org.apache.activemq.artemis.core.server.management.NotificationListener { // Constants ----------------------------------------------------- private static final Logger logger = Logger.getLogger(ActiveMQServerControlImpl.class); // Attributes ---------------------------------------------------- private final PostOffice postOffice; private final Configuration configuration; private final ResourceManager resourceManager; private final RemotingService remotingService; private final ActiveMQServer server; private final MessageCounterManager messageCounterManager; private final NotificationBroadcasterSupport broadcaster; private final AtomicLong notifSeq = new AtomicLong(0); // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public ActiveMQServerControlImpl(final PostOffice postOffice, final Configuration configuration, final ResourceManager resourceManager, final RemotingService remotingService, final ActiveMQServer messagingServer, final MessageCounterManager messageCounterManager, final StorageManager storageManager, final NotificationBroadcasterSupport broadcaster) throws Exception { super(ActiveMQServerControl.class, storageManager); this.postOffice = postOffice; this.configuration = configuration; this.resourceManager = resourceManager; this.remotingService = remotingService; server = messagingServer; this.messageCounterManager = messageCounterManager; this.broadcaster = broadcaster; server.getManagementService().addNotificationListener(this); } // ActiveMQServerControlMBean implementation -------------------- @Override public boolean isStarted() { if (AuditLogger.isEnabled()) { AuditLogger.isStarted(this.server); } clearIO(); try { return server.isStarted(); } finally { blockOnIO(); } } @Override public String getVersion() { if (AuditLogger.isEnabled()) { AuditLogger.getVersion(this.server); } checkStarted(); clearIO(); try { return server.getVersion().getFullVersion(); } finally { blockOnIO(); } } @Override public boolean isBackup() { if (AuditLogger.isEnabled()) { AuditLogger.isBackup(this.server); } checkStarted(); clearIO(); try { return server.getHAPolicy().isBackup(); } finally { blockOnIO(); } } @Override public boolean isSharedStore() { if (AuditLogger.isEnabled()) { AuditLogger.isSharedStore(this.server); } checkStarted(); clearIO(); try { return server.getHAPolicy().isSharedStore(); } finally { blockOnIO(); } } @Override public String getBindingsDirectory() { if (AuditLogger.isEnabled()) { AuditLogger.getBindingsDirectory(this.server); } checkStarted(); clearIO(); try { return configuration.getBindingsDirectory(); } finally { blockOnIO(); } } public String[] getInterceptorClassNames() { checkStarted(); clearIO(); try { return configuration.getIncomingInterceptorClassNames().toArray(new String[configuration.getIncomingInterceptorClassNames().size()]); } finally { blockOnIO(); } } @Override public String[] getIncomingInterceptorClassNames() { if (AuditLogger.isEnabled()) { AuditLogger.getIncomingInterceptorClassNames(this.server); } checkStarted(); clearIO(); try { return configuration.getIncomingInterceptorClassNames().toArray(new String[configuration.getIncomingInterceptorClassNames().size()]); } finally { blockOnIO(); } } @Override public String[] getOutgoingInterceptorClassNames() { if (AuditLogger.isEnabled()) { AuditLogger.getOutgoingInterceptorClassNames(this.server); } checkStarted(); clearIO(); try { return configuration.getOutgoingInterceptorClassNames().toArray(new String[configuration.getOutgoingInterceptorClassNames().size()]); } finally { blockOnIO(); } } @Override public int getJournalBufferSize() { if (AuditLogger.isEnabled()) { AuditLogger.getJournalBufferSize(this.server); } checkStarted(); clearIO(); try { return configuration.getJournalType() == JournalType.ASYNCIO ? configuration.getJournalBufferSize_AIO() : configuration.getJournalBufferSize_NIO(); } finally { blockOnIO(); } } @Override public int getJournalBufferTimeout() { if (AuditLogger.isEnabled()) { AuditLogger.getJournalBufferTimeout(this.server); } checkStarted(); clearIO(); try { return configuration.getJournalType() == JournalType.ASYNCIO ? configuration.getJournalBufferTimeout_AIO() : configuration.getJournalBufferTimeout_NIO(); } finally { blockOnIO(); } } @Override public void setFailoverOnServerShutdown(boolean failoverOnServerShutdown) { if (AuditLogger.isEnabled()) { AuditLogger.setFailoverOnServerShutdown(this.server, failoverOnServerShutdown); } checkStarted(); clearIO(); try { HAPolicy haPolicy = server.getHAPolicy(); if (haPolicy instanceof SharedStoreSlavePolicy) { ((SharedStoreSlavePolicy) haPolicy).setFailoverOnServerShutdown(failoverOnServerShutdown); } } finally { blockOnIO(); } } @Override public boolean isFailoverOnServerShutdown() { if (AuditLogger.isEnabled()) { AuditLogger.isFailoverOnServerShutdown(this.server); } checkStarted(); clearIO(); try { HAPolicy haPolicy = server.getHAPolicy(); if (haPolicy instanceof SharedStoreSlavePolicy) { return ((SharedStoreSlavePolicy) haPolicy).isFailoverOnServerShutdown(); } else { return false; } } finally { blockOnIO(); } } @Override public int getJournalMaxIO() { if (AuditLogger.isEnabled()) { AuditLogger.getJournalMaxIO(this.server); } checkStarted(); clearIO(); try { return configuration.getJournalType() == JournalType.ASYNCIO ? configuration.getJournalMaxIO_AIO() : configuration.getJournalMaxIO_NIO(); } finally { blockOnIO(); } } @Override public String getJournalDirectory() { if (AuditLogger.isEnabled()) { AuditLogger.getJournalDirectory(this.server); } checkStarted(); clearIO(); try { return configuration.getJournalDirectory(); } finally { blockOnIO(); } } @Override public int getJournalFileSize() { if (AuditLogger.isEnabled()) { AuditLogger.getJournalFileSize(this.server); } checkStarted(); clearIO(); try { return configuration.getJournalFileSize(); } finally { blockOnIO(); } } @Override public int getJournalMinFiles() { if (AuditLogger.isEnabled()) { AuditLogger.getJournalMinFiles(this.server); } checkStarted(); clearIO(); try { return configuration.getJournalMinFiles(); } finally { blockOnIO(); } } @Override public int getJournalCompactMinFiles() { if (AuditLogger.isEnabled()) { AuditLogger.getJournalCompactMinFiles(this.server); } checkStarted(); clearIO(); try { return configuration.getJournalCompactMinFiles(); } finally { blockOnIO(); } } @Override public int getJournalCompactPercentage() { if (AuditLogger.isEnabled()) { AuditLogger.getJournalCompactPercentage(this.server); } checkStarted(); clearIO(); try { return configuration.getJournalCompactPercentage(); } finally { blockOnIO(); } } @Override public boolean isPersistenceEnabled() { if (AuditLogger.isEnabled()) { AuditLogger.isPersistenceEnabled(this.server); } checkStarted(); clearIO(); try { return configuration.isPersistenceEnabled(); } finally { blockOnIO(); } } @Override public String getJournalType() { if (AuditLogger.isEnabled()) { AuditLogger.getJournalType(this.server); } checkStarted(); clearIO(); try { return configuration.getJournalType().toString(); } finally { blockOnIO(); } } @Override public String getPagingDirectory() { if (AuditLogger.isEnabled()) { AuditLogger.getPagingDirectory(this.server); } checkStarted(); clearIO(); try { return configuration.getPagingDirectory(); } finally { blockOnIO(); } } @Override public int getScheduledThreadPoolMaxSize() { if (AuditLogger.isEnabled()) { AuditLogger.getScheduledThreadPoolMaxSize(this.server); } checkStarted(); clearIO(); try { return configuration.getScheduledThreadPoolMaxSize(); } finally { blockOnIO(); } } @Override public int getThreadPoolMaxSize() { if (AuditLogger.isEnabled()) { AuditLogger.getThreadPoolMaxSize(this.server); } checkStarted(); clearIO(); try { return configuration.getThreadPoolMaxSize(); } finally { blockOnIO(); } } @Override public long getSecurityInvalidationInterval() { if (AuditLogger.isEnabled()) { AuditLogger.getSecurityInvalidationInterval(this.server); } checkStarted(); clearIO(); try { return configuration.getSecurityInvalidationInterval(); } finally { blockOnIO(); } } @Override public boolean isClustered() { if (AuditLogger.isEnabled()) { AuditLogger.isClustered(this.server); } checkStarted(); clearIO(); try { return configuration.isClustered(); } finally { blockOnIO(); } } @Override public boolean isCreateBindingsDir() { if (AuditLogger.isEnabled()) { AuditLogger.isCreateBindingsDir(this.server); } checkStarted(); clearIO(); try { return configuration.isCreateBindingsDir(); } finally { blockOnIO(); } } @Override public boolean isCreateJournalDir() { if (AuditLogger.isEnabled()) { AuditLogger.isCreateJournalDir(this.server); } checkStarted(); clearIO(); try { return configuration.isCreateJournalDir(); } finally { blockOnIO(); } } @Override public boolean isJournalSyncNonTransactional() { if (AuditLogger.isEnabled()) { AuditLogger.isJournalSyncNonTransactional(this.server); } checkStarted(); clearIO(); try { return configuration.isJournalSyncNonTransactional(); } finally { blockOnIO(); } } @Override public boolean isJournalSyncTransactional() { if (AuditLogger.isEnabled()) { AuditLogger.isJournalSyncTransactional(this.server); } checkStarted(); clearIO(); try { return configuration.isJournalSyncTransactional(); } finally { blockOnIO(); } } @Override public boolean isSecurityEnabled() { if (AuditLogger.isEnabled()) { AuditLogger.isSecurityEnabled(this.server); } checkStarted(); clearIO(); try { return configuration.isSecurityEnabled(); } finally { blockOnIO(); } } @Override public boolean isAsyncConnectionExecutionEnabled() { if (AuditLogger.isEnabled()) { AuditLogger.isAsyncConnectionExecutionEnabled(this.server); } checkStarted(); clearIO(); try { return configuration.isAsyncConnectionExecutionEnabled(); } finally { blockOnIO(); } } @Override public int getDiskScanPeriod() { if (AuditLogger.isEnabled()) { AuditLogger.getDiskScanPeriod(this.server); } checkStarted(); clearIO(); try { return configuration.getDiskScanPeriod(); } finally { blockOnIO(); } } @Override public int getMaxDiskUsage() { if (AuditLogger.isEnabled()) { AuditLogger.getMaxDiskUsage(this.server); } checkStarted(); clearIO(); try { return configuration.getMaxDiskUsage(); } finally { blockOnIO(); } } @Override public long getGlobalMaxSize() { if (AuditLogger.isEnabled()) { AuditLogger.getGlobalMaxSize(this.server); } checkStarted(); clearIO(); try { return configuration.getGlobalMaxSize(); } finally { blockOnIO(); } } @Override public long getAddressMemoryUsage() { if (AuditLogger.isEnabled()) { AuditLogger.getAddressMemoryUsage(this.server); } checkStarted(); clearIO(); try { //this should not happen but if it does, return -1 to highlight it is not working if (server.getPagingManager() == null) { return -1L; } return server.getPagingManager().getGlobalSize(); } finally { blockOnIO(); } } @Override public int getAddressMemoryUsagePercentage() { if (AuditLogger.isEnabled()) { AuditLogger.getAddressMemoryUsagePercentage(this.server); } long globalMaxSize = getGlobalMaxSize(); // no max size set implies 0% used if (globalMaxSize <= 0) { return 0; } long memoryUsed = getAddressMemoryUsage(); if (memoryUsed <= 0) { return 0; } double result = (100D * memoryUsed) / globalMaxSize; return (int) result; } @Override public boolean freezeReplication() { if (AuditLogger.isEnabled()) { AuditLogger.freezeReplication(this.server); } Activation activation = server.getActivation(); if (activation instanceof SharedNothingLiveActivation) { SharedNothingLiveActivation liveActivation = (SharedNothingLiveActivation) activation; liveActivation.freezeReplication(); return true; } return false; } private enum AddressInfoTextFormatter { Long { @Override public StringBuilder format(AddressInfo addressInfo, StringBuilder output) { output.append("Address [name=").append(addressInfo.getName()); output.append(", routingTypes={"); final EnumSet<RoutingType> routingTypes = addressInfo.getRoutingTypes(); if (!routingTypes.isEmpty()) { for (RoutingType routingType : routingTypes) { output.append(routingType).append(','); } // delete hanging comma output.deleteCharAt(output.length() - 1); } output.append('}'); output.append(", autoCreated=").append(addressInfo.isAutoCreated()); output.append(']'); return output; } }; public abstract StringBuilder format(AddressInfo addressInfo, StringBuilder output); } public enum QueueTextFormatter { Long { @Override StringBuilder format(Queue queue, StringBuilder output) { output.append("Queue [name=").append(queue.getName()); output.append(", address=").append(queue.getAddress()); output.append(", routingType=").append(queue.getRoutingType()); final Filter filter = queue.getFilter(); if (filter != null) { output.append(", filter=").append(filter.getFilterString()); } output.append(", durable=").append(queue.isDurable()); final int maxConsumers = queue.getMaxConsumers(); if (maxConsumers != Queue.MAX_CONSUMERS_UNLIMITED) { output.append(", maxConsumers=").append(queue.getMaxConsumers()); } output.append(", purgeOnNoConsumers=").append(queue.isPurgeOnNoConsumers()); output.append(", autoCreateAddress=").append(queue.isAutoCreated()); output.append(", exclusive=").append(queue.isExclusive()); output.append(", lastValue=").append(queue.isLastValue()); output.append(", lastValueKey=").append(queue.getLastValueKey()); output.append(", nonDestructive=").append(queue.isNonDestructive()); output.append(", consumersBeforeDispatch=").append(queue.getConsumersBeforeDispatch()); output.append(", delayBeforeDispatch=").append(queue.getDelayBeforeDispatch()); output.append(", autoCreateAddress=").append(queue.isAutoCreated()); output.append(']'); return output; } }; abstract StringBuilder format(Queue queue, StringBuilder output); } @Override public String createAddress(String name, String routingTypes) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.createAddress(this.server, name, routingTypes); } checkStarted(); clearIO(); try { EnumSet<RoutingType> set = EnumSet.noneOf(RoutingType.class); for (String routingType : ListUtil.toList(routingTypes)) { set.add(RoutingType.valueOf(routingType)); } final AddressInfo addressInfo = new AddressInfo(new SimpleString(name), set); if (server.addAddressInfo(addressInfo)) { return AddressInfoTextFormatter.Long.format(addressInfo, new StringBuilder()).toString(); } else { throw ActiveMQMessageBundle.BUNDLE.addressAlreadyExists(addressInfo.getName()); } } finally { blockOnIO(); } } @Override public String updateAddress(String name, String routingTypes) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.updateAddress(this.server, name, routingTypes); } checkStarted(); clearIO(); try { final EnumSet<RoutingType> routingTypeSet; if (routingTypes == null) { routingTypeSet = null; } else { routingTypeSet = EnumSet.noneOf(RoutingType.class); final String[] routingTypeNames = routingTypes.split(","); for (String routingTypeName : routingTypeNames) { routingTypeSet.add(RoutingType.valueOf(routingTypeName)); } } if (!server.updateAddressInfo(SimpleString.toSimpleString(name), routingTypeSet)) { throw ActiveMQMessageBundle.BUNDLE.addressDoesNotExist(SimpleString.toSimpleString(name)); } return AddressInfoTextFormatter.Long.format(server.getAddressInfo(SimpleString.toSimpleString(name)), new StringBuilder()).toString(); } finally { blockOnIO(); } } @Override public void deleteAddress(String name) throws Exception { deleteAddress(name, false); } @Override public void deleteAddress(String name, boolean force) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.deleteAddress(this.server, name, force); } checkStarted(); clearIO(); try { server.removeAddressInfo(new SimpleString(name), null, force); } catch (ActiveMQException e) { throw new IllegalStateException(e.getMessage()); } finally { blockOnIO(); } } @Deprecated @Override public void deployQueue(final String address, final String name, final String filterString) throws Exception { deployQueue(address, name, filterString, true); } @Deprecated @Override public void deployQueue(final String address, final String name, final String filterStr, final boolean durable) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.deployQueue(this.server, address, name, filterStr, durable); } checkStarted(); SimpleString filter = filterStr == null ? null : new SimpleString(filterStr); clearIO(); try { server.createQueue(SimpleString.toSimpleString(address), server.getAddressSettingsRepository().getMatch(address).getDefaultQueueRoutingType(), new SimpleString(name), filter, durable, false); } finally { blockOnIO(); } } @Override public void createQueue(final String address, final String name) throws Exception { createQueue(address, name, true); } @Override public void createQueue(final String address, final String name, final String routingType) throws Exception { createQueue(address, name, true, routingType); } @Override public void createQueue(final String address, final String name, final boolean durable) throws Exception { createQueue(address, name, null, durable); } @Override public void createQueue(final String address, final String name, final boolean durable, final String routingType) throws Exception { createQueue(address, name, null, durable, routingType); } @Override public void createQueue(final String address, final String name, final String filterStr, final boolean durable) throws Exception { createQueue(address, name, filterStr, durable, server.getAddressSettingsRepository().getMatch(address == null ? name : address).getDefaultQueueRoutingType().toString()); } @Override public void createQueue(final String address, final String name, final String filterStr, final boolean durable, final String routingType) throws Exception { AddressSettings addressSettings = server.getAddressSettingsRepository().getMatch(address == null ? name : address); createQueue(address, routingType, name, filterStr, durable, addressSettings.getDefaultMaxConsumers(), addressSettings.isDefaultPurgeOnNoConsumers(), addressSettings.isAutoCreateAddresses()); } @Override public String createQueue(String address, String routingType, String name, String filterStr, boolean durable, int maxConsumers, boolean purgeOnNoConsumers, boolean autoCreateAddress) throws Exception { AddressSettings addressSettings = server.getAddressSettingsRepository().getMatch(address == null ? name : address); return createQueue( address, routingType, name, filterStr, durable, maxConsumers, purgeOnNoConsumers, addressSettings.isDefaultExclusiveQueue(), addressSettings.isDefaultGroupRebalance(), addressSettings.getDefaultGroupBuckets(), addressSettings.isDefaultLastValueQueue(), addressSettings.getDefaultLastValueKey() == null ? null : addressSettings.getDefaultLastValueKey().toString(), addressSettings.isDefaultNonDestructive(), addressSettings.getDefaultConsumersBeforeDispatch(), addressSettings.getDefaultDelayBeforeDispatch(), addressSettings.isAutoDeleteCreatedQueues(), addressSettings.getAutoDeleteQueuesDelay(), addressSettings.getAutoDeleteQueuesMessageCount(), autoCreateAddress ); } @Override public String createQueue(String address, String routingType, String name, String filterStr, boolean durable, int maxConsumers, boolean purgeOnNoConsumers, boolean exclusive, boolean groupRebalance, int groupBuckets, boolean lastValue, String lastValueKey, boolean nonDestructive, int consumersBeforeDispatch, long delayBeforeDispatch, boolean autoCreateAddress) throws Exception { AddressSettings addressSettings = server.getAddressSettingsRepository().getMatch(address == null ? name : address); return createQueue( address, routingType, name, filterStr, durable, maxConsumers, purgeOnNoConsumers, exclusive, groupRebalance, groupBuckets, lastValue, lastValueKey, nonDestructive, consumersBeforeDispatch, delayBeforeDispatch, addressSettings.isAutoDeleteCreatedQueues(), addressSettings.getAutoDeleteQueuesDelay(), addressSettings.getAutoDeleteQueuesMessageCount(), autoCreateAddress); } @Override public String createQueue(String address, String routingType, String name, String filterStr, boolean durable, int maxConsumers, boolean purgeOnNoConsumers, boolean exclusive, boolean groupRebalance, int groupBuckets, boolean lastValue, String lastValueKey, boolean nonDestructive, int consumersBeforeDispatch, long delayBeforeDispatch, boolean autoDelete, long autoDeleteDelay, long autoDeleteMessageCount, boolean autoCreateAddress) throws Exception { AddressSettings addressSettings = server.getAddressSettingsRepository().getMatch(address == null ? name : address); return createQueue( address, routingType, name, filterStr, durable, maxConsumers, purgeOnNoConsumers, exclusive, groupRebalance, groupBuckets, addressSettings.getDefaultGroupFirstKey() == null ? null : addressSettings.getDefaultGroupFirstKey().toString(), lastValue, lastValueKey, nonDestructive, consumersBeforeDispatch, delayBeforeDispatch, autoDelete, autoDeleteDelay, autoDeleteMessageCount, autoCreateAddress ); } @Override public String createQueue(String address, String routingType, String name, String filterStr, boolean durable, int maxConsumers, boolean purgeOnNoConsumers, boolean exclusive, boolean groupRebalance, int groupBuckets, String groupFirstKey, boolean lastValue, String lastValueKey, boolean nonDestructive, int consumersBeforeDispatch, long delayBeforeDispatch, boolean autoDelete, long autoDeleteDelay, long autoDeleteMessageCount, boolean autoCreateAddress) throws Exception { AddressSettings addressSettings = server.getAddressSettingsRepository().getMatch(address == null ? name : address); return createQueue( address, routingType, name, filterStr, durable, maxConsumers, purgeOnNoConsumers, exclusive, groupRebalance, groupBuckets, groupFirstKey, lastValue, lastValueKey, nonDestructive, consumersBeforeDispatch, delayBeforeDispatch, autoDelete, autoDeleteDelay, autoDeleteMessageCount, autoCreateAddress, addressSettings.getDefaultRingSize() ); } @Override public String createQueue(String address, String routingType, String name, String filterStr, boolean durable, int maxConsumers, boolean purgeOnNoConsumers, boolean exclusive, boolean groupRebalance, int groupBuckets, String groupFirstKey, boolean lastValue, String lastValueKey, boolean nonDestructive, int consumersBeforeDispatch, long delayBeforeDispatch, boolean autoDelete, long autoDeleteDelay, long autoDeleteMessageCount, boolean autoCreateAddress, long ringSize) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.createQueue(this.server, null, address, routingType, name, filterStr, durable, maxConsumers, purgeOnNoConsumers, exclusive, groupRebalance, groupBuckets, groupFirstKey, lastValue, lastValueKey, nonDestructive, consumersBeforeDispatch, delayBeforeDispatch, autoDelete, autoDeleteDelay, autoDeleteMessageCount, autoCreateAddress, ringSize); } checkStarted(); clearIO(); SimpleString filter = filterStr == null ? null : new SimpleString(filterStr); try { if (filterStr != null && !filterStr.trim().equals("")) { filter = new SimpleString(filterStr); } final Queue queue = server.createQueue(SimpleString.toSimpleString(address), RoutingType.valueOf(routingType.toUpperCase()), SimpleString.toSimpleString(name), filter, durable, false, maxConsumers, purgeOnNoConsumers, exclusive, groupRebalance, groupBuckets, SimpleString.toSimpleString(groupFirstKey), lastValue, SimpleString.toSimpleString(lastValueKey), nonDestructive, consumersBeforeDispatch, delayBeforeDispatch, autoDelete, autoDeleteDelay, autoDeleteMessageCount, autoCreateAddress, ringSize); return QueueTextFormatter.Long.format(queue, new StringBuilder()).toString(); } catch (ActiveMQException e) { throw new IllegalStateException(e.getMessage()); } finally { blockOnIO(); } } @Deprecated @Override public String updateQueue(String name, String routingType, Integer maxConsumers, Boolean purgeOnNoConsumers) throws Exception { return updateQueue(name, routingType, maxConsumers, purgeOnNoConsumers, null); } @Deprecated @Override public String updateQueue(String name, String routingType, Integer maxConsumers, Boolean purgeOnNoConsumers, Boolean exclusive) throws Exception { return updateQueue(name, routingType, maxConsumers, purgeOnNoConsumers, exclusive, null); } @Override public String updateQueue(String name, String routingType, Integer maxConsumers, Boolean purgeOnNoConsumers, Boolean exclusive, String user) throws Exception { return updateQueue(name, routingType, null, maxConsumers, purgeOnNoConsumers, exclusive, null, null, null, null, null, user); } @Override public String updateQueue(String name, String routingType, String filter, Integer maxConsumers, Boolean purgeOnNoConsumers, Boolean exclusive, Boolean groupRebalance, Integer groupBuckets, Boolean nonDestructive, Integer consumersBeforeDispatch, Long delayBeforeDispatch, String user) throws Exception { return updateQueue(name, routingType, filter, maxConsumers, purgeOnNoConsumers, exclusive, groupRebalance, groupBuckets, null, nonDestructive, consumersBeforeDispatch, delayBeforeDispatch, user); } @Override public String updateQueue(String name, String routingType, String filter, Integer maxConsumers, Boolean purgeOnNoConsumers, Boolean exclusive, Boolean groupRebalance, Integer groupBuckets, String groupFirstKey, Boolean nonDestructive, Integer consumersBeforeDispatch, Long delayBeforeDispatch, String user) throws Exception { return updateQueue(name, routingType, filter, maxConsumers, purgeOnNoConsumers, exclusive, groupRebalance, groupBuckets, null, nonDestructive, consumersBeforeDispatch, delayBeforeDispatch, user, null); } @Override public String updateQueue(String name, String routingType, String filter, Integer maxConsumers, Boolean purgeOnNoConsumers, Boolean exclusive, Boolean groupRebalance, Integer groupBuckets, String groupFirstKey, Boolean nonDestructive, Integer consumersBeforeDispatch, Long delayBeforeDispatch, String user, Long ringSize) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.updateQueue(this.server, name, routingType, filter, maxConsumers, purgeOnNoConsumers, exclusive, groupRebalance, groupBuckets, groupFirstKey, nonDestructive, consumersBeforeDispatch, delayBeforeDispatch, user, ringSize); } checkStarted(); clearIO(); try { final Queue queue = server.updateQueue(name, routingType != null ? RoutingType.valueOf(routingType) : null, filter, maxConsumers, purgeOnNoConsumers, exclusive, groupRebalance, groupBuckets, groupFirstKey, nonDestructive, consumersBeforeDispatch, delayBeforeDispatch, user); if (queue == null) { throw ActiveMQMessageBundle.BUNDLE.noSuchQueue(new SimpleString(name)); } return QueueTextFormatter.Long.format(queue, new StringBuilder()).toString(); } finally { blockOnIO(); } } @Override public String[] getQueueNames() { return getQueueNames(null); } @Override public String[] getQueueNames(String routingType) { if (AuditLogger.isEnabled()) { AuditLogger.getQueueNames(this.server, routingType); } checkStarted(); clearIO(); try { Object[] queueControls = server.getManagementService().getResources(QueueControl.class); List<String> names = new ArrayList<>(); for (int i = 0; i < queueControls.length; i++) { QueueControl queueControl = (QueueControl) queueControls[i]; if (routingType != null && queueControl.getRoutingType().equals(routingType.toUpperCase())) { names.add(queueControl.getName()); } else if (routingType == null) { names.add(queueControl.getName()); } } String[] result = new String[names.size()]; return names.toArray(result); } finally { blockOnIO(); } } @Override public String[] getClusterConnectionNames() { if (AuditLogger.isEnabled()) { AuditLogger.getClusterConnectionNames(this.server); } checkStarted(); clearIO(); try { List<String> names = new ArrayList<>(); for (ClusterConnection clusterConnection : server.getClusterManager().getClusterConnections()) { names.add(clusterConnection.getName().toString()); } String[] result = new String[names.size()]; return names.toArray(result); } finally { blockOnIO(); } } @Override public String getUptime() { if (AuditLogger.isEnabled()) { AuditLogger.getUptime(this.server); } checkStarted(); clearIO(); try { return server.getUptime(); } finally { blockOnIO(); } } @Override public long getUptimeMillis() { if (AuditLogger.isEnabled()) { AuditLogger.getUptimeMillis(this.server); } checkStarted(); clearIO(); try { return server.getUptimeMillis(); } finally { blockOnIO(); } } @Override public boolean isReplicaSync() { if (AuditLogger.isEnabled()) { AuditLogger.isReplicaSync(this.server); } checkStarted(); clearIO(); try { return server.isReplicaSync(); } finally { blockOnIO(); } } @Override public String[] getAddressNames() { if (AuditLogger.isEnabled()) { AuditLogger.getAddressNames(this.server); } checkStarted(); clearIO(); try { Object[] addresses = server.getManagementService().getResources(AddressControl.class); String[] names = new String[addresses.length]; for (int i = 0; i < addresses.length; i++) { AddressControl address = (AddressControl) addresses[i]; names[i] = address.getAddress(); } return names; } finally { blockOnIO(); } } @Override public void destroyQueue(final String name, final boolean removeConsumers, final boolean autoDeleteAddress) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.destroyQueue(this.server, null, name, removeConsumers, autoDeleteAddress); } checkStarted(); clearIO(); try { SimpleString queueName = new SimpleString(name); server.destroyQueue(queueName, null, !removeConsumers, removeConsumers, autoDeleteAddress); } finally { blockOnIO(); } } @Override public void destroyQueue(final String name, final boolean removeConsumers) throws Exception { destroyQueue(name, removeConsumers, false); } @Override public void destroyQueue(final String name) throws Exception { destroyQueue(name, false); } @Override public String getAddressInfo(String address) throws ActiveMQAddressDoesNotExistException { if (AuditLogger.isEnabled()) { AuditLogger.getAddressInfo(this.server, address); } checkStarted(); clearIO(); try { final AddressInfo addressInfo = server.getAddressInfo(SimpleString.toSimpleString(address)); if (addressInfo == null) { throw ActiveMQMessageBundle.BUNDLE.addressDoesNotExist(SimpleString.toSimpleString(address)); } else { return AddressInfoTextFormatter.Long.format(addressInfo, new StringBuilder()).toString(); } } finally { blockOnIO(); } } @Override public String listBindingsForAddress(String address) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listBindingsForAddress(this.server, address); } checkStarted(); clearIO(); try { final Bindings bindings = server.getPostOffice().lookupBindingsForAddress(new SimpleString(address)); return bindings == null ? "" : bindings.getBindings().stream().map(Binding::toManagementString).collect(Collectors.joining(",")); } finally { blockOnIO(); } } @Override public String listAddresses(String separator) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listAddresses(this.server, separator); } checkStarted(); clearIO(); try { final Set<SimpleString> addresses = server.getPostOffice().getAddresses(); TreeSet<SimpleString> sortAddress = new TreeSet<>(new Comparator<SimpleString>() { @Override public int compare(SimpleString o1, SimpleString o2) { return o1.toString().compareToIgnoreCase(o2.toString()); } }); sortAddress.addAll(addresses); StringBuilder result = new StringBuilder(); for (SimpleString string : sortAddress) { if (result.length() > 0) { result.append(separator); } result.append(string); } return result.toString(); } finally { blockOnIO(); } } @Override public int getConnectionCount() { if (AuditLogger.isEnabled()) { AuditLogger.getConnectionCount(this.server); } checkStarted(); clearIO(); try { return server.getConnectionCount(); } finally { blockOnIO(); } } @Override public long getTotalConnectionCount() { if (AuditLogger.isEnabled()) { AuditLogger.getTotalConnectionCount(this.server); } checkStarted(); clearIO(); try { return server.getTotalConnectionCount(); } finally { blockOnIO(); } } @Override public long getTotalMessageCount() { if (AuditLogger.isEnabled()) { AuditLogger.getTotalMessageCount(this.server); } checkStarted(); clearIO(); try { return server.getTotalMessageCount(); } finally { blockOnIO(); } } @Override public long getTotalMessagesAdded() { if (AuditLogger.isEnabled()) { AuditLogger.getTotalMessagesAdded(this.server); } checkStarted(); clearIO(); try { return server.getTotalMessagesAdded(); } finally { blockOnIO(); } } @Override public long getTotalMessagesAcknowledged() { if (AuditLogger.isEnabled()) { AuditLogger.getTotalMessagesAcknowledged(this.server); } checkStarted(); clearIO(); try { return server.getTotalMessagesAcknowledged(); } finally { blockOnIO(); } } @Override public long getTotalConsumerCount() { if (AuditLogger.isEnabled()) { AuditLogger.getTotalConsumerCount(this.server); } checkStarted(); clearIO(); try { return server.getTotalConsumerCount(); } finally { blockOnIO(); } } @Override public void enableMessageCounters() { if (AuditLogger.isEnabled()) { AuditLogger.enableMessageCounters(this.server); } checkStarted(); clearIO(); try { setMessageCounterEnabled(true); } finally { blockOnIO(); } } @Override public void disableMessageCounters() { if (AuditLogger.isEnabled()) { AuditLogger.disableMessageCounters(this.server); } checkStarted(); clearIO(); try { setMessageCounterEnabled(false); } finally { blockOnIO(); } } @Override public void resetAllMessageCounters() { if (AuditLogger.isEnabled()) { AuditLogger.resetAllMessageCounters(this.server); } checkStarted(); clearIO(); try { messageCounterManager.resetAllCounters(); } finally { blockOnIO(); } } @Override public void resetAllMessageCounterHistories() { if (AuditLogger.isEnabled()) { AuditLogger.resetAllMessageCounterHistories(this.server); } checkStarted(); clearIO(); try { messageCounterManager.resetAllCounterHistories(); } finally { blockOnIO(); } } @Override public boolean isMessageCounterEnabled() { if (AuditLogger.isEnabled()) { AuditLogger.isMessageCounterEnabled(this.server); } checkStarted(); clearIO(); try { return configuration.isMessageCounterEnabled(); } finally { blockOnIO(); } } @Override public synchronized long getMessageCounterSamplePeriod() { if (AuditLogger.isEnabled()) { AuditLogger.getMessageCounterSamplePeriod(this.server); } checkStarted(); clearIO(); try { return messageCounterManager.getSamplePeriod(); } finally { blockOnIO(); } } @Override public synchronized void setMessageCounterSamplePeriod(final long newPeriod) { if (AuditLogger.isEnabled()) { AuditLogger.setMessageCounterSamplePeriod(this.server, newPeriod); } checkStarted(); clearIO(); try { if (newPeriod < MessageCounterManagerImpl.MIN_SAMPLE_PERIOD) { if (newPeriod <= 0) { throw ActiveMQMessageBundle.BUNDLE.periodMustGreaterThanZero(newPeriod); } ActiveMQServerLogger.LOGGER.invalidMessageCounterPeriod(newPeriod); } if (messageCounterManager != null && newPeriod != messageCounterManager.getSamplePeriod()) { messageCounterManager.reschedule(newPeriod); } } finally { blockOnIO(); } } @Override public int getMessageCounterMaxDayCount() { if (AuditLogger.isEnabled()) { AuditLogger.getMessageCounterMaxDayCount(this.server); } checkStarted(); clearIO(); try { return messageCounterManager.getMaxDayCount(); } finally { blockOnIO(); } } @Override public void setMessageCounterMaxDayCount(final int count) { if (AuditLogger.isEnabled()) { AuditLogger.setMessageCounterMaxDayCount(this.server, count); } checkStarted(); clearIO(); try { if (count <= 0) { throw ActiveMQMessageBundle.BUNDLE.greaterThanZero(count); } messageCounterManager.setMaxDayCount(count); } finally { blockOnIO(); } } @Override public String[] listPreparedTransactions() { if (AuditLogger.isEnabled()) { AuditLogger.listPreparedTransactions(this.server); } checkStarted(); clearIO(); try { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); Map<Xid, Long> xids = resourceManager.getPreparedTransactionsWithCreationTime(); ArrayList<Entry<Xid, Long>> xidsSortedByCreationTime = new ArrayList<>(xids.entrySet()); Collections.sort(xidsSortedByCreationTime, new Comparator<Entry<Xid, Long>>() { @Override public int compare(final Entry<Xid, Long> entry1, final Entry<Xid, Long> entry2) { // sort by creation time, oldest first return entry1.getValue().compareTo(entry2.getValue()); } }); String[] s = new String[xidsSortedByCreationTime.size()]; int i = 0; for (Map.Entry<Xid, Long> entry : xidsSortedByCreationTime) { Date creation = new Date(entry.getValue()); Xid xid = entry.getKey(); s[i++] = dateFormat.format(creation) + " base64: " + XidImpl.toBase64String(xid) + " " + xid.toString(); } return s; } finally { blockOnIO(); } } @Override public String listPreparedTransactionDetailsAsJSON() throws Exception { return listPreparedTransactionDetailsAsJSON((xid, tx, creation) -> new CoreTransactionDetail(xid, tx, creation)); } public String listPreparedTransactionDetailsAsJSON(TransactionDetailFactory factory) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listPreparedTransactionDetailsAsJSON(this.server); } checkStarted(); clearIO(); try { Map<Xid, Long> xids = resourceManager.getPreparedTransactionsWithCreationTime(); if (xids == null || xids.size() == 0) { return ""; } ArrayList<Entry<Xid, Long>> xidsSortedByCreationTime = new ArrayList<>(xids.entrySet()); Collections.sort(xidsSortedByCreationTime, new Comparator<Entry<Xid, Long>>() { @Override public int compare(final Entry<Xid, Long> entry1, final Entry<Xid, Long> entry2) { // sort by creation time, oldest first return entry1.getValue().compareTo(entry2.getValue()); } }); JsonArrayBuilder txDetailListJson = JsonLoader.createArrayBuilder(); for (Map.Entry<Xid, Long> entry : xidsSortedByCreationTime) { Xid xid = entry.getKey(); Transaction tx = resourceManager.getTransaction(xid); if (tx == null) { continue; } TransactionDetail detail = factory.createTransactionDetail(xid, tx, entry.getValue()); txDetailListJson.add(detail.toJSON()); } return txDetailListJson.build().toString(); } finally { blockOnIO(); } } @Override public String listPreparedTransactionDetailsAsHTML() throws Exception { return listPreparedTransactionDetailsAsHTML((xid, tx, creation) -> new CoreTransactionDetail(xid, tx, creation)); } public String listPreparedTransactionDetailsAsHTML(TransactionDetailFactory factory) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listPreparedTransactionDetailsAsHTML(this.server, factory); } checkStarted(); clearIO(); try { Map<Xid, Long> xids = resourceManager.getPreparedTransactionsWithCreationTime(); if (xids == null || xids.size() == 0) { return "<h3>*** Prepared Transaction Details ***</h3><p>No entry.</p>"; } ArrayList<Entry<Xid, Long>> xidsSortedByCreationTime = new ArrayList<>(xids.entrySet()); Collections.sort(xidsSortedByCreationTime, new Comparator<Entry<Xid, Long>>() { @Override public int compare(final Entry<Xid, Long> entry1, final Entry<Xid, Long> entry2) { // sort by creation time, oldest first return entry1.getValue().compareTo(entry2.getValue()); } }); StringBuilder html = new StringBuilder(); html.append("<h3>*** Prepared Transaction Details ***</h3>"); for (Map.Entry<Xid, Long> entry : xidsSortedByCreationTime) { Xid xid = entry.getKey(); Transaction tx = resourceManager.getTransaction(xid); if (tx == null) { continue; } TransactionDetail detail = factory.createTransactionDetail(xid, tx, entry.getValue()); JsonObject txJson = detail.toJSON(); html.append("<table border=\"1\">"); html.append("<tr><th>creation_time</th>"); html.append("<td>" + txJson.get(TransactionDetail.KEY_CREATION_TIME) + "</td>"); html.append("<th>xid_as_base_64</th>"); html.append("<td colspan=\"3\">" + txJson.get(TransactionDetail.KEY_XID_AS_BASE64) + "</td></tr>"); html.append("<tr><th>xid_format_id</th>"); html.append("<td>" + txJson.get(TransactionDetail.KEY_XID_FORMAT_ID) + "</td>"); html.append("<th>xid_global_txid</th>"); html.append("<td>" + txJson.get(TransactionDetail.KEY_XID_GLOBAL_TXID) + "</td>"); html.append("<th>xid_branch_qual</th>"); html.append("<td>" + txJson.get(TransactionDetail.KEY_XID_BRANCH_QUAL) + "</td></tr>"); html.append("<tr><th colspan=\"6\">Message List</th></tr>"); html.append("<tr><td colspan=\"6\">"); html.append("<table border=\"1\" cellspacing=\"0\" cellpadding=\"0\">"); JsonArray msgs = txJson.getJsonArray(TransactionDetail.KEY_TX_RELATED_MESSAGES); for (int i = 0; i < msgs.size(); i++) { JsonObject msgJson = msgs.getJsonObject(i); JsonObject props = msgJson.getJsonObject(TransactionDetail.KEY_MSG_PROPERTIES); StringBuilder propstr = new StringBuilder(); Set<String> keys = props.keySet(); for (String key : keys) { propstr.append(key); propstr.append("="); propstr.append(props.get(key)); propstr.append(", "); } html.append("<th>operation_type</th>"); html.append("<td>" + msgJson.get(TransactionDetail.KEY_MSG_OP_TYPE) + "</th>"); html.append("<th>message_type</th>"); html.append("<td>" + msgJson.get(TransactionDetail.KEY_MSG_TYPE) + "</td></tr>"); html.append("<tr><th>properties</th>"); html.append("<td colspan=\"3\">" + propstr.toString() + "</td></tr>"); } html.append("</table></td></tr>"); html.append("</table><br>"); } return html.toString(); } finally { blockOnIO(); } } @Override public String[] listHeuristicCommittedTransactions() { if (AuditLogger.isEnabled()) { AuditLogger.listHeuristicCommittedTransactions(this.server); } checkStarted(); clearIO(); try { List<Xid> xids = resourceManager.getHeuristicCommittedTransactions(); String[] s = new String[xids.size()]; int i = 0; for (Xid xid : xids) { s[i++] = XidImpl.toBase64String(xid); } return s; } finally { blockOnIO(); } } @Override public String[] listHeuristicRolledBackTransactions() { if (AuditLogger.isEnabled()) { AuditLogger.listHeuristicRolledBackTransactions(this.server); } checkStarted(); clearIO(); try { List<Xid> xids = resourceManager.getHeuristicRolledbackTransactions(); String[] s = new String[xids.size()]; int i = 0; for (Xid xid : xids) { s[i++] = XidImpl.toBase64String(xid); } return s; } finally { blockOnIO(); } } @Override public synchronized boolean commitPreparedTransaction(final String transactionAsBase64) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.commitPreparedTransaction(this.server, transactionAsBase64); } checkStarted(); clearIO(); try { List<Xid> xids = resourceManager.getPreparedTransactions(); for (Xid xid : xids) { if (XidImpl.toBase64String(xid).equals(transactionAsBase64)) { Transaction transaction = resourceManager.removeTransaction(xid); transaction.commit(false); long recordID = server.getStorageManager().storeHeuristicCompletion(xid, true); storageManager.waitOnOperations(); resourceManager.putHeuristicCompletion(recordID, xid, true); return true; } } return false; } finally { blockOnIO(); } } @Override public synchronized boolean rollbackPreparedTransaction(final String transactionAsBase64) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.rollbackPreparedTransaction(this.server, transactionAsBase64); } checkStarted(); clearIO(); try { List<Xid> xids = resourceManager.getPreparedTransactions(); for (Xid xid : xids) { if (XidImpl.toBase64String(xid).equals(transactionAsBase64)) { Transaction transaction = resourceManager.removeTransaction(xid); transaction.rollback(); long recordID = server.getStorageManager().storeHeuristicCompletion(xid, false); server.getStorageManager().waitOnOperations(); resourceManager.putHeuristicCompletion(recordID, xid, false); return true; } } return false; } finally { blockOnIO(); } } @Override public String[] listRemoteAddresses() { if (AuditLogger.isEnabled()) { AuditLogger.listRemoteAddresses(this.server); } checkStarted(); clearIO(); try { Set<RemotingConnection> connections = remotingService.getConnections(); String[] remoteAddresses = new String[connections.size()]; int i = 0; for (RemotingConnection connection : connections) { remoteAddresses[i++] = connection.getRemoteAddress(); } return remoteAddresses; } finally { blockOnIO(); } } @Override public String[] listRemoteAddresses(final String ipAddress) { if (AuditLogger.isEnabled()) { AuditLogger.listRemoteAddresses(this.server, ipAddress); } checkStarted(); clearIO(); try { Set<RemotingConnection> connections = remotingService.getConnections(); List<String> remoteConnections = new ArrayList<>(); for (RemotingConnection connection : connections) { String remoteAddress = connection.getRemoteAddress(); if (remoteAddress.contains(ipAddress)) { remoteConnections.add(connection.getRemoteAddress()); } } return remoteConnections.toArray(new String[remoteConnections.size()]); } finally { blockOnIO(); } } @Override public boolean closeConnectionsForAddress(final String ipAddress) { if (AuditLogger.isEnabled()) { AuditLogger.closeConnectionsForAddress(this.server, ipAddress); } checkStarted(); clearIO(); try { boolean closed = false; Set<RemotingConnection> connections = remotingService.getConnections(); for (RemotingConnection connection : connections) { String remoteAddress = connection.getRemoteAddress(); if (remoteAddress.contains(ipAddress)) { connection.fail(ActiveMQMessageBundle.BUNDLE.connectionsClosedByManagement(ipAddress)); remotingService.removeConnection(connection.getID()); closed = true; } } return closed; } finally { blockOnIO(); } } @Override public boolean closeConsumerConnectionsForAddress(final String address) { if (AuditLogger.isEnabled()) { AuditLogger.closeConsumerConnectionsForAddress(this.server, address); } boolean closed = false; checkStarted(); clearIO(); try { for (Binding binding : postOffice.getMatchingBindings(SimpleString.toSimpleString(address)).getBindings()) { if (binding instanceof LocalQueueBinding) { Queue queue = ((LocalQueueBinding) binding).getQueue(); for (Consumer consumer : queue.getConsumers()) { if (consumer instanceof ServerConsumer) { ServerConsumer serverConsumer = (ServerConsumer) consumer; RemotingConnection connection = null; for (RemotingConnection potentialConnection : remotingService.getConnections()) { if (potentialConnection.getID().toString().equals(serverConsumer.getConnectionID())) { connection = potentialConnection; } } if (connection != null) { remotingService.removeConnection(connection.getID()); connection.fail(ActiveMQMessageBundle.BUNDLE.consumerConnectionsClosedByManagement(address)); closed = true; } } } } } } catch (Exception e) { ActiveMQServerLogger.LOGGER.failedToCloseConsumerConnectionsForAddress(address, e); } finally { blockOnIO(); } return closed; } @Override public boolean closeConnectionsForUser(final String userName) { if (AuditLogger.isEnabled()) { AuditLogger.closeConnectionsForUser(this.server, userName); } boolean closed = false; checkStarted(); clearIO(); try { for (ServerSession serverSession : server.getSessions()) { if (serverSession.getUsername() != null && serverSession.getUsername().equals(userName)) { RemotingConnection connection = null; for (RemotingConnection potentialConnection : remotingService.getConnections()) { if (potentialConnection.getID().toString().equals(serverSession.getConnectionID().toString())) { connection = potentialConnection; } } if (connection != null) { remotingService.removeConnection(connection.getID()); connection.fail(ActiveMQMessageBundle.BUNDLE.connectionsForUserClosedByManagement(userName)); closed = true; } } } } finally { blockOnIO(); } return closed; } @Override public boolean closeConnectionWithID(final String ID) { if (AuditLogger.isEnabled()) { AuditLogger.closeConnectionWithID(this.server, ID); } checkStarted(); clearIO(); try { for (RemotingConnection connection : remotingService.getConnections()) { if (connection.getID().toString().equals(ID)) { remotingService.removeConnection(connection.getID()); connection.fail(ActiveMQMessageBundle.BUNDLE.connectionWithIDClosedByManagement(ID)); return true; } } } finally { blockOnIO(); } return false; } @Override public boolean closeSessionWithID(final String connectionID, final String ID) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.closeSessionWithID(this.server, connectionID, ID); } checkStarted(); clearIO(); try { List<ServerSession> sessions = server.getSessions(connectionID); for (ServerSession session : sessions) { if (session.getName().equals(ID.toString())) { session.close(true); return true; } } } finally { blockOnIO(); } return false; } @Override public boolean closeConsumerWithID(final String sessionID, final String ID) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.closeConsumerWithID(this.server, sessionID, ID); } checkStarted(); clearIO(); try { Set<ServerSession> sessions = server.getSessions(); for (ServerSession session : sessions) { if (session.getName().equals(sessionID.toString())) { Set<ServerConsumer> serverConsumers = session.getServerConsumers(); for (ServerConsumer serverConsumer : serverConsumers) { if (serverConsumer.sequentialID() == Long.valueOf(ID)) { serverConsumer.disconnect(); return true; } } } } } finally { blockOnIO(); } return false; } @Override public String[] listConnectionIDs() { if (AuditLogger.isEnabled()) { AuditLogger.listConnectionIDs(this.server); } checkStarted(); clearIO(); try { Set<RemotingConnection> connections = remotingService.getConnections(); String[] connectionIDs = new String[connections.size()]; int i = 0; for (RemotingConnection connection : connections) { connectionIDs[i++] = connection.getID().toString(); } return connectionIDs; } finally { blockOnIO(); } } @Override public String[] listSessions(final String connectionID) { if (AuditLogger.isEnabled()) { AuditLogger.listSessions(this.server, connectionID); } checkStarted(); clearIO(); try { List<ServerSession> sessions = server.getSessions(connectionID); String[] sessionIDs = new String[sessions.size()]; int i = 0; for (ServerSession serverSession : sessions) { sessionIDs[i++] = serverSession.getName(); } return sessionIDs; } finally { blockOnIO(); } } /* (non-Javadoc) * @see org.apache.activemq.artemis.api.core.management.ActiveMQServerControl#listProducersInfoAsJSON() */ @Override public String listProducersInfoAsJSON() throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listProducersInfoAsJSON(this.server); } JsonArrayBuilder producers = JsonLoader.createArrayBuilder(); for (ServerSession session : server.getSessions()) { session.describeProducersInfo(producers); } return producers.build().toString(); } @Override public String listConnections(String options, int page, int pageSize) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listConnections(this.server, options, page, pageSize); } checkStarted(); clearIO(); try { server.getPostOffice().getAddresses(); ConnectionView view = new ConnectionView(server); view.setCollection(server.getRemotingService().getConnections()); view.setOptions(options); return view.getResultsAsJson(page, pageSize); } finally { blockOnIO(); } } @Override public String listSessions(String options, int page, int pageSize) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listSessions(this.server, options, page, pageSize); } checkStarted(); clearIO(); try { SessionView view = new SessionView(); view.setCollection(server.getSessions()); view.setOptions(options); return view.getResultsAsJson(page, pageSize); } finally { blockOnIO(); } } @Override public String listConsumers(String options, int page, int pageSize) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listConsumers(this.server, options, page, pageSize); } checkStarted(); clearIO(); try { Set<ServerConsumer> consumers = new HashSet(); for (ServerSession session : server.getSessions()) { consumers.addAll(session.getServerConsumers()); } ConsumerView view = new ConsumerView(server); view.setCollection(consumers); view.setOptions(options); return view.getResultsAsJson(page, pageSize); } finally { blockOnIO(); } } @Override public String listAddresses(String options, int page, int pageSize) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listAddresses(this.server, options, page, pageSize); } checkStarted(); clearIO(); try { final Set<SimpleString> addresses = server.getPostOffice().getAddresses(); List<AddressInfo> addressInfo = new ArrayList<>(); for (SimpleString address : addresses) { AddressInfo info = server.getPostOffice().getAddressInfo(address); //ignore if no longer available if (info != null) { addressInfo.add(info); } } AddressView view = new AddressView(server); view.setCollection(addressInfo); view.setOptions(options); return view.getResultsAsJson(page, pageSize); } finally { blockOnIO(); } } @Override public String listQueues(String options, int page, int pageSize) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listQueues(this.server, options, page, pageSize); } checkStarted(); clearIO(); try { List<QueueControl> queues = new ArrayList<>(); Object[] qs = server.getManagementService().getResources(QueueControl.class); for (int i = 0; i < qs.length; i++) { queues.add((QueueControl) qs[i]); } QueueView view = new QueueView(server); view.setCollection(queues); view.setOptions(options); return view.getResultsAsJson(page, pageSize); } finally { blockOnIO(); } } @Override public String listProducers(@Parameter(name = "Options") String options, @Parameter(name = "Page Number") int page, @Parameter(name = "Page Size") int pageSize) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listProducers(this.server, options, page, pageSize); } checkStarted(); clearIO(); try { Set<ServerProducer> producers = new HashSet<>(); for (ServerSession session : server.getSessions()) { producers.addAll(session.getServerProducers().values()); } ProducerView view = new ProducerView(server); view.setCollection(producers); view.setOptions(options); return view.getResultsAsJson(page, pageSize); } finally { blockOnIO(); } } @Override public String listConnectionsAsJSON() throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listConnectionsAsJSON(this.server); } checkStarted(); clearIO(); try { JsonArrayBuilder array = JsonLoader.createArrayBuilder(); Set<RemotingConnection> connections = server.getRemotingService().getConnections(); for (RemotingConnection connection : connections) { JsonObjectBuilder obj = JsonLoader.createObjectBuilder().add("connectionID", connection.getID().toString()).add("clientAddress", connection.getRemoteAddress()).add("creationTime", connection.getCreationTime()).add("implementation", connection.getClass().getSimpleName()).add("sessionCount", server.getSessions(connection.getID().toString()).size()); array.add(obj); } return array.build().toString(); } finally { blockOnIO(); } } @Override public String listSessionsAsJSON(final String connectionID) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listSessionsAsJSON(this.server, connectionID); } checkStarted(); clearIO(); JsonArrayBuilder array = JsonLoader.createArrayBuilder(); try { List<ServerSession> sessions = server.getSessions(connectionID); for (ServerSession sess : sessions) { buildSessionJSON(array, sess); } } finally { blockOnIO(); } return array.build().toString(); } @Override public String listAllSessionsAsJSON() throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listAllSessionsAsJSON(this.server); } checkStarted(); clearIO(); JsonArrayBuilder array = JsonLoader.createArrayBuilder(); try { Set<ServerSession> sessions = server.getSessions(); for (ServerSession sess : sessions) { buildSessionJSON(array, sess); } } finally { blockOnIO(); } return array.build().toString(); } public void buildSessionJSON(JsonArrayBuilder array, ServerSession sess) { JsonObjectBuilder obj = JsonLoader.createObjectBuilder().add("sessionID", sess.getName()).add("creationTime", sess.getCreationTime()).add("consumerCount", sess.getServerConsumers().size()); if (sess.getValidatedUser() != null) { obj.add("principal", sess.getValidatedUser()); } if (sess.getMetaData() != null) { final JsonObjectBuilder metadata = JsonLoader.createObjectBuilder(); for (Entry<String, String> entry : sess.getMetaData().entrySet()) { metadata.add(entry.getKey(), entry.getValue()); } obj.add("metadata", metadata); } array.add(obj); } @Override public String listConsumersAsJSON(String connectionID) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listConsumersAsJSON(this.server, connectionID); } checkStarted(); clearIO(); try { JsonArrayBuilder array = JsonLoader.createArrayBuilder(); Set<RemotingConnection> connections = server.getRemotingService().getConnections(); for (RemotingConnection connection : connections) { if (connectionID.equals(connection.getID().toString())) { List<ServerSession> sessions = server.getSessions(connectionID); for (ServerSession session : sessions) { Set<ServerConsumer> consumers = session.getServerConsumers(); for (ServerConsumer consumer : consumers) { JsonObject obj = toJSONObject(consumer); if (obj != null) { array.add(obj); } } } } } return array.build().toString(); } finally { blockOnIO(); } } @Override public String listAllConsumersAsJSON() throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listAllConsumersAsJSON(this.server); } checkStarted(); clearIO(); try { JsonArrayBuilder array = JsonLoader.createArrayBuilder(); Set<ServerSession> sessions = server.getSessions(); for (ServerSession session : sessions) { Set<ServerConsumer> consumers = session.getServerConsumers(); for (ServerConsumer consumer : consumers) { JsonObject obj = toJSONObject(consumer); if (obj != null) { array.add(obj); } } } return array.build().toString(); } finally { blockOnIO(); } } private JsonObject toJSONObject(ServerConsumer consumer) throws Exception { JsonObjectBuilder obj = JsonLoader.createObjectBuilder().add("consumerID", consumer.getID()).add("connectionID", consumer.getConnectionID().toString()).add("sessionID", consumer.getSessionID()).add("queueName", consumer.getQueue().getName().toString()).add("browseOnly", consumer.isBrowseOnly()).add("creationTime", consumer.getCreationTime()).add("deliveringCount", consumer.getDeliveringMessages().size()); if (consumer.getFilter() != null) { obj.add("filter", consumer.getFilter().getFilterString().toString()); } return obj.build(); } @Override public Object[] getConnectors() throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.getConnectors(this.server); } checkStarted(); clearIO(); try { Collection<TransportConfiguration> connectorConfigurations = configuration.getConnectorConfigurations().values(); Object[] ret = new Object[connectorConfigurations.size()]; int i = 0; for (TransportConfiguration config : connectorConfigurations) { Object[] tc = new Object[3]; tc[0] = config.getName(); tc[1] = config.getFactoryClassName(); tc[2] = config.getParams(); ret[i++] = tc; } return ret; } finally { blockOnIO(); } } @Override public String getConnectorsAsJSON() throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.getConnectorsAsJSON(this.server); } checkStarted(); clearIO(); try { JsonArrayBuilder array = JsonLoader.createArrayBuilder(); for (TransportConfiguration config : configuration.getConnectorConfigurations().values()) { array.add(config.toJson()); } return array.build().toString(); } finally { blockOnIO(); } } @Override public void addSecuritySettings(final String addressMatch, final String sendRoles, final String consumeRoles, final String createDurableQueueRoles, final String deleteDurableQueueRoles, final String createNonDurableQueueRoles, final String deleteNonDurableQueueRoles, final String manageRoles) throws Exception { addSecuritySettings(addressMatch, sendRoles, consumeRoles, createDurableQueueRoles, deleteDurableQueueRoles, createNonDurableQueueRoles, deleteNonDurableQueueRoles, manageRoles, ""); } @Override public void addSecuritySettings(final String addressMatch, final String sendRoles, final String consumeRoles, final String createDurableQueueRoles, final String deleteDurableQueueRoles, final String createNonDurableQueueRoles, final String deleteNonDurableQueueRoles, final String manageRoles, final String browseRoles) throws Exception { addSecuritySettings(addressMatch, sendRoles, consumeRoles, createDurableQueueRoles, deleteDurableQueueRoles, createNonDurableQueueRoles, deleteNonDurableQueueRoles, manageRoles, browseRoles, "", ""); } @Override public void addSecuritySettings(final String addressMatch, final String sendRoles, final String consumeRoles, final String createDurableQueueRoles, final String deleteDurableQueueRoles, final String createNonDurableQueueRoles, final String deleteNonDurableQueueRoles, final String manageRoles, final String browseRoles, final String createAddressRoles, final String deleteAddressRoles) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.addSecuritySettings(this.server, addressMatch, sendRoles, consumeRoles, createDurableQueueRoles, deleteDurableQueueRoles, createNonDurableQueueRoles, deleteNonDurableQueueRoles, manageRoles, browseRoles, createAddressRoles, deleteAddressRoles); } checkStarted(); clearIO(); try { Set<Role> roles = SecurityFormatter.createSecurity(sendRoles, consumeRoles, createDurableQueueRoles, deleteDurableQueueRoles, createNonDurableQueueRoles, deleteNonDurableQueueRoles, manageRoles, browseRoles, createAddressRoles, deleteAddressRoles); server.getSecurityRepository().addMatch(addressMatch, roles); PersistedRoles persistedRoles = new PersistedRoles(addressMatch, sendRoles, consumeRoles, createDurableQueueRoles, deleteDurableQueueRoles, createNonDurableQueueRoles, deleteNonDurableQueueRoles, manageRoles, browseRoles, createAddressRoles, deleteAddressRoles); storageManager.storeSecurityRoles(persistedRoles); } finally { blockOnIO(); } } @Override public void removeSecuritySettings(final String addressMatch) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.removeSecuritySettings(this.server, addressMatch); } checkStarted(); clearIO(); try { server.getSecurityRepository().removeMatch(addressMatch); storageManager.deleteSecurityRoles(new SimpleString(addressMatch)); } finally { blockOnIO(); } } @Override public Object[] getRoles(final String addressMatch) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.getRoles(this.server, addressMatch); } checkStarted(); clearIO(); try { Set<Role> roles = server.getSecurityRepository().getMatch(addressMatch); Object[] objRoles = new Object[roles.size()]; int i = 0; for (Role role : roles) { objRoles[i++] = new Object[]{role.getName(), CheckType.SEND.hasRole(role), CheckType.CONSUME.hasRole(role), CheckType.CREATE_DURABLE_QUEUE.hasRole(role), CheckType.DELETE_DURABLE_QUEUE.hasRole(role), CheckType.CREATE_NON_DURABLE_QUEUE.hasRole(role), CheckType.DELETE_NON_DURABLE_QUEUE.hasRole(role), CheckType.MANAGE.hasRole(role)}; } return objRoles; } finally { blockOnIO(); } } @Override public String getRolesAsJSON(final String addressMatch) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.getRolesAsJSON(this.server, addressMatch); } checkStarted(); clearIO(); try { JsonArrayBuilder json = JsonLoader.createArrayBuilder(); Set<Role> roles = server.getSecurityRepository().getMatch(addressMatch); for (Role role : roles) { json.add(role.toJson()); } return json.build().toString(); } finally { blockOnIO(); } } @Override public String getAddressSettingsAsJSON(final String address) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.getAddressSettingsAsJSON(this.server, address); } checkStarted(); AddressSettings addressSettings = server.getAddressSettingsRepository().getMatch(address); String policy = addressSettings.getAddressFullMessagePolicy() == AddressFullMessagePolicy.PAGE ? "PAGE" : addressSettings.getAddressFullMessagePolicy() == AddressFullMessagePolicy.BLOCK ? "BLOCK" : addressSettings.getAddressFullMessagePolicy() == AddressFullMessagePolicy.DROP ? "DROP" : "FAIL"; String consumerPolicy = addressSettings.getSlowConsumerPolicy() == SlowConsumerPolicy.NOTIFY ? "NOTIFY" : "KILL"; JsonObjectBuilder settings = JsonLoader.createObjectBuilder(); if (addressSettings.getDeadLetterAddress() != null) { settings.add("DLA", addressSettings.getDeadLetterAddress().toString()); } if (addressSettings.getExpiryAddress() != null) { settings.add("expiryAddress", addressSettings.getExpiryAddress().toString()); } return settings.add("expiryDelay", addressSettings.getExpiryDelay()) .add("maxDeliveryAttempts", addressSettings.getMaxDeliveryAttempts()) .add("pageCacheMaxSize", addressSettings.getPageCacheMaxSize()) .add("maxSizeBytes", addressSettings.getMaxSizeBytes()) .add("pageSizeBytes", addressSettings.getPageSizeBytes()) .add("redeliveryDelay", addressSettings.getRedeliveryDelay()) .add("redeliveryMultiplier", addressSettings.getRedeliveryMultiplier()) .add("maxRedeliveryDelay", addressSettings.getMaxRedeliveryDelay()) .add("redistributionDelay", addressSettings.getRedistributionDelay()) .add("lastValueQueue", addressSettings.isDefaultLastValueQueue()) .add("sendToDLAOnNoRoute", addressSettings.isSendToDLAOnNoRoute()) .add("addressFullMessagePolicy", policy) .add("slowConsumerThreshold", addressSettings.getSlowConsumerThreshold()) .add("slowConsumerCheckPeriod", addressSettings.getSlowConsumerCheckPeriod()) .add("slowConsumerPolicy", consumerPolicy) .add("autoCreateJmsQueues", addressSettings.isAutoCreateJmsQueues()) .add("autoDeleteJmsQueues", addressSettings.isAutoDeleteJmsQueues()) .add("autoCreateJmsTopics", addressSettings.isAutoCreateJmsTopics()) .add("autoDeleteJmsTopics", addressSettings.isAutoDeleteJmsTopics()) .add("autoCreateQueues", addressSettings.isAutoCreateQueues()) .add("autoDeleteQueues", addressSettings.isAutoDeleteQueues()) .add("autoCreateAddresses", addressSettings.isAutoCreateAddresses()) .add("autoDeleteAddresses", addressSettings.isAutoDeleteAddresses()) .add("configDeleteQueues", addressSettings.getConfigDeleteQueues().toString()) .add("configDeleteAddresses", addressSettings.getConfigDeleteAddresses().toString()) .add("maxSizeBytesRejectThreshold", addressSettings.getMaxSizeBytesRejectThreshold()) .add("defaultLastValueKey", addressSettings.getDefaultLastValueKey() == null ? "" : addressSettings.getDefaultLastValueKey().toString()) .add("defaultNonDestructive", addressSettings.isDefaultNonDestructive()) .add("defaultExclusiveQueue", addressSettings.isDefaultExclusiveQueue()) .add("defaultGroupRebalance", addressSettings.isDefaultGroupRebalance()) .add("defaultGroupBuckets", addressSettings.getDefaultGroupBuckets()) .add("defaultGroupFirstKey", addressSettings.getDefaultGroupFirstKey() == null ? "" : addressSettings.getDefaultGroupFirstKey().toString()) .add("defaultMaxConsumers", addressSettings.getDefaultMaxConsumers()) .add("defaultPurgeOnNoConsumers", addressSettings.isDefaultPurgeOnNoConsumers()) .add("defaultConsumersBeforeDispatch", addressSettings.getDefaultConsumersBeforeDispatch()) .add("defaultDelayBeforeDispatch", addressSettings.getDefaultDelayBeforeDispatch()) .add("defaultQueueRoutingType", addressSettings.getDefaultQueueRoutingType().toString()) .add("defaultAddressRoutingType", addressSettings.getDefaultAddressRoutingType().toString()) .add("defaultConsumerWindowSize", addressSettings.getDefaultConsumerWindowSize()) .add("defaultRingSize", addressSettings.getDefaultRingSize()) .add("autoDeleteCreatedQueues", addressSettings.isAutoDeleteCreatedQueues()) .add("autoDeleteQueuesDelay", addressSettings.getAutoDeleteQueuesDelay()) .add("autoDeleteQueuesMessageCount", addressSettings.getAutoDeleteQueuesMessageCount()) .add("autoDeleteAddressesDelay", addressSettings.getAutoDeleteAddressesDelay()) .add("redeliveryCollisionAvoidanceFactor", addressSettings.getRedeliveryCollisionAvoidanceFactor()) .add("retroactiveMessageCount", addressSettings.getRetroactiveMessageCount()) .add("autoCreateDeadLetterResources", addressSettings.isAutoCreateDeadLetterResources()) .add("deadLetterQueuePrefix", addressSettings.getDeadLetterQueuePrefix().toString()) .add("deadLetterQueueSuffix", addressSettings.getDeadLetterQueueSuffix().toString()) .add("autoCreateExpiryResources", addressSettings.isAutoCreateExpiryResources()) .add("expiryQueuePrefix", addressSettings.getExpiryQueuePrefix().toString()) .add("expiryQueueSuffix", addressSettings.getExpiryQueueSuffix().toString()) .build() .toString(); } @Override public void addAddressSettings(final String address, final String DLA, final String expiryAddress, final long expiryDelay, final boolean lastValueQueue, final int deliveryAttempts, final long maxSizeBytes, final int pageSizeBytes, final int pageMaxCacheSize, final long redeliveryDelay, final double redeliveryMultiplier, final long maxRedeliveryDelay, final long redistributionDelay, final boolean sendToDLAOnNoRoute, final String addressFullMessagePolicy, final long slowConsumerThreshold, final long slowConsumerCheckPeriod, final String slowConsumerPolicy, final boolean autoCreateJmsQueues, final boolean autoDeleteJmsQueues, final boolean autoCreateJmsTopics, final boolean autoDeleteJmsTopics) throws Exception { addAddressSettings(address, DLA, expiryAddress, expiryDelay, lastValueQueue, deliveryAttempts, maxSizeBytes, pageSizeBytes, pageMaxCacheSize, redeliveryDelay, redeliveryMultiplier, maxRedeliveryDelay, redistributionDelay, sendToDLAOnNoRoute, addressFullMessagePolicy, slowConsumerThreshold, slowConsumerCheckPeriod, slowConsumerPolicy, autoCreateJmsQueues, autoDeleteJmsQueues, autoCreateJmsTopics, autoDeleteJmsTopics, AddressSettings.DEFAULT_AUTO_CREATE_QUEUES, AddressSettings.DEFAULT_AUTO_DELETE_QUEUES, AddressSettings.DEFAULT_AUTO_CREATE_ADDRESSES, AddressSettings.DEFAULT_AUTO_DELETE_ADDRESSES); } @Override public void addAddressSettings(final String address, final String DLA, final String expiryAddress, final long expiryDelay, final boolean defaultLastValueQueue, final int maxDeliveryAttempts, final long maxSizeBytes, final int pageSizeBytes, final int pageMaxCacheSize, final long redeliveryDelay, final double redeliveryMultiplier, final long maxRedeliveryDelay, final long redistributionDelay, final boolean sendToDLAOnNoRoute, final String addressFullMessagePolicy, final long slowConsumerThreshold, final long slowConsumerCheckPeriod, final String slowConsumerPolicy, final boolean autoCreateJmsQueues, final boolean autoDeleteJmsQueues, final boolean autoCreateJmsTopics, final boolean autoDeleteJmsTopics, final boolean autoCreateQueues, final boolean autoDeleteQueues, final boolean autoCreateAddresses, final boolean autoDeleteAddresses) throws Exception { addAddressSettings(address, DLA, expiryAddress, expiryDelay, defaultLastValueQueue, maxDeliveryAttempts, maxSizeBytes, pageSizeBytes, pageMaxCacheSize, redeliveryDelay, redeliveryMultiplier, maxRedeliveryDelay, redistributionDelay, sendToDLAOnNoRoute, addressFullMessagePolicy, slowConsumerThreshold, slowConsumerCheckPeriod, slowConsumerPolicy, autoCreateJmsQueues, autoDeleteJmsQueues, autoCreateJmsTopics, autoDeleteJmsTopics, autoCreateQueues, autoDeleteQueues, autoCreateAddresses, autoDeleteAddresses, AddressSettings.DEFAULT_CONFIG_DELETE_QUEUES.toString(), AddressSettings.DEFAULT_CONFIG_DELETE_ADDRESSES.toString(), AddressSettings.DEFAULT_ADDRESS_REJECT_THRESHOLD, ActiveMQDefaultConfiguration.getDefaultLastValueKey() == null ? null : ActiveMQDefaultConfiguration.getDefaultLastValueKey().toString(), ActiveMQDefaultConfiguration.getDefaultNonDestructive(), ActiveMQDefaultConfiguration.getDefaultExclusive(), ActiveMQDefaultConfiguration.getDefaultGroupRebalance(), ActiveMQDefaultConfiguration.getDefaultGroupBuckets(), ActiveMQDefaultConfiguration.getDefaultGroupFirstKey() == null ? null : ActiveMQDefaultConfiguration.getDefaultGroupFirstKey().toString(), ActiveMQDefaultConfiguration.getDefaultMaxQueueConsumers(), ActiveMQDefaultConfiguration.getDefaultPurgeOnNoConsumers(), ActiveMQDefaultConfiguration.getDefaultConsumersBeforeDispatch(), ActiveMQDefaultConfiguration.getDefaultDelayBeforeDispatch(), ActiveMQDefaultConfiguration.getDefaultRoutingType().toString(), ActiveMQDefaultConfiguration.getDefaultRoutingType().toString(), ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQDefaultConfiguration.getDefaultRingSize(), AddressSettings.DEFAULT_AUTO_DELETE_CREATED_QUEUES, AddressSettings.DEFAULT_AUTO_DELETE_QUEUES_DELAY, AddressSettings.DEFAULT_AUTO_DELETE_QUEUES_MESSAGE_COUNT, AddressSettings.DEFAULT_AUTO_DELETE_ADDRESSES_DELAY, AddressSettings.DEFAULT_REDELIVER_COLLISION_AVOIDANCE_FACTOR, ActiveMQDefaultConfiguration.getDefaultRetroactiveMessageCount()); } @Override public void addAddressSettings(final String address, final String DLA, final String expiryAddress, final long expiryDelay, final boolean defaultLastValueQueue, final int maxDeliveryAttempts, final long maxSizeBytes, final int pageSizeBytes, final int pageMaxCacheSize, final long redeliveryDelay, final double redeliveryMultiplier, final long maxRedeliveryDelay, final long redistributionDelay, final boolean sendToDLAOnNoRoute, final String addressFullMessagePolicy, final long slowConsumerThreshold, final long slowConsumerCheckPeriod, final String slowConsumerPolicy, final boolean autoCreateJmsQueues, final boolean autoDeleteJmsQueues, final boolean autoCreateJmsTopics, final boolean autoDeleteJmsTopics, final boolean autoCreateQueues, final boolean autoDeleteQueues, final boolean autoCreateAddresses, final boolean autoDeleteAddresses, final String configDeleteQueues, final String configDeleteAddresses, final long maxSizeBytesRejectThreshold, final String defaultLastValueKey, final boolean defaultNonDestructive, final boolean defaultExclusiveQueue, final boolean defaultGroupRebalance, final int defaultGroupBuckets, final String defaultGroupFirstKey, final int defaultMaxConsumers, final boolean defaultPurgeOnNoConsumers, final int defaultConsumersBeforeDispatch, final long defaultDelayBeforeDispatch, final String defaultQueueRoutingType, final String defaultAddressRoutingType, final int defaultConsumerWindowSize, final long defaultRingSize, final boolean autoDeleteCreatedQueues, final long autoDeleteQueuesDelay, final long autoDeleteQueuesMessageCount, final long autoDeleteAddressesDelay, final double redeliveryCollisionAvoidanceFactor, final long retroactiveMessageCount) throws Exception { addAddressSettings(address, DLA, expiryAddress, expiryDelay, defaultLastValueQueue, maxDeliveryAttempts, maxSizeBytes, pageSizeBytes, pageMaxCacheSize, redeliveryDelay, redeliveryMultiplier, maxRedeliveryDelay, redistributionDelay, sendToDLAOnNoRoute, addressFullMessagePolicy, slowConsumerThreshold, slowConsumerCheckPeriod, slowConsumerPolicy, autoCreateJmsQueues, autoDeleteJmsQueues, autoCreateJmsTopics, autoDeleteJmsTopics, autoCreateQueues, autoDeleteQueues, autoCreateAddresses, autoDeleteAddresses, configDeleteQueues, configDeleteAddresses, maxSizeBytesRejectThreshold, defaultLastValueKey, defaultNonDestructive, defaultExclusiveQueue, defaultGroupRebalance, defaultGroupBuckets, defaultGroupFirstKey, defaultMaxConsumers, defaultPurgeOnNoConsumers, defaultConsumersBeforeDispatch, defaultDelayBeforeDispatch, defaultQueueRoutingType, defaultAddressRoutingType, defaultConsumerWindowSize, defaultRingSize, autoDeleteCreatedQueues, autoDeleteQueuesDelay, autoDeleteQueuesMessageCount, autoDeleteAddressesDelay, redeliveryCollisionAvoidanceFactor, retroactiveMessageCount, AddressSettings.DEFAULT_AUTO_CREATE_DEAD_LETTER_RESOURCES, AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_PREFIX.toString(), AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_SUFFIX.toString(), AddressSettings.DEFAULT_AUTO_CREATE_EXPIRY_RESOURCES, AddressSettings.DEFAULT_EXPIRY_QUEUE_PREFIX.toString(), AddressSettings.DEFAULT_EXPIRY_QUEUE_SUFFIX.toString()); } @Override public void addAddressSettings(final String address, final String DLA, final String expiryAddress, final long expiryDelay, final boolean defaultLastValueQueue, final int maxDeliveryAttempts, final long maxSizeBytes, final int pageSizeBytes, final int pageMaxCacheSize, final long redeliveryDelay, final double redeliveryMultiplier, final long maxRedeliveryDelay, final long redistributionDelay, final boolean sendToDLAOnNoRoute, final String addressFullMessagePolicy, final long slowConsumerThreshold, final long slowConsumerCheckPeriod, final String slowConsumerPolicy, final boolean autoCreateJmsQueues, final boolean autoDeleteJmsQueues, final boolean autoCreateJmsTopics, final boolean autoDeleteJmsTopics, final boolean autoCreateQueues, final boolean autoDeleteQueues, final boolean autoCreateAddresses, final boolean autoDeleteAddresses, final String configDeleteQueues, final String configDeleteAddresses, final long maxSizeBytesRejectThreshold, final String defaultLastValueKey, final boolean defaultNonDestructive, final boolean defaultExclusiveQueue, final boolean defaultGroupRebalance, final int defaultGroupBuckets, final String defaultGroupFirstKey, final int defaultMaxConsumers, final boolean defaultPurgeOnNoConsumers, final int defaultConsumersBeforeDispatch, final long defaultDelayBeforeDispatch, final String defaultQueueRoutingType, final String defaultAddressRoutingType, final int defaultConsumerWindowSize, final long defaultRingSize, final boolean autoDeleteCreatedQueues, final long autoDeleteQueuesDelay, final long autoDeleteQueuesMessageCount, final long autoDeleteAddressesDelay, final double redeliveryCollisionAvoidanceFactor, final long retroactiveMessageCount, final boolean autoCreateDeadLetterResources, final String deadLetterQueuePrefix, final String deadLetterQueueSuffix, final boolean autoCreateExpiryResources, final String expiryQueuePrefix, final String expiryQueueSuffix) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.addAddressSettings(this.server, address, DLA, expiryAddress, expiryDelay, defaultLastValueQueue, maxDeliveryAttempts, maxSizeBytes, pageSizeBytes, pageMaxCacheSize, redeliveryDelay, redeliveryMultiplier, maxRedeliveryDelay, redistributionDelay, sendToDLAOnNoRoute, addressFullMessagePolicy, slowConsumerThreshold, slowConsumerCheckPeriod, slowConsumerPolicy, autoCreateJmsQueues, autoDeleteJmsQueues, autoCreateJmsTopics, autoDeleteJmsTopics, autoCreateQueues, autoDeleteQueues, autoCreateAddresses, autoDeleteAddresses, configDeleteQueues, configDeleteAddresses, maxSizeBytesRejectThreshold, defaultLastValueKey, defaultNonDestructive, defaultExclusiveQueue, defaultGroupRebalance, defaultGroupBuckets, defaultGroupFirstKey, defaultMaxConsumers, defaultPurgeOnNoConsumers, defaultConsumersBeforeDispatch, defaultDelayBeforeDispatch, defaultQueueRoutingType, defaultAddressRoutingType, defaultConsumerWindowSize, defaultRingSize, autoDeleteCreatedQueues, autoDeleteQueuesDelay, autoDeleteQueuesMessageCount, autoDeleteAddressesDelay, redeliveryCollisionAvoidanceFactor, retroactiveMessageCount, autoCreateDeadLetterResources, deadLetterQueuePrefix, deadLetterQueueSuffix, autoCreateExpiryResources, expiryQueuePrefix, expiryQueueSuffix); } checkStarted(); // JBPAPP-6334 requested this to be pageSizeBytes > maxSizeBytes if (pageSizeBytes > maxSizeBytes && maxSizeBytes > 0) { throw new IllegalStateException("pageSize has to be lower than maxSizeBytes. Invalid argument (" + pageSizeBytes + " < " + maxSizeBytes + ")"); } if (maxSizeBytes < -1) { throw new IllegalStateException("Invalid argument on maxSizeBytes"); } AddressSettings addressSettings = new AddressSettings(); addressSettings.setDeadLetterAddress(DLA == null ? null : new SimpleString(DLA)); addressSettings.setExpiryAddress(expiryAddress == null ? null : new SimpleString(expiryAddress)); addressSettings.setExpiryDelay(expiryDelay); addressSettings.setDefaultLastValueQueue(defaultLastValueQueue); addressSettings.setMaxDeliveryAttempts(maxDeliveryAttempts); addressSettings.setPageCacheMaxSize(pageMaxCacheSize); addressSettings.setMaxSizeBytes(maxSizeBytes); addressSettings.setPageSizeBytes(pageSizeBytes); addressSettings.setRedeliveryDelay(redeliveryDelay); addressSettings.setRedeliveryMultiplier(redeliveryMultiplier); addressSettings.setMaxRedeliveryDelay(maxRedeliveryDelay); addressSettings.setRedistributionDelay(redistributionDelay); addressSettings.setSendToDLAOnNoRoute(sendToDLAOnNoRoute); addressSettings.setAddressFullMessagePolicy(addressFullMessagePolicy == null ? AddressSettings.DEFAULT_ADDRESS_FULL_MESSAGE_POLICY : AddressFullMessagePolicy.valueOf(addressFullMessagePolicy.toUpperCase())); addressSettings.setSlowConsumerThreshold(slowConsumerThreshold); addressSettings.setSlowConsumerCheckPeriod(slowConsumerCheckPeriod); addressSettings.setSlowConsumerPolicy(slowConsumerPolicy == null ? AddressSettings.DEFAULT_SLOW_CONSUMER_POLICY : SlowConsumerPolicy.valueOf(slowConsumerPolicy.toUpperCase())); addressSettings.setAutoCreateJmsQueues(autoCreateJmsQueues); addressSettings.setAutoDeleteJmsQueues(autoDeleteJmsQueues); addressSettings.setAutoCreateJmsTopics(autoCreateJmsTopics); addressSettings.setAutoDeleteJmsTopics(autoDeleteJmsTopics); addressSettings.setAutoCreateQueues(autoCreateQueues); addressSettings.setAutoDeleteQueues(autoDeleteQueues); addressSettings.setAutoCreateAddresses(autoCreateAddresses); addressSettings.setAutoDeleteAddresses(autoDeleteAddresses); addressSettings.setConfigDeleteQueues(configDeleteQueues == null ? AddressSettings.DEFAULT_CONFIG_DELETE_QUEUES : DeletionPolicy.valueOf(configDeleteQueues.toUpperCase())); addressSettings.setConfigDeleteAddresses(configDeleteAddresses == null ? AddressSettings.DEFAULT_CONFIG_DELETE_ADDRESSES : DeletionPolicy.valueOf(configDeleteAddresses.toUpperCase())); addressSettings.setMaxSizeBytesRejectThreshold(maxSizeBytesRejectThreshold); addressSettings.setDefaultLastValueKey(defaultLastValueKey == null ? ActiveMQDefaultConfiguration.getDefaultLastValueKey() : new SimpleString(defaultLastValueKey)); addressSettings.setDefaultNonDestructive(defaultNonDestructive); addressSettings.setDefaultExclusiveQueue(defaultExclusiveQueue); addressSettings.setDefaultGroupRebalance(defaultGroupRebalance); addressSettings.setDefaultGroupBuckets(defaultGroupBuckets); addressSettings.setDefaultGroupFirstKey(defaultGroupFirstKey == null ? ActiveMQDefaultConfiguration.getDefaultGroupFirstKey() : new SimpleString(defaultGroupFirstKey)); addressSettings.setDefaultMaxConsumers(defaultMaxConsumers); addressSettings.setDefaultPurgeOnNoConsumers(defaultPurgeOnNoConsumers); addressSettings.setDefaultConsumersBeforeDispatch(defaultConsumersBeforeDispatch); addressSettings.setDefaultDelayBeforeDispatch(defaultDelayBeforeDispatch); addressSettings.setDefaultQueueRoutingType(defaultQueueRoutingType == null ? ActiveMQDefaultConfiguration.getDefaultRoutingType() : RoutingType.valueOf(defaultQueueRoutingType.toUpperCase())); addressSettings.setDefaultAddressRoutingType(defaultAddressRoutingType == null ? ActiveMQDefaultConfiguration.getDefaultRoutingType() : RoutingType.valueOf(defaultAddressRoutingType.toUpperCase())); addressSettings.setDefaultConsumerWindowSize(defaultConsumerWindowSize); addressSettings.setDefaultRingSize(defaultRingSize); addressSettings.setAutoDeleteCreatedQueues(autoDeleteCreatedQueues); addressSettings.setAutoDeleteQueuesDelay(autoDeleteQueuesDelay); addressSettings.setAutoDeleteQueuesMessageCount(autoDeleteQueuesMessageCount); addressSettings.setAutoDeleteAddressesDelay(autoDeleteAddressesDelay); addressSettings.setRedeliveryCollisionAvoidanceFactor(redeliveryCollisionAvoidanceFactor); addressSettings.setRetroactiveMessageCount(retroactiveMessageCount); addressSettings.setAutoCreateDeadLetterResources(autoCreateDeadLetterResources); addressSettings.setDeadLetterQueuePrefix(deadLetterQueuePrefix == null ? null : new SimpleString(deadLetterQueuePrefix)); addressSettings.setDeadLetterQueueSuffix(deadLetterQueueSuffix == null ? null : new SimpleString(deadLetterQueueSuffix)); addressSettings.setAutoCreateExpiryResources(autoCreateExpiryResources); addressSettings.setExpiryQueuePrefix(expiryQueuePrefix == null ? null : new SimpleString(expiryQueuePrefix)); addressSettings.setExpiryQueueSuffix(expiryQueueSuffix == null ? null : new SimpleString(expiryQueueSuffix)); server.getAddressSettingsRepository().addMatch(address, addressSettings); storageManager.storeAddressSetting(new PersistedAddressSetting(new SimpleString(address), addressSettings)); } @Override public void removeAddressSettings(final String addressMatch) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.removeAddressSettings(this.server, addressMatch); } checkStarted(); server.getAddressSettingsRepository().removeMatch(addressMatch); storageManager.deleteAddressSetting(new SimpleString(addressMatch)); } public void sendQueueInfoToQueue(final String queueName, final String address) throws Exception { checkStarted(); clearIO(); try { postOffice.sendQueueInfoToQueue(new SimpleString(queueName), new SimpleString(address == null ? "" : address)); GroupingHandler handler = server.getGroupingHandler(); if (handler != null) { // the group handler would miss responses if the group was requested before the reset was done // on that case we ask the groupinghandler to replay its send in case it's waiting for the information handler.resendPending(); } } finally { blockOnIO(); } } @Override public String[] getDivertNames() { if (AuditLogger.isEnabled()) { AuditLogger.getDivertNames(this.server); } checkStarted(); clearIO(); try { Object[] diverts = server.getManagementService().getResources(DivertControl.class); String[] names = new String[diverts.length]; for (int i = 0; i < diverts.length; i++) { DivertControl divert = (DivertControl) diverts[i]; names[i] = divert.getUniqueName(); } return names; } finally { blockOnIO(); } } @Override public void createDivert(final String name, final String routingName, final String address, final String forwardingAddress, final boolean exclusive, final String filterString, final String transformerClassName) throws Exception { createDivert(name, routingName, address, forwardingAddress, exclusive, filterString, transformerClassName, ActiveMQDefaultConfiguration.getDefaultDivertRoutingType()); } @Override public void createDivert(final String name, final String routingName, final String address, final String forwardingAddress, final boolean exclusive, final String filterString, final String transformerClassName, final String routingType) throws Exception { createDivert(name, routingName, address, forwardingAddress, exclusive, filterString, transformerClassName, (String) null, routingType); } @Override public void createDivert(final String name, final String routingName, final String address, final String forwardingAddress, final boolean exclusive, final String filterString, final String transformerClassName, final String transformerPropertiesAsJSON, final String routingType) throws Exception { createDivert(name, routingName, address, forwardingAddress, exclusive, filterString, transformerClassName, JsonUtil.readJsonProperties(transformerPropertiesAsJSON), routingType); } @Override public void createDivert(final String name, final String routingName, final String address, final String forwardingAddress, final boolean exclusive, final String filterString, final String transformerClassName, final Map<String, String> transformerProperties, final String routingType) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.createDivert(this.server, name, routingName, address, forwardingAddress, exclusive, filterString, transformerClassName, transformerProperties, routingType); } checkStarted(); clearIO(); try { TransformerConfiguration transformerConfiguration = transformerClassName == null ? null : new TransformerConfiguration(transformerClassName).setProperties(transformerProperties); DivertConfiguration config = new DivertConfiguration().setName(name).setRoutingName(routingName).setAddress(address).setForwardingAddress(forwardingAddress).setExclusive(exclusive).setFilterString(filterString).setTransformerConfiguration(transformerConfiguration).setRoutingType(ComponentConfigurationRoutingType.valueOf(routingType)); server.deployDivert(config); } finally { blockOnIO(); } } @Override public void destroyDivert(final String name) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.destroyDivert(this.server, name); } checkStarted(); clearIO(); try { server.destroyDivert(SimpleString.toSimpleString(name)); } finally { blockOnIO(); } } @Override public String[] getBridgeNames() { if (AuditLogger.isEnabled()) { AuditLogger.getBridgeNames(this.server); } checkStarted(); clearIO(); try { Object[] bridges = server.getManagementService().getResources(BridgeControl.class); String[] names = new String[bridges.length]; for (int i = 0; i < bridges.length; i++) { BridgeControl bridge = (BridgeControl) bridges[i]; names[i] = bridge.getName(); } return names; } finally { blockOnIO(); } } @Override public void createBridge(final String name, final String queueName, final String forwardingAddress, final String filterString, final String transformerClassName, final long retryInterval, final double retryIntervalMultiplier, final int initialConnectAttempts, final int reconnectAttempts, final boolean useDuplicateDetection, final int confirmationWindowSize, final int producerWindowSize, final long clientFailureCheckPeriod, final String staticConnectorsOrDiscoveryGroup, boolean useDiscoveryGroup, final boolean ha, final String user, final String password) throws Exception { createBridge(name, queueName, forwardingAddress, filterString, transformerClassName, (String) null, retryInterval, retryIntervalMultiplier, initialConnectAttempts, reconnectAttempts, useDuplicateDetection, confirmationWindowSize, producerWindowSize, clientFailureCheckPeriod, staticConnectorsOrDiscoveryGroup, useDiscoveryGroup, ha, user, password); } @Override public void createBridge(final String name, final String queueName, final String forwardingAddress, final String filterString, final String transformerClassName, final String transformerPropertiesAsJSON, final long retryInterval, final double retryIntervalMultiplier, final int initialConnectAttempts, final int reconnectAttempts, final boolean useDuplicateDetection, final int confirmationWindowSize, final int producerWindowSize, final long clientFailureCheckPeriod, final String staticConnectorsOrDiscoveryGroup, boolean useDiscoveryGroup, final boolean ha, final String user, final String password) throws Exception { createBridge(name, queueName, forwardingAddress, filterString, transformerClassName, JsonUtil.readJsonProperties(transformerPropertiesAsJSON), retryInterval, retryIntervalMultiplier, initialConnectAttempts, reconnectAttempts, useDuplicateDetection, confirmationWindowSize, producerWindowSize, clientFailureCheckPeriod, staticConnectorsOrDiscoveryGroup, useDiscoveryGroup, ha, user, password); } @Override public void createBridge(final String name, final String queueName, final String forwardingAddress, final String filterString, final String transformerClassName, final Map<String, String> transformerProperties, final long retryInterval, final double retryIntervalMultiplier, final int initialConnectAttempts, final int reconnectAttempts, final boolean useDuplicateDetection, final int confirmationWindowSize, final int producerWindowSize, final long clientFailureCheckPeriod, final String staticConnectorsOrDiscoveryGroup, boolean useDiscoveryGroup, final boolean ha, final String user, final String password) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.createBridge(this.server, name, queueName, forwardingAddress, filterString, transformerClassName, transformerProperties, retryInterval, retryIntervalMultiplier, initialConnectAttempts, reconnectAttempts, useDuplicateDetection, confirmationWindowSize, producerWindowSize, clientFailureCheckPeriod, staticConnectorsOrDiscoveryGroup, useDiscoveryGroup, ha, user, "****"); } checkStarted(); clearIO(); try { TransformerConfiguration transformerConfiguration = transformerClassName == null ? null : new TransformerConfiguration(transformerClassName).setProperties(transformerProperties); BridgeConfiguration config = new BridgeConfiguration().setName(name).setQueueName(queueName).setForwardingAddress(forwardingAddress).setFilterString(filterString).setTransformerConfiguration(transformerConfiguration).setClientFailureCheckPeriod(clientFailureCheckPeriod).setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryIntervalMultiplier).setInitialConnectAttempts(initialConnectAttempts).setReconnectAttempts(reconnectAttempts).setUseDuplicateDetection(useDuplicateDetection).setConfirmationWindowSize(confirmationWindowSize).setProducerWindowSize(producerWindowSize).setHA(ha).setUser(user).setPassword(password); if (useDiscoveryGroup) { config.setDiscoveryGroupName(staticConnectorsOrDiscoveryGroup); } else { config.setStaticConnectors(ListUtil.toList(staticConnectorsOrDiscoveryGroup)); } server.deployBridge(config); } finally { blockOnIO(); } } @Override public void createBridge(final String name, final String queueName, final String forwardingAddress, final String filterString, final String transformerClassName, final long retryInterval, final double retryIntervalMultiplier, final int initialConnectAttempts, final int reconnectAttempts, final boolean useDuplicateDetection, final int confirmationWindowSize, final long clientFailureCheckPeriod, final String staticConnectorsOrDiscoveryGroup, boolean useDiscoveryGroup, final boolean ha, final String user, final String password) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.createBridge(this.server, name, queueName, forwardingAddress, filterString, transformerClassName, retryInterval, retryIntervalMultiplier, initialConnectAttempts, reconnectAttempts, useDuplicateDetection, confirmationWindowSize, clientFailureCheckPeriod, staticConnectorsOrDiscoveryGroup, useDiscoveryGroup, ha, user, "****"); } checkStarted(); clearIO(); try { TransformerConfiguration transformerConfiguration = transformerClassName == null ? null : new TransformerConfiguration(transformerClassName); BridgeConfiguration config = new BridgeConfiguration().setName(name).setQueueName(queueName).setForwardingAddress(forwardingAddress).setFilterString(filterString).setTransformerConfiguration(transformerConfiguration).setClientFailureCheckPeriod(clientFailureCheckPeriod).setRetryInterval(retryInterval).setRetryIntervalMultiplier(retryIntervalMultiplier).setInitialConnectAttempts(initialConnectAttempts).setReconnectAttempts(reconnectAttempts).setUseDuplicateDetection(useDuplicateDetection).setConfirmationWindowSize(confirmationWindowSize).setHA(ha).setUser(user).setPassword(password); if (useDiscoveryGroup) { config.setDiscoveryGroupName(staticConnectorsOrDiscoveryGroup); } else { config.setStaticConnectors(ListUtil.toList(staticConnectorsOrDiscoveryGroup)); } server.deployBridge(config); } finally { blockOnIO(); } } @Override public void destroyBridge(final String name) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.destroyBridge(this.server, name); } checkStarted(); clearIO(); try { server.destroyBridge(name); } finally { blockOnIO(); } } @Override public void createConnectorService(final String name, final String factoryClass, final Map<String, Object> parameters) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.createConnectorService(this.server, name, factoryClass, parameters); } checkStarted(); clearIO(); try { final ConnectorServiceConfiguration config = new ConnectorServiceConfiguration().setName(name).setFactoryClassName(factoryClass).setParams(parameters); ConnectorServiceFactory factory = server.getServiceRegistry().getConnectorService(config); server.getConnectorsService().createService(config, factory); } finally { blockOnIO(); } } @Override public void destroyConnectorService(final String name) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.destroyConnectorService(this.server, name); } checkStarted(); clearIO(); try { server.getConnectorsService().destroyService(name); } finally { blockOnIO(); } } @Override public String[] getConnectorServices() { if (AuditLogger.isEnabled()) { AuditLogger.getConnectorServices(this.server); } checkStarted(); clearIO(); try { return server.getConnectorsService().getConnectors().keySet().toArray(new String[0]); } finally { blockOnIO(); } } @Override public void forceFailover() throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.forceFailover(this.server); } checkStarted(); clearIO(); Thread t = new Thread() { @Override public void run() { try { server.stop(true, true); } catch (Throwable e) { logger.warn(e.getMessage(), e); } } }; t.start(); } public void updateDuplicateIdCache(String address, Object[] ids) throws Exception { clearIO(); try { DuplicateIDCache duplicateIDCache = server.getPostOffice().getDuplicateIDCache(new SimpleString(address)); for (Object id : ids) { duplicateIDCache.addToCache(((String) id).getBytes(), null); } } finally { blockOnIO(); } } @Override public void scaleDown(String connector) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.scaleDown(this.server, connector); } checkStarted(); clearIO(); HAPolicy haPolicy = server.getHAPolicy(); if (haPolicy instanceof LiveOnlyPolicy) { LiveOnlyPolicy liveOnlyPolicy = (LiveOnlyPolicy) haPolicy; if (liveOnlyPolicy.getScaleDownPolicy() == null) { liveOnlyPolicy.setScaleDownPolicy(new ScaleDownPolicy()); } liveOnlyPolicy.getScaleDownPolicy().setEnabled(true); if (connector != null) { liveOnlyPolicy.getScaleDownPolicy().getConnectors().add(0, connector); } server.fail(true); } } @Override public String listNetworkTopology() throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listNetworkTopology(this.server); } checkStarted(); clearIO(); try { JsonArrayBuilder brokers = JsonLoader.createArrayBuilder(); ClusterManager clusterManager = server.getClusterManager(); if (clusterManager != null) { Set<ClusterConnection> clusterConnections = clusterManager.getClusterConnections(); for (ClusterConnection clusterConnection : clusterConnections) { Topology topology = clusterConnection.getTopology(); Collection<TopologyMemberImpl> members = topology.getMembers(); for (TopologyMemberImpl member : members) { JsonObjectBuilder obj = JsonLoader.createObjectBuilder(); TransportConfiguration live = member.getLive(); if (live != null) { obj.add("nodeID", member.getNodeId()).add("live", live.getParams().get("host") + ":" + live.getParams().get("port")); TransportConfiguration backup = member.getBackup(); if (backup != null) { obj.add("backup", backup.getParams().get("host") + ":" + backup.getParams().get("port")); } } brokers.add(obj); } } } return brokers.build().toString(); } finally { blockOnIO(); } } // NotificationEmitter implementation ---------------------------- @Override public void removeNotificationListener(final NotificationListener listener, final NotificationFilter filter, final Object handback) throws ListenerNotFoundException { if (AuditLogger.isEnabled()) { AuditLogger.removeNotificationListener(this.server, listener, filter, handback); } clearIO(); try { broadcaster.removeNotificationListener(listener, filter, handback); } finally { blockOnIO(); } } @Override public void removeNotificationListener(final NotificationListener listener) throws ListenerNotFoundException { if (AuditLogger.isEnabled()) { AuditLogger.removeNotificationListener(this.server, listener); } clearIO(); try { broadcaster.removeNotificationListener(listener); } finally { blockOnIO(); } } @Override public void addNotificationListener(final NotificationListener listener, final NotificationFilter filter, final Object handback) throws IllegalArgumentException { if (AuditLogger.isEnabled()) { AuditLogger.addNotificationListener(this.server, listener, filter, handback); } clearIO(); try { broadcaster.addNotificationListener(listener, filter, handback); } finally { blockOnIO(); } } @Override public MBeanNotificationInfo[] getNotificationInfo() { if (AuditLogger.isEnabled()) { AuditLogger.getNotificationInfo(this.server); } CoreNotificationType[] values = CoreNotificationType.values(); String[] names = new String[values.length]; for (int i = 0; i < values.length; i++) { names[i] = values[i].toString(); } return new MBeanNotificationInfo[]{new MBeanNotificationInfo(names, this.getClass().getName(), "Notifications emitted by a Core Server")}; } // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- private synchronized void setMessageCounterEnabled(final boolean enable) { if (isStarted()) { if (configuration.isMessageCounterEnabled() && !enable) { stopMessageCounters(); } else if (!configuration.isMessageCounterEnabled() && enable) { startMessageCounters(); } } configuration.setMessageCounterEnabled(enable); } private void startMessageCounters() { messageCounterManager.start(); } private void stopMessageCounters() { messageCounterManager.stop(); messageCounterManager.resetAllCounters(); messageCounterManager.resetAllCounterHistories(); } @Override public long getConnectionTTLOverride() { if (AuditLogger.isEnabled()) { AuditLogger.getConnectionTTLOverride(this.server); } return configuration.getConnectionTTLOverride(); } @Override public int getIDCacheSize() { if (AuditLogger.isEnabled()) { AuditLogger.getIDCacheSize(this.server); } return configuration.getIDCacheSize(); } @Override public String getLargeMessagesDirectory() { if (AuditLogger.isEnabled()) { AuditLogger.getLargeMessagesDirectory(this.server); } return configuration.getLargeMessagesDirectory(); } @Override public String getManagementAddress() { if (AuditLogger.isEnabled()) { AuditLogger.getManagementAddress(this.server); } return configuration.getManagementAddress().toString(); } @Override public String getNodeID() { if (AuditLogger.isEnabled()) { AuditLogger.getNodeID(this.server); } return server.getNodeID() == null ? null : server.getNodeID().toString(); } @Override public String getManagementNotificationAddress() { if (AuditLogger.isEnabled()) { AuditLogger.getManagementNotificationAddress(this.server); } return configuration.getManagementNotificationAddress().toString(); } @Override public long getMessageExpiryScanPeriod() { if (AuditLogger.isEnabled()) { AuditLogger.getMessageExpiryScanPeriod(this.server); } return configuration.getMessageExpiryScanPeriod(); } @Override public long getMessageExpiryThreadPriority() { if (AuditLogger.isEnabled()) { AuditLogger.getMessageExpiryThreadPriority(this.server); } return configuration.getMessageExpiryThreadPriority(); } @Override public long getTransactionTimeout() { if (AuditLogger.isEnabled()) { AuditLogger.getTransactionTimeout(this.server); } return configuration.getTransactionTimeout(); } @Override public long getTransactionTimeoutScanPeriod() { if (AuditLogger.isEnabled()) { AuditLogger.getTransactionTimeoutScanPeriod(this.server); } return configuration.getTransactionTimeoutScanPeriod(); } @Override public boolean isPersistDeliveryCountBeforeDelivery() { if (AuditLogger.isEnabled()) { AuditLogger.isPersistDeliveryCountBeforeDelivery(this.server); } return configuration.isPersistDeliveryCountBeforeDelivery(); } @Override public boolean isPersistIDCache() { if (AuditLogger.isEnabled()) { AuditLogger.isPersistIDCache(this.server); } return configuration.isPersistIDCache(); } @Override public boolean isWildcardRoutingEnabled() { if (AuditLogger.isEnabled()) { AuditLogger.isWildcardRoutingEnabled(this.server); } return configuration.isWildcardRoutingEnabled(); } @Override protected MBeanOperationInfo[] fillMBeanOperationInfo() { return MBeanInfoHelper.getMBeanOperationsInfo(ActiveMQServerControl.class); } @Override protected MBeanAttributeInfo[] fillMBeanAttributeInfo() { return MBeanInfoHelper.getMBeanAttributesInfo(ActiveMQServerControl.class); } private void checkStarted() { if (!server.isStarted()) { throw new IllegalStateException("Broker is not started. It can not be managed yet"); } } public String[] listTargetAddresses(final String sessionID) { ServerSession session = server.getSessionByID(sessionID); if (session != null) { return session.getTargetAddresses(); } return new String[0]; } @Override public void onNotification(org.apache.activemq.artemis.core.server.management.Notification notification) { if (!(notification.getType() instanceof CoreNotificationType)) return; CoreNotificationType type = (CoreNotificationType) notification.getType(); if (type == CoreNotificationType.SESSION_CREATED) { TypedProperties props = notification.getProperties(); /* * If the SESSION_CREATED notification is received from another node in the cluster, no broadcast call is made. * To keep the original logic to avoid calling the broadcast multiple times for the same SESSION_CREATED notification in the cluster. */ if (props.getIntProperty(ManagementHelper.HDR_DISTANCE) > 0) { return; } } this.broadcaster.sendNotification(new Notification(type.toString(), this, notifSeq.incrementAndGet(), notification.toString())); } @Override public void addUser(String username, String password, String roles, boolean plaintext) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.addUser(this.server, username, "****", roles, plaintext); } tcclInvoke(ActiveMQServerControlImpl.class.getClassLoader(), () -> internalAddUser(username, password, roles, plaintext)); } private void internalAddUser(String username, String password, String roles, boolean plaintext) throws Exception { PropertiesLoginModuleConfigurator config = getPropertiesLoginModuleConfigurator(); config.addNewUser(username, plaintext ? password : PasswordMaskingUtil.getHashProcessor().hash(password), roles.split(",")); config.save(); } private String getSecurityDomain() { return server.getSecurityManager().getDomain(); } @Override public String listUser(String username) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.listUser(this.server, username); } return (String) tcclCall(ActiveMQServerControlImpl.class.getClassLoader(), () -> internaListUser(username)); } private String internaListUser(String username) throws Exception { PropertiesLoginModuleConfigurator config = getPropertiesLoginModuleConfigurator(); Map<String, Set<String>> info = config.listUser(username); JsonArrayBuilder users = JsonLoader.createArrayBuilder(); for (Entry<String, Set<String>> entry : info.entrySet()) { JsonObjectBuilder user = JsonLoader.createObjectBuilder(); user.add("username", entry.getKey()); JsonArrayBuilder roles = JsonLoader.createArrayBuilder(); for (String role : entry.getValue()) { roles.add(role); } user.add("roles", roles); users.add(user); } return users.build().toString(); } @Override public void removeUser(String username) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.removeUser(this.server, username); } tcclInvoke(ActiveMQServerControlImpl.class.getClassLoader(), () -> internalRemoveUser(username)); } private void internalRemoveUser(String username) throws Exception { PropertiesLoginModuleConfigurator config = getPropertiesLoginModuleConfigurator(); config.removeUser(username); config.save(); } @Override public void resetUser(String username, String password, String roles, boolean plaintext) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.resetUser(this.server, username, "****", roles, plaintext); } tcclInvoke(ActiveMQServerControlImpl.class.getClassLoader(), () -> internalresetUser(username, password, roles, plaintext)); } @Override public void resetUser(String username, String password, String roles) throws Exception { resetUser(username, password, roles, true); } private void internalresetUser(String username, String password, String roles, boolean plaintext) throws Exception { PropertiesLoginModuleConfigurator config = getPropertiesLoginModuleConfigurator(); // don't hash a null password even if plaintext = false config.updateUser(username, password == null ? password : plaintext ? password : PasswordMaskingUtil.getHashProcessor().hash(password), roles == null ? null : roles.split(",")); config.save(); } private PropertiesLoginModuleConfigurator getPropertiesLoginModuleConfigurator() throws Exception { URL configurationUrl = server.getConfiguration().getConfigurationUrl(); if (configurationUrl == null) { throw ActiveMQMessageBundle.BUNDLE.failedToLocateConfigURL(); } String path = configurationUrl.getPath(); return new PropertiesLoginModuleConfigurator(getSecurityDomain(), path.substring(0, path.lastIndexOf("/"))); } }
package org.odk.collect.app.injection; import android.app.Application; import android.content.Context; import android.telephony.SmsManager; import org.odk.collect.app.dao.FormsDao; import org.odk.collect.app.dao.InstancesDao; import org.odk.collect.app.events.RxEventBus; import org.odk.collect.app.http.CollectServerClient; import org.odk.collect.app.http.HttpClientConnection; import org.odk.collect.app.http.OpenRosaHttpInterface; import org.odk.collect.app.http.mock.MockHttpClientConnection; import org.odk.collect.app.http.mock.MockHttpClientConnectionError; import org.odk.collect.app.injection.config.scopes.PerApplication; import org.odk.collect.app.tasks.sms.SmsSubmissionManager; import org.odk.collect.app.tasks.sms.contracts.SmsSubmissionManagerContract; import org.odk.collect.app.utilities.WebCredentialsUtils; import javax.inject.Named; import dagger.Module; import dagger.Provides; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Test Module used for unit testing. * Providing seemingly production dependencies because they are all * running on the Shadows of Robolectric. */ @Module public class TestModule { @Provides SmsManager provideSmsManager() { return SmsManager.getDefault(); } @Provides SmsSubmissionManagerContract provideSmsSubmissionManager(Application application) { return new SmsSubmissionManager(application); } @Provides FormsDao provideFormsDao() { FormsDao formsDao = mock(FormsDao.class); when(formsDao.isFormEncrypted(anyString(), anyString())).thenReturn(false); return formsDao; } @Provides InstancesDao provideInstancesDao() { return mock(InstancesDao.class); } @Provides Context context(Application application) { return application; } @PerApplication @Provides RxEventBus provideRxEventBus() { return new RxEventBus(); } @Provides MockHttpClientConnection provideMockHttpClientConnection() { return new MockHttpClientConnection(); } @Provides MockHttpClientConnectionError provideMockHttpClientConnectionError() { return new MockHttpClientConnectionError(); } @Provides @Named("StubbedData") CollectServerClient provideTestCollectServerClient(MockHttpClientConnection httpClientConnection) { return new CollectServerClient(httpClientConnection, new WebCredentialsUtils()); } @Provides @Named("NullGet") CollectServerClient provideTestCollectServerClientError(MockHttpClientConnectionError httpClientConnection) { return new CollectServerClient(httpClientConnection, new WebCredentialsUtils()); } @Provides public OpenRosaHttpInterface provideHttpInterface() { return new HttpClientConnection(); } @Provides public WebCredentialsUtils provideWebCredentials() { return new WebCredentialsUtils(); } }
package me.ionar.salhack.managers; import java.io.File; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import me.ionar.salhack.SalHackMod; import me.ionar.salhack.main.SalHack; import me.ionar.salhack.module.Module; import me.ionar.salhack.module.Module.ModuleType; import me.ionar.salhack.module.Value; import me.ionar.salhack.module.combat.*; import me.ionar.salhack.module.exploit.*; import me.ionar.salhack.module.misc.*; import me.ionar.salhack.module.movement.*; import me.ionar.salhack.module.render.*; import me.ionar.salhack.module.schematica.*; import me.ionar.salhack.module.ui.*; import me.ionar.salhack.module.world.*; import me.ionar.salhack.preset.Preset; import me.ionar.salhack.util.ReflectionUtil; import me.ionar.salhack.util.render.RenderUtil; import net.minecraft.client.gui.GuiScreen; public class ModuleManager { public static ModuleManager Get() { return SalHack.GetModuleManager(); } public ModuleManager() { } public ArrayList<Module> Mods = new ArrayList<Module>(); private ArrayList<Module> ArrayListAnimations = new ArrayList<Module>(); private KeybindsModule Keybinds = null; public void Init() { /// Combat Add(new AimbotModule()); Add(new AntiBots()); Add(new AntiCityBossModule()); Add(new Auto32kModule()); Add(new AutoArmorModule()); Add(new AutoCityModule()); Add(new AutoCrystalModule()); Add(new AutoCrystalRewrite()); Add(new AutoTotemModule()); Add(new AutoTrap()); Add(new AutoTrapFeet()); Add(new BowSpamModule()); Add(new CriticalsModule()); Add(new HoleFillerModule()); Add(new KillAuraModule()); Add(new OffhandModule()); Add(new ReachModule()); Add(new SelfTrapModule()); Add(new SurroundModule()); Add(new VelocityModule()); /// Exploit Add(new AntiHungerModule()); Add(new CoordTPExploitModule()); Add(new CrashExploitModule()); Add(new EntityDesyncModule()); Add(new LiquidInteractModule()); Add(new MountBypassModule()); Add(new NoMiningTrace()); Add(new NewChunksModule()); Add(new PacketCancellerModule()); Add(new PacketFlyModule()); Add(new PortalGodModeModule()); Add(new SwingModule()); /// Misc Add(new AntiAFKModule()); Add(new AutoBonemealModule()); Add(new AutoEatModule()); Add(new AutoDyeModule()); Add(new AutoFarmlandModule()); Add(new AutoMendArmorModule()); Add(new AutoMountModule()); Add(new AutoReconnectModule()); Add(new AutoShearModule()); Add(new AutoShovelPathModule()); Add(new AutoSignModule()); Add(new AutoTameModule()); Add(new AutoTendModule()); Add(new BuildHeightModule()); Add(new ChatModificationsModule()); Add(new ChatNotifierModule()); Add(new ChestStealerModule()); Add(new ChestSwapModule()); Add(new DiscordRPCModule()); Add(new FakePlayer()); Add(new FriendsModule()); Add(new GlobalLocationModule()); Add(new HotbarCacheModule()); Add(new MiddleClickFriendsModule()); Add(new RetardChatModule()); Add(new StopWatchModule()); Add(new TotemPopNotifierModule()); Add(new VisualRangeModule()); Add(new XCarryModule()); /// Movement Add(new AntiLevitationModule()); Add(new AutoWalkModule()); Add(new BlinkModule()); Add(new ElytraFlyModule()); Add(new EntityControlModule()); Add(new FlightModule()); Add(new NoFallModule()); Add(new NoRotateModule()); Add(new NoSlowModule()); Add(new JesusModule()); Add(new SafeWalkModule()); Add(new SneakModule()); Add(new SpeedModule()); Add(new SprintModule()); Add(new StepModule()); Add(new YawModule()); /// Render Add(new AntiFog()); Add(new BlockHighlightModule()); Add(new BreakHighlightModule()); Add(new BrightnessModule()); Add(new ChunkAnimator()); Add(new CityESPModule()); Add(new ContainerPreviewModule()); Add(new EntityESPModule()); Add(new FarmESPModule()); Add(new FreecamModule()); Add(new HandProgressModule()); Add(new HoleESPModule()); Add(new NametagsModule()); Add(new NoBobModule()); Add(new NoRenderModule()); Add(new ShulkerPreviewModule()); Add(new SkeletonModule()); Add(new StorageESPModule()); Add(new TracersModule()); Add(new TrajectoriesModule()); Add(new ViewClipModule()); Add(new VoidESPModule()); Add(new WaypointsModule()); /// UI Add(new ColorsModule()); Add(new ConsoleModule()); Add(new ClickGuiModule()); Add(new HudEditorModule()); Add(new HudModule()); Add(Keybinds = new KeybindsModule()); Add(new ReliantChatModule()); /// World Add(new AutoBuilderModule()); Add(new AutoNameTagModule()); Add(new AutoToolModule()); Add(new AutoTunnelModule()); Add(new AutoWitherModule()); Add(new EnderChestFarmer()); Add(new FastPlaceModule()); Add(new LawnmowerModule()); Add(new NoGlitchBlocksModule()); Add(new NoWeatherModule()); Add(new NukerModule()); Add(new ScaffoldModule()); Add(new SpeedyGonzales()); Add(new StashFinderModule()); Add(new StashLoggerModule()); Add(new TimerModule()); Add(new TorchAnnihilatorModule()); /// Schematica Add(new PrinterModule()); Add(new PrinterBypassModule()); LoadExternalModules(); Mods.sort((p_Mod1, p_Mod2) -> p_Mod1.getDisplayName().compareTo(p_Mod2.getDisplayName())); final Preset preset = PresetsManager.Get().getActivePreset(); Mods.forEach(mod -> { preset.initValuesForMod(mod); }); Mods.forEach(mod -> { mod.init(); }); } public void Add(Module mod) { try { for (Field field : mod.getClass().getDeclaredFields()) { if (Value.class.isAssignableFrom(field.getType())) { if (!field.isAccessible()) { field.setAccessible(true); } final Value val = (Value) field.get(mod); val.InitalizeMod(mod); mod.getValueList().add(val); } } Mods.add(mod); } catch (Exception e) { e.printStackTrace(); } } public final List<Module> GetModuleList(ModuleType p_Type) { List<Module> list = new ArrayList<>(); for (Module module : Mods) { if (module.getType().equals(p_Type)) { list.add(module); } } // Organize alphabetically list.sort(Comparator.comparing(Module::getDisplayName)); return list; } public final List<Module> GetModuleList() { return Mods; } public void OnKeyPress(String string) { if (string == null || string.isEmpty() || string.equalsIgnoreCase("NONE")) return; Mods.forEach(p_Mod -> { if (p_Mod.IsKeyPressed(string)) { p_Mod.toggle(); } }); } public Module GetMod(Class p_Class) { /*Mods.forEach(p_Mod -> { if (p_Mod.getClass() == p_Class) return p_Mod; });*/ for (Module l_Mod : Mods) { if (l_Mod.getClass() == p_Class) return l_Mod; } SalHackMod.log.error("Could not find the class " + p_Class.getName() + " in Mods list"); return null; } public Module GetModLike(String p_String) { for (Module l_Mod : Mods) { if (l_Mod.GetArrayListDisplayName().toLowerCase().startsWith(p_String.toLowerCase())) return l_Mod; } return null; } public void OnModEnable(Module p_Mod) { ArrayListAnimations.remove(p_Mod); ArrayListAnimations.add(p_Mod); final Comparator<Module> comparator = (first, second) -> { final String firstName = first.GetFullArrayListDisplayName(); final String secondName = second.GetFullArrayListDisplayName(); final float dif = RenderUtil.getStringWidth(secondName) - RenderUtil.getStringWidth(firstName); return dif != 0 ? (int) dif : secondName.compareTo(firstName); }; ArrayListAnimations = (ArrayList<Module>) ArrayListAnimations.stream() .sorted(comparator) .collect(Collectors.toList()); } public void Update() { if (ArrayListAnimations.isEmpty()) return; Module l_Mod = ArrayListAnimations.get(0); if ((l_Mod.RemainingXAnimation -= (RenderUtil.getStringWidth(l_Mod.GetFullArrayListDisplayName()) / 10)) <= 0) { ArrayListAnimations.remove(l_Mod); l_Mod.RemainingXAnimation = 0; } } public boolean IgnoreStrictKeybinds() { if (GuiScreen.isAltKeyDown() && !Keybinds.Alt.getValue()) return true; if (GuiScreen.isCtrlKeyDown() && !Keybinds.Ctrl.getValue()) return true; if (GuiScreen.isShiftKeyDown() && !Keybinds.Shift.getValue()) return true; return false; } public void LoadExternalModules() { // from seppuku try { final File dir = new File("SalHack/CustomMods"); for (Class newClass : ReflectionUtil.getClassesEx(dir.getPath())) { if (newClass == null) continue; // if we have found a class and the class inherits "Module" if (Module.class.isAssignableFrom(newClass)) { //create a new instance of the class final Module module = (Module) newClass.newInstance(); if (module != null) { // initialize the modules Add(module); } } } } catch (Exception e) { e.printStackTrace(); } } }
class Solution { public void wallsAndGates(int[][] rooms) { int EMPTY = Integer.MAX_VALUE; int GATE = 0; List<int[]> DIRECTIONS = Arrays.asList( new int[] { 1, 0}, new int[] {-1, 0}, new int[] { 0, 1}, new int[] { 0, -1} ); int rows = rooms.length; if (0 == rows) { return; } int cols = rooms[0].length; Queue<int[]> bfs = new LinkedList<>(); for (int row = 0; rows > row; ++row) { for (int col = 0; cols > col; ++col) { if (GATE == rooms[row][col]) { bfs.add(new int[] { row, col }); } } } while (!bfs.isEmpty()) { int[] point = bfs.poll(); int row = point[0]; int col = point[1]; for (int[] direction : DIRECTIONS) { int newRow = row + direction[0]; int newCol = col + direction[1]; if (0 > newRow || 0 > newCol || rows <= newRow || cols <= newCol || EMPTY != rooms[newRow][newCol]) { continue; } rooms[newRow][newCol] = 1 + rooms[row][col]; bfs.add(new int[] { newRow, newCol }); } } } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.opensearch.model.v20171225; import com.aliyuncs.RoaAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.opensearch.Endpoint; /** * @author auto create * @version */ public class PushUserAnalyzerEntriesRequest extends RoaAcsRequest<PushUserAnalyzerEntriesResponse> { private String name; public PushUserAnalyzerEntriesRequest() { super("OpenSearch", "2017-12-25", "PushUserAnalyzerEntries", "opensearch"); setUriPattern("/v4/openapi/user-analyzers/[name]/entries/actions/bulk"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public String getName() { return this.name; } public void setName(String name) { this.name = name; if(name != null){ putPathParameter("name", name); } } @Override public Class<PushUserAnalyzerEntriesResponse> getResponseClass() { return PushUserAnalyzerEntriesResponse.class; } }
package com.c2b.ethWallet.util; import java.util.regex.Pattern; /** * 校验器:利用正则表达式校验邮箱、手机号等 * * @author zhangchunming * */ public class Validator { /** * 正则表达式:验证用户名 */ public static final String REGEX_USERNAME = "^[a-zA-Z]\\w{5,17}$"; /** * 正则表达式:验证密码 */ public static final String REGEX_PASSWORD = "^[a-zA-Z0-9]{6,16}$"; /** * 正则表达式:验证密码 */ public static final String REGEX_PASSWORD_LETTER_NUMBER = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$"; /** * 正则表达式:验证账号 */ public static final String REGEX_ACCOUNT_LETTER_NUMBER = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{1,}$"; /** * 正则表达式:验证手机号 */ // public static final String REGEX_MOBILE = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$"; public static final String REGEX_MOBILE = "^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(14[0-9]{1}))+\\d{8})$"; public static final String REGEX_PHONE_STR = "^(1\\d{10}(,)?)+$"; /** * 正则表达式:验证邮箱 */ public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; /** * 正则表达式:验证汉字 */ public static final String REGEX_CHINESE = "^[\u4e00-\u9fa5],{0,}$"; /** * 正则表达式:验证身份证 */ public static final String REGEX_ID_CARD = "(^\\d{18}$)|(^\\d{15}$)"; /** * 正则表达式:验证URL */ public static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?"; /** * 正则表达式:验证IP地址 */ public static final String REGEX_IP_ADDR = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)"; /** * 正则表达式:验证正整数1-6位 */ public static final String REGEX_NUMBER6 = "^[1-9]\\d{5}$"; /** * 正则表达式:验证正整数6位 */ public static final String REGEX_6NUMBER = "^[0-9]{6}$"; /** * 正则表达式:验证正整数最高7位 */ public static final String REGEX_NUMBER_MAX7 = "^[1-9]\\d{0,6}$"; /** * 正则表达式:验证整数 */ public static final String REGEX_INTEGER = "^[0-9]+$"; /** * 正则表达式:验证金额,最多保留4位小数 */ public static final String REGEX_MONEY4 = "^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,4})?$"; /** * 正则表达式:验证金额,最多保留3位小数 */ public static final String REGEX_MONEY3 = "^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,3})?$"; /** * 正则表达式:验证金额,最多保留2位小数 */ public static final String REGEX_MONEY2 = "^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"; /** * 正则表达式:验证金额 */ public static final String REGEX_MONEY = "^([1-9]{1}\\d*)$"; /** * 校验用户名 * * @param username * @return 校验通过返回true,否则返回false */ public static boolean isUsername(String username) { return Pattern.matches(REGEX_USERNAME, username); } /** * 校验密码 * * @param password * @return 校验通过返回true,否则返回false */ public static boolean isPassword(String password) { return Pattern.matches(REGEX_PASSWORD, password); } /** * 校验密码(由字母和数字组成) * @param password * @return 校验通过返回true,否则返回false */ public static boolean isPasswordByLetterAndNum(String password) { return Pattern.matches(REGEX_PASSWORD_LETTER_NUMBER, password); } /** * @describe:校验账号是否由字母和数字组成 * @author: zhangchunming * @date: 2017年3月6日下午5:17:45 * @param account * @return: boolean */ public static boolean isAccountByLetterAndNum(String account) { return Pattern.matches(REGEX_ACCOUNT_LETTER_NUMBER, account); } /** * 校验手机号 * @param mobile * @return 校验通过返回true,否则返回false */ public static boolean isMobile(String mobile) { return Pattern.matches(REGEX_MOBILE, mobile); } /** * @describe:校验手机号,多个手机号‘,’隔开,需与isMobile配合使用 * @author: zhangchunming * @date: 2016年11月23日下午8:06:29 * @param phoneStr * @return: boolean */ public static boolean isPhoneStr(String phoneStr) { return Pattern.matches(REGEX_PHONE_STR, phoneStr); } /** * 校验邮箱 * * @param email * @return 校验通过返回true,否则返回false */ public static boolean isEmail(String email) { return Pattern.matches(REGEX_EMAIL, email); } /** * 校验汉字 * * @param chinese * @return 校验通过返回true,否则返回false */ public static boolean isChinese(String chinese) { return Pattern.matches(REGEX_CHINESE, chinese); } /** * 校验身份证 * * @param idCard * @return 校验通过返回true,否则返回false */ public static boolean isIDCard(String idCard) { return Pattern.matches(REGEX_ID_CARD, idCard); } /** * 校验URL * * @param url * @return 校验通过返回true,否则返回false */ public static boolean isUrl(String url) { return Pattern.matches(REGEX_URL, url); } /** * 校验IP地址 * * @param ipAddr * @return */ public static boolean isIPAddr(String ipAddr) { return Pattern.matches(REGEX_IP_ADDR, ipAddr); } /** * @describe:校验1-6位正整数 * @param str * @return: boolean */ public static boolean isNumber6(String str) { return Pattern.matches(REGEX_NUMBER6, str); } /** * @describe:校验6位正整数 * @param str * @return: boolean */ public static boolean is6Number(String str) { return Pattern.matches(REGEX_6NUMBER, str); } /** * @describe:最大7位正整数 * @author: zhangchunming * @date: 2016年9月20日下午9:40:37 * @param str * @return: boolean */ public static boolean isNumberMax7(String str) { return Pattern.matches(REGEX_NUMBER_MAX7, str); } /** * @describe:校验整数 * @param str * @return: boolean */ public static boolean isInteger(String str) { return Pattern.matches(REGEX_INTEGER, str); } /** * @describe:校验金额,最多可以保留四位小数 * @author: zhangchunming * @date: 2016年10月8日下午4:39:24 * @param str * @return: boolean */ public static boolean isMoney4(String str) { return Pattern.matches(REGEX_MONEY4, str); } /** * @describe:校验金额,最多可以保留三位小数 * @author: zhangchunming * @date: 2016年10月8日下午4:39:24 * @param str * @return: boolean */ public static boolean isMoney3(String str) { return Pattern.matches(REGEX_MONEY3, str); } /** * @describe:校验金额,最多可以保留2位小数 * @author: zhangchunming * @date: 2017年1月6日下午18:39:24 * @param str * @return: boolean */ public static boolean isMoney2(String str) { return Pattern.matches(REGEX_MONEY2, str); } /** * @describe:校验金额 * @author: zhangchunming * @date: 2016年11月1日下午4:13:42 * @param str * @return: boolean */ public static boolean isMoney(String str) { return Pattern.matches(REGEX_MONEY, str); } /**| * @describe:密码6-16位数,由数字,字母,特殊符号组成 * @author: zhangchunming * @date: 2016年10月24日下午4:02:33 * @param password * @return: boolean */ public static boolean isPassword2(String str) { boolean is=true; //去除前后空格 str=str.replaceAll("(^\\s*)|(\\s*$)",""); //位数不对,设置为false if(str.length()<6 || str.length()>16){ is=false; }; //全是数字 String sz="^[0-9]{1,}$"; //全是字母 String zm="^[a-zA-Z]{1,}$"; //全是特殊字符; String ts="^[`~!@#\\$%\\^\\&\\*\\(\\)_\\+<>\\?:\"\\{\\},\\.\\\\/\\;'\\[\\]]{1,}$"; if(Pattern.matches(sz,str)){ is=false; }; if(Pattern.matches(zm,str)){ is=false; }; if(Pattern.matches(ts,str)){ is=false; }; return is; } public static void main(String[] args) { /* String username = "fdsdfsdj"; System.out.println(Validator.isUsername(username)); System.out.println(Validator.isChinese(username)); String str = "10000000"; System.out.println(Validator.isNumberMax7(str));*/ // String phone = "13300100100"; // System.out.println(Validator.isMobile(phone));//111107 // System.out.println(Validator.is6Number("111102")); System.out.println(Validator.isAccountByLetterAndNum("1c")); /* String money = "120.0123"; System.out.println(Validator.isMoney4(money)); String password = " alkg "; password=password.replaceAll("(^\\s*)|(\\s*$)","");*/ } }
package io.vertx.test.codegen.testapi; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import java.util.List; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ @VertxGen public interface InterfaceParameterizedByParameterizedTypeArgMethodOverride<T> extends GenericAbstractInterface<GenericInterface<T>> { @Override GenericInterface<T> foo(); @Override List<GenericInterface<T>> bar(); @Override void juu(Handler<AsyncResult<GenericInterface<T>>> handler); @Override void daa(Handler<GenericInterface<T>> handler); @Override void collargol(GenericInterface<T> t); @Override void selfArg(GenericAbstractInterface<GenericInterface<T>> self); }
// Copyright (c) YugaByte, Inc. package com.yugabyte.yw.commissioner.tasks; import static com.yugabyte.yw.common.AssertHelper.assertJsonEqual; import static com.yugabyte.yw.common.ModelFactory.createUniverse; import static com.yugabyte.yw.models.TaskInfo.State.Failure; import static com.yugabyte.yw.models.TaskInfo.State.Success; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.yugabyte.yw.commissioner.tasks.params.NodeTaskParams; import com.yugabyte.yw.common.ApiUtils; import com.yugabyte.yw.common.ModelFactory; import com.yugabyte.yw.common.ShellResponse; import com.yugabyte.yw.forms.UniverseDefinitionTaskParams; import com.yugabyte.yw.models.AvailabilityZone; import com.yugabyte.yw.models.Customer; import com.yugabyte.yw.models.Region; import com.yugabyte.yw.models.TaskInfo; import com.yugabyte.yw.models.Universe; import com.yugabyte.yw.models.helpers.TaskType; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import org.yb.client.ChangeMasterClusterConfigResponse; import org.yb.client.GetLoadMovePercentResponse; import org.yb.client.GetMasterClusterConfigResponse; import org.yb.client.YBClient; import org.yb.master.CatalogEntityInfo; import play.libs.Json; @RunWith(MockitoJUnitRunner.class) public class StopNodeInUniverseTest extends CommissionerBaseTest { private Universe defaultUniverse; @Override @Before public void setUp() { super.setUp(); Region region = Region.create(defaultProvider, "region-1", "Region 1", "yb-image-1"); AvailabilityZone.createOrThrow(region, "az-1", "AZ 1", "subnet-1"); // create default universe UniverseDefinitionTaskParams.UserIntent userIntent = new UniverseDefinitionTaskParams.UserIntent(); userIntent.numNodes = 3; userIntent.ybSoftwareVersion = "yb-version"; userIntent.accessKeyCode = "demo-access"; userIntent.regionList = ImmutableList.of(region.uuid); defaultUniverse = createUniverse(defaultCustomer.getCustomerId()); Universe.saveDetails( defaultUniverse.universeUUID, ApiUtils.mockUniverseUpdater(userIntent, true /* setMasters */)); ShellResponse dummyShellResponse = new ShellResponse(); dummyShellResponse.message = "true"; when(mockNodeManager.nodeCommand(any(), any())).thenReturn(dummyShellResponse); YBClient mockClient = mock(YBClient.class); try { doNothing().when(mockClient).waitForMasterLeader(anyLong()); } catch (Exception e) { } CatalogEntityInfo.SysClusterConfigEntryPB.Builder configBuilder = CatalogEntityInfo.SysClusterConfigEntryPB.newBuilder().setVersion(1); GetMasterClusterConfigResponse mockConfigResponse = new GetMasterClusterConfigResponse(1111, "", configBuilder.build(), null); ChangeMasterClusterConfigResponse mockMasterChangeConfigResponse = new ChangeMasterClusterConfigResponse(1112, "", null); GetLoadMovePercentResponse mockGetLoadMovePercentResponse = new GetLoadMovePercentResponse(0, "", 100.0, 0, 0, null); try { when(mockYBClient.getClient(any(), any())).thenReturn(mockClient); when(mockClient.getMasterClusterConfig()).thenReturn(mockConfigResponse); when(mockClient.changeMasterClusterConfig(any())).thenReturn(mockMasterChangeConfigResponse); when(mockClient.getLeaderBlacklistCompletion()).thenReturn(mockGetLoadMovePercentResponse); } catch (Exception e) { } } private TaskInfo submitTask(NodeTaskParams taskParams, String nodeName) { taskParams.expectedUniverseVersion = 2; taskParams.nodeName = nodeName; try { UUID taskUUID = commissioner.submit(TaskType.StopNodeInUniverse, taskParams); return waitForTask(taskUUID); } catch (InterruptedException e) { assertNull(e.getMessage()); } return null; } private static final List<TaskType> STOP_NODE_TASK_SEQUENCE = ImmutableList.of( TaskType.ModifyBlackList, TaskType.SetNodeState, TaskType.ModifyBlackList, TaskType.WaitForLeaderBlacklistCompletion, TaskType.AnsibleClusterServerCtl, TaskType.ModifyBlackList, TaskType.UpdateNodeProcess, TaskType.SetNodeState, TaskType.UniverseUpdateSucceeded, TaskType.ModifyBlackList); private static final List<JsonNode> STOP_NODE_TASK_EXPECTED_RESULTS = ImmutableList.of( Json.toJson(ImmutableMap.of()), Json.toJson(ImmutableMap.of("state", "Stopping")), Json.toJson(ImmutableMap.of()), Json.toJson(ImmutableMap.of()), Json.toJson(ImmutableMap.of("process", "tserver", "command", "stop")), Json.toJson(ImmutableMap.of()), Json.toJson(ImmutableMap.of("processType", "TSERVER", "isAdd", false)), Json.toJson(ImmutableMap.of("state", "Stopped")), Json.toJson(ImmutableMap.of()), Json.toJson(ImmutableMap.of())); private static final List<TaskType> STOP_NODE_TASK_SEQUENCE_MASTER = ImmutableList.of( TaskType.ModifyBlackList, TaskType.SetNodeState, TaskType.ModifyBlackList, TaskType.WaitForLeaderBlacklistCompletion, TaskType.AnsibleClusterServerCtl, TaskType.ModifyBlackList, TaskType.AnsibleClusterServerCtl, TaskType.WaitForMasterLeader, TaskType.UpdateNodeProcess, TaskType.ChangeMasterConfig, TaskType.UpdateNodeProcess, TaskType.SetNodeState, TaskType.UniverseUpdateSucceeded, TaskType.ModifyBlackList); private static final List<JsonNode> STOP_NODE_TASK_SEQUENCE_MASTER_RESULTS = ImmutableList.of( Json.toJson(ImmutableMap.of()), Json.toJson(ImmutableMap.of("state", "Stopping")), Json.toJson(ImmutableMap.of()), Json.toJson(ImmutableMap.of()), Json.toJson(ImmutableMap.of("process", "tserver", "command", "stop")), Json.toJson(ImmutableMap.of()), Json.toJson(ImmutableMap.of("process", "master", "command", "stop")), Json.toJson(ImmutableMap.of()), Json.toJson(ImmutableMap.of("processType", "TSERVER", "isAdd", false)), Json.toJson(ImmutableMap.of()), Json.toJson(ImmutableMap.of("processType", "MASTER", "isAdd", false)), Json.toJson(ImmutableMap.of("state", "Stopped")), Json.toJson(ImmutableMap.of()), Json.toJson(ImmutableMap.of())); private void assertStopNodeSequence( Map<Integer, List<TaskInfo>> subTasksByPosition, boolean isMaster) { int position = 0; if (isMaster) { for (TaskType taskType : STOP_NODE_TASK_SEQUENCE_MASTER) { List<TaskInfo> tasks = subTasksByPosition.get(position); assertEquals(1, tasks.size()); assertEquals(taskType, tasks.get(0).getTaskType()); JsonNode expectedResults = STOP_NODE_TASK_SEQUENCE_MASTER_RESULTS.get(position); List<JsonNode> taskDetails = tasks.stream().map(TaskInfo::getTaskDetails).collect(Collectors.toList()); assertJsonEqual(expectedResults, taskDetails.get(0)); position++; } } else { for (TaskType taskType : STOP_NODE_TASK_SEQUENCE) { List<TaskInfo> tasks = subTasksByPosition.get(position); assertEquals(1, tasks.size()); assertEquals(taskType, tasks.get(0).getTaskType()); JsonNode expectedResults = STOP_NODE_TASK_EXPECTED_RESULTS.get(position); List<JsonNode> taskDetails = tasks.stream().map(TaskInfo::getTaskDetails).collect(Collectors.toList()); assertJsonEqual(expectedResults, taskDetails.get(0)); position++; } } } @Test public void testStopMasterNode() { NodeTaskParams taskParams = new NodeTaskParams(); taskParams.universeUUID = defaultUniverse.universeUUID; TaskInfo taskInfo = submitTask(taskParams, "host-n1"); assertEquals(Success, taskInfo.getTaskState()); verify(mockNodeManager, times(3)).nodeCommand(any(), any()); List<TaskInfo> subTasks = taskInfo.getSubTasks(); Map<Integer, List<TaskInfo>> subTasksByPosition = subTasks.stream().collect(Collectors.groupingBy(TaskInfo::getPosition)); assertEquals(subTasksByPosition.size(), STOP_NODE_TASK_SEQUENCE_MASTER.size()); assertStopNodeSequence(subTasksByPosition, true); } @Test public void testStopNonMasterNode() { NodeTaskParams taskParams = new NodeTaskParams(); Customer customer = ModelFactory.testCustomer("tc2", "Test Customer 2"); Universe universe = createUniverse(customer.getCustomerId()); UniverseDefinitionTaskParams.UserIntent userIntent = new UniverseDefinitionTaskParams.UserIntent(); userIntent.numNodes = 5; userIntent.replicationFactor = 3; universe = Universe.saveDetails( universe.universeUUID, ApiUtils.mockUniverseUpdater(userIntent, true /* setMasters */)); taskParams.universeUUID = universe.universeUUID; TaskInfo taskInfo = submitTask(taskParams, "host-n4"); assertEquals(Success, taskInfo.getTaskState()); verify(mockNodeManager, times(2)).nodeCommand(any(), any()); List<TaskInfo> subTasks = taskInfo.getSubTasks(); Map<Integer, List<TaskInfo>> subTasksByPosition = subTasks.stream().collect(Collectors.groupingBy(TaskInfo::getPosition)); assertEquals(subTasksByPosition.size(), STOP_NODE_TASK_SEQUENCE.size()); assertStopNodeSequence(subTasksByPosition, false); } @Test public void testStopUnknownNode() { NodeTaskParams taskParams = new NodeTaskParams(); taskParams.universeUUID = defaultUniverse.universeUUID; TaskInfo taskInfo = submitTask(taskParams, "host-n9"); verify(mockNodeManager, times(0)).nodeCommand(any(), any()); assertEquals(Failure, taskInfo.getTaskState()); } }
/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package leap.lang.asm.util; import java.io.FileInputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import leap.lang.asm.Attribute; import leap.lang.asm.ClassReader; import leap.lang.asm.Handle; import leap.lang.asm.Label; import leap.lang.asm.Opcodes; import leap.lang.asm.Type; import leap.lang.asm.TypePath; /** * A {@link Printer} that prints the ASM code to generate the classes if visits. * * @author Eric Bruneton */ public class ASMifier1 extends Printer { /** * The name of the visitor variable in the produced code. */ protected final String name; /** * Identifier of the annotation visitor variable in the produced code. */ protected final int id; /** * The label names. This map associates String values to Label keys. It is * used only in ASMifierMethodVisitor. */ protected Map<Label, String> labelNames; /** * Pseudo access flag used to distinguish class access flags. */ private static final int ACCESS_CLASS = 262144; /** * Pseudo access flag used to distinguish field access flags. */ private static final int ACCESS_FIELD = 524288; /** * Pseudo access flag used to distinguish inner class flags. */ private static final int ACCESS_INNER = 1048576; /** * Constructs a new {@link ASMifier1}. <i>Subclasses must not use this * constructor</i>. Instead, they must use the * {@link #ASMifier(int, String, int)} version. * * @throws IllegalStateException * If a subclass calls this constructor. */ public ASMifier1() { this(Opcodes.ASM5, "cw", 0); if (getClass() != ASMifier1.class) { throw new IllegalStateException(); } } /** * Constructs a new {@link ASMifier1}. * * @param api * the ASM API version implemented by this class. Must be one of * {@link Opcodes#ASM4} or {@link Opcodes#ASM5}. * @param name * the name of the visitor variable in the produced code. * @param id * identifier of the annotation visitor variable in the produced * code. */ protected ASMifier1(final int api, final String name, final int id) { super(api); this.name = name; this.id = id; } /** * Prints the ASM source code to generate the given class to the standard * output. * <p> * Usage: ASMifier [-debug] &lt;binary class name or class file name&gt; * * @param args * the command line arguments. * * @throws Exception * if the class cannot be found, or if an IO exception occurs. */ public static void main(final String[] args) throws Exception { int i = 0; int flags = ClassReader.SKIP_DEBUG; boolean ok = true; if (args.length < 1 || args.length > 2) { ok = false; } if (ok && "-debug".equals(args[0])) { i = 1; flags = 0; if (args.length != 2) { ok = false; } } if (!ok) { System.err .println("Prints the ASM code to generate the given class."); System.err.println("Usage: ASMifier [-debug] " + "<fully qualified class name or class file name>"); return; } ClassReader cr; if (args[i].endsWith(".class") || args[i].indexOf('\\') > -1 || args[i].indexOf('/') > -1) { cr = new ClassReader(new FileInputStream(args[i])); } else { cr = new ClassReader(args[i]); } cr.accept(new TraceClassVisitor(null, new ASMifier1(), new PrintWriter( System.out)), flags); } // ------------------------------------------------------------------------ // Classes // ------------------------------------------------------------------------ @Override public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { String simpleName; int n = name.lastIndexOf('/'); if (n == -1) { simpleName = name; } else { text.add("package asm." + name.substring(0, n).replace('/', '.') + ";\n"); simpleName = name.substring(n + 1); } text.add("import java.util.*;\n"); text.add("import org.objectweb.asm.*;\n"); text.add("public class " + simpleName + "Dump implements Opcodes {\n\n"); text.add("public static byte[] dump () throws Exception {\n\n"); text.add("ClassWriter cw = new ClassWriter(0);\n"); text.add("FieldVisitor fv;\n"); text.add("MethodVisitor mv;\n"); text.add("AnnotationVisitor av0;\n\n"); buf.setLength(0); buf.append("cw.visit("); switch (version) { case Opcodes.V1_1: buf.append("V1_1"); break; case Opcodes.V1_2: buf.append("V1_2"); break; case Opcodes.V1_3: buf.append("V1_3"); break; case Opcodes.V1_4: buf.append("V1_4"); break; case Opcodes.V1_5: buf.append("V1_5"); break; case Opcodes.V1_6: buf.append("V1_6"); break; case Opcodes.V1_7: buf.append("V1_7"); break; default: buf.append(version); break; } buf.append(", "); appendAccess(access | ACCESS_CLASS); buf.append(", "); appendConstant(name); buf.append(", "); appendConstant(signature); buf.append(", "); appendConstant(superName); buf.append(", "); if (interfaces != null && interfaces.length > 0) { buf.append("new String[] {"); for (int i = 0; i < interfaces.length; ++i) { buf.append(i == 0 ? " " : ", "); appendConstant(interfaces[i]); } buf.append(" }"); } else { buf.append("null"); } buf.append(");\n\n"); text.add(buf.toString()); } @Override public void visitSource(final String file, final String debug) { buf.setLength(0); buf.append("cw.visitSource("); appendConstant(file); buf.append(", "); appendConstant(debug); buf.append(");\n\n"); text.add(buf.toString()); } @Override public void visitOuterClass(final String owner, final String name, final String desc) { buf.setLength(0); buf.append("cw.visitOuterClass("); appendConstant(owner); buf.append(", "); appendConstant(name); buf.append(", "); appendConstant(desc); buf.append(");\n\n"); text.add(buf.toString()); } @Override public ASMifier1 visitClassAnnotation(final String desc, final boolean visible) { return visitAnnotation(desc, visible); } @Override public ASMifier1 visitClassTypeAnnotation(final int typeRef, final TypePath typePath, final String desc, final boolean visible) { return visitTypeAnnotation(typeRef, typePath, desc, visible); } @Override public void visitClassAttribute(final Attribute attr) { visitAttribute(attr); } @Override public void visitInnerClass(final String name, final String outerName, final String innerName, final int access) { buf.setLength(0); buf.append("cw.visitInnerClass("); appendConstant(name); buf.append(", "); appendConstant(outerName); buf.append(", "); appendConstant(innerName); buf.append(", "); appendAccess(access | ACCESS_INNER); buf.append(");\n\n"); text.add(buf.toString()); } @Override public ASMifier1 visitField(final int access, final String name, final String desc, final String signature, final Object value) { buf.setLength(0); buf.append("{\n"); buf.append("fv = cw.visitField("); appendAccess(access | ACCESS_FIELD); buf.append(", "); appendConstant(name); buf.append(", "); appendConstant(desc); buf.append(", "); appendConstant(signature); buf.append(", "); appendConstant(value); buf.append(");\n"); text.add(buf.toString()); ASMifier1 a = createASMifier("fv", 0); text.add(a.getText()); text.add("}\n"); return a; } @Override public ASMifier1 visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { buf.setLength(0); buf.append("{\n"); buf.append("mv = cw.visitMethod("); appendAccess(access); buf.append(", "); appendConstant(name); buf.append(", "); appendConstant(desc); buf.append(", "); appendConstant(signature); buf.append(", "); if (exceptions != null && exceptions.length > 0) { buf.append("new String[] {"); for (int i = 0; i < exceptions.length; ++i) { buf.append(i == 0 ? " " : ", "); appendConstant(exceptions[i]); } buf.append(" }"); } else { buf.append("null"); } buf.append(");\n"); text.add(buf.toString()); ASMifier1 a = createASMifier("mv", 0); text.add(a.getText()); text.add("}\n"); return a; } @Override public void visitClassEnd() { text.add("cw.visitEnd();\n\n"); text.add("return cw.toByteArray();\n"); text.add("}\n"); text.add("}\n"); } // ------------------------------------------------------------------------ // Annotations // ------------------------------------------------------------------------ @Override public void visit(final String name, final Object value) { buf.setLength(0); buf.append("av").append(id).append(".visit("); appendConstant(buf, name); buf.append(", "); appendConstant(buf, value); buf.append(");\n"); text.add(buf.toString()); } @Override public void visitEnum(final String name, final String desc, final String value) { buf.setLength(0); buf.append("av").append(id).append(".visitEnum("); appendConstant(buf, name); buf.append(", "); appendConstant(buf, desc); buf.append(", "); appendConstant(buf, value); buf.append(");\n"); text.add(buf.toString()); } @Override public ASMifier1 visitAnnotation(final String name, final String desc) { buf.setLength(0); buf.append("{\n"); buf.append("AnnotationVisitor av").append(id + 1).append(" = av"); buf.append(id).append(".visitAnnotation("); appendConstant(buf, name); buf.append(", "); appendConstant(buf, desc); buf.append(");\n"); text.add(buf.toString()); ASMifier1 a = createASMifier("av", id + 1); text.add(a.getText()); text.add("}\n"); return a; } @Override public ASMifier1 visitArray(final String name) { buf.setLength(0); buf.append("{\n"); buf.append("AnnotationVisitor av").append(id + 1).append(" = av"); buf.append(id).append(".visitArray("); appendConstant(buf, name); buf.append(");\n"); text.add(buf.toString()); ASMifier1 a = createASMifier("av", id + 1); text.add(a.getText()); text.add("}\n"); return a; } @Override public void visitAnnotationEnd() { buf.setLength(0); buf.append("av").append(id).append(".visitEnd();\n"); text.add(buf.toString()); } // ------------------------------------------------------------------------ // Fields // ------------------------------------------------------------------------ @Override public ASMifier1 visitFieldAnnotation(final String desc, final boolean visible) { return visitAnnotation(desc, visible); } @Override public ASMifier1 visitFieldTypeAnnotation(final int typeRef, final TypePath typePath, final String desc, final boolean visible) { return visitTypeAnnotation(typeRef, typePath, desc, visible); } @Override public void visitFieldAttribute(final Attribute attr) { visitAttribute(attr); } @Override public void visitFieldEnd() { buf.setLength(0); buf.append(name).append(".visitEnd();\n"); text.add(buf.toString()); } // ------------------------------------------------------------------------ // Methods // ------------------------------------------------------------------------ @Override public void visitParameter(String parameterName, int access) { buf.setLength(0); buf.append(name).append(".visitParameter("); appendString(buf, parameterName); buf.append(", "); appendAccess(access); text.add(buf.append(");\n").toString()); } @Override public ASMifier1 visitAnnotationDefault() { buf.setLength(0); buf.append("{\n").append("av0 = ").append(name) .append(".visitAnnotationDefault();\n"); text.add(buf.toString()); ASMifier1 a = createASMifier("av", 0); text.add(a.getText()); text.add("}\n"); return a; } @Override public ASMifier1 visitMethodAnnotation(final String desc, final boolean visible) { return visitAnnotation(desc, visible); } @Override public ASMifier1 visitMethodTypeAnnotation(final int typeRef, final TypePath typePath, final String desc, final boolean visible) { return visitTypeAnnotation(typeRef, typePath, desc, visible); } @Override public ASMifier1 visitParameterAnnotation(final int parameter, final String desc, final boolean visible) { buf.setLength(0); buf.append("{\n").append("av0 = ").append(name) .append(".visitParameterAnnotation(").append(parameter) .append(", "); appendConstant(desc); buf.append(", ").append(visible).append(");\n"); text.add(buf.toString()); ASMifier1 a = createASMifier("av", 0); text.add(a.getText()); text.add("}\n"); return a; } @Override public void visitMethodAttribute(final Attribute attr) { visitAttribute(attr); } @Override public void visitCode() { } @Override public void visitFrame(final int type, final int nLocal, final Object[] local, final int nStack, final Object[] stack) { } @Override public void visitInsn(final int opcode) { buf.setLength(0); buf.append(name).append(".visitInsn(").append(OPCODES[opcode]) .append(");\n"); text.add(buf.toString()); } @Override public void visitIntInsn(final int opcode, final int operand) { buf.setLength(0); buf.append(name) .append(".visitIntInsn(") .append(OPCODES[opcode]) .append(", ") .append(opcode == Opcodes.NEWARRAY ? TYPES[operand] : Integer .toString(operand)).append(");\n"); text.add(buf.toString()); } @Override public void visitVarInsn(final int opcode, final int var) { buf.setLength(0); buf.append(name).append(".visitVarInsn(").append(OPCODES[opcode]) .append(", ").append(var).append(");\n"); text.add(buf.toString()); } @Override public void visitTypeInsn(final int opcode, final String type) { buf.setLength(0); buf.append(name).append(".visitTypeInsn(").append(OPCODES[opcode]) .append(", "); appendConstant(type); buf.append(");\n"); text.add(buf.toString()); } @Override public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) { buf.setLength(0); buf.append(this.name).append(".visitFieldInsn(") .append(OPCODES[opcode]).append(", "); appendConstant(owner); buf.append(", "); appendConstant(name); buf.append(", "); appendConstant(desc); buf.append(");\n"); text.add(buf.toString()); } @Deprecated @Override public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc) { if (api >= Opcodes.ASM5) { super.visitMethodInsn(opcode, owner, name, desc); return; } doVisitMethodInsn(opcode, owner, name, desc, opcode == Opcodes.INVOKEINTERFACE); } @Override public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc, final boolean itf) { if (api < Opcodes.ASM5) { super.visitMethodInsn(opcode, owner, name, desc, itf); return; } doVisitMethodInsn(opcode, owner, name, desc, itf); } private void doVisitMethodInsn(final int opcode, final String owner, final String name, final String desc, final boolean itf) { buf.setLength(0); buf.append(this.name).append(".visitMethodInsn(") .append(OPCODES[opcode]).append(", "); appendConstant(owner); buf.append(", "); appendConstant(name); buf.append(", "); appendConstant(desc); buf.append(", "); buf.append(itf ? "true" : "false"); buf.append(");\n"); text.add(buf.toString()); } @Override public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) { buf.setLength(0); buf.append(this.name).append(".visitInvokeDynamicInsn("); appendConstant(name); buf.append(", "); appendConstant(desc); buf.append(", "); appendConstant(bsm); buf.append(", new Object[]{"); for (int i = 0; i < bsmArgs.length; ++i) { appendConstant(bsmArgs[i]); if (i != bsmArgs.length - 1) { buf.append(", "); } } buf.append("});\n"); text.add(buf.toString()); } @Override public void visitJumpInsn(final int opcode, final Label label) { buf.setLength(0); declareLabel(label); buf.append("Jump : ").append(OPCODES[opcode]).append(" "); appendLabel(label); buf.append("\n\n"); text.add(buf.toString()); } @Override public void visitLabel(final Label label) { buf.setLength(0); declareLabel(label); if(text.size() > 0) { String s = (String)text.get(text.size() - 1); if(s.charAt(s.length() - 2) != '\n') { buf.append('\n'); } } //buf.append(name).append(".visitLabel("); appendLabel(label); //buf.append(");\n"); buf.append(":\n"); text.add(buf.toString()); } @Override public void visitLdcInsn(final Object cst) { buf.setLength(0); buf.append(name).append(".visitLdcInsn("); appendConstant(cst); buf.append(");\n"); text.add(buf.toString()); } @Override public void visitIincInsn(final int var, final int increment) { buf.setLength(0); buf.append(name).append(".visitIincInsn(").append(var).append(", ") .append(increment).append(");\n"); text.add(buf.toString()); } @Override public void visitTableSwitchInsn(final int min, final int max, final Label dflt, final Label... labels) { buf.setLength(0); for (int i = 0; i < labels.length; ++i) { declareLabel(labels[i]); } declareLabel(dflt); buf.append(name).append(".visitTableSwitchInsn(").append(min) .append(", ").append(max).append(", "); appendLabel(dflt); buf.append(", new Label[] {"); for (int i = 0; i < labels.length; ++i) { buf.append(i == 0 ? " " : ", "); appendLabel(labels[i]); } buf.append(" });\n"); text.add(buf.toString()); } @Override public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) { buf.setLength(0); for (int i = 0; i < labels.length; ++i) { declareLabel(labels[i]); } declareLabel(dflt); buf.append(name).append(".visitLookupSwitchInsn("); appendLabel(dflt); buf.append(", new int[] {"); for (int i = 0; i < keys.length; ++i) { buf.append(i == 0 ? " " : ", ").append(keys[i]); } buf.append(" }, new Label[] {"); for (int i = 0; i < labels.length; ++i) { buf.append(i == 0 ? " " : ", "); appendLabel(labels[i]); } buf.append(" });\n"); text.add(buf.toString()); } @Override public void visitMultiANewArrayInsn(final String desc, final int dims) { buf.setLength(0); buf.append(name).append(".visitMultiANewArrayInsn("); appendConstant(desc); buf.append(", ").append(dims).append(");\n"); text.add(buf.toString()); } @Override public ASMifier1 visitInsnAnnotation(final int typeRef, final TypePath typePath, final String desc, final boolean visible) { return visitTypeAnnotation("visitInsnAnnotation", typeRef, typePath, desc, visible); } @Override public void visitTryCatchBlock(final Label start, final Label end, final Label handler, final String type) { buf.setLength(0); declareLabel(start); declareLabel(end); declareLabel(handler); buf.append(name).append(".visitTryCatchBlock("); appendLabel(start); buf.append(", "); appendLabel(end); buf.append(", "); appendLabel(handler); buf.append(", "); appendConstant(type); buf.append(");\n"); text.add(buf.toString()); } @Override public ASMifier1 visitTryCatchAnnotation(final int typeRef, final TypePath typePath, final String desc, final boolean visible) { return visitTypeAnnotation("visitTryCatchAnnotation", typeRef, typePath, desc, visible); } @Override public void visitLocalVariable(final String name, final String desc, final String signature, final Label start, final Label end, final int index) { } @Override public Printer visitLocalVariableAnnotation(int typeRef, TypePath typePath, Label[] start, Label[] end, int[] index, String desc, boolean visible) { buf.setLength(0); buf.append("{\n").append("av0 = ").append(name) .append(".visitLocalVariableAnnotation("); buf.append(typeRef); buf.append(", TypePath.fromString(\"").append(typePath).append("\"), "); buf.append("new Label[] {"); for (int i = 0; i < start.length; ++i) { buf.append(i == 0 ? " " : ", "); appendLabel(start[i]); } buf.append(" }, new Label[] {"); for (int i = 0; i < end.length; ++i) { buf.append(i == 0 ? " " : ", "); appendLabel(end[i]); } buf.append(" }, new int[] {"); for (int i = 0; i < index.length; ++i) { buf.append(i == 0 ? " " : ", ").append(index[i]); } buf.append(" }, "); appendConstant(desc); buf.append(", ").append(visible).append(");\n"); text.add(buf.toString()); ASMifier1 a = createASMifier("av", 0); text.add(a.getText()); text.add("}\n"); return a; } @Override public void visitLineNumber(final int line, final Label start) { } @Override public void visitMaxs(final int maxStack, final int maxLocals) { } @Override public void visitMethodEnd() { } // ------------------------------------------------------------------------ // Common methods // ------------------------------------------------------------------------ public ASMifier1 visitAnnotation(final String desc, final boolean visible) { buf.setLength(0); buf.append("{\n").append("av0 = ").append(name) .append(".visitAnnotation("); appendConstant(desc); buf.append(", ").append(visible).append(");\n"); text.add(buf.toString()); ASMifier1 a = createASMifier("av", 0); text.add(a.getText()); text.add("}\n"); return a; } public ASMifier1 visitTypeAnnotation(final int typeRef, final TypePath typePath, final String desc, final boolean visible) { return visitTypeAnnotation("visitTypeAnnotation", typeRef, typePath, desc, visible); } public ASMifier1 visitTypeAnnotation(final String method, final int typeRef, final TypePath typePath, final String desc, final boolean visible) { buf.setLength(0); buf.append("{\n").append("av0 = ").append(name).append(".") .append(method).append("("); buf.append(typeRef); buf.append(", TypePath.fromString(\"").append(typePath).append("\"), "); appendConstant(desc); buf.append(", ").append(visible).append(");\n"); text.add(buf.toString()); ASMifier1 a = createASMifier("av", 0); text.add(a.getText()); text.add("}\n"); return a; } public void visitAttribute(final Attribute attr) { buf.setLength(0); buf.append("// ATTRIBUTE ").append(attr.type).append('\n'); if (attr instanceof ASMifiable) { if (labelNames == null) { labelNames = new HashMap<Label, String>(); } buf.append("{\n"); ((ASMifiable) attr).asmify(buf, "attr", labelNames); buf.append(name).append(".visitAttribute(attr);\n"); buf.append("}\n"); } text.add(buf.toString()); } // ------------------------------------------------------------------------ // Utility methods // ------------------------------------------------------------------------ protected ASMifier1 createASMifier(final String name, final int id) { return new ASMifier1(Opcodes.ASM5, name, id); } /** * Appends a string representation of the given access modifiers to * {@link #buf buf}. * * @param access * some access modifiers. */ void appendAccess(final int access) { boolean first = true; if ((access & Opcodes.ACC_PUBLIC) != 0) { buf.append("ACC_PUBLIC"); first = false; } if ((access & Opcodes.ACC_PRIVATE) != 0) { buf.append("ACC_PRIVATE"); first = false; } if ((access & Opcodes.ACC_PROTECTED) != 0) { buf.append("ACC_PROTECTED"); first = false; } if ((access & Opcodes.ACC_FINAL) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_FINAL"); first = false; } if ((access & Opcodes.ACC_STATIC) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_STATIC"); first = false; } if ((access & Opcodes.ACC_SYNCHRONIZED) != 0) { if (!first) { buf.append(" + "); } if ((access & ACCESS_CLASS) == 0) { buf.append("ACC_SYNCHRONIZED"); } else { buf.append("ACC_SUPER"); } first = false; } if ((access & Opcodes.ACC_VOLATILE) != 0 && (access & ACCESS_FIELD) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_VOLATILE"); first = false; } if ((access & Opcodes.ACC_BRIDGE) != 0 && (access & ACCESS_CLASS) == 0 && (access & ACCESS_FIELD) == 0) { if (!first) { buf.append(" + "); } buf.append("ACC_BRIDGE"); first = false; } if ((access & Opcodes.ACC_VARARGS) != 0 && (access & ACCESS_CLASS) == 0 && (access & ACCESS_FIELD) == 0) { if (!first) { buf.append(" + "); } buf.append("ACC_VARARGS"); first = false; } if ((access & Opcodes.ACC_TRANSIENT) != 0 && (access & ACCESS_FIELD) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_TRANSIENT"); first = false; } if ((access & Opcodes.ACC_NATIVE) != 0 && (access & ACCESS_CLASS) == 0 && (access & ACCESS_FIELD) == 0) { if (!first) { buf.append(" + "); } buf.append("ACC_NATIVE"); first = false; } if ((access & Opcodes.ACC_ENUM) != 0 && ((access & ACCESS_CLASS) != 0 || (access & ACCESS_FIELD) != 0 || (access & ACCESS_INNER) != 0)) { if (!first) { buf.append(" + "); } buf.append("ACC_ENUM"); first = false; } if ((access & Opcodes.ACC_ANNOTATION) != 0 && ((access & ACCESS_CLASS) != 0 || (access & ACCESS_INNER) != 0)) { if (!first) { buf.append(" + "); } buf.append("ACC_ANNOTATION"); first = false; } if ((access & Opcodes.ACC_ABSTRACT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_ABSTRACT"); first = false; } if ((access & Opcodes.ACC_INTERFACE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_INTERFACE"); first = false; } if ((access & Opcodes.ACC_STRICT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_STRICT"); first = false; } if ((access & Opcodes.ACC_SYNTHETIC) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_SYNTHETIC"); first = false; } if ((access & Opcodes.ACC_DEPRECATED) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_DEPRECATED"); first = false; } if ((access & Opcodes.ACC_MANDATED) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_MANDATED"); first = false; } if (first) { buf.append('0'); } } /** * Appends a string representation of the given constant to the given * buffer. * * @param cst * an {@link Integer}, {@link Float}, {@link Long}, * {@link Double} or {@link String} object. May be <tt>null</tt>. */ protected void appendConstant(final Object cst) { appendConstant(buf, cst); } /** * Appends a string representation of the given constant to the given * buffer. * * @param buf * a string buffer. * @param cst * an {@link Integer}, {@link Float}, {@link Long}, * {@link Double} or {@link String} object. May be <tt>null</tt>. */ static void appendConstant(final StringBuffer buf, final Object cst) { if (cst == null) { buf.append("null"); } else if (cst instanceof String) { appendString(buf, (String) cst); } else if (cst instanceof Type) { buf.append("Type.getType(\""); buf.append(((Type) cst).getDescriptor()); buf.append("\")"); } else if (cst instanceof Handle) { buf.append("new Handle("); Handle h = (Handle) cst; buf.append("Opcodes.").append(HANDLE_TAG[h.getTag()]) .append(", \""); buf.append(h.getOwner()).append("\", \""); buf.append(h.getName()).append("\", \""); buf.append(h.getDesc()).append("\")"); } else if (cst instanceof Byte) { buf.append("new Byte((byte)").append(cst).append(')'); } else if (cst instanceof Boolean) { buf.append(((Boolean) cst).booleanValue() ? "Boolean.TRUE" : "Boolean.FALSE"); } else if (cst instanceof Short) { buf.append("new Short((short)").append(cst).append(')'); } else if (cst instanceof Character) { int c = ((Character) cst).charValue(); buf.append("new Character((char)").append(c).append(')'); } else if (cst instanceof Integer) { buf.append("new Integer(").append(cst).append(')'); } else if (cst instanceof Float) { buf.append("new Float(\"").append(cst).append("\")"); } else if (cst instanceof Long) { buf.append("new Long(").append(cst).append("L)"); } else if (cst instanceof Double) { buf.append("new Double(\"").append(cst).append("\")"); } else if (cst instanceof byte[]) { byte[] v = (byte[]) cst; buf.append("new byte[] {"); for (int i = 0; i < v.length; i++) { buf.append(i == 0 ? "" : ",").append(v[i]); } buf.append('}'); } else if (cst instanceof boolean[]) { boolean[] v = (boolean[]) cst; buf.append("new boolean[] {"); for (int i = 0; i < v.length; i++) { buf.append(i == 0 ? "" : ",").append(v[i]); } buf.append('}'); } else if (cst instanceof short[]) { short[] v = (short[]) cst; buf.append("new short[] {"); for (int i = 0; i < v.length; i++) { buf.append(i == 0 ? "" : ",").append("(short)").append(v[i]); } buf.append('}'); } else if (cst instanceof char[]) { char[] v = (char[]) cst; buf.append("new char[] {"); for (int i = 0; i < v.length; i++) { buf.append(i == 0 ? "" : ",").append("(char)") .append((int) v[i]); } buf.append('}'); } else if (cst instanceof int[]) { int[] v = (int[]) cst; buf.append("new int[] {"); for (int i = 0; i < v.length; i++) { buf.append(i == 0 ? "" : ",").append(v[i]); } buf.append('}'); } else if (cst instanceof long[]) { long[] v = (long[]) cst; buf.append("new long[] {"); for (int i = 0; i < v.length; i++) { buf.append(i == 0 ? "" : ",").append(v[i]).append('L'); } buf.append('}'); } else if (cst instanceof float[]) { float[] v = (float[]) cst; buf.append("new float[] {"); for (int i = 0; i < v.length; i++) { buf.append(i == 0 ? "" : ",").append(v[i]).append('f'); } buf.append('}'); } else if (cst instanceof double[]) { double[] v = (double[]) cst; buf.append("new double[] {"); for (int i = 0; i < v.length; i++) { buf.append(i == 0 ? "" : ",").append(v[i]).append('d'); } buf.append('}'); } } private void declareFrameTypes(final int n, final Object[] o) { for (int i = 0; i < n; ++i) { if (o[i] instanceof Label) { declareLabel((Label) o[i]); } } } private void appendFrameTypes(final int n, final Object[] o) { for (int i = 0; i < n; ++i) { if (i > 0) { buf.append(", "); } if (o[i] instanceof String) { appendConstant(o[i]); } else if (o[i] instanceof Integer) { switch (((Integer) o[i]).intValue()) { case 0: buf.append("Opcodes.TOP"); break; case 1: buf.append("Opcodes.INTEGER"); break; case 2: buf.append("Opcodes.FLOAT"); break; case 3: buf.append("Opcodes.DOUBLE"); break; case 4: buf.append("Opcodes.LONG"); break; case 5: buf.append("Opcodes.NULL"); break; case 6: buf.append("Opcodes.UNINITIALIZED_THIS"); break; } } else { appendLabel((Label) o[i]); } } } /** * Appends a declaration of the given label to {@link #buf buf}. This * declaration is of the form "Label lXXX = new Label();". Does nothing if * the given label has already been declared. * * @param l * a label. */ protected void declareLabel(final Label l) { if (labelNames == null) { labelNames = new HashMap<Label, String>(); } String name = labelNames.get(l); if (name == null) { name = "l" + labelNames.size(); labelNames.put(l, name); //buf.append("Label ").append(name).append(" = new Label();\n"); } } /** * Appends the name of the given label to {@link #buf buf}. The given label * <i>must</i> already have a name. One way to ensure this is to always call * {@link #declareLabel declared} before calling this method. * * @param l * a label. */ protected void appendLabel(final Label l) { buf.append(labelNames.get(l)); } }
package engine.racedetectionengine.wcp.distance; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Stack; import engine.racedetectionengine.State; import event.Lock; import event.Thread; import event.Variable; import util.vectorclock.ClockPair; import util.vectorclock.VectorClock; //Manages the clocks and other data structures used by the WCP algorithm public class WCPState extends State { // Internal data public HashMap<Thread, Integer> threadToIndex; private HashSet<Lock> lockSet; private HashSet<Variable> variableSet; private int numThreads; // Data used for algorithm private ArrayList<Integer> clockThread; private ArrayList<VectorClock> WCPThread; public ArrayList<VectorClock> HBPredecessorThread; public HashMap<Lock, VectorClock> HBPredecessorLock; public ArrayList<VectorClock> WCPPredecessorThread; public HashMap<Lock, VectorClock> WCPPredecessorLock; public HashMap<Lock, HashMap<Long, HashMap<Long, HashMap<Thread, VectorClock>>>> lastReleaseLockReadVariableThread; public HashMap<Lock, HashMap<Long, HashMap<Long, HashMap<Thread, VectorClock>>>> lastReleaseLockWriteVariableThread; public HashMap<Variable, VectorClock> readVariable; public HashMap<Variable, VectorClock> writeVariable; /*** * The next two clocks are relevant for and only for the "forceOrder" feature ***/ public HashMap<Variable, VectorClock> HBPredecessorReadVariable; public HashMap<Variable, VectorClock> HBPredecessorWriteVariable; /*********************************************************************************/ public WCPView view; // Data used for online tracking of locks and variables public HashMap<Thread, Stack<HashSet<Variable>>> mapThreadReadVarSetStack = new HashMap<Thread, Stack<HashSet<Variable>>>(); public HashMap<Thread, Stack<HashSet<Variable>>> mapThreadWriteVarSetStack = new HashMap<Thread, Stack<HashSet<Variable>>>(); public HashMap<Thread, Stack<Lock>> mapThreadLockStack = new HashMap<Thread, Stack<Lock>>(); // Data for offline space saving public HashMap<String, HashMap<String, HashSet<String>>> existsLockReadVariableThreads; public HashMap<String, HashMap<String, HashSet<String>>> existsLockWriteVariableThreads; public HashMap<String, Long> variableToReadEquivalenceClass; public HashMap<String, Long> variableToWriteEquivalenceClass; // Space saving private VectorClock local_vc_imax; // parameter flags public boolean forceOrder; // Distance stats public HashMap<Variable, HashMap<Thread, Long>> readVariableAuxId; public HashMap<Variable, HashMap<Thread, Long>> writeVariableAuxId; // == stats == public long maxMaxDistance = 0; public long sumMaxDistance = 0; public long maxMinDistance = 0; public long sumMinDistance = 0; public long numRaces = 0; public HashSet<Integer> racyVars = new HashSet<Integer>(); public WCPState(HashSet<Thread> tSet, boolean forceOrder) { this.forceOrder = forceOrder; initInternalData(tSet); initData(tSet); initOnlineData(); } private void initInternalData(HashSet<Thread> tSet) { this.threadToIndex = new HashMap<Thread, Integer>(); this.numThreads = 0; Iterator<Thread> tIter = tSet.iterator(); while (tIter.hasNext()) { Thread thread = tIter.next(); this.threadToIndex.put(thread, (Integer) this.numThreads); this.numThreads++; } this.lockSet = new HashSet<Lock>(); this.variableSet = new HashSet<Variable>(); local_vc_imax = new VectorClock(this.numThreads); } private void initialize1DArrayOfVectorClocksWithBottom(ArrayList<VectorClock> arr, int len) { for (int i = 0; i < len; i++) { arr.add(new VectorClock(this.numThreads)); } } public void initData(HashSet<Thread> tSet) { // Initialize clockThread this.clockThread = new ArrayList<Integer>(); for (int i = 0; i < this.numThreads; i++) { this.clockThread.add((Integer) 1); } // initialize WCPThread this.WCPThread = new ArrayList<VectorClock>(); initialize1DArrayOfVectorClocksWithBottom(this.WCPThread, this.numThreads); // initialize HBPredecessorThread this.HBPredecessorThread = new ArrayList<VectorClock>(); initialize1DArrayOfVectorClocksWithBottom(this.HBPredecessorThread, this.numThreads); // initialize HBPredecessorLock this.HBPredecessorLock = new HashMap<Lock, VectorClock>(); // initialize WCPPredecessorThread this.WCPPredecessorThread = new ArrayList<VectorClock>(); initialize1DArrayOfVectorClocksWithBottom(this.WCPPredecessorThread, this.numThreads); // initialize WCPPredecessorLock this.WCPPredecessorLock = new HashMap<Lock, VectorClock>(); this.lastReleaseLockReadVariableThread = new HashMap<Lock, HashMap<Long, HashMap<Long, HashMap<Thread, VectorClock>>>>(); this.lastReleaseLockWriteVariableThread = new HashMap<Lock, HashMap<Long, HashMap<Long, HashMap<Thread, VectorClock>>>>(); // initialize readVariable this.readVariable = new HashMap<Variable, VectorClock>(); // initialize writeVariable this.writeVariable = new HashMap<Variable, VectorClock>(); // initialize HBPredecessorReadVariable this.HBPredecessorReadVariable = new HashMap<Variable, VectorClock>(); // initialize HBPredecessorWriteVariable this.HBPredecessorWriteVariable = new HashMap<Variable, VectorClock>(); // initialize view this.view = new WCPView(tSet); // distance stats this.readVariableAuxId = new HashMap<Variable, HashMap<Thread, Long>>(); this.writeVariableAuxId = new HashMap<Variable, HashMap<Thread, Long>>(); } public void initOnlineData() { mapThreadReadVarSetStack = new HashMap<Thread, Stack<HashSet<Variable>>>(); mapThreadWriteVarSetStack = new HashMap<Thread, Stack<HashSet<Variable>>>(); mapThreadLockStack = new HashMap<Thread, Stack<Lock>>(); } // Access methods private <E> E getVectorClockFrom1DArray(ArrayList<E> arr, int index) { if (index < 0 || index >= arr.size()) { throw new IllegalArgumentException("Illegal Out of Bound access"); } return arr.get(index); } private void checkAndAddLock(Lock l) { if (!lockSet.contains(l)) { lockSet.add(l); HBPredecessorLock.put(l, new VectorClock(this.numThreads)); WCPPredecessorLock.put(l, new VectorClock(this.numThreads)); String lName = l.getName(); if (existsLockReadVariableThreads.containsKey(lName)) { this.lastReleaseLockReadVariableThread.put(l, new HashMap<Long, HashMap<Long, HashMap<Thread, VectorClock>>>()); for (Variable v : variableSet) { String vName = v.getName(); Long vEquivRead = this.variableToReadEquivalenceClass.get(vName); Long vEquivWrite = this.variableToWriteEquivalenceClass.get(vName); if (existsLockReadVariableThreads.get(lName).containsKey(vName)) { if (!lastReleaseLockReadVariableThread.get(l) .containsKey(vEquivRead)) { this.lastReleaseLockReadVariableThread.get(l).put(vEquivRead, new HashMap<Long, HashMap<Thread, VectorClock>>()); } if (!lastReleaseLockReadVariableThread.get(l).get(vEquivRead) .containsKey(vEquivWrite)) { this.lastReleaseLockReadVariableThread.get(l).get(vEquivRead) .put(vEquivWrite, new HashMap<Thread, VectorClock>()); } for (Thread t : this.threadToIndex.keySet()) { if (existsLockReadVariableThreads.get(lName).get(vName) .contains(t.getName())) { this.lastReleaseLockReadVariableThread.get(l) .get(vEquivRead).get(vEquivWrite) .put(t, new VectorClock(this.numThreads)); } } } } } if (existsLockWriteVariableThreads.containsKey(lName)) { this.lastReleaseLockWriteVariableThread.put(l, new HashMap<Long, HashMap<Long, HashMap<Thread, VectorClock>>>()); for (Variable v : variableSet) { String vName = v.getName(); Long vEquivRead = this.variableToReadEquivalenceClass.get(vName); Long vEquivWrite = this.variableToWriteEquivalenceClass.get(vName); if (existsLockWriteVariableThreads.get(lName).containsKey(vName)) { if (!lastReleaseLockWriteVariableThread.get(l) .containsKey(vEquivRead)) { this.lastReleaseLockWriteVariableThread.get(l).put(vEquivRead, new HashMap<Long, HashMap<Thread, VectorClock>>()); } if (!lastReleaseLockWriteVariableThread.get(l).get(vEquivRead) .containsKey(vEquivWrite)) { this.lastReleaseLockWriteVariableThread.get(l).get(vEquivRead) .put(vEquivWrite, new HashMap<Thread, VectorClock>()); } for (Thread t : this.threadToIndex.keySet()) { if (existsLockWriteVariableThreads.get(lName).get(vName) .contains(t.getName())) { this.lastReleaseLockWriteVariableThread.get(l) .get(vEquivRead).get(vEquivWrite) .put(t, new VectorClock(this.numThreads)); } } } } } view.checkAndAddLock(l); } } private void checkAndAddVariable(Variable v) { if (!variableSet.contains(v)) { variableSet.add(v); Long vEquivRead = this.variableToReadEquivalenceClass.get(v.getName()); Long vEquivWrite = this.variableToWriteEquivalenceClass.get(v.getName()); for (Lock l : lockSet) { if (existsLockReadVariableThreads.containsKey(l.getName())) { if (existsLockReadVariableThreads.get(l.getName()) .containsKey(v.getName())) { if (!this.lastReleaseLockReadVariableThread.get(l) .containsKey(vEquivRead)) { this.lastReleaseLockReadVariableThread.get(l).put(vEquivRead, new HashMap<Long, HashMap<Thread, VectorClock>>()); } if (!this.lastReleaseLockReadVariableThread.get(l).get(vEquivRead) .containsKey(vEquivWrite)) { this.lastReleaseLockReadVariableThread.get(l).get(vEquivRead) .put(vEquivWrite, new HashMap<Thread, VectorClock>()); } HashSet<String> threads = existsLockReadVariableThreads .get(l.getName()).get(v.getName()); for (Thread t : this.threadToIndex.keySet()) { if (threads.contains(t.getName())) { if (!lastReleaseLockReadVariableThread.get(l) .get(vEquivRead).get(vEquivWrite) .containsKey(t)) { this.lastReleaseLockReadVariableThread.get(l) .get(vEquivRead).get(vEquivWrite) .put(t, new VectorClock(this.numThreads)); } } } } } if (existsLockWriteVariableThreads.containsKey(l.getName())) { if (existsLockWriteVariableThreads.get(l.getName()) .containsKey(v.getName())) { if (!this.lastReleaseLockWriteVariableThread.get(l) .containsKey(vEquivRead)) { this.lastReleaseLockWriteVariableThread.get(l).put(vEquivRead, new HashMap<Long, HashMap<Thread, VectorClock>>()); } if (!this.lastReleaseLockWriteVariableThread.get(l) .get(vEquivRead).containsKey(vEquivWrite)) { this.lastReleaseLockWriteVariableThread.get(l).get(vEquivRead) .put(vEquivWrite, new HashMap<Thread, VectorClock>()); } HashSet<String> threads = existsLockWriteVariableThreads .get(l.getName()).get(v.getName()); for (Thread t : this.threadToIndex.keySet()) { if (threads.contains(t.getName())) { if (!lastReleaseLockWriteVariableThread.get(l) .get(vEquivRead).get(vEquivWrite) .containsKey(t)) { this.lastReleaseLockWriteVariableThread.get(l) .get(vEquivRead).get(vEquivWrite) .put(t, new VectorClock(this.numThreads)); } } } } } } readVariable.put(v, new VectorClock(this.numThreads)); writeVariable.put(v, new VectorClock(this.numThreads)); HBPredecessorReadVariable.put(v, new VectorClock(this.numThreads)); HBPredecessorWriteVariable.put(v, new VectorClock(this.numThreads)); readVariableAuxId.put(v, new HashMap<Thread, Long>()); writeVariableAuxId.put(v, new HashMap<Thread, Long>()); } } public int getClockThread(Thread t) { int tIndex = threadToIndex.get(t); return clockThread.get(tIndex); } public VectorClock generateVectorClockFromClockThread(Thread t) { int tIndex = threadToIndex.get(t); VectorClock wcpClock = getVectorClock(WCPThread, t); VectorClock pred = getVectorClock(WCPPredecessorThread, t); int tValue = getClockThread(t); wcpClock.copyFrom(pred); wcpClock.setClockIndex(tIndex, tValue); return wcpClock; } public void incClockThread(Thread t) { int tIndex = threadToIndex.get(t); int origVal = clockThread.get(tIndex); clockThread.set(tIndex, (Integer) (origVal + 1)); } public <E> E getVectorClock(ArrayList<E> arr, Thread t) { int tIndex = threadToIndex.get(t); return getVectorClockFrom1DArray(arr, tIndex); } public <E> E getVectorClock(HashMap<Lock, E> arr, Lock l) { checkAndAddLock(l); return arr.get(l); } public <E> E getVectorClock(HashMap<Variable, E> arr, Variable v) { checkAndAddVariable(v); return arr.get(v); } public <E> E getVectorClock( HashMap<Lock, HashMap<Long, HashMap<Long, HashMap<Thread, E>>>> arr, Lock l, Variable v, Thread t) { checkAndAddLock(l); checkAndAddVariable(v); Long vEquivRead = this.variableToReadEquivalenceClass.get(v.getName()); Long vEquivWrite = this.variableToWriteEquivalenceClass.get(v.getName()); if (!arr.containsKey(l)) throw new IllegalArgumentException("No l found"); if (!arr.get(l).containsKey(vEquivRead)) throw new IllegalArgumentException("No vEquivRead"); if (!arr.get(l).get(vEquivRead).containsKey(vEquivWrite)) throw new IllegalArgumentException("No vEquivRead"); if (!arr.get(l).get(vEquivRead).get(vEquivWrite).containsKey(t)) throw new IllegalArgumentException("No t found"); return arr.get(l).get(vEquivRead).get(vEquivWrite).get(t); } public void updateViewAsWriterAtAcquire(Lock l, Thread t) { checkAndAddLock(l); if (!this.view.lockThreadLastInteraction.get(l.getName()) .containsKey(t.getName())) { throw new IllegalArgumentException( "Invalid operation : No critical section on lock " + l.getName() + " in thread " + t.getName()); } VectorClock C_t = generateVectorClockFromClockThread(t); view.pushClockPair(l, new ClockPair(C_t)); } public void readViewOfWriters(Lock l, Thread t) { checkAndAddLock(l); if (!this.view.lockThreadLastInteraction.get(l.getName()) .containsKey(t.getName())) { throw new IllegalArgumentException( "Invalid operation : No critical section on lock " + l.getName() + " in thread " + t.getName()); } local_vc_imax.setToZero(); VectorClock P_t = getVectorClock(WCPPredecessorThread, t); VectorClock C_t = generateVectorClockFromClockThread(t); view.getMaxLowerBound(t, l, C_t, local_vc_imax); P_t.updateWithMax(P_t, local_vc_imax); } public void updateViewAsWriterAtRelease(Lock l, Thread t) { checkAndAddLock(l); if (!this.view.lockThreadLastInteraction.get(l.getName()) .containsKey(t.getName())) { throw new IllegalArgumentException( "Invalid operation : No critical section on lock " + l.getName() + " in thread " + t.getName()); } VectorClock C_t = generateVectorClockFromClockThread(t); VectorClock H_t = getVectorClock(HBPredecessorThread, t); view.updateTopRelease(l, C_t, H_t); } public void printThreadClock() { ArrayList<VectorClock> printVC = new ArrayList<VectorClock>(); for (Thread thread : threadToIndex.keySet()) { VectorClock C_t = generateVectorClockFromClockThread(thread); printVC.add(C_t); } System.out.println(printVC); System.out.println(); System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); } public <T> HashSet<T> stackToSet(Stack<T> stack) { HashSet<T> set = new HashSet<T>(); for (T t : stack) { set.add(t); } return set; } public HashSet<Lock> getSetFromStack(Thread t) { return stackToSet(this.mapThreadLockStack.get(t)); } public boolean isLockAcquired(Thread t, Lock l) { checkAndAddLock(l); if (!this.view.lockThreadLastInteraction.get(l.getName()) .containsKey(t.getName())) { throw new IllegalArgumentException( "Invalid operation : No critical section on lock " + l.getName() + " in thread " + t.getName()); } return this.getSetFromStack(t).contains(l); } public boolean isThreadRelevant(Thread t) { return this.threadToIndex.containsKey(t); } public void printViewSize() { this.view.printSize(); } public void printMemory() { System.err.println("Number of threads = " + Integer.toString(this.numThreads)); System.err.println("Number of locks = " + Integer.toString(this.lockSet.size())); System.err.println( "Number of variables = " + Integer.toString(this.variableSet.size())); this.view.printSize(); } public int getIndex(VectorClock vc, Thread t) { int tIndex = threadToIndex.get(t); return vc.getClockIndex(tIndex); } public long getMaxAuxId(VectorClock confVC, VectorClock currVC, HashMap<Thread, Long> auxId_conf) { long maxId = -1; for (Thread t : auxId_conf.keySet()) { int tIndex_conf = getIndex(confVC, t); int tIndex_curr = getIndex(currVC, t); if (tIndex_conf > tIndex_curr) { long auxId_VC = auxId_conf.get(t); if (maxId < auxId_VC) { maxId = auxId_VC; } } } return maxId; } public long getMinAuxId(VectorClock confVC, VectorClock currVC, HashMap<Thread, Long> auxId_conf) { long minId = -1; for (Thread t : auxId_conf.keySet()) { int tIndex_conf = getIndex(confVC, t); int tIndex_curr = getIndex(currVC, t); if (tIndex_conf > tIndex_curr) { long auxId_VC = auxId_conf.get(t); if (minId == -1) { minId = auxId_VC; } else { if (minId > auxId_VC) { minId = auxId_VC; } } } } return minId; } public void destroyLock(Lock l) { if (!lockSet.contains(l)) { throw new IllegalArgumentException( "Cannot delete non-existent lock " + l.getName()); } else { lockSet.remove(l); HBPredecessorLock.remove(l); WCPPredecessorLock.remove(l); lastReleaseLockReadVariableThread.remove(l); lastReleaseLockWriteVariableThread.remove(l); view.destroyLock(l); } } public void destroyLockThreadStack(Lock l, Thread t) { if (!lockSet.contains(l)) { throw new IllegalArgumentException( "Cannot delete stacks for non-existent lock " + l.getName()); } else if (!threadToIndex.containsKey(t)) { throw new IllegalArgumentException( "Cannot delete stacks for non-existent thread " + t.getName()); } else if (!this.view.lockThreadLastInteraction.get(l.getName()) .containsKey(t.getName())) { throw new IllegalArgumentException( "Invalid operation : No critical section on lock " + l.getName() + " in thread " + t.getName()); } else { view.destroyLockThreadStack(l, t); } } }
package com.takeoffmediareactnativebitmovinplayer; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.webkit.JavascriptInterface; import com.bitmovin.analytics.BitmovinAnalyticsConfig; import com.bitmovin.analytics.bitmovin.player.BitmovinPlayerCollector; import com.bitmovin.player.PlayerView; import com.bitmovin.player.api.Player; import com.bitmovin.player.api.PlayerConfig; import com.bitmovin.player.api.drm.WidevineConfig; import com.bitmovin.player.api.event.PlayerEvent; import com.bitmovin.player.api.media.subtitle.SubtitleTrack; import com.bitmovin.player.api.media.thumbnail.ThumbnailTrack; import com.bitmovin.player.api.source.Source; import com.bitmovin.player.api.source.SourceConfig; import com.bitmovin.player.api.source.SourceType; import com.bitmovin.player.api.ui.FullscreenHandler; import com.bitmovin.player.api.ui.StyleConfig; import com.bitmovin.player.ui.CustomMessageHandler; import com.bitmovin.player.api.event.EventListener; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import com.facebook.react.common.MapBuilder; import com.facebook.react.uimanager.SimpleViewManager; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.events.RCTEventEmitter; import java.util.HashMap; import java.util.Map; import java.util.Objects; import org.jetbrains.annotations.NotNull; import org.json.JSONException; import org.json.JSONObject; public class ReactNativeBitmovinPlayerManager extends SimpleViewManager<PlayerView> implements FullscreenHandler, LifecycleEventListener { public static final String REACT_CLASS = "ReactNativeBitmovinPlayer"; private SourceConfig sourceConfig; private BitmovinPlayerCollector analyticsCollector; private PlayerView _playerView; private Player _player; private boolean _fullscreen; private boolean _PiP; private ThemedReactContext _reactContext; private Integer heartbeat = 30; private Double offset = 0.0; private boolean nextCallback = false; private boolean customSeek = false; private ReadableMap configuration = null; private final PlayerConfig playerConfig = new PlayerConfig(); private HashMap<String, String> metaDataMap = new HashMap<String, String>(); private boolean playerShouldPause = true; @NotNull @Override public String getName() { return REACT_CLASS; } public Map getExportedCustomBubblingEventTypeConstants() { return MapBuilder.builder() .put( "onReady", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onReady") ) ) .put( "onChromecast", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onChromecast") ) ) .put( "onEvent", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onEvent") ) ) .put( "onForward", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onForward") ) ) .put( "onRewind", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onRewind") ) ) .put( "onPlay", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onPlay") ) ) .put( "onPause", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onPause") ) ) .put( "onTimeChanged", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onTimeChanged") ) ) .put( "onStallStarted", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onStallStarted") ) ) .put( "onStallEnded", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onStallEnded") ) ) .put( "onPlaybackFinished", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onPlaybackFinished") ) ) .put( "onRenderFirstFrame", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onRenderFirstFrame") ) ) .put( "onError", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "_onPlayerError") ) ) .put( "onMuted", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onMuted") ) ) .put( "onUnmuted", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onUnmuted") ) ) .put( "onPiPEnter", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onPiPAvailabilityChanged") ) ) .put( "onPiPEnter", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onPiPEnter") ) ) .put( "onPiPEnter", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onPiPExit") ) ) .put( "onSeek", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onSeek") ) ) .put( "onSeeked", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onSeeked") ) ) .put( "onFullscreenEnter", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "onFullscreenEnter") ) ) .put( "_onFullscreenExit", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of("bubbled", "_onFullscreenExit") ) ) .build(); } // Create a custom javascriptInterface object which takes over the Bitmovin Web UI -> native calls Object javascriptInterface = new Object() { @JavascriptInterface public void closePlayerAsync(String data) { WritableMap map = Arguments.createMap(); map.putString("message", "closePlayer"); map.putString("time", String.valueOf(_player.getCurrentTime())); map.putString("volume", String.valueOf(_player.getVolume())); map.putString("duration", String.valueOf(_player.getDuration())); if (analyticsCollector != null) { analyticsCollector.detachPlayer(); } try { _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onEvent", map); } catch (Exception e) { throw new ClassCastException(String.format("Cannot onEvent closePlater error message: %s", e.getMessage())); } removeListeners(); _player.unload(); _player.destroy(); } @JavascriptInterface public void nextEpisodeAsync(String data) { WritableMap map = Arguments.createMap(); map.putString("message", "nextEpisode"); map.putString("time", String.valueOf(_player.getCurrentTime())); map.putString("volume", String.valueOf(_player.getVolume())); map.putString("duration", String.valueOf(_player.getDuration())); if (analyticsCollector != null) { analyticsCollector.detachPlayer(); } try { _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onEvent", map); } catch (Exception e) { throw new ClassCastException(String.format("Cannot onEvent nextEpisode error message: %s", e.getMessage())); } removeListeners(); _player.unload(); _player.destroy(); } @JavascriptInterface public void chromecastAsync(String data) { WritableMap map = Arguments.createMap(); map.putString("message", "chromecast"); map.putString("time", String.valueOf(_player.getCurrentTime())); map.putString("volume", String.valueOf(_player.getVolume())); map.putString("duration", String.valueOf(_player.getDuration())); try { _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onChromecast", map); } catch (Exception e) { throw new ClassCastException(String.format("Cannot onChromecast error message: %s", e.getMessage())); } } @JavascriptInterface public void forwardButtonAsync(String data) { WritableMap map = Arguments.createMap(); map.putString("message", "forwardButton"); map.putString("time", String.valueOf(_player.getCurrentTime())); map.putString("volume", String.valueOf(_player.getVolume())); map.putString("duration", String.valueOf(_player.getDuration())); _player.seek(_player.getCurrentTime() + 10); customSeek = true; try { _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onForward", map); } catch (Exception e) { throw new ClassCastException(String.format("Cannot onForward error message: %s", e.getMessage())); } } @JavascriptInterface public void rewindButtonAsync(String data) { WritableMap map = Arguments.createMap(); map.putString("message", "rewindButton"); map.putString("time", String.valueOf(_player.getCurrentTime())); map.putString("volume", String.valueOf(_player.getVolume())); map.putString("duration", String.valueOf(_player.getDuration())); _player.seek(_player.getCurrentTime() - 10); customSeek = true; try { _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onRewind", map); } catch (Exception e) { throw new ClassCastException(String.format("Cannot onRewind error message: %s", e.getMessage())); } } }; // Setup CustomMessageHandler for communication with Bitmovin Web UI private final CustomMessageHandler customMessageHandler = new CustomMessageHandler(javascriptInterface); @NotNull @Override public PlayerView createViewInstance(@NotNull ThemedReactContext context) { _reactContext = context; try { ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(),PackageManager.GET_META_DATA); String BITMOVIN_CSS = appInfo.metaData.getString("BITMOVIN_PLAYER_CSS"); String BITMOVIN_JS = appInfo.metaData.getString("BITMOVIN_PLAYER_JS"); if (!BITMOVIN_CSS.equals("") && !BITMOVIN_JS.equals("")) { StyleConfig styleConfig = new StyleConfig(); styleConfig.setPlayerUiCss(BITMOVIN_CSS); styleConfig.setPlayerUiJs(BITMOVIN_JS); playerConfig.setStyleConfig(styleConfig); } } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } _player = Player.create(context, playerConfig); _playerView = new PlayerView(context, _player); _playerView.setCustomMessageHandler(customMessageHandler); _fullscreen = false; setListeners(); nextCallback = false; return _playerView; } @Override public void onDropViewInstance(@NotNull PlayerView view) { removeListeners(); _playerView.onDestroy(); super.onDropViewInstance(view); _player = null; _playerView = null; } @ReactProp(name = "analytics") public void setAnalytics(PlayerView view, ReadableMap analytics) { String title = ""; String videoId = ""; String userId = ""; String cdnProvider = ""; String customData1 = ""; String customData2 = ""; String customData3 = ""; String customData4 = ""; if (analytics != null && analytics.getString("title") != null) { title = analytics.getString("title"); } if (analytics != null && analytics.getString("videoId") != null) { videoId = analytics.getString("videoId"); } if (analytics != null && analytics.getString("userId") != null) { userId = analytics.getString("userId"); } if (analytics != null && analytics.getString("cdnProvider") != null) { cdnProvider = analytics.getString("cdnProvider"); } if (analytics != null && analytics.getString("customData1") != null) { customData1 = analytics.getString("customData1"); } if (analytics != null && analytics.getString("customData2") != null) { customData2 = analytics.getString("customData2"); } if (analytics != null && analytics.getString("customData3") != null) { customData3 = analytics.getString("customData3"); } if (analytics != null && analytics.getString("customData4") != null) { customData4 = analytics.getString("customData4"); } try { ApplicationInfo appInfo = _reactContext.getPackageManager().getApplicationInfo(_reactContext.getPackageName(),PackageManager.GET_META_DATA); String BITMOVIN_ANALYTICS_LICENSE_KEY = appInfo.metaData.getString("BITMOVIN_ANALYTICS_LICENSE_KEY"); if ( analytics != null && BITMOVIN_ANALYTICS_LICENSE_KEY != null && !BITMOVIN_ANALYTICS_LICENSE_KEY.equals("") ) { // Create a BitmovinAnalyticsConfig using your Bitmovin analytics license key and (optionally) your Bitmovin Player Key BitmovinAnalyticsConfig bitmovinAnalyticsConfig = new BitmovinAnalyticsConfig(BITMOVIN_ANALYTICS_LICENSE_KEY); bitmovinAnalyticsConfig.setVideoId(videoId); bitmovinAnalyticsConfig.setTitle(title); bitmovinAnalyticsConfig.setCustomUserId(userId); bitmovinAnalyticsConfig.setCdnProvider(cdnProvider); bitmovinAnalyticsConfig.setCustomData1(customData1); bitmovinAnalyticsConfig.setCustomData2(customData2); bitmovinAnalyticsConfig.setCustomData3(customData3); bitmovinAnalyticsConfig.setCustomData4(customData4); // Create a BitmovinPlayerCollector object using the BitmovinAnalyitcsConfig you just created analyticsCollector = new BitmovinPlayerCollector(bitmovinAnalyticsConfig, _reactContext); // Attach your player instance analyticsCollector.attachPlayer(_player); } else { throw new ClassCastException("Cannot connect Analytics, add you license key."); } } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } @ReactProp(name = "configuration") public void setConfiguration(PlayerView view, ReadableMap config) { configuration = config; String advisory; boolean hasNextEpisode; if (config != null && config.getString("url") != null) { hasNextEpisode = config.getBoolean("hasNextEpisode"); if (config.hasKey("hearbeat")) { heartbeat = (int)config.getDouble("hearbeat"); } sourceConfig = new SourceConfig( Objects.requireNonNull(config.getString("url")), SourceType.Dash ); if (config.getMap("advisory") != null) { metaDataMap.put("hasNextEpisode", hasNextEpisode ? "true" : "false"); try { advisory = Objects.requireNonNull(config.getMap("advisory")).toString(); metaDataMap.put("advisory", new JSONObject(advisory).toString()); } catch (JSONException e) { e.printStackTrace(); } sourceConfig.setMetadata(metaDataMap); } if (config.getString("title") != null) { sourceConfig.setTitle(Objects.requireNonNull(config.getString("title"))); } if (config.getString("subtitle") != null) { sourceConfig.setDescription(Objects.requireNonNull(config.getString("subtitle"))); } if (config.getString("thumbnails") != null) { ThumbnailTrack thumbnailTrack = new ThumbnailTrack(Objects.requireNonNull(config.getString("thumbnails"))); sourceConfig.setThumbnailTrack(thumbnailTrack); } if (config.getString("poster") != null) { sourceConfig.setPosterImage(Objects.requireNonNull(config.getString("poster")), false); } if (config.getString("subtitles") != null) { SubtitleTrack subtitleTrack = new SubtitleTrack(config.getString("subtitles"), "text/vtt", "en", "en", false, "en"); sourceConfig.addSubtitleTrack(subtitleTrack); } if (config.hasKey("startOffset")) { sourceConfig.getOptions().setStartOffset(config.getDouble("startOffset")); } if (config.getMap("drm") != null) { String drmConf = Objects.requireNonNull(config.getMap("drm")).toString(); try { JSONObject drmMapObj = new JSONObject(drmConf); String drmNativeMap = drmMapObj.getJSONObject("NativeMap").toString(); JSONObject drm = new JSONObject(drmNativeMap); if (drm.getString("isDrmEn").equals("true")) { String licenseUrl = drm.getString("licenseUrl"); String drmHeader = drm.getString("header"); String drmToken = drm.getString("token"); HashMap<String, String> drmWVConfigHeader = new HashMap<>(); drmWVConfigHeader.put(drmHeader, drmToken); WidevineConfig widevineConfig = new WidevineConfig(licenseUrl); widevineConfig.setHttpHeaders(drmWVConfigHeader); sourceConfig.setDrmConfig(widevineConfig); } } catch (JSONException e) { e.printStackTrace(); } } Source source = Source.create(sourceConfig); _player.load(source); } } @ReactProp(name = "hasChromecast") public void setChromecast(PlayerView view, Boolean hasChromecast) { metaDataMap.put("hasChromecast", hasChromecast ? "true" : "false"); if(sourceConfig != null) { sourceConfig.setMetadata(metaDataMap); } } @Override public void onResume() {} @Override public void onPause() {} @Override public void onDestroy() {} @Override public void onFullscreenRequested() { _fullscreen = true; } @Override public void onFullscreenExitRequested() { _fullscreen = false; } @Override public void onHostResume() { _playerView.onResume(); } @Override public void onHostPause() { _playerView.onPause(); } @Override public void onHostDestroy() { _playerView.onDestroy(); } @Override public boolean isFullscreen() { return _fullscreen; } private void setListeners() { _player.on(PlayerEvent.Ready.class, onReadyListener); _player.on(PlayerEvent.Play.class, onPlayListener); _player.on(PlayerEvent.Paused.class, onPausedListener); _player.on(PlayerEvent.TimeChanged.class, onTimeChangedListener); _player.on(PlayerEvent.PlaybackFinished.class, onPlaybackFinishedistener); _player.on(PlayerEvent.RenderFirstFrame.class, onRenderFirstFrameListener); _player.on(PlayerEvent.Error.class, onErrorListener); _player.on(PlayerEvent.Muted.class, onMutedListener); _player.on(PlayerEvent.Unmuted.class, onUnmutedListener); _player.on(PlayerEvent.Seek.class, onSeekListener); _player.on(PlayerEvent.Seeked.class, onSeekedListener); _player.on(PlayerEvent.FullscreenEnter.class, onFullscreenEnterListener); _player.on(PlayerEvent.FullscreenExit.class, onFullscreenExitListener); } private void removeListeners() { _player.off(onReadyListener); _player.off(onPlayListener); _player.off(onPausedListener); _player.off(onTimeChangedListener); _player.off(onPlaybackFinishedistener); _player.off(onRenderFirstFrameListener); _player.off(onErrorListener); _player.off(onMutedListener); _player.off(onUnmutedListener); _player.off(onSeekListener); _player.off(onSeekedListener); _player.off(onFullscreenEnterListener); _player.off(onFullscreenExitListener); } private final EventListener<PlayerEvent.Ready> onReadyListener = event -> { if(_player != null && _player.getSource() != null){ WritableMap map = Arguments.createMap(); map.putString("message", "load"); map.putString("volume", String.valueOf(_player.getVolume())); map.putString("duration", String.valueOf(_player.getDuration())); _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onReady", map); } }; private final EventListener<PlayerEvent.Play> onPlayListener = event -> { if(_player != null && _player.getSource() != null){ WritableMap map = Arguments.createMap(); map.putString("message", "play"); map.putDouble("time", event.getTime()); map.putString("volume", String.valueOf(_player.getVolume())); map.putString("duration", String.valueOf(_player.getDuration())); _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onPlay", map); } }; private final EventListener<PlayerEvent.Paused> onPausedListener = event -> { if(_player != null && _player.getSource() != null){ WritableMap map = Arguments.createMap(); map.putString("message", "pause"); map.putDouble("time", event.getTime()); map.putString("volume", String.valueOf(_player.getVolume())); map.putString("duration", String.valueOf(_player.getDuration())); _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onPause", map); } }; private final EventListener<PlayerEvent.TimeChanged> onTimeChangedListener = event -> { if(_player != null && _player.getSource() != null){ // next if (configuration != null && configuration.hasKey("nextPlayback") && event.getTime() != 0.0) { if (event.getTime() <= _player.getDuration() - (configuration.getDouble("nextPlayback")) && nextCallback) { nextCallback = false; } if (event.getTime() > _player.getDuration() - (configuration.getDouble("nextPlayback")) && !nextCallback) { nextCallback = true; WritableMap map = Arguments.createMap(); map.putString("message", "next"); _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onEvent", map); } } // save if((event.getTime() > (offset + heartbeat) || event.getTime() < (offset - heartbeat)) && event.getTime() < (_player.getDuration())) { offset = event.getTime(); WritableMap map = Arguments.createMap(); map.putString("message", "save"); map.putString("time", String.valueOf(_player.getCurrentTime())); map.putString("volume", String.valueOf(_player.getVolume())); map.putString("duration", String.valueOf(_player.getDuration())); _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onEvent", map); } } }; private final EventListener<PlayerEvent.PlaybackFinished> onPlaybackFinishedistener = event -> { if(_player != null && _player.getSource() != null){ WritableMap map = Arguments.createMap(); _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onPlaybackFinished", map); } }; private final EventListener<PlayerEvent.RenderFirstFrame> onRenderFirstFrameListener = event -> { if(_player != null && _player.getSource() != null){ WritableMap map = Arguments.createMap(); _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onRenderFirstFrame", map); } }; private final EventListener<PlayerEvent.Error> onErrorListener = event -> { if(_player != null && _player.getSource() != null){ WritableMap map = Arguments.createMap(); WritableMap errorMap = Arguments.createMap(); errorMap.putInt("code", Integer.parseInt(String.valueOf(event.getCode()))); errorMap.putString("message", event.getMessage()); map.putMap("error", errorMap); _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onError", map); } }; private final EventListener<PlayerEvent.Muted> onMutedListener = event -> { if(_player != null && _player.getSource() != null){ WritableMap map = Arguments.createMap(); _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onMuted", map); } }; private final EventListener<PlayerEvent.Unmuted> onUnmutedListener = event -> { if(_player != null && _player.getSource() != null){ WritableMap map = Arguments.createMap(); _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onUnmuted", map); } }; private final EventListener<PlayerEvent.Seek> onSeekListener = event -> { if(_player != null && _player.getSource() != null){ WritableMap map = Arguments.createMap(); map.putString("message", "seek"); map.putString("time", String.valueOf(_player.getCurrentTime())); map.putDouble("position", event.getTimestamp()); map.putString("volume", String.valueOf(_player.getVolume())); map.putString("duration", String.valueOf(_player.getDuration())); if (customSeek) { customSeek = false; } else { _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onSeek", map); } } }; private final EventListener<PlayerEvent.Seeked> onSeekedListener = event -> { if(_player != null && _player.getSource() != null){ WritableMap map = Arguments.createMap(); _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onSeeked", map); } }; private final EventListener<PlayerEvent.FullscreenEnter> onFullscreenEnterListener = event -> { if(_player != null && _player.getSource() != null){ WritableMap map = Arguments.createMap(); _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onFullscreenEnter", map); } }; private final EventListener<PlayerEvent.FullscreenExit> onFullscreenExitListener = event -> { if(_player != null && _player.getSource() != null){ WritableMap map = Arguments.createMap(); _reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( _playerView.getId(), "onFullscreenExit", map); } }; }
package com.hotbitmapgg.bilibili.entity.discover; import java.util.List; /** * Created by hcc on 2016/10/3 15:47 * 100332338@qq.com * <p> * 话题中心模型类 */ public class TopicCenterInfo { private int code; private int total; private int pages; private List<ListBean> list; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } public List<ListBean> getList() { return list; } public void setList(List<ListBean> list) { this.list = list; } public static class ListBean { private String title; private String cover; private String link; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCover() { return cover; } public void setCover(String cover) { this.cover = cover; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } } }
/* * Licensed to the Hipparchus project under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.orekit.propagation.events; import org.hipparchus.ode.nonstiff.AdamsBashforthFieldIntegrator; import org.hipparchus.ode.nonstiff.DormandPrince853FieldIntegrator; import org.hipparchus.util.Decimal64; import org.hipparchus.util.Decimal64Field; import org.orekit.orbits.OrbitType; import org.orekit.propagation.FieldPropagator; import org.orekit.propagation.FieldSpacecraftState; import org.orekit.propagation.numerical.FieldNumericalPropagator; /** * Test event handling with a {@link FieldNumericalPropagator} and a {@link * AdamsBashforthFieldIntegrator}. * * @author Evan Ward */ public class FieldCloseEventsNumericalABTest extends FieldCloseEventsAbstractTest<Decimal64> { /** Constructor. */ public FieldCloseEventsNumericalABTest() { super(Decimal64Field.getInstance()); } /** * Create a propagator using the {@link #initialOrbit}. * * @param stepSize of integrator. * @return a usable propagator. */ public FieldPropagator<Decimal64> getPropagator(double stepSize) { double[][] tol = FieldNumericalPropagator .tolerances(v(10000), initialOrbit, OrbitType.CARTESIAN); final AdamsBashforthFieldIntegrator<Decimal64> integrator = new AdamsBashforthFieldIntegrator<>(field, 4, stepSize, stepSize, tol[0], tol[1]); final DormandPrince853FieldIntegrator<Decimal64> starter = new DormandPrince853FieldIntegrator<>( field, stepSize / 100, stepSize / 10, tol[0], tol[1]); starter.setInitialStepSize(v(stepSize / 20)); integrator.setStarterIntegrator(starter); final FieldNumericalPropagator<Decimal64> propagator = new FieldNumericalPropagator<>(field, integrator); propagator.setInitialState(new FieldSpacecraftState<>(initialOrbit)); propagator.setOrbitType(OrbitType.CARTESIAN); return propagator; } }
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.pnc.rest.configuration; /** * Constants for Swagger documentation API. * * @author Sebastian Laskawiec */ public interface SwaggerConstants { public static final String SUCCESS_DESCRIPTION = "Success with results"; public static final int SUCCESS_CODE = 200; public static final String ENTITY_CREATED_DESCRIPTION = "Entity successfully created"; public static final int ENTITY_CREATED_CODE = 200; public static final String NO_CONTENT_DESCRIPTION = "Success but no content provided"; public static final int NO_CONTENT_CODE = 204; public static final String INVALID_DESCRIPTION = "Invalid input parameters or validation error"; public static final int INVALID_CODE = 400; public static final String CONFLICTED_DESCRIPTION = "Conflict while saving an entity"; public static final int CONFLICTED_CODE = 409; public static final String SERVER_ERROR_DESCRIPTION = "Server error"; public static final int SERVER_ERROR_CODE = 500; public static final String FORBIDDEN_DESCRIPTION = "User must be logged in."; public static final int FORBIDDEN_CODE = 403; public static final String NOT_FOUND_DESCRIPTION = "Can not find specified result"; public static final int NOT_FOUND_CODE = 404; public static final String PAGE_INDEX_DESCRIPTION = "Page Index"; public static final String PAGE_INDEX_QUERY_PARAM = "pageIndex"; public static final String PAGE_INDEX_DEFAULT_VALUE = "0"; public static final String PAGE_SIZE_DESCRIPTION = "Pagination size"; public static final String PAGE_SIZE_QUERY_PARAM = "pageSize"; public static final String PAGE_SIZE_DEFAULT_VALUE = "50"; public static final String SORTING_DESCRIPTION = "Sorting RSQL"; public static final String SORTING_QUERY_PARAM = "sort"; public static final String QUERY_DESCRIPTION = "RSQL Query"; public static final String QUERY_QUERY_PARAM = "q"; public static final String SEARCH_DESCRIPTION = "Since this endpoint does not support queries, " + "fulltext search is hard-coded for some predefined fields (record id, configuration name) " + "and performed using this argument. " + "Empty string leaves all data unfiltered."; public static final String SEARCH_QUERY_PARAM = "search"; public static final String SEARCH_DEFAULT_VALUE = ""; }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tinkerpop.gremlin.process.traversal.traverser.util; import org.apache.tinkerpop.gremlin.process.traversal.util.FastNoSuchElementException; import org.apache.tinkerpop.gremlin.process.traversal.Traverser; import java.io.Serializable; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.Spliterator; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class TraverserSet<S> extends AbstractSet<Traverser.Admin<S>> implements Set<Traverser.Admin<S>>, Queue<Traverser.Admin<S>>, Serializable { private final Map<Traverser.Admin<S>, Traverser.Admin<S>> map = new LinkedHashMap<>(); public TraverserSet() { } public TraverserSet(final Traverser.Admin<S> traverser) { this.map.put(traverser, traverser); } @Override public Iterator<Traverser.Admin<S>> iterator() { return this.map.values().iterator(); } public Traverser.Admin<S> get(final Traverser.Admin<S> traverser) { return this.map.get(traverser); } @Override public int size() { return this.map.size(); } public long bulkSize() { return this.map.values().stream().map(Traverser::bulk).reduce(0l, (a, b) -> a + b); } @Override public boolean isEmpty() { return this.map.isEmpty(); } @Override public boolean contains(final Object traverser) { return this.map.containsKey(traverser); } @Override public boolean add(final Traverser.Admin<S> traverser) { final Traverser.Admin<S> existing = this.map.get(traverser); if (null == existing) { this.map.put(traverser, traverser); return true; } else { existing.merge(traverser); return false; } } @Override public boolean offer(final Traverser.Admin<S> traverser) { return this.add(traverser); } @Override public Traverser.Admin<S> remove() { // pop, exception if empty final Iterator<Traverser.Admin<S>> iterator = this.map.values().iterator(); if (!iterator.hasNext()) throw FastNoSuchElementException.instance(); final Traverser.Admin<S> next = iterator.next(); iterator.remove(); return next; } @Override public Traverser.Admin<S> poll() { // pop, null if empty return this.map.isEmpty() ? null : this.remove(); } @Override public Traverser.Admin<S> element() { // peek, exception if empty return this.iterator().next(); } @Override public Traverser.Admin<S> peek() { // peek, null if empty return this.map.isEmpty() ? null : this.iterator().next(); } @Override public boolean remove(final Object traverser) { return this.map.remove(traverser) != null; } @Override public void clear() { this.map.clear(); } @Override public Spliterator<Traverser.Admin<S>> spliterator() { return this.map.values().spliterator(); } @Override public String toString() { return this.map.keySet().toString(); } public void sort(final Comparator<Traverser<S>> comparator) { final List<Traverser.Admin<S>> list = new ArrayList<>(this.map.values()); Collections.sort(list, comparator); this.map.clear(); list.forEach(traverser -> this.map.put(traverser, traverser)); } }
package cc.protea.spreedly; import cc.protea.util.http.Response; public class SpreedlyException extends Exception { private static final long serialVersionUID = 1L; public Response response = null; public String errorMessage; public String errorCode; public SpreedlyException(final Exception e) { super(e); } public SpreedlyException(final Exception e, final Response response) { super(e); this.response = response; } public SpreedlyException(final Exception e, final String errorCode, final String errorMessage) { super(e); this.errorCode = errorCode; this.errorMessage = errorMessage; } }
package com.lpq.mail.entity; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * mail_send_info * @author */ @Data public class MailSendInfo implements Serializable { private Integer id; private Integer userId; private String subject; private String from; private String to; private String content; private Date date; private static final long serialVersionUID = 1L; }
package com.amazonaws.serverless.sqseventsource.messageprocessor; import com.amazonaws.services.sqs.model.Message; /** * Deserializes an SQS message into the parameterized type. * * @param <T> deserialize type. */ public interface SQSMessageDeserializer<T> { /** * Deserializes the given message into an object. * * @param message SQS message to deserialize. * @return deserialized result. */ T deserialize(Message message); }
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.cnd.debugger.common2.debugger.actions; import org.openide.util.actions.CallableSystemAction; import org.openide.util.HelpCtx; import org.netbeans.modules.cnd.debugger.common2.debugger.State; import org.netbeans.modules.cnd.debugger.common2.debugger.StateListener; import org.netbeans.modules.cnd.debugger.common2.debugger.NativeDebugger; import org.netbeans.modules.cnd.debugger.common2.debugger.NativeDebuggerManager; /** * PopLastDebuggerCall the current process */ public class PopLastDebuggerCallAction extends CallableSystemAction implements StateListener { /** Generated serial version UID. */ static final long serialVersionUID = -8705899978543961455L; // interface CallableSystemAction @Override protected boolean asynchronous() { return false; } // interface CallableSystemAction @Override public void performAction() { NativeDebugger debugger = NativeDebuggerManager.get().currentDebugger(); if (debugger != null) { debugger.popLastDebuggerCall(); } } // interface SystemAction @Override public String getName() { return Catalog.get("LBL_PopCall"); // NOI18N } // interface SystemAction @Override public HelpCtx getHelpCtx() { return new HelpCtx ("Welcome_fdide_home"); // NOI18N } // interface SystemAction @Override protected String iconResource() { return "org/netbeans/modules/cnd/debugger/common2/icons/pop_last_debugger_call.gif"; // NOI18N } // interface SystemAction @Override protected void initialize() { super.initialize(); setEnabled(false); } // interface StateListener @Override public void update(State state) { boolean enable = false; if (state != null) { enable = state.isProcess && state.isListening(); enable &= state.isDebuggerCall; if (state.isCore) enable = false; } setEnabled(enable); } }
package util.guavatest; /** * FileName NPE.java * @Description TODO * * @author hzhuolirong * 2016年12月23日 */ public class NPE { }
/* * This file is part of "lunisolar-magma". * * (C) Copyright 2014-2019 Lunisolar (http://lunisolar.eu/). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.lunisolar.magma.func.build.std; import eu.lunisolar.magma.func.*; // NOSONAR import eu.lunisolar.magma.asserts.*; // NOSONAR import javax.annotation.Nonnull; // NOSONAR import javax.annotation.Nullable; // NOSONAR import java.util.Objects;// NOSONAR import eu.lunisolar.magma.basics.meta.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR import eu.lunisolar.magma.func.action.*; // NOSONAR import eu.lunisolar.magma.func.consumer.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR import eu.lunisolar.magma.func.function.*; // NOSONAR import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR import eu.lunisolar.magma.func.function.from.*; // NOSONAR import eu.lunisolar.magma.func.function.to.*; // NOSONAR import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR import eu.lunisolar.magma.func.predicate.*; // NOSONAR import eu.lunisolar.magma.func.supplier.*; // NOSONAR import org.assertj.core.api.Assertions; //NOSONAR import org.assertj.core.api.ObjectAssert;//NOSONAR import org.testng.annotations.*; //NOSONAR import java.util.regex.Pattern; //NOSONAR import java.text.ParseException; //NOSONAR import eu.lunisolar.magma.basics.exceptions.*; //NOSONAR import java.util.concurrent.atomic.AtomicInteger; //NOSONAR import java.util.function.*; //NOSONAR import static eu.lunisolar.magma.func.build.std.ToDoubleFunctionBuilder.toDblFunction; import static eu.lunisolar.magma.func.build.std.ToDoubleFunctionBuilder.toDblFunctionFrom; import static org.assertj.core.api.Assertions.*; //NOSONAR public class ToDoubleFunctionBuilderTest<T>{ @SuppressWarnings("unchecked") public static final DefaultAttests<ObjectAssert> A = new DefaultAttests() { }; @Test public void testOtherwiseThrow() { assertThatThrownBy(() -> { ToDoubleFunction<Integer> function = toDblFunctionFrom(b-> b .build() ); function.applyAsDouble(100); fail("No exception was thrown."); }) .isExactlyInstanceOf(IllegalStateException.class) .hasMessageContaining("There is no case configured for the arguments (if any)."); } @Test public void testHandlingCanBeSetOnlyOnce() { assertThatThrownBy(() -> { ToDoubleFunction<Integer> function = toDblFunctionFrom(b-> b .withHandling(h -> h.wrapIf(RuntimeException.class::isInstance, RuntimeException::new)) .build(h -> h.wrapIf(RuntimeException.class::isInstance, RuntimeException::new)) ); fail("No exception was thrown."); }) .isExactlyInstanceOf(UnsupportedOperationException.class) .hasMessageContaining("Handling is already set for this builder."); } @Test public void testHandling() { assertThatThrownBy(() -> { ToDoubleFunction<Integer> function = toDblFunctionFrom(b -> b .otherwise(a -> { throw new RuntimeException("ORIGINAL"); }) .build(h -> h.wrapIf(RuntimeException.class::isInstance, IllegalStateException::new, "NEW EXCEPTION")) ); function.applyAsDouble(100); fail("No exception was thrown."); }) .isExactlyInstanceOf(IllegalStateException.class) .hasMessageContaining("NEW EXCEPTION") .hasCauseExactlyInstanceOf(RuntimeException.class); } @Test public void testBuild() { ToDoubleFunction<Integer> function = toDblFunctionFrom( b -> b .aCase(ce -> ce.of(a -> a == 0) .evaluate(a -> 0d)) .inCase(a -> a > 0 && a < 10).evaluate(a -> 1d) .inCase(a -> a > 10 && a < 20).evaluate(a -> 2d) .otherwise(a -> 99d) .build() ); A.attestToDblFunc(function) .doesApplyAsDbl(0).when(null).to(a -> a.isEqualTo(0d)) .doesApplyAsDbl(5).when(null).to(a -> a.isEqualTo(1d)) .doesApplyAsDbl(15).when(null).to(a -> a.isEqualTo(2d)) .doesApplyAsDbl(10).when(null).to(a -> a.isEqualTo(99d)) ; } }