gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/** * Copyright 2005-2014 Red Hat, Inc. * * Red Hat 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 io.fabric8.mq.fabric; import java.beans.PropertyEditorManager; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Dictionary; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import javax.jms.ConnectionFactory; import io.fabric8.api.Container; import io.fabric8.api.FabricService; import io.fabric8.groups.Group; import io.fabric8.groups.GroupListener; import io.fabric8.mq.fabric.discovery.FabricDiscoveryAgent; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; import org.apache.activemq.network.DiscoveryNetworkConnector; import org.apache.activemq.network.NetworkConnector; import org.apache.activemq.spring.SpringBrokerContext; import org.apache.activemq.spring.Utils; import org.apache.activemq.util.IntrospectionSupport; import org.apache.curator.framework.CuratorFramework; import org.apache.xbean.classloader.MultiParentClassLoader; import org.apache.xbean.spring.context.ResourceXmlApplicationContext; import org.apache.xbean.spring.context.impl.URIEditor; import org.osgi.framework.BundleContext; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedServiceFactory; import org.osgi.service.url.URLStreamHandlerService; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; import static io.fabric8.mq.fabric.discovery.FabricDiscoveryAgent.ActiveMQNode; public class ActiveMQServiceFactory implements ManagedServiceFactory, ServiceTrackerCustomizer<CuratorFramework, CuratorFramework> { public static final Logger LOG = LoggerFactory.getLogger(ActiveMQServiceFactory.class); public static final ThreadLocal<Properties> CONFIG_PROPERTIES = new ThreadLocal<Properties>(); private BundleContext bundleContext; // Pool management private Set<String> ownedPools = new HashSet<String>(); // Maintain a registry of configuration based on ManagedServiceFactory events. private Map<String, ClusteredConfiguration> configurations = new HashMap<String, ClusteredConfiguration>(); // Curator and FabricService tracking private ServiceTracker<FabricService, FabricService> fabricService; private ConfigThread config_thread; private CuratorFramework curator; private final List<ServiceReference<CuratorFramework>> boundCuratorRefs = new ArrayList<ServiceReference<CuratorFramework>>(); private ServiceTracker<CuratorFramework, CuratorFramework> curatorService; private Filter filter; private ServiceTracker<URLStreamHandlerService, URLStreamHandlerService> urlHandlerService; public ActiveMQServiceFactory(BundleContext bundleContext) throws InvalidSyntaxException { this.bundleContext = bundleContext; // code that was inlined through all Scala ActiveMQServiceFactory class config_thread = new ConfigThread(); config_thread.setName("ActiveMQ Configuration Watcher"); config_thread.start(); fabricService = new ServiceTracker<FabricService, FabricService>(this.bundleContext, FabricService.class, null); fabricService.open(); curatorService = new ServiceTracker<CuratorFramework, CuratorFramework>(this.bundleContext, CuratorFramework.class, this); curatorService.open(); // we need to make sure "profile" url handler is available filter = FrameworkUtil.createFilter("(&(objectClass=org.osgi.service.url.URLStreamHandlerService)(url.handler.protocol=profile))"); urlHandlerService = new ServiceTracker<URLStreamHandlerService, URLStreamHandlerService>(this.bundleContext, filter, null); urlHandlerService.open(); } /* statics - from Scala object */ static { PropertyEditorManager.registerEditor(URI.class, URIEditor.class); } public static void info(String str) { if (LOG.isInfoEnabled()) { LOG.info(str); } } public static void info(String str, Object... args) { if (LOG.isInfoEnabled()) { LOG.info(String.format(str, args)); } } public static void debug(String str) { if (LOG.isDebugEnabled()) { LOG.debug(str); } } public static void debug(String str, Object... args) { if (LOG.isDebugEnabled()) { LOG.debug(String.format(str, args)); } } public static void warn(String str) { if (LOG.isWarnEnabled()) { LOG.warn(str); } } public static void warn(String str, Object... args) { if (LOG.isWarnEnabled()) { LOG.warn(String.format(str, args)); } } public static Dictionary<String, Object> toDictionary(Properties properties) { Hashtable<String, Object> answer = new Hashtable<String, Object>(); for (String k : properties.stringPropertyNames()) { answer.put(k, properties.getProperty(k)); } return answer; } public static Properties toProperties(Dictionary<?, ?> properties) { Properties props = new Properties(); Enumeration<?> keys = properties.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); Object value = properties.get(key); props.put(key.toString(), value != null ? value.toString() : ""); } return props; } public static <T> T arg_error(String msg) { throw new IllegalArgumentException(msg); } public ServerInfo createBroker(String uri, Properties properties) throws Exception { CONFIG_PROPERTIES.set(properties); try { ClassLoader classLoader = new MultiParentClassLoader("xbean", new URL[0], new ClassLoader[] { this.getClass().getClassLoader(), BrokerService.class.getClassLoader() }); Thread.currentThread().setContextClassLoader(classLoader); Resource resource = Utils.resourceFromString(uri); ResourceXmlApplicationContext ctx = new ResourceXmlApplicationContext(resource) { @Override protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) { reader.setValidating(false); } }; String[] names = ctx.getBeanNamesForType(BrokerService.class); BrokerService broker = null; for (String name : names) { broker = ctx.getBean(name, BrokerService.class); if (broker != null) { break; } } if (broker == null) { arg_error("Configuration did not contain a BrokerService"); } String networks = properties.getProperty("network", ""); String[] networksTab = networks.split(","); for (String name : networksTab) { if (!name.isEmpty()) { LOG.info("Adding network connector " + name); NetworkConnector nc = new DiscoveryNetworkConnector(new URI("fabric:" + name)); nc.setName("fabric-" + name); Map<String, Object> networkProperties = new HashMap<String, Object>(); // use default credentials for network connector (if none was specified) networkProperties.put("network.userName", "admin"); networkProperties.put("network.password", properties.getProperty("zookeeper.password")); for (String k : properties.stringPropertyNames()) { networkProperties.put(k, properties.getProperty(k)); } IntrospectionSupport.setProperties(nc, networkProperties, "network."); if (broker != null) { // and if it's null, then exception was thrown already. It's just IDEA complaining broker.addNetworkConnector(nc); } } } SpringBrokerContext brokerContext = new SpringBrokerContext(); brokerContext.setConfigurationUrl(resource.getURL().toExternalForm()); brokerContext.setApplicationContext(ctx); if (broker != null) { broker.setBrokerContext(brokerContext); } return new ServerInfo(ctx, broker, resource); } finally { CONFIG_PROPERTIES.remove(); } } /* now non-static members from Scala class */ public synchronized boolean can_own_pool(ClusteredConfiguration cc) { return cc.pool == null || !ownedPools.contains(cc.pool); } public synchronized boolean take_pool(ClusteredConfiguration cc) { if (cc.pool == null) { return true; } else { if (ownedPools.contains(cc.pool)) { return false; } else { ownedPools.add(cc.pool); fire_pool_change(cc); return true; } } } public synchronized void return_pool(ClusteredConfiguration cc) { if (cc.pool != null) { ownedPools.remove(cc.pool); fire_pool_change(cc); } } private void fire_pool_change(final ClusteredConfiguration cc) { (new Thread() { @Override public void run() { synchronized (ActiveMQServiceFactory.this) { for (ClusteredConfiguration c : configurations.values()) { if (c != cc && c != null && c.pool != null && c.pool.equals(cc.pool)) { c.update_pool_state(); } } } } }).start(); } // ManagedServiceFactory implementation @Override public String getName() { return "ActiveMQ Server Controller"; } @Override public synchronized void updated(String pid, Dictionary<String, ?> properties) throws ConfigurationException { try { deleted(pid); configurations.put(pid, new ClusteredConfiguration(toProperties(properties))); } catch (Exception e) { ConfigurationException configurationException = new ConfigurationException(null, "Unable to parse ActiveMQ configuration: " + e.getMessage()); configurationException.initCause(e); throw configurationException; } } @Override public synchronized void deleted(String pid) { ClusteredConfiguration cc = configurations.remove(pid); if (cc != null) { try { cc.close(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } // ServiceTrackerCustomizer implementation @Override public CuratorFramework addingService(ServiceReference<CuratorFramework> reference) { final CuratorFramework curator = bundleContext.getService(reference); boundCuratorRefs.add(reference); Collections.sort(boundCuratorRefs); ServiceReference<CuratorFramework> bind = boundCuratorRefs.get(0); try { if (bind == reference) { bindCurator(curator); } else { bindCurator(curatorService.getService(bind)); } } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } return curator; } @Override public void modifiedService(ServiceReference<CuratorFramework> reference, CuratorFramework service) { } @Override public void removedService(ServiceReference<CuratorFramework> reference, CuratorFramework service) { boundCuratorRefs.remove(reference); try { if (boundCuratorRefs.isEmpty()) { bindCurator(null); } else { bindCurator(curatorService.getService(boundCuratorRefs.get(0))); } } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } private void bindCurator(CuratorFramework curator) throws Exception { this.curator = curator; synchronized (ActiveMQServiceFactory.this) { for (ClusteredConfiguration c : configurations.values()) { c.updateCurator(curator); } } } // Lifecycle public synchronized void destroy() throws InterruptedException { config_thread.running = false; config_thread.interrupt(); config_thread.join(); for (String pid : configurations.keySet()) { deleted(pid); } fabricService.close(); curatorService.close(); urlHandlerService.close(); } /** * 3 items that define Broker */ private static class ServerInfo { private /*_1*/ ResourceXmlApplicationContext context; private /*_2*/ BrokerService broker; private /*_3*/ Resource resource; public ServerInfo(ResourceXmlApplicationContext context, BrokerService broker, Resource resource) { this.context = context; this.broker = broker; this.resource = resource; } public ResourceXmlApplicationContext getContext() { return context; } public BrokerService getBroker() { return broker; } public Resource getResource() { return resource; } } private class ClusteredConfiguration { private Properties properties; private String name; private String data; private String config; private String group; private String pool; private String[] connectors; private boolean replicating; private boolean standalone; private boolean registerService; private boolean configCheck; private boolean pool_enabled = false; private long lastModified = -1L; private volatile ServerInfo server; private FabricDiscoveryAgent discoveryAgent = null; private final AtomicBoolean started = new AtomicBoolean(); // private final AtomicInteger startAttempt = new AtomicInteger(); private ExecutorService executor = Executors.newSingleThreadExecutor(); private Future<?> start_future = null; private Future<?> stop_future = null; private ServiceRegistration<javax.jms.ConnectionFactory> cfServiceRegistration = null; ClusteredConfiguration(Properties properties) throws Exception { this.properties = properties; this.name = properties.getProperty("broker-name"); if (this.name == null) this.name = System.getProperty("runtime.id"); this.data = properties.getProperty("data"); if (this.data == null) this.data = "data" + System.getProperty("file.separator") + this.name; this.config = properties.getProperty("config"); if (this.config == null) ActiveMQServiceFactory.arg_error("config property must be set"); this.group = properties.getProperty("group"); if (this.group == null) this.group = "default"; this.pool = properties.getProperty("standby.pool"); if (this.pool == null) this.pool = "default"; String connectorsProperty = properties.getProperty("connectors", ""); this.connectors = connectorsProperty.split("\\s"); this.replicating = "true".equalsIgnoreCase(properties.getProperty("replicating")); this.standalone = "true".equalsIgnoreCase(properties.getProperty("standalone")); this.registerService = "true".equalsIgnoreCase(properties.getProperty("registerService")); this.configCheck = "true".equalsIgnoreCase(properties.getProperty("config.check")); // code directly invoked in Scala case class ensure_broker_name_is_set(); if (standalone) { if (started.compareAndSet(false, true)) { info("Standalone broker %s is starting.", name); start(); } } else { urlHandlerService.waitForService(60000L); updateCurator(curator); } } private void ensure_broker_name_is_set() { if (!properties.containsKey("broker-name")) { properties.setProperty("broker-name", name); } if (!properties.containsKey("data")) { properties.setProperty("data", data); } } public synchronized void update_pool_state() { boolean value = can_own_pool(this); if (pool_enabled != value) { try { pool_enabled = value; if (value) { if (pool != null) { info("Broker %s added to pool %s.", name, pool); } discoveryAgent.start(); } else { if (pool != null) { info("Broker %s removed from pool %s.", name, pool); } discoveryAgent.stop(); } } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } public void osgiRegister(BrokerService broker) { final javax.jms.ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + broker.getBrokerName() + "?create=false"); Hashtable<String, String> properties = new Hashtable<String, String>(); properties.put("name", broker.getBrokerName()); cfServiceRegistration = bundleContext.registerService(ConnectionFactory.class/*.getName()*/, connectionFactory, properties); debug("registerService of type " + javax.jms.ConnectionFactory.class.getName() + " as: " + connectionFactory + " with name: " + broker.getBrokerName() + "; " + cfServiceRegistration); } public void osgiUnregister(BrokerService broker) { if (cfServiceRegistration != null) { cfServiceRegistration.unregister(); } debug("unregister connection factory for: " + broker.getBrokerName() + "; " + cfServiceRegistration); } private void start() { if (start_future == null || start_future.isDone()) { info("Broker %s is being started.", name); start_future = executor.submit(new Runnable() { @Override public void run() { boolean started = false; while (!started) { try { doStart(); if (server != null && server.getResource() != null) { lastModified = server.getResource().lastModified(); } started = true; } catch (Throwable e) { if (start_future.isCancelled() || Thread.currentThread().isInterrupted()) { info("Broker %s interrupted while starting", name); break; } info("Broker %s failed to start. Will try again in 10 seconds", name); LOG.error("Exception on start: " + e.getMessage(), e); try { Thread.sleep(1000 * 10); } catch (InterruptedException ignore) { info("Broker %s interrupted while starting", name); break; } } } } }); } } private void doStart() throws Exception { // If we are in a fabric, let pass along the zk password in the props. FabricService fs = fabricService.getService(); if (fs != null) { Container container = fs.getCurrentContainer(); if (!properties.containsKey("container.id")) { properties.setProperty("container.id", container.getId()); } if (!properties.containsKey("container.ip")) { properties.setProperty("container.ip", container.getIp()); } if (!properties.containsKey("zookeeper.url")) { properties.setProperty("zookeeper.url", fs.getZookeeperUrl()); } if (!properties.containsKey("zookeeper.password")) { properties.setProperty("zookeeper.password", fs.getZookeeperPassword()); } } // ok boot up the server.. info("booting up a broker from: " + config); server = createBroker(config, properties); // configure ports for (TransportConnector t : server.getBroker().getTransportConnectors()) { String portKey = t.getName() + "-port"; if (properties.containsKey(portKey)) { URI template = t.getUri(); t.setUri(new URI(template.getScheme(), template.getUserInfo(), template.getHost(), Integer.valueOf("" + properties.get(portKey)), template.getPath(), template.getQuery(), template.getFragment())); } } server.getBroker().start(); info("Broker %s has started.", name); server.getBroker().waitUntilStarted(); server.getBroker().addShutdownHook(new Runnable() { @Override public void run() { // Start up the server again if it shutdown. Perhaps // it has lost a Locker and wants a restart. if (started.get() && server != null) { if (server.getBroker().isRestartAllowed() && server.getBroker().isRestartRequested()) { info("Restarting broker '%s' after shutdown on restart request", name); if (!standalone) { discoveryAgent.setServices(new String[0]); } start(); } else { info("Broker '%s' shut down, giving up being master", name); try { updateCurator(curator); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } } }); // we only register once broker startup has completed. if (replicating) { discoveryAgent.start(); } // Update the advertised endpoint URIs that clients can use. if (!standalone || replicating) { registerConnectors(); } if (registerService) { osgiRegister(server.getBroker()); } } private void registerConnectors() throws Exception { List<String> services = new LinkedList<String>(); for (String name : connectors) { TransportConnector connector = server.getBroker().getConnectorByName(name); if (connector == null) { warn("ActiveMQ broker '%s' does not have a connector called '%s'", name, name); } else { services.add(connector.getConnectUri().getScheme() + "://${zk:" + System.getProperty("runtime.id") + "/ip}:" + connector.getPublishableConnectURI().getPort()); } } discoveryAgent.setServices(services.toArray(new String[services.size()])); } public void close() throws Exception { synchronized (this) { if (pool_enabled) { return_pool(this); } if (discoveryAgent != null) { discoveryAgent.stop(); } if (started.get()) { stop(); } } if (started.compareAndSet(true, false)) { waitForStop(); } executor.shutdownNow(); } public synchronized void stop() { interruptAndWaitForStart(); if (stop_future == null || stop_future.isDone()) { stop_future = executor.submit(new Runnable() { @Override public void run() { doStop(); } }); } } private void doStop() { final ServerInfo s = server; // working with a volatile if (s != null) { try { s.getBroker().stop(); s.getBroker().waitUntilStopped(); if (!standalone || replicating) { // clear out the services as we are no longer alive discoveryAgent.setServices(new String[0]); } if (registerService) { osgiUnregister(s.getBroker()); } } catch (Throwable e) { LOG.debug("Exception on stop: " + e.getMessage(), e); } try { s.getContext().close(); } catch (Throwable e) { LOG.debug("Exception on close: " + e.getMessage(), e); } server = null; } } private void waitForStop() throws ExecutionException, InterruptedException { if (stop_future != null && !stop_future.isDone()) { stop_future.get(); } } private void interruptAndWaitForStart() { if (start_future != null && !start_future.isDone()) { start_future.cancel(true); } } public void updateCurator(CuratorFramework curator) throws Exception { if (!standalone) { synchronized (this) { if (discoveryAgent != null) { discoveryAgent.stop(); discoveryAgent = null; if (started.compareAndSet(true, false)) { info("Lost zookeeper service for broker %s, stopping the broker.", name); stop(); waitForStop(); return_pool(this); pool_enabled = false; } } waitForStop(); if (curator != null) { info("Found zookeeper service for broker %s.", name); discoveryAgent = new FabricDiscoveryAgent(); discoveryAgent.setAgent(System.getProperty("runtime.id")); discoveryAgent.setId(name); discoveryAgent.setGroupName(group); discoveryAgent.setCurator(curator); if (replicating) { if (started.compareAndSet(false, true)) { info("Replicating broker %s is starting.", name); start(); } } else { discoveryAgent.getGroup().add(new GroupListener<ActiveMQNode>() { @Override public void groupEvent(Group<ActiveMQNode> group, GroupEvent event) { if (event.equals(GroupEvent.CONNECTED) || event.equals(GroupEvent.CHANGED)) { try { if (discoveryAgent.getGroup().isMaster(name)) { if (started.compareAndSet(false, true)) { if (take_pool(ClusteredConfiguration.this)) { info("Broker %s is now the master, starting the broker.", name); start(); } else { update_pool_state(); started.set(false); } } else { if (discoveryAgent.getServices().isEmpty()) { info("Reconnected to the group", name); registerConnectors(); } } } else { if (started.compareAndSet(true, false)) { return_pool(ClusteredConfiguration.this); info("Broker %s is now a slave, stopping the broker.", name); stop(); } else { if (event.equals(GroupEvent.CHANGED)) { info("Broker %s is slave", name); discoveryAgent.setServices(new String[0]); } } } } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } else if (event.equals(GroupEvent.DISCONNECTED)) { info("Disconnected from the group", name); discoveryAgent.setServices(new String[0]); pool_enabled = false; } } }); info("Broker %s is waiting to become the master", name); update_pool_state(); } } } } } } private class ConfigThread extends Thread { private boolean running = true; @Override public void run() { while (running) { for (ClusteredConfiguration c: configurations.values()) { try { if (c.configCheck && c.lastModified != -1 && c.server != null) { long lm = c.server.getResource().lastModified(); if (lm != c.lastModified) { c.lastModified = lm; info("updating " + c.properties); updated((String) c.properties.get("service.pid"), toDictionary(c.properties)); } } } catch (Throwable t) { // ? } } try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { // ? } } } } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.nio.channels.FileChannel; import java.util.ArrayList; import javax.imageio.metadata.IIOMetadataNode; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.omg.CORBA.Environment; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class JSGen { public static void main(String[] args) throws IOException { if(args.length != 3) { System.out.println("ERROR: Incorrect Parameters."); System.out.println("Expected: JSGen [XMLDirectory] [XSLFile] [OutputFile]"); System.exit(0); } new JSGen(args[0], args[1], args[2]); } public JSGen(String directory, String inputXslFile, String inputOutputFile) throws IOException { URL directoryURL = new URL(new URL("file", null, System.getProperty("user.dir")), directory); URL xslURL = new URL(new URL("file", null, System.getProperty("user.dir")), inputXslFile); URL outputURL = new URL(new URL("file", null, System.getProperty("user.dir")), inputOutputFile); File directoryFile = new File(directoryURL.getPath()); File xslFile = new File(xslURL.getPath()); File outputFile = new File(outputURL.getPath()); if(!directoryFile.exists()) { System.out.println("ERROR: Directory does not exist. Exiting..."); return; } if(!directoryFile.isDirectory()) { System.out.println("ERROR: XMLDirectory is not a directory. Exiting..."); return; } if(!xslFile.exists() || !xslFile.canRead()) { System.out.println("ERROR: Could not read xsl file. Exiting..."); System.exit(0); } if(outputFile.exists()) { outputFile.delete(); } try //Check the file location { outputFile.createNewFile(); } catch (IOException e) { System.out.println("ERROR: Could not create output file. Exiting..."); System.exit(0); } File[] xmlFiles = directoryFile.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if(name.endsWith(".xml")) { return true; } return false; } }); //Concatenate into one file try { File tempFile = File.createTempFile("xmlgen", ".xml"); PrintWriter writer = new PrintWriter(tempFile); writer.println("<root>"); for(File xmlFile: xmlFiles) { BufferedReader bufferedReader = new BufferedReader(new FileReader(xmlFile)); String line = bufferedReader.readLine(); while(line != null) { if(!line.trim().startsWith("<?")) { writer.println(line); } line = bufferedReader.readLine(); } bufferedReader.close(); } writer.println("</root>"); writer.close(); //Parse and capture scanner things XMLGenHandler handler = new XMLGenHandler(); SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); parser.parse(tempFile, handler); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new StreamSource(xslFile)); transformer.transform(new StreamSource(handler.getTempFile()), new StreamResult(new FileOutputStream(outputFile))); System.out.println("Javascript file successfully generated."); } catch (TransformerConfigurationException e) { System.err.println("ERROR: XSLT config exception: " + e.getMessage()); System.exit(0); } catch (TransformerException e) { System.err.println("ERROR: XSLT exception: " + e.getMessage()); System.exit(0); } } catch(IOException e) { System.err.println("ERROR: file concatenation: " + e.getMessage()); System.exit(0); } catch (ParserConfigurationException e) { System.err.println("ERROR: parser config: " + e.getMessage()); System.exit(0); } catch (SAXException e) { System.err.println("ERROR: parser exception: " + e.getMessage()); System.exit(0); } } private class XMLGenHandler extends DefaultHandler { private File outputFile; private PrintWriter outputWriter; private String parentNode; private String currentNode; private String lastName; private ArrayList<String> hierarchy; private String nodeName; private ArrayList<String> nodeParams; private ArrayList<String> nodeMethods; private ArrayList<String> nodeReturns; private boolean isNodeScanner; private boolean isJSObjectFalse; private boolean isActiveX; private boolean isVsControls; private ArrayList<String> scannerParams; private ArrayList<String> scannerMethods; private ArrayList<String> scannerReturns; private String text; public XMLGenHandler() throws IOException { outputFile = File.createTempFile("JSGen", null); outputWriter = new PrintWriter(outputFile); hierarchy = new ArrayList<String>(); scannerParams = new ArrayList<String>(); scannerMethods = new ArrayList<String>(); scannerReturns = new ArrayList<String>(); outputWriter.println("<ALLOBJECTS>"); } @Override public void endDocument() throws SAXException { finishWriting(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { hierarchy.add(qName.toLowerCase()); if(qName.equalsIgnoreCase("func")) { nodeName = ""; nodeParams = new ArrayList<String>(); nodeMethods = new ArrayList<String>(); nodeReturns = new ArrayList<String>(); isNodeScanner = false; isJSObjectFalse = false; isVsControls = false; isActiveX = false; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if(qName.equalsIgnoreCase("name") && hierarchy.size() >= 2 && hierarchy.get(hierarchy.size() - 2).equals("func")) { nodeName = text; if(nodeName.equalsIgnoreCase("scanner")) { isNodeScanner = true; } } else if(qName.equalsIgnoreCase("name") && hierarchy.size() >= 3 && hierarchy.get(hierarchy.size() - 2).equals("param") && hierarchy.get(hierarchy.size() - 3).equals("params_with_attributes")) { nodeParams.add(text); } else if(qName.equalsIgnoreCase("name") && hierarchy.size() >= 3 && hierarchy.get(hierarchy.size() - 2).equals("param") && hierarchy.get(hierarchy.size() - 3).equals("params_no_attributes")) { //is a method name nodeMethods.add(text); } else if(qName.equalsIgnoreCase("tag_name")) { //is a event nodeReturns.add(text); } else if(qName.equalsIgnoreCase("path")) { if(text.startsWith("Barcode Scanner\\")) { //Is a scanner tag isNodeScanner = true; } else if(text.startsWith("legacyObjects")) { isActiveX = true; } } else if(qName.equalsIgnoreCase("func")) { //Store Data if(isNodeScanner && !isJSObjectFalse) { scannerParams.addAll(nodeParams); scannerMethods.addAll(nodeMethods); scannerReturns.addAll(nodeReturns); } else if(!isJSObjectFalse && !isActiveX) { writeNode(); } } else if(qName.equalsIgnoreCase("jsobject")) { if(text.equalsIgnoreCase("false")) { isJSObjectFalse = true; } } else if(qName.equalsIgnoreCase("vscontrols")) { nodeParams.remove(nodeParams.size() -1); } hierarchy.remove(hierarchy.size() -1); text = null; } @Override public void characters(char[] ch, int start, int length) throws SAXException { text = new String(ch, start, length); } public File getTempFile() { return outputFile; } private void writeNode() { outputWriter.println("\t<FUNC>"); outputWriter.println("\t\t<NAME>" + nodeName + "</NAME>"); for(String method: nodeMethods) { outputWriter.println("\t\t<METHOD><NAME>" + method + "</NAME></METHOD>"); } for(String param: nodeParams) { outputWriter.println("\t\t<PARAM><NAME>" + param + "</NAME></PARAM>"); } for(String param: nodeReturns) { outputWriter.println("\t\t<RETURNS><NAME>" + param + "</NAME></RETURNS>"); } outputWriter.println("\t</FUNC>"); } private void writeScanner() { outputWriter.println("\t<FUNC>"); outputWriter.println("\t\t<NAME>scanner</NAME>"); for(String method: scannerMethods) { outputWriter.println("\t\t<METHOD><NAME>" + method + "</NAME></METHOD>"); } for(String param: scannerParams) { outputWriter.println("\t\t<PARAM><NAME>" + param + "</NAME></PARAM>"); } for(String param: scannerReturns) { outputWriter.println("\t\t<RETURNS><NAME>" + param + "</NAME></RETURNS>"); } outputWriter.println("\t</FUNC>"); } private void finishWriting() { writeScanner(); outputWriter.println("</ALLOBJECTS>"); outputWriter.close(); } } }
/* * 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.calcite.adapter.splunk; import org.apache.calcite.adapter.splunk.util.StringUtils; import org.apache.calcite.plan.RelOptRule; import org.apache.calcite.plan.RelOptRuleCall; import org.apache.calcite.plan.RelOptRuleOperand; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.logical.LogicalFilter; import org.apache.calcite.rel.logical.LogicalProject; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeField; import org.apache.calcite.rel.type.RelRecordType; import org.apache.calcite.rex.RexCall; import org.apache.calcite.rex.RexInputRef; import org.apache.calcite.rex.RexLiteral; import org.apache.calcite.rex.RexNode; import org.apache.calcite.rex.RexSlot; import org.apache.calcite.sql.SqlBinaryOperator; import org.apache.calcite.sql.SqlKind; import org.apache.calcite.sql.SqlOperator; import org.apache.calcite.sql.fun.SqlStdOperatorTable; import org.apache.calcite.sql.type.SqlTypeName; import org.apache.calcite.util.NlsString; import org.apache.calcite.util.Pair; import com.google.common.collect.ImmutableSet; import org.slf4j.Logger; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * Planner rule to push filters and projections to Splunk. */ public class SplunkPushDownRule extends RelOptRule { private static final Logger LOGGER = StringUtils.getClassTracer(SplunkPushDownRule.class); private static final Set<SqlKind> SUPPORTED_OPS = ImmutableSet.of( SqlKind.CAST, SqlKind.EQUALS, SqlKind.LESS_THAN, SqlKind.LESS_THAN_OR_EQUAL, SqlKind.GREATER_THAN, SqlKind.GREATER_THAN_OR_EQUAL, SqlKind.NOT_EQUALS, SqlKind.LIKE, SqlKind.AND, SqlKind.OR, SqlKind.NOT); public static final SplunkPushDownRule PROJECT_ON_FILTER = new SplunkPushDownRule( operand( LogicalProject.class, operand( LogicalFilter.class, operand( LogicalProject.class, operand(SplunkTableScan.class, none())))), "proj on filter on proj"); public static final SplunkPushDownRule FILTER_ON_PROJECT = new SplunkPushDownRule( operand( LogicalFilter.class, operand( LogicalProject.class, operand(SplunkTableScan.class, none()))), "filter on proj"); public static final SplunkPushDownRule FILTER = new SplunkPushDownRule( operand( LogicalFilter.class, operand(SplunkTableScan.class, none())), "filter"); public static final SplunkPushDownRule PROJECT = new SplunkPushDownRule( operand( LogicalProject.class, operand(SplunkTableScan.class, none())), "proj"); /** Creates a SplunkPushDownRule. */ protected SplunkPushDownRule(RelOptRuleOperand rule, String id) { super(rule, "SplunkPushDownRule: " + id); } // ~ Methods -------------------------------------------------------------- // implement RelOptRule public void onMatch(RelOptRuleCall call) { LOGGER.debug(description); int relLength = call.rels.length; SplunkTableScan splunkRel = (SplunkTableScan) call.rels[relLength - 1]; LogicalFilter filter; LogicalProject topProj = null; LogicalProject bottomProj = null; RelDataType topRow = splunkRel.getRowType(); int filterIdx = 2; if (call.rels[relLength - 2] instanceof LogicalProject) { bottomProj = (LogicalProject) call.rels[relLength - 2]; filterIdx = 3; // bottom projection will change the field count/order topRow = bottomProj.getRowType(); } String filterString; if (filterIdx <= relLength && call.rels[relLength - filterIdx] instanceof LogicalFilter) { filter = (LogicalFilter) call.rels[relLength - filterIdx]; int topProjIdx = filterIdx + 1; if (topProjIdx <= relLength && call.rels[relLength - topProjIdx] instanceof LogicalProject) { topProj = (LogicalProject) call.rels[relLength - topProjIdx]; } RexCall filterCall = (RexCall) filter.getCondition(); SqlOperator op = filterCall.getOperator(); List<RexNode> operands = filterCall.getOperands(); LOGGER.debug("fieldNames: {}", getFieldsString(topRow)); final StringBuilder buf = new StringBuilder(); if (getFilter(op, operands, buf, topRow.getFieldNames())) { filterString = buf.toString(); } else { return; // can't handle } } else { filterString = ""; } // top projection will change the field count/order if (topProj != null) { topRow = topProj.getRowType(); } LOGGER.debug("pre transformTo fieldNames: {}", getFieldsString(topRow)); call.transformTo( appendSearchString( filterString, splunkRel, topProj, bottomProj, topRow, null)); } /** * Appends a search string. * * @param toAppend Search string to append * @param splunkRel Relational expression * @param topProj Top projection * @param bottomProj Bottom projection */ protected RelNode appendSearchString( String toAppend, SplunkTableScan splunkRel, LogicalProject topProj, LogicalProject bottomProj, RelDataType topRow, RelDataType bottomRow) { StringBuilder updateSearchStr = new StringBuilder(splunkRel.search); if (!toAppend.isEmpty()) { updateSearchStr.append(" ").append(toAppend); } List<RelDataTypeField> bottomFields = bottomRow == null ? null : bottomRow.getFieldList(); List<RelDataTypeField> topFields = topRow == null ? null : topRow.getFieldList(); if (bottomFields == null) { bottomFields = splunkRel.getRowType().getFieldList(); } // handle bottom projection (ie choose a subset of the table fields) if (bottomProj != null) { List<RelDataTypeField> tmp = new ArrayList<RelDataTypeField>(); List<RelDataTypeField> dRow = bottomProj.getRowType().getFieldList(); for (RexNode rn : bottomProj.getProjects()) { RelDataTypeField rdtf; if (rn instanceof RexSlot) { RexSlot rs = (RexSlot) rn; rdtf = bottomFields.get(rs.getIndex()); } else { rdtf = dRow.get(tmp.size()); } tmp.add(rdtf); } bottomFields = tmp; } // field renaming: to -> from List<Pair<String, String>> renames = new LinkedList<Pair<String, String>>(); // handle top projection (ie reordering and renaming) List<RelDataTypeField> newFields = bottomFields; if (topProj != null) { LOGGER.debug("topProj: {}", String.valueOf(topProj.getPermutation())); newFields = new ArrayList<RelDataTypeField>(); int i = 0; for (RexNode rn : topProj.getProjects()) { RexInputRef rif = (RexInputRef) rn; RelDataTypeField field = bottomFields.get(rif.getIndex()); if (!bottomFields.get(rif.getIndex()).getName() .equals(topFields.get(i).getName())) { renames.add( new Pair<String, String>( bottomFields.get(rif.getIndex()).getName(), topFields.get(i).getName())); field = topFields.get(i); } newFields.add(field); } } if (!renames.isEmpty()) { updateSearchStr.append("| rename "); for (Pair<String, String> p : renames) { updateSearchStr.append(p.left).append(" AS ") .append(p.right).append(" "); } } RelDataType resultType = new RelRecordType(newFields); String searchWithFilter = updateSearchStr.toString(); RelNode rel = new SplunkTableScan( splunkRel.getCluster(), splunkRel.getTable(), splunkRel.splunkTable, searchWithFilter, splunkRel.earliest, splunkRel.latest, resultType.getFieldNames()); LOGGER.debug( "end of appendSearchString fieldNames: {}", rel.getRowType().getFieldNames()); return rel; } // ~ Private Methods ------------------------------------------------------ private static RelNode addProjectionRule(LogicalProject proj, RelNode rel) { if (proj == null) { return rel; } return LogicalProject.create(rel, proj.getProjects(), proj.getRowType()); } // TODO: use StringBuilder instead of String // TODO: refactor this to use more tree like parsing, need to also // make sure we use parens properly - currently precedence // rules are simply left to right private boolean getFilter(SqlOperator op, List<RexNode> operands, StringBuilder s, List<String> fieldNames) { if (!valid(op.getKind())) { return false; } boolean like = false; switch (op.getKind()) { case NOT: // NOT op pre-pended s = s.append(" NOT "); break; case CAST: return asd(false, operands, s, fieldNames, 0); case LIKE: like = true; break; } for (int i = 0; i < operands.size(); i++) { if (!asd(like, operands, s, fieldNames, i)) { return false; } if (op instanceof SqlBinaryOperator && i == 0) { s.append(" ").append(op).append(" "); } } return true; } private boolean asd(boolean like, List<RexNode> operands, StringBuilder s, List<String> fieldNames, int i) { RexNode operand = operands.get(i); if (operand instanceof RexCall) { s.append("("); final RexCall call = (RexCall) operand; boolean b = getFilter( call.getOperator(), call.getOperands(), s, fieldNames); if (!b) { return false; } s.append(")"); } else { if (operand instanceof RexInputRef) { if (i != 0) { return false; } int fieldIndex = ((RexInputRef) operand).getIndex(); String name = fieldNames.get(fieldIndex); s.append(name); } else { // RexLiteral String tmp = toString(like, (RexLiteral) operand); if (tmp == null) { return false; } s.append(tmp); } } return true; } private boolean valid(SqlKind kind) { return SUPPORTED_OPS.contains(kind); } private String toString(SqlOperator op) { if (op.equals(SqlStdOperatorTable.LIKE)) { return SqlStdOperatorTable.EQUALS.toString(); } else if (op.equals(SqlStdOperatorTable.NOT_EQUALS)) { return "!="; } return op.toString(); } public static String searchEscape(String str) { if (str.isEmpty()) { return "\"\""; } StringBuilder sb = new StringBuilder(str.length()); boolean quote = false; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c == '"' || c == '\\') { sb.append('\\'); } sb.append(c); quote |= !(Character.isLetterOrDigit(c) || c == '_'); } if (quote || sb.length() != str.length()) { sb.insert(0, '"'); sb.append('"'); return sb.toString(); } return str; } private String toString(boolean like, RexLiteral literal) { String value = null; SqlTypeName litSqlType = literal.getTypeName(); if (SqlTypeName.NUMERIC_TYPES.contains(litSqlType)) { value = literal.getValue().toString(); } else if (litSqlType.equals(SqlTypeName.CHAR)) { value = ((NlsString) literal.getValue()).getValue(); if (like) { value = value.replaceAll("%", "*"); } value = searchEscape(value); } return value; } // transform the call from SplunkUdxRel to FarragoJavaUdxRel // usually used to stop the optimizer from calling us protected void transformToFarragoUdxRel( RelOptRuleCall call, SplunkTableScan splunkRel, LogicalFilter filter, LogicalProject topProj, LogicalProject bottomProj) { assert false; /* RelNode rel = new EnumerableTableScan( udxRel.getCluster(), udxRel.getTable(), udxRel.getRowType(), udxRel.getServerMofId()); rel = RelOptUtil.createCastRel(rel, udxRel.getRowType(), true); rel = addProjectionRule(bottomProj, rel); if (filter != null) { rel = new LogicalFilter(filter.getCluster(), rel, filter.getCondition()); } rel = addProjectionRule(topProj, rel); call.transformTo(rel); */ } public static String getFieldsString(RelDataType row) { return row.getFieldNames().toString(); } } // End SplunkPushDownRule.java
/* * * Paros and its related class files. * * Paros is an HTTP/HTTPS proxy for assessing web application security. * Copyright (C) 2003-2004 Chinotec Technologies Company * * This program is free software; you can redistribute it and/or * modify it under the terms of the Clarified Artistic License * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // ZAP: 2014/02/21 Issue 1043: Custom active scan dialog - moved code from AbstractParamDialog // ZAP: 2015/02/16 Issue 1528: Support user defined font size // ZAP: 2016/06/14 Issue 2578: Must click on text in Options column to select row // ZAP: 2016/08/23 Respect sort parameter when adding intermediate panels // ZAP: 2016/10/27 Explicitly show other panel when the selected panel is removed. package org.parosproxy.paros.view; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import org.apache.log4j.Logger; import org.parosproxy.paros.Constant; import org.zaproxy.zap.extension.help.ExtensionHelp; import org.zaproxy.zap.utils.DisplayUtils; import org.zaproxy.zap.utils.FontUtils; import org.zaproxy.zap.utils.ZapTextField; public class AbstractParamContainerPanel extends JSplitPane { private static final String DEFAULT_ROOT_NODE_NAME = "Root"; private static final long serialVersionUID = -5223178126156052670L; protected Object paramObject = null; private Hashtable<String, AbstractParamPanel> tablePanel = new Hashtable<>(); private JButton btnHelp = null; private JPanel jPanel = null; private JTree treeParam = null; private JPanel jPanel1 = null; private JPanel panelParam = null; private JPanel panelHeadline = null; private ZapTextField txtHeadline = null; private DefaultTreeModel treeModel = null; // @jve:decl-index=0:parse,visual-constraint="14,12" private DefaultMutableTreeNode rootNode = null; // @jve:decl-index=0:parse,visual-constraint="10,50" private JScrollPane jScrollPane = null; private JScrollPane jScrollPane1 = null; // ZAP: show the last selected panel private String nameLastSelectedPanel = null; private AbstractParamPanel currentShownPanel; private ShowHelpAction showHelpAction = null; // ZAP: Added logger private static Logger log = Logger.getLogger(AbstractParamContainerPanel.class); /** * Constructs an {@code AbstractParamContainerPanel} with a default root node's name ({@value #DEFAULT_ROOT_NODE_NAME}). */ public AbstractParamContainerPanel() { super(); initialize(); } /** * Constructs an {@code AbstractParamContainerPanel} with the given root node's name. * * @param rootName the name of the root node */ public AbstractParamContainerPanel(String rootName) { initialize(); getRootNode().setUserObject(rootName); } /** * This method initializes this */ private void initialize() { this.setContinuousLayout(true); this.setRightComponent(getJPanel1()); // ZAP: added more space for readability (was 175) this.setDividerLocation(200); this.setDividerSize(3); this.setResizeWeight(0.3D); this.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.LOWERED)); this.setLeftComponent(getJScrollPane()); } /** * This method initializes jPanel * * @return javax.swing.JPanel */ private JPanel getJPanel() { if (jPanel == null) { java.awt.GridBagConstraints gridBagConstraints7 = new GridBagConstraints(); java.awt.GridBagConstraints gridBagConstraints5 = new GridBagConstraints(); gridBagConstraints5.gridwidth = 2; java.awt.GridBagConstraints gridBagConstraints2 = new GridBagConstraints(); jPanel = new JPanel(); jPanel.setLayout(new GridBagLayout()); jPanel.setName("jPanel"); gridBagConstraints2.weightx = 1.0; gridBagConstraints2.weighty = 1.0; gridBagConstraints2.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints5.gridx = 0; gridBagConstraints5.gridy = 1; gridBagConstraints5.ipadx = 0; gridBagConstraints5.ipady = 0; gridBagConstraints5.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints5.weightx = 1.0D; gridBagConstraints5.weighty = 1.0D; gridBagConstraints5.insets = new Insets(2, 5, 5, 0); gridBagConstraints5.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints7.weightx = 1.0; gridBagConstraints7.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints7.gridx = 0; gridBagConstraints7.gridy = 0; gridBagConstraints7.insets = new Insets(2, 5, 5, 0); jPanel.add(getPanelHeadline(), gridBagConstraints7); jPanel.add(getPanelParam(), gridBagConstraints5); GridBagConstraints gbc_button = new GridBagConstraints(); gbc_button.insets = new Insets(0, 5, 0, 5); gbc_button.gridx = 1; gbc_button.gridy = 0; jPanel.add(getHelpButton(), gbc_button); } return jPanel; } /** * This method initializes treeParam * * @return javax.swing.JTree */ private JTree getTreeParam() { if (treeParam == null) { treeParam = new JTree(); treeParam.setModel(getTreeModel()); treeParam.setShowsRootHandles(true); treeParam.setRootVisible(true); treeParam.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() { @Override public void valueChanged(javax.swing.event.TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) getTreeParam().getLastSelectedPathComponent(); if (node == null) { return; } String name = (String) node.getUserObject(); showParamPanel(name); } }); DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); renderer.setLeafIcon(null); renderer.setOpenIcon(null); renderer.setClosedIcon(null); treeParam.setCellRenderer(renderer); treeParam.setRowHeight(DisplayUtils.getScaledSize(18)); treeParam.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { TreePath path = treeParam.getClosestPathForLocation(e.getX(), e.getY()); if (path != null && !treeParam.isPathSelected(path)) { treeParam.setSelectionPath(path); } } }); } return treeParam; } /** * This method initializes jPanel1 * * @return javax.swing.JPanel */ private JPanel getJPanel1() { if (jPanel1 == null) { jPanel1 = new JPanel(); jPanel1.setLayout(new CardLayout()); jPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); jPanel1.add(getJScrollPane1(), getJScrollPane1().getName()); } return jPanel1; } /** * This method initializes panelParam * * @return javax.swing.JPanel */ //protected JPanel getPanelParam() { private JPanel getPanelParam() { if (panelParam == null) { panelParam = new JPanel(); panelParam.setLayout(new CardLayout()); panelParam.setPreferredSize(new java.awt.Dimension(300, 300)); panelParam.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); } return panelParam; } /** * Gets the headline panel, that shows the name of the (selected) panel and has the help button. * * @return the headline panel, never {@code null}. * @see #getTxtHeadline() * @see #getHelpButton() */ private JPanel getPanelHeadline() { if (panelHeadline == null) { panelHeadline = new JPanel(); panelHeadline.setLayout(new BorderLayout(0, 0)); txtHeadline = getTxtHeadline(); panelHeadline.add(txtHeadline, BorderLayout.CENTER); JButton button = getHelpButton(); panelHeadline.add(button, BorderLayout.EAST); } return panelHeadline; } /** * Gets text field that shows the name of the selected panel. * * @return the text field that shows the name of the selected panel */ private ZapTextField getTxtHeadline() { if (txtHeadline == null) { txtHeadline = new ZapTextField(); txtHeadline.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED)); txtHeadline.setEditable(false); txtHeadline.setEnabled(false); txtHeadline.setBackground(java.awt.Color.white); txtHeadline.setFont(FontUtils.getFont(Font.BOLD)); } return txtHeadline; } /** * This method initializes treeModel * * @return javax.swing.tree.DefaultTreeModel */ private DefaultTreeModel getTreeModel() { if (treeModel == null) { treeModel = new DefaultTreeModel(getRootNode()); treeModel.setRoot(getRootNode()); } return treeModel; } /** * This method initializes rootNode * * @return javax.swing.tree.DefaultMutableTreeNode */ protected DefaultMutableTreeNode getRootNode() { if (rootNode == null) { rootNode = new DefaultMutableTreeNode(DEFAULT_ROOT_NODE_NAME); } return rootNode; } private DefaultMutableTreeNode addParamNode(String[] paramSeq, boolean sort) { String param = null; DefaultMutableTreeNode parent = getRootNode(); DefaultMutableTreeNode child = null; DefaultMutableTreeNode result = null; for (int i = 0; i < paramSeq.length; i++) { param = paramSeq[i]; result = null; for (int j = 0; j < parent.getChildCount(); j++) { child = (DefaultMutableTreeNode) parent.getChildAt(j); if (child.toString().equalsIgnoreCase(param)) { result = child; break; } } if (result == null) { result = new DefaultMutableTreeNode(param); addNewNode(parent, result, sort); } parent = result; } return parent; } private void addNewNode(DefaultMutableTreeNode parent, DefaultMutableTreeNode node, boolean sort) { if (!sort) { getTreeModel().insertNodeInto(node, parent, parent.getChildCount()); return; } String name = node.toString(); int pos = 0; for (; pos < parent.getChildCount(); pos++) { if (name.compareToIgnoreCase(parent.getChildAt(pos).toString()) < 0) { break; } } getTreeModel().insertNodeInto(node, parent, pos); } /** * Adds the given panel with the given name positioned under the given parents (or root node if none given). * <p> * If not sorted the panel is appended to existing panels. * * @param parentParams the name of the parent nodes of the panel, might be {@code null}. * @param name the name of the panel, must not be {@code null}. * @param panel the panel, must not be {@code null}. * @param sort {@code true} if the panel should be added in alphabetic order, {@code false} otherwise */ // ZAP: Added sort option public void addParamPanel(String[] parentParams, String name, AbstractParamPanel panel, boolean sort) { if (parentParams != null) { addNewNode(addParamNode(parentParams, sort), new DefaultMutableTreeNode(name), sort); } else { // No need to create node. This is the root panel. } panel.setName(name); getPanelParam().add(panel, name); tablePanel.put(name, panel); } /** * Adds the given panel, with its {@link java.awt.Component#getName() own name}, positioned under the given parents (or root * node if none given). * <p> * If not sorted the panel is appended to existing panels. * * @param parentParams the name of the parent nodes of the panel, might be {@code null}. * @param panel the panel, must not be {@code null}. * @param sort {@code true} if the panel should be added in alphabetic order, {@code false} otherwise */ public void addParamPanel(String[] parentParams, AbstractParamPanel panel, boolean sort) { addParamPanel(parentParams, panel.getName(), panel, sort); } /** * Removes the given panel. * * @param panel the panel that will be removed */ public void removeParamPanel(AbstractParamPanel panel) { if (currentShownPanel == panel) { currentShownPanel = null; nameLastSelectedPanel = null; if (isShowing()) { if (tablePanel.isEmpty()) { getTxtHeadline().setText(""); getHelpButton().setVisible(false); } else { getTreeParam().setSelectionPath(new TreePath(getFirstAvailableNode().getPath())); } } } DefaultMutableTreeNode node = this.getTreeNodeFromPanelName(panel.getName(), true); if (node != null) { getTreeModel().removeNodeFromParent(node); } getPanelParam().remove(panel); tablePanel.remove(panel.getName()); } private DefaultMutableTreeNode getFirstAvailableNode() { if (((DefaultMutableTreeNode) getTreeModel().getRoot()).getChildCount() > 0) { return (DefaultMutableTreeNode) ((DefaultMutableTreeNode) getTreeModel().getRoot()).getChildAt(0); } return getTreeNodeFromPanelName(tablePanel.keys().nextElement()); } // ZAP: Made public so that other classes can specify which panel is displayed public void showParamPanel(String parent, String child) { if (parent == null || child == null) { return; } AbstractParamPanel panel = tablePanel.get(parent); if (panel == null) { return; } showParamPanel(panel, parent); } /** * Shows the panel with the given name. * <p> * Nothing happens if there's no panel with the given name (or the name is empty or {@code null}). * <p> * The previously shown panel (if any) is notified that it will be hidden. * * @param name the name of the panel to be shown */ public void showParamPanel(String name) { if (name == null || name.equals("")) { return; } // exit if panel name not found. AbstractParamPanel panel = tablePanel.get(name); if (panel == null) { return; } showParamPanel(panel, name); } /** * Shows the panel with the given name. * <p> * The previously shown panel (if any) is notified that it will be hidden. * * @param panel the panel that will be notified that is now shown, must not be {@code null}. * @param name the name of the panel that will be shown, must not be {@code null}. * @see AbstractParamPanel#onHide() * @see AbstractParamPanel#onShow() */ public void showParamPanel(AbstractParamPanel panel, String name) { if (currentShownPanel == panel) { return; } // ZAP: Notify previously shown panel that it was hidden if (currentShownPanel != null) { currentShownPanel.onHide(); } nameLastSelectedPanel = name; currentShownPanel = panel; getPanelHeadline(); getTxtHeadline().setText(name); getHelpButton().setVisible(panel.getHelpIndex() != null); getShowHelpAction().setHelpIndex(panel.getHelpIndex()); CardLayout card = (CardLayout) getPanelParam().getLayout(); card.show(getPanelParam(), name); // ZAP: Notify the new panel that it is now shown panel.onShow(); } /** * Initialises all panels with the given object. * * @param obj the object that contains the data to be shown in the panels and save them * @see #validateParam() * @see #saveParam() */ public void initParam(Object obj) { paramObject = obj; Enumeration<AbstractParamPanel> en = tablePanel.elements(); AbstractParamPanel panel = null; while (en.hasMoreElements()) { panel = en.nextElement(); panel.initParam(obj); } } /** * Validates all panels, throwing an exception if there's any validation error. * <p> * The message of the exception can be shown in GUI components (for example, an error dialogue) callers can expect an * internationalised message. * * @throws Exception if there's any validation error. * @see #initParam(Object) * @see #saveParam() */ public void validateParam() throws Exception { Enumeration<AbstractParamPanel> en = tablePanel.elements(); AbstractParamPanel panel = null; while (en.hasMoreElements()) { panel = en.nextElement(); panel.validateParam(paramObject); } } /** * Saves the data of all panels, throwing an exception if there's any error. * <p> * The message of the exception can be shown in GUI components (for example, an error dialogue) callers can expect an * internationalised message. * * @throws Exception if there's any error while saving the data. * @see #initParam(Object) * @see #validateParam() */ public void saveParam() throws Exception { Enumeration<AbstractParamPanel> en = tablePanel.elements(); AbstractParamPanel panel = null; while (en.hasMoreElements()) { panel = en.nextElement(); panel.saveParam(paramObject); } } public void expandRoot() { getTreeParam().expandPath(new TreePath(getRootNode())); } public void showDialog(boolean showRoot) { showDialog(showRoot, null); } // ZAP: Added option to specify panel - note this only supports one level at the moment // ZAP: show the last selected panel public void showDialog(boolean showRoot, String panel) { expandRoot(); try { DefaultMutableTreeNode node = null; if (panel != null) { node = getTreeNodeFromPanelName(panel); } if (node == null) { if (nameLastSelectedPanel != null) { node = getTreeNodeFromPanelName(nameLastSelectedPanel); } else if (showRoot) { node = (DefaultMutableTreeNode) getTreeModel().getRoot(); } else if (((DefaultMutableTreeNode) getTreeModel().getRoot()).getChildCount() > 0) { node = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) getTreeModel().getRoot()).getChildAt(0); } } if (node != null) { showParamPanel(node.toString()); getTreeParam().setSelectionPath(new TreePath(node.getPath())); } } catch (Exception e) { // ZAP: log errors log.error(e.getMessage(), e); } } // ZAP: Added accessor to the panels /** * Gets the panels shown on this dialog. * * @return the panels */ protected Collection<AbstractParamPanel> getPanels() { return tablePanel.values(); } // ZAP: show the last selected panel private DefaultMutableTreeNode getTreeNodeFromPanelName(String panel) { return this.getTreeNodeFromPanelName(panel, true); } private DefaultMutableTreeNode getTreeNodeFromPanelName(String panel, boolean recurse) { return this.getTreeNodeFromPanelName(((DefaultMutableTreeNode) getTreeModel().getRoot()), panel, recurse); } private DefaultMutableTreeNode getTreeNodeFromPanelName(DefaultMutableTreeNode parent, String panel, boolean recurse) { DefaultMutableTreeNode node = null; // ZAP: Added @SuppressWarnings annotation. @SuppressWarnings("unchecked") Enumeration<DefaultMutableTreeNode> children = parent.children(); while (children.hasMoreElements()) { DefaultMutableTreeNode child = children.nextElement(); if (panel.equals(child.toString())) { node = child; break; } else if (recurse) { node = this.getTreeNodeFromPanelName(child, panel, true); if (node != null) { break; } } } return node; } // Useful method for debugging panel issues ;) public void printTree() { this.printTree(((DefaultMutableTreeNode) getTreeModel().getRoot()), 0); } private void printTree(DefaultMutableTreeNode parent, int level) { for (int i = 0; i < level; i++) { System.out.print(" "); } System.out.print(parent.toString()); AbstractParamPanel panel = tablePanel.get(parent.toString()); if (panel != null) { System.out.print(" (" + panel.hashCode() + ")"); } System.out.println(); @SuppressWarnings("unchecked") Enumeration<DefaultMutableTreeNode> children = parent.children(); while (children.hasMoreElements()) { DefaultMutableTreeNode child = children.nextElement(); this.printTree(child, level + 1); } } public void renamePanel(AbstractParamPanel panel, String newPanelName) { DefaultMutableTreeNode node = getTreeNodeFromPanelName(panel.getName(), true); DefaultMutableTreeNode newNode = getTreeNodeFromPanelName(newPanelName, true); if (node != null && newNode == null) { // TODO work out which of these lines are really necessary ;) DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent(); node.setUserObject(newPanelName); tablePanel.remove(panel.getName()); int index = parent.getIndex(node); getTreeModel().removeNodeFromParent(node); getTreeModel().insertNodeInto(node, parent, index); if (panel == currentShownPanel) { this.nameLastSelectedPanel = newPanelName; this.currentShownPanel = null; } this.getPanelParam().remove(panel); panel.setName(newPanelName); tablePanel.put(newPanelName, panel); this.getPanelParam().add(newPanelName, panel); getTreeModel().nodeChanged(node); getTreeModel().nodeChanged(node.getParent()); } } /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setViewportView(getTreeParam()); jScrollPane.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); } return jScrollPane; } /** * This method initializes jScrollPane1 * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane1() { if (jScrollPane1 == null) { jScrollPane1 = new JScrollPane(); jScrollPane1.setName("jScrollPane1"); jScrollPane1.setViewportView(getJPanel()); jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); jScrollPane1.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_NEVER); } return jScrollPane1; } /** * Gets the button that allows to show the help page of the panel. * * @return the button to show the help page of the panel, never {@code null}. * @see #getShowHelpAction() */ private JButton getHelpButton() { if (btnHelp == null) { btnHelp = new JButton(); btnHelp.setBorder(null); btnHelp.setIcon(new ImageIcon(AbstractParamContainerPanel.class.getResource("/resource/icon/16/201.png"))); // help icon btnHelp.addActionListener(getShowHelpAction()); btnHelp.setToolTipText(Constant.messages.getString("menu.help")); } return btnHelp; } /** * Gets the action listener responsible to show the help page of the panel. * * @return the action listener that shows the help page of the panel, never {@code null}. * @see ShowHelpAction#setHelpIndex(String) */ private ShowHelpAction getShowHelpAction() { if (showHelpAction == null) { showHelpAction = new ShowHelpAction(); } return showHelpAction; } /** * An {@code ActionListener} that shows the help page using an index. */ private static final class ShowHelpAction implements ActionListener { private String helpIndex = null; @Override public void actionPerformed(ActionEvent e) { if (helpIndex != null) { ExtensionHelp.showHelp(helpIndex); } } /** * Sets the help index used to select and show the help page. * <p> * If {@code null} no help page is shown. * * @param helpIndex the help index of the help page, might be {@code null}. */ public void setHelpIndex(String helpIndex) { this.helpIndex = helpIndex; } } }
/* * Copyright (c) 2010-2019 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.model.intest; import com.evolveum.icf.dummy.resource.BreakMode; import com.evolveum.icf.dummy.resource.DummyAccount; import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.delta.*; import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; import com.evolveum.midpoint.schema.ObjectDeltaOperation; import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.DisplayableValue; import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.PolicyViolationException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; import org.testng.annotations.Test; import javax.xml.bind.JAXBException; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import static com.evolveum.midpoint.schema.GetOperationOptions.createRaw; import static com.evolveum.midpoint.schema.GetOperationOptions.createTolerateRawData; import static org.testng.AssertJUnit.*; /** * @author semancik * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestStrangeCases extends AbstractInitializedModelIntegrationTest { private static final File TEST_DIR = new File("src/test/resources/strange"); private static final File USER_DEGHOULASH_FILE = new File(TEST_DIR, "user-deghoulash.xml"); private static final String USER_DEGHOULASH_OID = "c0c010c0-d34d-b33f-f00d-1d11dd11dd11"; private static final String USER_DEGHOULASH_NAME = "deghoulash"; protected static final File USER_TEMPLATE_STRANGE_FILE = new File(TEST_DIR, "user-template-strange.xml"); protected static final String USER_TEMPLATE_STRANGE_OID = "830060c0-87f4-11e7-9a48-57789b5d92c7"; private static final String RESOURCE_DUMMY_CIRCUS_NAME = "circus"; private static final File RESOURCE_DUMMY_CIRCUS_FILE = new File(TEST_DIR, "resource-dummy-circus.xml"); private static final String RESOURCE_DUMMY_CIRCUS_OID = "65d73d14-bafb-11e6-9de3-ff46daf6e769"; private static final File ROLE_IDIOT_FILE = new File(TEST_DIR, "role-idiot.xml"); private static final String ROLE_IDIOT_OID = "12345678-d34d-b33f-f00d-555555550001"; private static final File ROLE_IDIOT_ASSIGNMENT_FILE = new File(TEST_DIR, "role-idiot-assignment.xml"); private static final String ROLE_IDIOT_ASSIGNMENT_OID = "12345678-d34d-b33f-f00d-5a5555550001"; private static final File ROLE_STUPID_FILE = new File(TEST_DIR, "role-stupid.xml"); private static final String ROLE_STUPID_OID = "12345678-d34d-b33f-f00d-555555550002"; private static final File ROLE_STUPID_ASSIGNMENT_FILE = new File(TEST_DIR, "role-stupid-assignment.xml"); private static final String ROLE_STUPID_ASSIGNMENT_OID = "12345678-d34d-b33f-f00d-5a5555550002"; private static final File ROLE_BAD_CONSTRUCTION_RESOURCE_REF_FILE = new File(TEST_DIR, "role-bad-construction-resource-ref.xml"); private static final String ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID = "54084f2c-eba0-11e5-8278-03ea5d7058d9"; private static final File ROLE_META_BAD_CONSTRUCTION_RESOURCE_REF_FILE = new File(TEST_DIR, "role-meta-bad-construction-resource-ref.xml"); private static final String ROLE_META_BAD_CONSTRUCTION_RESOURCE_REF_OID = "90b931ae-eba8-11e5-977a-b73ba58cf18b"; private static final File ROLE_TARGET_BAD_CONSTRUCTION_RESOURCE_REF_FILE = new File(TEST_DIR, "role-target-bad-construction-resource-ref.xml"); private static final String ROLE_TARGET_BAD_CONSTRUCTION_RESOURCE_REF_OID = "e69b791a-eba8-11e5-80f5-33732b18f10a"; private static final File ROLE_RECURSION_FILE = new File(TEST_DIR, "role-recursion.xml"); private static final String ROLE_RECURSION_OID = "12345678-d34d-b33f-f00d-555555550003"; private static final File ROLE_RECURSION_ASSIGNMENT_FILE = new File(TEST_DIR, "role-recursion-assignment.xml"); private static final String ROLE_RECURSION_ASSIGNMENT_OID = "12345678-d34d-b33f-f00d-5a5555550003"; private static final String NON_EXISTENT_ACCOUNT_OID = "f000f000-f000-f000-f000-f000f000f000"; private static final String RESOURCE_NONEXISTENT_OID = "00000000-f000-f000-f000-f000f000f000"; private static final File CASE_APPROVAL_FILE = new File(TEST_DIR, "case-approval.xml"); private static final String CASE_APPROVAL_OID = "402d844c-66c5-4070-8608-f0c4010284b9"; public static final File SYSTEM_CONFIGURATION_STRANGE_FILE = new File(TEST_DIR, "system-configuration-strange.xml"); private static final XMLGregorianCalendar USER_DEGHOULASH_FUNERAL_TIMESTAMP = XmlTypeConverter.createXMLGregorianCalendar(1771, 1, 2, 11, 22, 33); private static final File TREASURE_ISLAND_FILE = new File(TEST_DIR, "treasure-island.txt"); private static String treasureIsland; private String accountGuybrushOid; private String accountJackOid; private String accountJackRedOid; public TestStrangeCases() throws JAXBException { super(); } @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); initDummyResource(RESOURCE_DUMMY_CIRCUS_NAME, RESOURCE_DUMMY_CIRCUS_FILE, RESOURCE_DUMMY_CIRCUS_OID, initTask, initResult); getDummyResourceController(RESOURCE_DUMMY_RED_NAME).addAccount(ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", "Monkey Island"); repoAddObjectFromFile(ACCOUNT_GUYBRUSH_DUMMY_RED_FILE, initResult); treasureIsland = IOUtils.toString(new FileInputStream(TREASURE_ISLAND_FILE)).replace("\r\n", "\n"); // for Windows compatibility addObject(ROLE_IDIOT_FILE, initTask, initResult); addObject(ROLE_STUPID_FILE, initTask, initResult); addObject(ROLE_IDIOT_ASSIGNMENT_FILE, initTask, initResult); addObject(ROLE_RECURSION_FILE, initTask, initResult); addObject(ROLE_BAD_CONSTRUCTION_RESOURCE_REF_FILE, initTask, initResult); addObject(ROLE_META_BAD_CONSTRUCTION_RESOURCE_REF_FILE, initTask, initResult); repoAddObjectFromFile(USER_TEMPLATE_STRANGE_FILE, initResult); setDefaultObjectTemplate(UserType.COMPLEX_TYPE, USER_TEMPLATE_STRANGE_OID, initResult); // DebugUtil.setDetailedDebugDump(true); } @Override protected File getSystemConfigurationFile() { return SYSTEM_CONFIGURATION_STRANGE_FILE; } /** * Make sure we can log in as administrator. There are some problems in the * system configuration (e.g. unknown collection). But this should not profibit * login. * * Note: this will probably die even before it gets to this test. Test class * initialization won't work if administrator cannot log in. But initialization * code may change in the future. Therefore it is better to have also an explicit * test for this. * * MID-5328 */ @Test public void test010SanityAdministrator() throws Exception { final String TEST_NAME = "test010SanityAdministrator"; displayTestTitle(TEST_NAME); // GIVEN // WHEN loginAdministrator(); // THEN assertLoggedInUsername(USER_ADMINISTRATOR_USERNAME); } /** * Recursion role points to itself. The assignment should fail. * MID-3652 */ @Test public void test050AddRoleRecursionAssignment() throws Exception { final String TEST_NAME = "test050AddRoleRecursionAssignment"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); try { // WHEN addObject(ROLE_RECURSION_ASSIGNMENT_FILE, task, result); assertNotReached(); } catch (PolicyViolationException e) { // This is expected display("Expected exception", e); } // THEN assertFailure(result); assertNoObject(RoleType.class, ROLE_RECURSION_ASSIGNMENT_OID); } /** * Stupid: see Idiot * Idiot: see Stupid * * In this case the assignment loop is broken after few attempts. * * MID-3652 */ @Test public void test060AddRoleStupidAssignment() throws Exception { final String TEST_NAME = "test060AddRoleStupidAssignment"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); // WHEN addObject(ROLE_STUPID_ASSIGNMENT_FILE, task, result); // THEN assertSuccess(result); PrismObject<RoleType> role = getObject(RoleType.class, ROLE_STUPID_ASSIGNMENT_OID); assertObjectSanity(role); } /** * Attempt to add account (red) that already exists, but it is not linked. * Account is added using linkRef with account object. */ @Test public void test100ModifyUserGuybrushAddAccountDummyRedNoAttributesConflict() throws Exception { final String TEST_NAME = "test100ModifyUserGuybrushAddAccountDummyRedNoAttributesConflict"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); PrismObject<UserType> userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); PrismObject<ShadowType> account = PrismTestUtil.parseObject(ACCOUNT_GUYBRUSH_DUMMY_RED_FILE); // Remove the attributes. This will allow outbound mapping to take place instead. account.removeContainer(ShadowType.F_ATTRIBUTES); display("New account", account); ObjectDelta<UserType> userDelta = prismContext.deltaFactory().object() .createEmptyModifyDelta(UserType.class, USER_GUYBRUSH_OID); PrismReferenceValue accountRefVal = itemFactory().createReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = prismContext.deltaFactory().reference() .createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); Collection<ObjectDelta<? extends ObjectType>> deltas = (Collection)MiscUtil.createCollection(userDelta); dummyAuditService.clear(); try { // WHEN modelService.executeChanges(deltas, null, task, getCheckingProgressListenerCollection(), result); AssertJUnit.fail("Unexpected executeChanges success"); } catch (ObjectAlreadyExistsException e) { // This is expected display("Expected exception", e); } //TODO: this is not yet expected.. there is a checking code in the ProjectionValueProcessor.. // the situation is that the account which should be created has the same ICFS_NAME as the on already existing in resource // as the resource-dummy-red doesn't contain synchronization configuration part, we don't know the rule according to // which to try to match newly created account and the old one, therefore it will now ended in this ProjectionValuesProcessor with the error // this is not a trivial fix, so it has to be designed first.. (the same problem in TestAssignmentError.test222UserAssignAccountDeletedShadowRecomputeNoSync() // //WHEN // displayWhen(TEST_NAME); // modelService.executeChanges(MiscUtil.createCollection(userDelta), null, task, getCheckingProgressListenerCollection(), result); // // // THEN // displayThen(TEST_NAME); // assertPartialError(result); // end of TODO: // Check accountRef PrismObject<UserType> userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); UserType userGuybrushType = userAfter.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userGuybrushType.getLinkRef().size()); ObjectReferenceType accountRefType = userGuybrushType.getLinkRef().get(0); String accountOid = accountRefType.getOid(); assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); assertNull("Unexpected object in accountRefValue", accountRefValue.getObject()); // Check shadow PrismObject<ShadowType> accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); // Check account PrismObject<ShadowType> accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood"); // Check account in dummy resource assertDefaultDummyAccount(ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", true); result.computeStatus(); display("executeChanges result", result); TestUtil.assertFailure("executeChanges result", result); // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); dummyAuditService.assertAnyRequestDeltas(); Collection<ObjectDeltaOperation<? extends ObjectType>> auditExecution0Deltas = dummyAuditService.getExecutionDeltas(0); assertEquals("Wrong number of execution deltas", 0, auditExecution0Deltas.size()); dummyAuditService.assertExecutionOutcome(OperationResultStatus.FATAL_ERROR); //TODO: enable after fixing the above mentioned problem in ProjectionValueProcessor // // Strictly speaking, there should be just 2 records, not 3. // // But this is a strange case, not a common one. Midpoint does two attempts. // // We do not really mind about extra provisioning attempts. // assertEquals("Wrong number of execution deltas", 3, auditExecution0Deltas.size()); // // SUCCESS because there is a handled error. Real error is in next audit record. // dummyAuditService.assertExecutionOutcome(0, OperationResultStatus.SUCCESS); // // auditExecution0Deltas = dummyAuditService.getExecutionDeltas(1); // assertEquals("Wrong number of execution deltas", 2, auditExecution0Deltas.size()); // dummyAuditService.assertExecutionOutcome(1, OperationResultStatus.PARTIAL_ERROR); } @Test public void test180DeleteHalfAssignmentFromUser() throws Exception { String TEST_NAME = "test180DeleteHalfAssignmentFromUser"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); PrismObject<UserType> userOtis = createUser("otis", "Otis"); fillinUserAssignmentAccountConstruction(userOtis, RESOURCE_DUMMY_OID); display("Half-assigned user", userOtis); // Remember the assignment so we know what to remove AssignmentType assignmentType = userOtis.asObjectable().getAssignment().iterator().next(); // Add to repo to avoid processing of the assignment String userOtisOid = repositoryService.addObject(userOtis, null, result); ObjectDelta<UserType> userDelta = prismContext.deltaFactory().object().createModificationDeleteContainer(UserType.class, userOtisOid, UserType.F_ASSIGNMENT, assignmentType.asPrismContainerValue().clone()); Collection<ObjectDelta<? extends ObjectType>> deltas = MiscSchemaUtil.createCollection(userDelta); // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, getCheckingProgressListenerCollection(), result); // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); PrismObject<UserType> userOtisAfter = getUser(userOtisOid); assertNotNull("Otis is gone!", userOtisAfter); // Check accountRef assertUserNoAccountRefs(userOtisAfter); // Check if dummy resource account is gone assertNoDummyAccount("otis"); // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); dummyAuditService.assertAnyRequestDeltas(); dummyAuditService.assertExecutionDeltas(1); dummyAuditService.assertHasDelta(ChangeType.MODIFY, UserType.class); dummyAuditService.assertExecutionSuccess(); } @Test public void test190DeleteHalfAssignedUser() throws Exception { String TEST_NAME = "test190DeleteHalfAssignedUser"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); PrismObject<UserType> userNavigator = createUser("navigator", "Head of the Navigator"); fillinUserAssignmentAccountConstruction(userNavigator, RESOURCE_DUMMY_OID); display("Half-assigned user", userNavigator); // Add to repo to avoid processing of the assignment String userNavigatorOid = repositoryService.addObject(userNavigator, null, result); ObjectDelta<UserType> userDelta = prismContext.deltaFactory().object().createDeleteDelta(UserType.class, userNavigatorOid ); Collection<ObjectDelta<? extends ObjectType>> deltas = MiscSchemaUtil.createCollection(userDelta); // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, getCheckingProgressListenerCollection(), result); // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); try { getUser(userNavigatorOid); AssertJUnit.fail("navigator is still alive!"); } catch (ObjectNotFoundException ex) { // This is OK } // Check if dummy resource account is gone assertNoDummyAccount("navigator"); // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); dummyAuditService.assertAnyRequestDeltas(); dummyAuditService.assertExecutionDeltas(1); dummyAuditService.assertHasDelta(ChangeType.DELETE, UserType.class); dummyAuditService.assertExecutionSuccess(); } /** * User with linkRef that points nowhere. * MID-2134 */ @Test public void test200ModifyUserJackBrokenAccountRefAndPolyString() throws Exception { final String TEST_NAME = "test200ModifyUserJackBrokenAccountRefAndPolyString"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); addBrokenAccountRef(USER_JACK_OID); // Make sure that the polystring does not have correct norm value PolyString fullNamePolyString = new PolyString("Magnificent Captain Jack Sparrow", null); // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, fullNamePolyString); // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result, 2); PrismObject<UserType> userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Magnificent Captain Jack Sparrow"); assertAccounts(USER_JACK_OID, 0); // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); dummyAuditService.assertAnyRequestDeltas(); dummyAuditService.assertExecutionDeltas(2); dummyAuditService.assertHasDelta(ChangeType.MODIFY, UserType.class); dummyAuditService.assertExecutionOutcome(OperationResultStatus.HANDLED_ERROR); } /** * Not much to see here. Just making sure that add account goes smoothly * after previous test. Also preparing setup for following tests. * The account is simply added, not assigned. This makes it quite fragile. * This is the way how we like it (in the tests). */ @Test public void test210ModifyUserAddAccount() throws Exception { final String TEST_NAME = "test210ModifyUserAddAccount"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); // WHEN displayWhen(TEST_NAME); modifyUserAddAccount(USER_JACK_OID, ACCOUNT_JACK_DUMMY_FILE, task, result); // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); // Check accountRef PrismObject<UserType> userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); accountJackOid = getSingleLinkOid(userJack); // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); } /** * Not much to see here. Just preparing setup for following tests. * The account is simply added, not assigned. This makes it quite fragile. * This is the way how we like it (in the tests). */ @Test public void test212ModifyUserAddAccountRed() throws Exception { final String TEST_NAME = "test212ModifyUserAddAccountRed"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); // WHEN displayWhen(TEST_NAME); modifyUserAddAccount(USER_JACK_OID, ACCOUNT_JACK_DUMMY_RED_FILE, task, result); // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); // Check accountRef PrismObject<UserType> userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); assertLinks(userJack, 2); accountJackRedOid = getLinkRefOid(userJack, RESOURCE_DUMMY_RED_OID); assertNotNull(accountJackRedOid); assertDefaultDummyAccount("jack", "Jack Sparrow", true); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, "jack", "Magnificent Captain Jack Sparrow", true); } /** * Cause schema violation on the account during a provisioning operation. This should fail * the operation, but other operations should proceed and the account should definitelly NOT * be unlinked. * MID-2134 */ @Test public void test212ModifyUserJackBrokenSchemaViolationPolyString() throws Exception { final String TEST_NAME = "test212ModifyUserJackBrokenSchemaViolationPolyString"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); getDummyResource().setModifyBreakMode(BreakMode.SCHEMA); // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, new PolyString("Cpt. Jack Sparrow", null)); // THEN displayThen(TEST_NAME); result.computeStatus(); display("Result", result); TestUtil.assertPartialError(result); PrismObject<UserType> userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Cpt. Jack Sparrow"); assertLinks(userJack, 2); String accountJackRedOidAfter = getLinkRefOid(userJack, RESOURCE_DUMMY_RED_OID); assertNotNull(accountJackRedOidAfter); // The change was not propagated here because of schema violation error assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); // The change should be propagated here normally assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Cpt. Jack Sparrow", true); } /** * Cause schema violation on the account during a provisioning operation. This should fail * the operation, but other operations should proceed and the account should definitelly NOT * be unlinked. * MID-2134 */ @Test public void test214ModifyUserJackBrokenPassword() throws Exception { final String TEST_NAME = "test214ModifyUserJackBrokenPassword"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); getDummyResource().setModifyBreakMode(BreakMode.SCHEMA); // WHEN displayWhen(TEST_NAME); modifyUserChangePassword(USER_JACK_OID, "whereStheRUM", task, result); // THEN displayThen(TEST_NAME); result.computeStatus(); display("Result", result); TestUtil.assertPartialError(result); PrismObject<UserType> userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Cpt. Jack Sparrow"); assertEncryptedUserPassword(userJack, "whereStheRUM"); assertLinks(userJack, 2); String accountJackRedOidAfter = getLinkRefOid(userJack, RESOURCE_DUMMY_RED_OID); assertNotNull(accountJackRedOidAfter); // The change was not propagated here because of schema violation error assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); // The change should be propagated here normally assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Cpt. Jack Sparrow", true); } /** * Cause modification that will be mapped to the account and that will cause * conflict (AlreadyExistsException). Make sure that midpoint does not end up * in endless loop. * MID-3451 */ @Test public void test220ModifyUserJackBrokenConflict() throws Exception { final String TEST_NAME = "test220ModifyUserJackBrokenConflict"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); getDummyResource().setModifyBreakMode(BreakMode.CONFLICT); // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_LOCALITY, task, result, createPolyString("High seas")); // THEN displayThen(TEST_NAME); result.computeStatus(); display("Result", result); TestUtil.assertPartialError(result); PrismObject<UserType> userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); PrismAsserts.assertPropertyValue(userJack, UserType.F_LOCALITY, createPolyString("High seas")); assertLinks(userJack, 2); String accountJackRedOidAfter = getLinkRefOid(userJack, RESOURCE_DUMMY_RED_OID); assertNotNull(accountJackRedOidAfter); // The change was not propagated here because of schema violation error assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Caribbean"); // The change should be propagated here normally assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Cpt. Jack Sparrow", true); assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "High seas"); getDummyResource().setModifyBreakMode(BreakMode.NONE); } /** * User modification triggers PolicyViolationException being thrown from the * user template mapping. Make sure that there is a user friendly message. * MID-2650 */ @Test public void test230ModifyUserJackUserTemplatePolicyViolation() throws Exception { final String TEST_NAME = "test230ModifyUserJackUserTemplatePolicyViolation"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); getDummyResource().setModifyBreakMode(BreakMode.NONE); dummyAuditService.clear(); try { // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_COST_CENTER, task, result, "broke"); assertNotReached(); } catch (ExpressionEvaluationException e) { // THEN displayThen(TEST_NAME); display("Exception (expected)", e); assertExceptionUserFriendly(e, "We do not serve your kind here"); display("Result", result); assertFailure(result); } PrismObject<UserType> userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); } // Lets test various extension magic and border cases now. This is maybe quite hight in the architecture for // this test, but we want to make sure that none of the underlying components will screw the things up. @Test public void test300ExtensionSanity() throws Exception { final String TEST_NAME = "test300ExtensionSanity"; displayTestTitle(TEST_NAME); PrismObjectDefinition<UserType> userDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); PrismContainerDefinition<Containerable> extensionContainerDef = userDef.findContainerDefinition(UserType.F_EXTENSION); PrismAsserts.assertPropertyDefinition(extensionContainerDef, PIRACY_SHIP, DOMUtil.XSD_STRING, 1, 1); PrismAsserts.assertIndexed(extensionContainerDef, PIRACY_SHIP, true); PrismAsserts.assertPropertyDefinition(extensionContainerDef, PIRACY_TALES, DOMUtil.XSD_STRING, 0, 1); PrismAsserts.assertIndexed(extensionContainerDef, PIRACY_TALES, false); PrismAsserts.assertPropertyDefinition(extensionContainerDef, PIRACY_WEAPON, DOMUtil.XSD_STRING, 0, -1); PrismAsserts.assertIndexed(extensionContainerDef, PIRACY_WEAPON, true); PrismAsserts.assertPropertyDefinition(extensionContainerDef, PIRACY_LOOT, DOMUtil.XSD_INT, 0, 1); PrismAsserts.assertIndexed(extensionContainerDef, PIRACY_LOOT, true); PrismAsserts.assertPropertyDefinition(extensionContainerDef, PIRACY_BAD_LUCK, DOMUtil.XSD_LONG, 0, -1); PrismAsserts.assertIndexed(extensionContainerDef, PIRACY_BAD_LUCK, null); PrismAsserts.assertPropertyDefinition(extensionContainerDef, PIRACY_FUNERAL_TIMESTAMP, DOMUtil.XSD_DATETIME, 0, 1); PrismAsserts.assertIndexed(extensionContainerDef, PIRACY_FUNERAL_TIMESTAMP, true); } @Test public void test301AddUserDeGhoulash() throws Exception { final String TEST_NAME = "test301AddUserDeGhoulash"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); PrismObject<UserType> user = PrismTestUtil.parseObject(USER_DEGHOULASH_FILE); ObjectDelta<UserType> userAddDelta = DeltaFactory.Object.createAddDelta(user); Collection<ObjectDelta<? extends ObjectType>> deltas = MiscSchemaUtil.createCollection(userAddDelta); // WHEN modelService.executeChanges(deltas, null, task, getCheckingProgressListenerCollection(), result); // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); PrismObject<UserType> userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAccounts(USER_DEGHOULASH_OID, 0); // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); dummyAuditService.assertAnyRequestDeltas(); dummyAuditService.assertExecutionDeltas(1); dummyAuditService.assertHasDelta(ChangeType.ADD, UserType.class); dummyAuditService.assertExecutionSuccess(); assertBasicDeGhoulashExtension(userDeGhoulash); } @Test public void test310SearchDeGhoulashByShip() throws Exception { final String TEST_NAME = "test310SearchDeGhoulashByShip"; searchDeGhoulash(TEST_NAME, PIRACY_SHIP, "The Undead Pot"); } // There is no test311SearchDeGhoulashByTales // We cannot search by "tales". This is non-indexed string. @Test public void test312SearchDeGhoulashByWeaponSpoon() throws Exception { final String TEST_NAME = "test312SearchDeGhoulashByWeaponSpoon"; searchDeGhoulash(TEST_NAME, PIRACY_WEAPON, "spoon"); } @Test public void test313SearchDeGhoulashByWeaponFork() throws Exception { final String TEST_NAME = "test313SearchDeGhoulashByWeaponFork"; searchDeGhoulash(TEST_NAME, PIRACY_WEAPON, "fork"); } @Test public void test314SearchDeGhoulashByLoot() throws Exception { final String TEST_NAME = "test314SearchDeGhoulashByLoot"; searchDeGhoulash(TEST_NAME, PIRACY_LOOT, 424242); } @Test public void test315SearchDeGhoulashByBadLuck13() throws Exception { final String TEST_NAME = "test315SearchDeGhoulashByBadLuck13"; searchDeGhoulash(TEST_NAME, PIRACY_BAD_LUCK, 13L); } // The "badLuck" property is non-indexed. But it is long, therefore it is still searchable @Test public void test316SearchDeGhoulashByBadLuck28561() throws Exception { final String TEST_NAME = "test316SearchDeGhoulashByBadLuck28561"; searchDeGhoulash(TEST_NAME, PIRACY_BAD_LUCK, 28561L); } @Test public void test317SearchDeGhoulashByFuneralTimestamp() throws Exception { final String TEST_NAME = "test317SearchDeGhoulashByFuneralTimestamp"; searchDeGhoulash(TEST_NAME, PIRACY_FUNERAL_TIMESTAMP, USER_DEGHOULASH_FUNERAL_TIMESTAMP); } private <T> void searchDeGhoulash(String testName, QName propName, T propValue) throws Exception { TestUtil.displayTestTitle(this, testName); // GIVEN Task task = taskManager.createTaskInstance(TestStrangeCases.class.getName() + "." + testName); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); // Simple query ObjectQuery query = prismContext.queryFor(UserType.class) .item(UserType.F_EXTENSION, propName).eq(propValue) .build(); // WHEN, THEN searchDeGhoulash(testName, query, task, result); // Complex query, combine with a name. This results in join down in the database query = prismContext.queryFor(UserType.class) .item(UserType.F_NAME).eq(USER_DEGHOULASH_NAME) .and().item(UserType.F_EXTENSION, propName).eq(propValue) .build(); // WHEN, THEN searchDeGhoulash(testName, query, task, result); } private <T> void searchDeGhoulash(String testName, ObjectQuery query, Task task, OperationResult result) throws Exception { // WHEN List<PrismObject<UserType>> users = modelService.searchObjects(UserType.class, query, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertFalse("No user found", users.isEmpty()); assertEquals("Wrong number of users found", 1, users.size()); PrismObject<UserType> userDeGhoulash = users.iterator().next(); display("Found user", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertBasicDeGhoulashExtension(userDeGhoulash); } private void assertBasicDeGhoulashExtension(PrismObject<UserType> userDeGhoulash) { assertExtension(userDeGhoulash, PIRACY_SHIP, "The Undead Pot"); assertExtension(userDeGhoulash, PIRACY_TALES, treasureIsland); assertExtension(userDeGhoulash, PIRACY_WEAPON, "fork", "spoon"); assertExtension(userDeGhoulash, PIRACY_LOOT, 424242); assertExtension(userDeGhoulash, PIRACY_BAD_LUCK, 13L, 169L, 2197L, 28561L, 371293L, 131313131313131313L); assertExtension(userDeGhoulash, PIRACY_FUNERAL_TIMESTAMP, USER_DEGHOULASH_FUNERAL_TIMESTAMP); } /** * Idiot and Stupid are cyclic roles. However, the assignment should proceed because now that's allowed. */ @Test public void test330AssignDeGhoulashIdiot() throws Exception { final String TEST_NAME = "test330AssignDeGhoulashIdiot"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); // WHEN assignRole(USER_DEGHOULASH_OID, ROLE_IDIOT_OID, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess(result); PrismObject<UserType> userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAssignedRoles(userDeGhoulash, ROLE_IDIOT_OID); } /** * Recursion role points to itself. The assignment should fail. * MID-3652 */ @Test public void test332AssignDeGhoulashRecursion() throws Exception { final String TEST_NAME = "test332AssignDeGhoulashRecursion"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); try { // WHEN assignRole(USER_DEGHOULASH_OID, ROLE_RECURSION_OID, task, result); assertNotReached(); } catch (PolicyViolationException e) { // This is expected display("Expected exception", e); } // THEN assertFailure(result); PrismObject<UserType> userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAssignedRoles(userDeGhoulash, ROLE_IDIOT_OID); } /** * Stupid: see Idiot * Idiot: see Stupid * * In this case the assignment loop is broken after few attempts. * * MID-3652 */ @Test public void test334AssignDeGhoulashStupidAssignment() throws Exception { final String TEST_NAME = "test334AssignDeGhoulashStupidAssignment"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); // WHEN assignRole(USER_DEGHOULASH_OID, ROLE_STUPID_ASSIGNMENT_OID, task, result); // THEN assertSuccess(result); PrismObject<UserType> userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAssignedRoles(userDeGhoulash, ROLE_IDIOT_OID, ROLE_STUPID_ASSIGNMENT_OID); } /** * Stupid: see Idiot * Idiot: see Stupid * * In this case the assignment loop is broken after few attempts. * * MID-3652 */ @Test public void test336UnassignDeGhoulashStupidAssignment() throws Exception { final String TEST_NAME = "test336UnassignDeGhoulashStupidAssignment"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); // WHEN unassignRole(USER_DEGHOULASH_OID, ROLE_STUPID_ASSIGNMENT_OID, task, result); // THEN assertSuccess(result); PrismObject<UserType> userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAssignedRoles(userDeGhoulash, ROLE_IDIOT_OID); } @Test public void test340AssignDeGhoulashConstructionNonExistentResource() throws Exception { final String TEST_NAME = "test340AssignDeGhoulashConstructionNonExistentResource"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); // WHEN // We have loose referential consistency. Even if the target resource is not present // the assignment should be added. The error is indicated in the result. assignAccountToUser(USER_DEGHOULASH_OID, RESOURCE_NONEXISTENT_OID, null, task, result); // THEN result.computeStatus(); display("Result", result); TestUtil.assertFailure(result); PrismObject<UserType> userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAssignments(userDeGhoulash, 2); } @Test public void test349UnAssignDeGhoulashConstructionNonExistentResource() throws Exception { final String TEST_NAME = "test349UnAssignDeGhoulashConstructionNonExistentResource"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); // WHEN unassignAccountFromUser(USER_DEGHOULASH_OID, RESOURCE_NONEXISTENT_OID, null, task, result); // THEN result.computeStatus(); display("Result", result); TestUtil.assertFailure(result); PrismObject<UserType> userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAssignments(userDeGhoulash, 1); assertAssignedRoles(userDeGhoulash, ROLE_IDIOT_OID); } @Test public void test350AssignDeGhoulashRoleBadConstructionResourceRef() throws Exception { final String TEST_NAME = "test350AssignDeGhoulashRoleBadConstructionResourceRef"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); // WHEN assignRole(USER_DEGHOULASH_OID, ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID, task, result); // THEN result.computeStatus(); display("result", result); TestUtil.assertPartialError(result); String message = result.getMessage(); TestUtil.assertMessageContains(message, "role:"+ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID); TestUtil.assertMessageContains(message, "Bad resourceRef in construction"); TestUtil.assertMessageContains(message, "this-oid-does-not-exist"); PrismObject<UserType> userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAssignedRoles(userDeGhoulash, ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID, ROLE_IDIOT_OID); } @Test public void test351UnAssignDeGhoulashRoleBadConstructionResourceRef() throws Exception { final String TEST_NAME = "test351UnAssignDeGhoulashRoleBadConstructionResourceRef"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); // WHEN unassignRole(USER_DEGHOULASH_OID, ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID, task, result); // THEN result.computeStatus(); display("result", result); TestUtil.assertPartialError(result); String message = result.getMessage(); TestUtil.assertMessageContains(message, "role:"+ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID); TestUtil.assertMessageContains(message, "Bad resourceRef in construction"); TestUtil.assertMessageContains(message, "this-oid-does-not-exist"); PrismObject<UserType> userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAssignedRoles(userDeGhoulash, ROLE_IDIOT_OID); } @Test public void test360AddRoleTargetBadConstructionResourceRef() throws Exception { final String TEST_NAME = "test360AddRoleTargetBadConstructionResourceRef"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); // WHEN addObject(ROLE_TARGET_BAD_CONSTRUCTION_RESOURCE_REF_FILE, task, result); // THEN result.computeStatus(); display("result", result); TestUtil.assertPartialError(result); String message = result.getMessage(); TestUtil.assertMessageContains(message, "role:"+ROLE_META_BAD_CONSTRUCTION_RESOURCE_REF_OID); TestUtil.assertMessageContains(message, "Bad resourceRef in construction metarole"); TestUtil.assertMessageContains(message, "this-oid-does-not-exist"); } @Test public void test400ImportJackMockTask() throws Exception { final String TEST_NAME = "test400ImportJackMockTask"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); // WHEN displayWhen(TEST_NAME); importObjectFromFile(TASK_MOCK_JACK_FILE); // THEN displayThen(TEST_NAME); result.computeStatus(); assertSuccess(result); waitForTaskFinish(TASK_MOCK_JACK_OID, false); } @Test public void test401ListTasks() throws Exception { final String TEST_NAME = "test401ListTasks"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); // WHEN displayWhen(TEST_NAME); List<PrismObject<TaskType>> objects = modelService.searchObjects(TaskType.class, null, null, task, result); // THEN displayThen(TEST_NAME); assertSuccess(result); display("Tasks", objects); assertEquals("Unexpected number of tasks", 1, objects.size()); boolean found = false; for (PrismObject<TaskType> object: objects) { if (object.getOid().equals(TASK_MOCK_JACK_OID)) { found = true; } } assertTrue("Mock task not found (model)", found); // ClusterStatusInformation clusterStatusInformation = taskManager.getRunningTasksClusterwide(result); // display("Cluster status", clusterStatusInformation); // TaskInfo jackTaskInfo = null; // Set<TaskInfo> taskInfos = clusterStatusInformation.getTasks(); // for (TaskInfo taskInfo: taskInfos) { // if (taskInfo.getOid().equals(TASK_MOCK_JACK_OID)) { // jackTaskInfo = taskInfo; // } // } // assertNotNull("Mock task not found (taskManager)", jackTaskInfo); // Make sure that the tasks still runs waitForTaskFinish(TASK_MOCK_JACK_OID, false); } /** * Delete user jack. See that Jack's tasks are still there (although they may be broken) */ @Test public void test410DeleteJack() throws Exception { final String TEST_NAME = "test410DeleteJack"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); // WHEN displayWhen(TEST_NAME); deleteObject(UserType.class, USER_JACK_OID, task, result); // THEN displayThen(TEST_NAME); assertSuccess(result); // Make sure the user is gone assertNoObject(UserType.class, USER_JACK_OID, task, result); List<PrismObject<TaskType>> objects = modelService.searchObjects(TaskType.class, null, null, task, result); display("Tasks", objects); assertEquals("Unexpected number of tastsk", 1, objects.size()); PrismObject<TaskType> jackTask = null; for (PrismObject<TaskType> object: objects) { if (object.getOid().equals(TASK_MOCK_JACK_OID)) { jackTask = object; } } assertNotNull("Mock task not found (model)", jackTask); display("Jack's task (model)", jackTask); // ClusterStatusInformation clusterStatusInformation = taskManager.getRunningTasksClusterwide(result); // display("Cluster status", clusterStatusInformation); // TaskInfo jackTaskInfo = null; // Set<TaskInfo> taskInfos = clusterStatusInformation.getTasks(); // for (TaskInfo taskInfo: taskInfos) { // if (taskInfo.getOid().equals(TASK_MOCK_JACK_OID)) { // jackTaskInfo = taskInfo; // } // } // assertNotNull("Mock task not found (taskManager)", jackTaskInfo); // display("Jack's task (taskManager)", jackTaskInfo); // TODO: check task status } /** * Adding approval case with a complex polystring name (no orig or norm). * Orig and norm should be automatically computed when the object is added. * MID-5577 */ @Test public void test450AddApprovalCase() throws Exception { final String TEST_NAME = "test450AddApprovalCase"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); // WHEN addObject(CASE_APPROVAL_FILE, task, result); // THEN assertSuccess(result); assertCaseAfter(CASE_APPROVAL_OID) .name() .assertOrig("Assigning role \"Manager\" to user \"vera\""); } @Test public void test500EnumerationExtension() throws Exception { final String TEST_NAME = "test500EnumerationExtension"; displayTestTitle(TEST_NAME); PrismObjectDefinition<UserType> userDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); PrismPropertyDefinition<String> markDef = userDef.findPropertyDefinition(ItemPath.create(UserType.F_EXTENSION, PIRACY_MARK)); // WHEN TestUtil.assertSetEquals("Wrong allowedValues in mark", MiscUtil.getValuesFromDisplayableValues(markDef.getAllowedValues()), "pegLeg","noEye","hook","tatoo","scar","bravery"); for (DisplayableValue<String> disp: markDef.getAllowedValues()) { if (disp.getValue().equals("pegLeg")) { assertEquals("Wrong pegLeg label", "Peg Leg", disp.getLabel()); } } } @Test public void test502EnumerationStoreGood() throws Exception { final String TEST_NAME = "test502EnumerationStoreGood"; displayTestTitle(TEST_NAME); // GIVEN PrismObjectDefinition<UserType> userDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); PrismPropertyDefinition<String> markDef = userDef.findPropertyDefinition(ItemPath.create(UserType.F_EXTENSION, PIRACY_MARK)); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); // WHEN modifyObjectReplaceProperty(UserType.class, USER_GUYBRUSH_OID, ItemPath.create(UserType.F_EXTENSION, PIRACY_MARK), task, result, "bravery"); // THEN displayThen(TEST_NAME); assertSuccess(result); PrismObject<UserType> user = getUser(USER_GUYBRUSH_OID); PrismProperty<String> markProp = user.findProperty(ItemPath.create(UserType.F_EXTENSION, PIRACY_MARK)); assertEquals("Bad mark", "bravery", markProp.getRealValue()); } /** * Guybrush has stored mark "bravery". Change schema so this value becomes illegal. * They try to read it. */ @Test // MID-2260 public void test510EnumerationGetBad() throws Exception { final String TEST_NAME = "test510EnumerationGetBad"; displayTestTitle(TEST_NAME); PrismObjectDefinition<UserType> userDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); PrismPropertyDefinition<String> markDef = userDef.findPropertyDefinition(ItemPath.create(UserType.F_EXTENSION, PIRACY_MARK)); Iterator<? extends DisplayableValue<String>> iterator = markDef.getAllowedValues().iterator(); DisplayableValue<String> braveryValue = null; while (iterator.hasNext()) { DisplayableValue<String> disp = iterator.next(); if (disp.getValue().equals("bravery")) { braveryValue = disp; iterator.remove(); } } // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); // WHEN PrismObject<UserType> user = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); // THEN displayThen(TEST_NAME); assertSuccess(result); PrismProperty<String> markProp = user.findProperty(ItemPath.create(UserType.F_EXTENSION, PIRACY_MARK)); assertEquals("Bad mark", null, markProp.getRealValue()); ((Collection) markDef.getAllowedValues()).add(braveryValue); // because of the following test } /** * Store value in extension/ship. Then remove extension/ship definition from the schema. * The next read should NOT fail, because of the 'tolerate raw data' mode. */ @Test public void test520ShipReadBadTolerateRawData() throws Exception { final String TEST_NAME = "test520ShipReadBadTolerateRawData"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); modifyObjectReplaceProperty(UserType.class, USER_GUYBRUSH_OID, ItemPath.create(UserType.F_EXTENSION, PIRACY_SHIP), task, result, "The Pink Lady"); assertSuccess(result); changeDefinition(PIRACY_SHIP, PIRACY_SHIP_BROKEN); // WHEN modelService.getObject(UserType.class, USER_GUYBRUSH_OID, SelectorOptions.createCollection(createTolerateRawData()), task, result); // THEN displayThen(TEST_NAME); assertSuccess(result); } private void changeDefinition(QName piracyShip, QName piracyShipBroken) { PrismObjectDefinition<UserType> userDef = prismContext.getSchemaRegistry() .findObjectDefinitionByCompileTimeClass(UserType.class); PrismContainerDefinition<?> extensionDefinition = userDef.getExtensionDefinition(); List<? extends ItemDefinition> extensionDefs = extensionDefinition.getComplexTypeDefinition().getDefinitions(); for (ItemDefinition itemDefinition : extensionDefs) { if (itemDefinition.getItemName().equals(piracyShip)) { //iterator.remove(); // not possible as the collection is unmodifiable itemDefinition.toMutable().setItemName(piracyShipBroken); } } } /** * Read guybrush again. * The operation should fail, because the raw mode itself does not allow raw data (except for some objects). * * TODO reconsider this eventually, and change the test */ @Test public void test522ShipReadBadRaw() throws Exception { final String TEST_NAME = "test522ShipReadBadRaw"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); // WHEN + THEN try { modelService.getObject(UserType.class, USER_GUYBRUSH_OID, SelectorOptions.createCollection(createRaw()), task, result); fail("unexpected success"); } catch (Throwable t) { System.out.println("Got expected exception: " + t); } } /** * Read guybrush again. * The operation should fail, because of the plain mode. * * TODO reconsider this eventually, and change the test */ @Test public void test524ShipReadBadPlain() throws Exception { final String TEST_NAME = "test524ShipReadBadPlain"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); // WHEN + THEN try { modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); fail("unexpected success"); } catch (Throwable t) { System.out.println("Got expected exception: " + t); } } @Test public void test529FixSchema() throws Exception { final String TEST_NAME = "test529FixSchema"; displayTestTitle(TEST_NAME); changeDefinition(PIRACY_SHIP_BROKEN, PIRACY_SHIP); } /** * Circus resource has a circular dependency. It should fail, but it should * fail with a proper error. * MID-3522 */ @Test public void test550AssignCircus() throws Exception { final String TEST_NAME = "test550AssignCircus"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); try { // WHEN assignAccountToUser(USER_GUYBRUSH_OID, RESOURCE_DUMMY_CIRCUS_OID, null, task, result); assertNotReached(); } catch (PolicyViolationException e) { // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertFailure(result); } } @Test public void test600AddUserGuybrushAssignAccount() throws Exception { final String TEST_NAME="test600AddUserGuybrushAssignAccount"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); PrismObject<UserType> userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); Collection<ObjectDelta<? extends ObjectType>> deltas = new ArrayList<>(); ObjectDelta<UserType> accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_GUYBRUSH_OID, RESOURCE_DUMMY_OID, null, true); deltas.add(accountAssignmentUserDelta); // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, getCheckingProgressListenerCollection(), result); // THEN displayThen(TEST_NAME); assertSuccess(result); PrismObject<UserType> userAfter = getUser(USER_GUYBRUSH_OID); display("User after change execution", userAfter); accountGuybrushOid = getSingleLinkOid(userAfter); // Check shadow PrismObject<ShadowType> accountShadow = repositoryService.getObject(ShadowType.class, accountGuybrushOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountGuybrushOid, USER_GUYBRUSH_USERNAME); // Check account PrismObject<ShadowType> accountModel = modelService.getObject(ShadowType.class, accountGuybrushOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountGuybrushOid, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); // Check account in dummy resource assertDefaultDummyAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); } /** * Set attribute that is not in the schema directly into dummy resource. * Get that account. Make sure that the operations does not die. */ @Test(enabled=false) // MID-2880 public void test610GetAccountGuybrushRogueAttribute() throws Exception { final String TEST_NAME="test600AddUserGuybrushAssignAccount"; displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); getDummyResource().setEnforceSchema(false); DummyAccount dummyAccount = getDummyAccount(null, USER_GUYBRUSH_USERNAME); dummyAccount.addAttributeValues("rogue", "habakuk"); getDummyResource().setEnforceSchema(true); // WHEN displayWhen(TEST_NAME); PrismObject<ShadowType> shadow = modelService.getObject(ShadowType.class, accountGuybrushOid, null, task, result); // THEN displayThen(TEST_NAME); assertSuccess(result); display("Shadow after", shadow); assertDummyAccountShadowModel(shadow, accountGuybrushOid, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); assertDummyAccountAttribute(null, USER_GUYBRUSH_USERNAME, "rogue", "habakuk"); } private <O extends ObjectType, T> void assertExtension(PrismObject<O> object, QName propName, T... expectedValues) { PrismContainer<Containerable> extensionContainer = object.findContainer(ObjectType.F_EXTENSION); assertNotNull("No extension container in "+object, extensionContainer); PrismProperty<T> extensionProperty = extensionContainer.findProperty(ItemName.fromQName(propName)); assertNotNull("No extension property "+propName+" in "+object, extensionProperty); PrismAsserts.assertPropertyValues("Values of extension property "+propName, extensionProperty.getValues(), expectedValues); } /** * Break the user in the repo by inserting accountRef that points nowhere. */ private void addBrokenAccountRef(String userOid) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { OperationResult result = new OperationResult(TestStrangeCases.class.getName() + ".addBrokenAccountRef"); Collection<? extends ItemDelta> modifications = prismContext.deltaFactory().reference().createModificationAddCollection(UserType.class, UserType.F_LINK_REF, NON_EXISTENT_ACCOUNT_OID); repositoryService.modifyObject(UserType.class, userOid, modifications , result); assertSuccess(result); } }
/** * Copyright (c) 2013-2020 Nikita Koksharov * * 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.redisson; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.stream.Stream; import org.redisson.api.RCountDownLatch; import org.redisson.api.RFuture; import org.redisson.api.RLock; import org.redisson.api.RPermitExpirableSemaphore; import org.redisson.api.RReadWriteLock; import org.redisson.api.RSemaphore; import org.redisson.api.RSet; import org.redisson.api.RedissonClient; import org.redisson.api.SortOrder; import org.redisson.api.mapreduce.RCollectionMapReduce; import org.redisson.client.RedisClient; import org.redisson.client.codec.Codec; import org.redisson.client.protocol.RedisCommands; import org.redisson.client.protocol.decoder.ListScanResult; import org.redisson.command.CommandAsyncExecutor; import org.redisson.iterator.RedissonBaseIterator; import org.redisson.mapreduce.RedissonCollectionMapReduce; import org.redisson.misc.RedissonPromise; /** * Distributed and concurrent implementation of {@link java.util.Set} * * @author Nikita Koksharov * * @param <V> value */ public class RedissonSet<V> extends RedissonExpirable implements RSet<V>, ScanIterator { RedissonClient redisson; public RedissonSet(CommandAsyncExecutor commandExecutor, String name, RedissonClient redisson) { super(commandExecutor, name); this.redisson = redisson; } public RedissonSet(Codec codec, CommandAsyncExecutor commandExecutor, String name, RedissonClient redisson) { super(codec, commandExecutor, name); this.redisson = redisson; } @Override public <KOut, VOut> RCollectionMapReduce<V, KOut, VOut> mapReduce() { return new RedissonCollectionMapReduce<V, KOut, VOut>(this, redisson, commandExecutor.getConnectionManager()); } @Override public int size() { return get(sizeAsync()); } @Override public RFuture<Integer> sizeAsync() { return commandExecutor.readAsync(getName(), codec, RedisCommands.SCARD_INT, getName()); } @Override public boolean isEmpty() { return size() == 0; } @Override public boolean contains(Object o) { return get(containsAsync(o)); } @Override public RFuture<Boolean> containsAsync(Object o) { String name = getName(o); return commandExecutor.readAsync(name, codec, RedisCommands.SISMEMBER, name, encode(o)); } @Override public ListScanResult<Object> scanIterator(String name, RedisClient client, long startPos, String pattern, int count) { return get(scanIteratorAsync(name, client, startPos, pattern, count)); } @Override public Iterator<V> iterator(int count) { return iterator(null, count); } @Override public Iterator<V> iterator(String pattern) { return iterator(pattern, 10); } @Override public Iterator<V> iterator(final String pattern, final int count) { return new RedissonBaseIterator<V>() { @Override protected ListScanResult<Object> iterator(RedisClient client, long nextIterPos) { return scanIterator(getName(), client, nextIterPos, pattern, count); } @Override protected void remove(Object value) { RedissonSet.this.remove((V) value); } }; } @Override public Iterator<V> iterator() { return iterator(null); } @Override public RFuture<Set<V>> readAllAsync() { return commandExecutor.readAsync(getName(), codec, RedisCommands.SMEMBERS, getName()); } @Override public Set<V> readAll() { return get(readAllAsync()); } @Override public Object[] toArray() { Set<Object> res = (Set<Object>) get(readAllAsync()); return res.toArray(); } @Override public <T> T[] toArray(T[] a) { Set<Object> res = (Set<Object>) get(readAllAsync()); return res.toArray(a); } @Override public boolean add(V e) { return get(addAsync(e)); } @Override public RFuture<Boolean> addAsync(V e) { String name = getName(e); return commandExecutor.writeAsync(name, codec, RedisCommands.SADD_SINGLE, name, encode(e)); } @Override public V removeRandom() { return get(removeRandomAsync()); } @Override public RFuture<V> removeRandomAsync() { return commandExecutor.writeAsync(getName(), codec, RedisCommands.SPOP_SINGLE, getName()); } @Override public Set<V> removeRandom(int amount) { return get(removeRandomAsync(amount)); } @Override public RFuture<Set<V>> removeRandomAsync(int amount) { return commandExecutor.writeAsync(getName(), codec, RedisCommands.SPOP, getName(), amount); } @Override public V random() { return get(randomAsync()); } @Override public RFuture<V> randomAsync() { return commandExecutor.writeAsync(getName(), codec, RedisCommands.SRANDMEMBER_SINGLE, getName()); } @Override public Set<V> random(int count) { return get(randomAsync(count)); } @Override public RFuture<Set<V>> randomAsync(int count) { return commandExecutor.writeAsync(getName(), codec, RedisCommands.SRANDMEMBER, getName(), count); } @Override public RFuture<Boolean> removeAsync(Object o) { String name = getName(o); return commandExecutor.writeAsync(name, codec, RedisCommands.SREM_SINGLE, name, encode(o)); } @Override public boolean remove(Object value) { return get(removeAsync((V) value)); } @Override public RFuture<Boolean> moveAsync(String destination, V member) { String name = getName(member); return commandExecutor.writeAsync(name, codec, RedisCommands.SMOVE, name, destination, encode(member)); } @Override public boolean move(String destination, V member) { return get(moveAsync(destination, member)); } @Override public boolean containsAll(Collection<?> c) { return get(containsAllAsync(c)); } @Override public RFuture<Boolean> containsAllAsync(Collection<?> c) { if (c.isEmpty()) { return RedissonPromise.newSucceededFuture(true); } String tempName = suffixName(getName(), "redisson_temp"); return commandExecutor.evalWriteAsync(getName(), codec, RedisCommands.EVAL_BOOLEAN, "redis.call('sadd', KEYS[2], unpack(ARGV)); " + "local size = redis.call('sdiff', KEYS[2], KEYS[1]);" + "redis.call('del', KEYS[2]); " + "return #size == 0 and 1 or 0; ", Arrays.<Object>asList(getName(), tempName), encode(c).toArray()); } @Override public boolean addAll(Collection<? extends V> c) { return get(addAllAsync(c)); } @Override public RFuture<Boolean> addAllAsync(Collection<? extends V> c) { if (c.isEmpty()) { return RedissonPromise.newSucceededFuture(false); } List<Object> args = new ArrayList<Object>(c.size() + 1); args.add(getName()); encode(args, c); return commandExecutor.writeAsync(getName(), codec, RedisCommands.SADD_BOOL, args.toArray()); } @Override public boolean retainAll(Collection<?> c) { return get(retainAllAsync(c)); } @Override public RFuture<Boolean> retainAllAsync(Collection<?> c) { if (c.isEmpty()) { return deleteAsync(); } String tempName = suffixName(getName(), "redisson_temp"); return commandExecutor.evalWriteAsync(getName(), codec, RedisCommands.EVAL_BOOLEAN, "redis.call('sadd', KEYS[2], unpack(ARGV)); " + "local prevSize = redis.call('scard', KEYS[1]); " + "local size = redis.call('sinterstore', KEYS[1], KEYS[1], KEYS[2]);" + "redis.call('del', KEYS[2]); " + "return size ~= prevSize and 1 or 0; ", Arrays.<Object>asList(getName(), tempName), encode(c).toArray()); } @Override public RFuture<Boolean> removeAllAsync(Collection<?> c) { if (c.isEmpty()) { return RedissonPromise.newSucceededFuture(false); } List<Object> args = new ArrayList<Object>(c.size() + 1); args.add(getName()); encode(args, c); return commandExecutor.writeAsync(getName(), codec, RedisCommands.SREM_SINGLE, args.toArray()); } @Override public boolean removeAll(Collection<?> c) { return get(removeAllAsync(c)); } @Override public int union(String... names) { return get(unionAsync(names)); } @Override public RFuture<Integer> unionAsync(String... names) { List<Object> args = new ArrayList<Object>(names.length + 1); args.add(getName()); args.addAll(Arrays.asList(names)); return commandExecutor.writeAsync(getName(), codec, RedisCommands.SUNIONSTORE_INT, args.toArray()); } @Override public Set<V> readUnion(String... names) { return get(readUnionAsync(names)); } @Override public RFuture<Set<V>> readUnionAsync(String... names) { List<Object> args = new ArrayList<Object>(names.length + 1); args.add(getName()); args.addAll(Arrays.asList(names)); return commandExecutor.writeAsync(getName(), codec, RedisCommands.SUNION, args.toArray()); } @Override public int diff(String... names) { return get(diffAsync(names)); } @Override public RFuture<Integer> diffAsync(String... names) { List<Object> args = new ArrayList<Object>(names.length + 1); args.add(getName()); args.addAll(Arrays.asList(names)); return commandExecutor.writeAsync(getName(), codec, RedisCommands.SDIFFSTORE_INT, args.toArray()); } @Override public Set<V> readDiff(String... names) { return get(readDiffAsync(names)); } @Override public RFuture<Set<V>> readDiffAsync(String... names) { List<Object> args = new ArrayList<Object>(names.length + 1); args.add(getName()); args.addAll(Arrays.asList(names)); return commandExecutor.writeAsync(getName(), codec, RedisCommands.SDIFF, args.toArray()); } @Override public int intersection(String... names) { return get(intersectionAsync(names)); } @Override public RFuture<Integer> intersectionAsync(String... names) { List<Object> args = new ArrayList<Object>(names.length + 1); args.add(getName()); args.addAll(Arrays.asList(names)); return commandExecutor.writeAsync(getName(), codec, RedisCommands.SINTERSTORE_INT, args.toArray()); } @Override public Set<V> readIntersection(String... names) { return get(readIntersectionAsync(names)); } @Override public RFuture<Set<V>> readIntersectionAsync(String... names) { List<Object> args = new ArrayList<Object>(names.length + 1); args.add(getName()); args.addAll(Arrays.asList(names)); return commandExecutor.writeAsync(getName(), codec, RedisCommands.SINTER, args.toArray()); } @Override public void clear() { delete(); } @Override @SuppressWarnings("AvoidInlineConditionals") public String toString() { Iterator<V> it = iterator(); if (! it.hasNext()) return "[]"; StringBuilder sb = new StringBuilder(); sb.append('['); for (;;) { V e = it.next(); sb.append(e == this ? "(this Collection)" : e); if (! it.hasNext()) return sb.append(']').toString(); sb.append(',').append(' '); } } @Override public Set<V> readSort(SortOrder order) { return get(readSortAsync(order)); } @Override public RFuture<Set<V>> readSortAsync(SortOrder order) { return commandExecutor.readAsync(getName(), codec, RedisCommands.SORT_SET, getName(), order); } @Override public Set<V> readSort(SortOrder order, int offset, int count) { return get(readSortAsync(order, offset, count)); } @Override public RFuture<Set<V>> readSortAsync(SortOrder order, int offset, int count) { return commandExecutor.readAsync(getName(), codec, RedisCommands.SORT_SET, getName(), "LIMIT", offset, count, order); } @Override public Set<V> readSort(String byPattern, SortOrder order) { return get(readSortAsync(byPattern, order)); } @Override public RFuture<Set<V>> readSortAsync(String byPattern, SortOrder order) { return commandExecutor.readAsync(getName(), codec, RedisCommands.SORT_SET, getName(), "BY", byPattern, order); } @Override public Set<V> readSort(String byPattern, SortOrder order, int offset, int count) { return get(readSortAsync(byPattern, order, offset, count)); } @Override public RFuture<Set<V>> readSortAsync(String byPattern, SortOrder order, int offset, int count) { return commandExecutor.readAsync(getName(), codec, RedisCommands.SORT_SET, getName(), "BY", byPattern, "LIMIT", offset, count, order); } @Override public <T> Collection<T> readSort(String byPattern, List<String> getPatterns, SortOrder order) { return (Collection<T>) get(readSortAsync(byPattern, getPatterns, order)); } @Override public <T> RFuture<Collection<T>> readSortAsync(String byPattern, List<String> getPatterns, SortOrder order) { return readSortAsync(byPattern, getPatterns, order, -1, -1); } @Override public <T> Collection<T> readSort(String byPattern, List<String> getPatterns, SortOrder order, int offset, int count) { return (Collection<T>) get(readSortAsync(byPattern, getPatterns, order, offset, count)); } @Override public <T> RFuture<Collection<T>> readSortAsync(String byPattern, List<String> getPatterns, SortOrder order, int offset, int count) { return readSortAsync(byPattern, getPatterns, order, offset, count, false); } @Override public Set<V> readSortAlpha(SortOrder order) { return get(readSortAlphaAsync(order)); } @Override public Set<V> readSortAlpha(SortOrder order, int offset, int count) { return get(readSortAlphaAsync(order, offset, count)); } @Override public Set<V> readSortAlpha(String byPattern, SortOrder order) { return get(readSortAlphaAsync(byPattern, order)); } @Override public Set<V> readSortAlpha(String byPattern, SortOrder order, int offset, int count) { return get(readSortAlphaAsync(byPattern, order, offset, count)); } @Override public <T> Collection<T> readSortAlpha(String byPattern, List<String> getPatterns, SortOrder order) { return (Collection<T>) get(readSortAlphaAsync(byPattern, getPatterns, order)); } @Override public <T> Collection<T> readSortAlpha(String byPattern, List<String> getPatterns, SortOrder order, int offset, int count) { return (Collection<T>) get(readSortAlphaAsync(byPattern, getPatterns, order, offset, count)); } @Override public RFuture<Set<V>> readSortAlphaAsync(SortOrder order) { return commandExecutor.readAsync(getName(), codec, RedisCommands.SORT_SET, getName(), "ALPHA", order); } @Override public RFuture<Set<V>> readSortAlphaAsync(SortOrder order, int offset, int count) { return commandExecutor.readAsync(getName(), codec, RedisCommands.SORT_SET, getName(), "LIMIT", offset, count, "ALPHA", order); } @Override public RFuture<Set<V>> readSortAlphaAsync(String byPattern, SortOrder order) { return commandExecutor.readAsync(getName(), codec, RedisCommands.SORT_SET, getName(), "BY", byPattern, "ALPHA", order); } @Override public RFuture<Set<V>> readSortAlphaAsync(String byPattern, SortOrder order, int offset, int count) { return commandExecutor.readAsync(getName(), codec, RedisCommands.SORT_SET, getName(), "BY", byPattern, "LIMIT", offset, count, "ALPHA", order); } @Override public <T> RFuture<Collection<T>> readSortAlphaAsync(String byPattern, List<String> getPatterns, SortOrder order) { return readSortAlphaAsync(byPattern, getPatterns, order, -1, -1); } @Override public <T> RFuture<Collection<T>> readSortAlphaAsync(String byPattern, List<String> getPatterns, SortOrder order, int offset, int count) { return readSortAsync(byPattern, getPatterns, order, offset, count, true); } @Override public int sortTo(String destName, SortOrder order) { return get(sortToAsync(destName, order)); } @Override public RFuture<Integer> sortToAsync(String destName, SortOrder order) { return sortToAsync(destName, null, Collections.<String>emptyList(), order, -1, -1); } @Override public int sortTo(String destName, SortOrder order, int offset, int count) { return get(sortToAsync(destName, order, offset, count)); } @Override public RFuture<Integer> sortToAsync(String destName, SortOrder order, int offset, int count) { return sortToAsync(destName, null, Collections.<String>emptyList(), order, offset, count); } @Override public int sortTo(String destName, String byPattern, SortOrder order, int offset, int count) { return get(sortToAsync(destName, byPattern, order, offset, count)); } @Override public int sortTo(String destName, String byPattern, SortOrder order) { return get(sortToAsync(destName, byPattern, order)); } @Override public RFuture<Integer> sortToAsync(String destName, String byPattern, SortOrder order) { return sortToAsync(destName, byPattern, Collections.<String>emptyList(), order, -1, -1); } @Override public RFuture<Integer> sortToAsync(String destName, String byPattern, SortOrder order, int offset, int count) { return sortToAsync(destName, byPattern, Collections.<String>emptyList(), order, offset, count); } @Override public int sortTo(String destName, String byPattern, List<String> getPatterns, SortOrder order) { return get(sortToAsync(destName, byPattern, getPatterns, order)); } @Override public RFuture<Integer> sortToAsync(String destName, String byPattern, List<String> getPatterns, SortOrder order) { return sortToAsync(destName, byPattern, getPatterns, order, -1, -1); } @Override public int sortTo(String destName, String byPattern, List<String> getPatterns, SortOrder order, int offset, int count) { return get(sortToAsync(destName, byPattern, getPatterns, order, offset, count)); } @Override public RFuture<Integer> sortToAsync(String destName, String byPattern, List<String> getPatterns, SortOrder order, int offset, int count) { List<Object> params = new ArrayList<Object>(); params.add(getName()); if (byPattern != null) { params.add("BY"); params.add(byPattern); } if (offset != -1 && count != -1) { params.add("LIMIT"); } if (offset != -1) { params.add(offset); } if (count != -1) { params.add(count); } for (String pattern : getPatterns) { params.add("GET"); params.add(pattern); } params.add(order); params.add("STORE"); params.add(destName); return commandExecutor.writeAsync(getName(), codec, RedisCommands.SORT_TO, params.toArray()); } @Override public boolean tryAdd(V... values) { return get(tryAddAsync(values)); } @Override public RFuture<Boolean> tryAddAsync(V... values) { return commandExecutor.evalWriteAsync(getName(), codec, RedisCommands.EVAL_BOOLEAN, "for i, v in ipairs(ARGV) do " + "if redis.call('sismember', KEYS[1], v) == 1 then " + "return 0; " + "end; " + "end; " + "for i=1, #ARGV, 5000 do " + "redis.call('sadd', KEYS[1], unpack(ARGV, i, math.min(i+4999, #ARGV))); " + "end; " + "return 1; ", Arrays.asList(getName()), encode(values).toArray()); } @Override public RPermitExpirableSemaphore getPermitExpirableSemaphore(V value) { String lockName = getLockByValue(value, "permitexpirablesemaphore"); return new RedissonPermitExpirableSemaphore(commandExecutor, lockName); } @Override public RSemaphore getSemaphore(V value) { String lockName = getLockByValue(value, "semaphore"); return new RedissonSemaphore(commandExecutor, lockName); } @Override public RCountDownLatch getCountDownLatch(V value) { String lockName = getLockByValue(value, "countdownlatch"); return new RedissonCountDownLatch(commandExecutor, lockName); } @Override public RLock getFairLock(V value) { String lockName = getLockByValue(value, "fairlock"); return new RedissonFairLock(commandExecutor, lockName); } @Override public RLock getLock(V value) { String lockName = getLockByValue(value, "lock"); return new RedissonLock(commandExecutor, lockName); } @Override public RReadWriteLock getReadWriteLock(V value) { String lockName = getLockByValue(value, "rw_lock"); return new RedissonReadWriteLock(commandExecutor, lockName); } @Override public RFuture<ListScanResult<Object>> scanIteratorAsync(String name, RedisClient client, long startPos, String pattern, int count) { if (pattern == null) { return commandExecutor.readAsync(client, name, codec, RedisCommands.SSCAN, name, startPos, "COUNT", count); } return commandExecutor.readAsync(client, name, codec, RedisCommands.SSCAN, name, startPos, "MATCH", pattern, "COUNT", count); } private <T> RFuture<Collection<T>> readSortAsync(String byPattern, List<String> getPatterns, SortOrder order, int offset, int count, boolean alpha) { List<Object> params = new ArrayList<Object>(); params.add(getName()); if (byPattern != null) { params.add("BY"); params.add(byPattern); } if (offset != -1 && count != -1) { params.add("LIMIT"); } if (offset != -1) { params.add(offset); } if (count != -1) { params.add(count); } if (getPatterns != null) { for (String pattern : getPatterns) { params.add("GET"); params.add(pattern); } } if (alpha) { params.add("ALPHA"); } if (order != null) { params.add(order); } return commandExecutor.readAsync(getName(), codec, RedisCommands.SORT_SET, params.toArray()); } @Override public Stream<V> stream(int count) { return toStream(iterator(count)); } @Override public Stream<V> stream(String pattern, int count) { return toStream(iterator(pattern, count)); } @Override public Stream<V> stream(String pattern) { return toStream(iterator(pattern)); } }
/* * 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.jackrabbit.oak.plugins.document; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import com.google.common.base.Function; import com.google.common.base.Stopwatch; import com.google.common.cache.Cache; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.primitives.Longs; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.model.Filters; import org.apache.commons.io.FileUtils; import org.apache.jackrabbit.oak.api.Blob; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.commons.json.JsopReader; import org.apache.jackrabbit.oak.commons.json.JsopTokenizer; import org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore; import org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStoreHelper; import org.apache.jackrabbit.oak.plugins.document.util.Utils; import org.bson.conversions.Bson; import org.jetbrains.annotations.Nullable; /** * Helper class to access package private method of DocumentNodeStore and other * classes in this package. */ public class DocumentNodeStoreHelper { private DocumentNodeStoreHelper() { } public static Cache<PathRev, DocumentNodeState> getNodesCache(DocumentNodeStore dns) { return dns.getNodeCache(); } public static void garbageReport(DocumentNodeStore dns) { System.out.print("Collecting top 100 nodes with most blob garbage "); Stopwatch sw = Stopwatch.createStarted(); Iterable<BlobReferences> refs = scan(dns, new BlobGarbageSizeComparator(), 100); for (BlobReferences br : refs) { System.out.println(br); } System.out.println("Collected in " + sw.stop()); } public static VersionGarbageCollector createVersionGC( DocumentNodeStore nodeStore, VersionGCSupport gcSupport) { return new VersionGarbageCollector(nodeStore, gcSupport); } private static Iterable<BlobReferences> scan(DocumentNodeStore store, Comparator<BlobReferences> comparator, int num) { long totalGarbage = 0; Iterable<NodeDocument> docs = getDocuments(store.getDocumentStore()); PriorityQueue<BlobReferences> queue = new PriorityQueue<BlobReferences>(num, comparator); List<Blob> blobs = Lists.newArrayList(); long docCount = 0; for (NodeDocument doc : docs) { if (++docCount % 10000 == 0) { System.out.print("."); } blobs.clear(); BlobReferences refs = collectReferences(doc, store); totalGarbage += refs.garbageSize; queue.add(refs); if (queue.size() > num) { queue.remove(); } } System.out.println(); List<BlobReferences> refs = Lists.newArrayList(); refs.addAll(queue); Collections.sort(refs, Collections.reverseOrder(comparator)); System.out.println("Total garbage size: " + FileUtils.byteCountToDisplaySize(totalGarbage)); System.out.println("Total number of nodes with blob references: " + docCount); System.out.println("total referenced / old referenced / # blob references / path"); return refs; } private static BlobReferences collectReferences(NodeDocument doc, DocumentNodeStore ns) { long blobSize = 0; long garbageSize = 0; int numBlobs = 0; List<Blob> blobs = Lists.newArrayList(); RevisionVector head = ns.getHeadRevision(); boolean exists = doc.getNodeAtRevision(ns, head, null) != null; for (String key : doc.keySet()) { if (!Utils.isPropertyName(key)) { continue; } boolean foundValid = false; Map<Revision, String> valueMap = doc.getLocalMap(key); for (Map.Entry<Revision, String> entry : valueMap.entrySet()) { blobs.clear(); String v = entry.getValue(); if (v != null) { loadValue(v, blobs, ns); } blobSize += size(blobs); if (foundValid) { garbageSize += size(blobs); } else if (Utils.isCommitted(ns.getCommitValue(entry.getKey(), doc))) { foundValid = true; } else { garbageSize += size(blobs); } numBlobs += blobs.size(); } } return new BlobReferences(doc.getPath(), blobSize, numBlobs, garbageSize, exists); } private static Iterable<NodeDocument> getDocuments(DocumentStore store) { if (store instanceof MongoDocumentStore) { // optimized implementation for MongoDocumentStore final MongoDocumentStore mds = (MongoDocumentStore) store; MongoCollection<BasicDBObject> dbCol = MongoDocumentStoreHelper.getDBCollection( mds, Collection.NODES); Bson query = Filters.eq(NodeDocument.HAS_BINARY_FLAG, NodeDocument.HAS_BINARY_VAL); FindIterable<BasicDBObject> cursor = dbCol.find(query); return Iterables.transform(cursor, new Function<DBObject, NodeDocument>() { @Nullable @Override public NodeDocument apply(DBObject input) { return MongoDocumentStoreHelper.convertFromDBObject(mds, Collection.NODES, input); } }); } else { return Utils.getSelectedDocuments(store, NodeDocument.HAS_BINARY_FLAG, NodeDocument.HAS_BINARY_VAL); } } private static long size(Iterable<Blob> blobs) { long size = 0; for (Blob b : blobs) { size += b.length(); } return size; } private static void loadValue(String v, java.util.Collection<Blob> blobs, DocumentNodeStore nodeStore) { JsopReader reader = new JsopTokenizer(v); PropertyState p; if (reader.matches('[')) { p = DocumentPropertyState.readArrayProperty("x", nodeStore, reader); if (p.getType() == Type.BINARIES) { for (int i = 0; i < p.count(); i++) { Blob b = p.getValue(Type.BINARY, i); blobs.add(b); } } } else { p = DocumentPropertyState.readProperty("x", nodeStore, reader); if (p.getType() == Type.BINARY) { Blob b = p.getValue(Type.BINARY); blobs.add(b); } } } private static class BlobReferences { final Path path; final long blobSize; final long garbageSize; final int numBlobs; final boolean exists; public BlobReferences(Path path, long blobSize, int numBlobs, long garbageSize, boolean exists) { this.path = path; this.blobSize = blobSize; this.garbageSize = garbageSize; this.numBlobs = numBlobs; this.exists = exists; } @Override public String toString() { String s = FileUtils.byteCountToDisplaySize(blobSize) + "\t" + FileUtils.byteCountToDisplaySize(garbageSize) + "\t" + numBlobs + "\t" + path; if (!exists) { s += "\t(deleted)"; } return s; } } private static class BlobGarbageSizeComparator implements Comparator<BlobReferences> { @Override public int compare(BlobReferences o1, BlobReferences o2) { int c = Longs.compare(o1.garbageSize, o2.garbageSize); if (c != 0) { return c; } return o1.path.compareTo(o2.path); } } }
/* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2002-2003 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.codehaus.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Commons", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.codehaus.org/>. */ package ccm.libs.org.codehaus.plexus.util; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; /** * <p><code>ExceptionUtils</code> provides utilities for manipulating * <code>Throwable</code> objects.</p> * * @author <a href="mailto:[email protected]">Daniel Rall</a> * @author Dmitri Plotnikov * @author Stephen Colebourne * @since 1.0 * @version $Id$ */ public class ExceptionUtils { /** * Used when printing stack frames to denote the start of a * wrapped exception. Package private for accessibility by test * suite. */ static final String WRAPPED_MARKER = " [wrapped] "; /** * The names of methods commonly used to access a wrapped * exception. */ protected static String[] CAUSE_METHOD_NAMES = { "getCause", "getNextException", "getTargetException", "getException", "getSourceException", "getRootCause", "getCausedByException", "getNested" }; /** * Constructs a new <code>ExceptionUtils</code>. Protected to * discourage instantiation. */ protected ExceptionUtils() { } /** * <p>Adds to the list of method names used in the search for <code>Throwable</code> * objects.</p> * * @param methodName the methodName to add to the list, null and empty strings are ignored */ public static void addCauseMethodName( String methodName ) { if ( methodName != null && methodName.length() > 0 ) { List list = new ArrayList( Arrays.asList( CAUSE_METHOD_NAMES ) ); list.add( methodName ); CAUSE_METHOD_NAMES = (String[]) list.toArray( new String[list.size()] ); } } /** * <p>Introspects the specified <code>Throwable</code> to obtain the cause.</p> * * <p>The method searches for methods with specific names that return a * <code>Throwable</code> object. This will pick up most wrapping exceptions, * including those from JDK 1.4, and * The method names can be added to using {@link #addCauseMethodName(String)}. * The default list searched for are:</p> * <ul> * <li><code>getCause()</code> * <li><code>getNextException()</code> * <li><code>getTargetException()</code> * <li><code>getException()</code> * <li><code>getSourceException()</code> * <li><code>getRootCause()</code> * <li><code>getCausedByException()</code> * <li><code>getNested()</code> * </ul> * * <p>In the absence of any such method, the object is inspected for a * <code>detail</code> field assignable to a <code>Throwable</code>.</p> * * <p>If none of the above is found, returns <code>null</code>.</p> * * @param throwable The exception to introspect for a cause. * @return The cause of the <code>Throwable</code>. * @throws NullPointerException if the throwable is null */ public static Throwable getCause( Throwable throwable ) { return getCause( throwable, CAUSE_METHOD_NAMES ); } /** * <p>Introspects the specified <code>Throwable</code> to obtain the cause * using a supplied array of method names.</p> * * @param throwable The exception to introspect for a cause. * @return The cause of the <code>Throwable</code>. * @throws NullPointerException if the method names array is null or contains null * @throws NullPointerException if the throwable is null */ public static Throwable getCause( Throwable throwable, String[] methodNames ) { Throwable cause = getCauseUsingWellKnownTypes( throwable ); if ( cause == null ) { for ( int i = 0; i < methodNames.length; i++ ) { cause = getCauseUsingMethodName( throwable, methodNames[i] ); if ( cause != null ) { break; } } if ( cause == null ) { cause = getCauseUsingFieldName( throwable, "detail" ); } } return cause; } /** * <p>Walks through the exception chain to the last element -- the * "root" of the tree -- using {@link #getCause(Throwable)}, and * returns that exception.</p> * * @param throwable the throwable to get the root cause for * @return The root cause of the <code>Throwable</code>. */ public static Throwable getRootCause( Throwable throwable ) { Throwable cause = getCause( throwable ); if ( cause != null ) { throwable = cause; while ( ( throwable = getCause( throwable ) ) != null ) { cause = throwable; } } return cause; } /** * <p>Uses <code>instanceof</code> checks to examine the exception, * looking for well known types which could contain chained or * wrapped exceptions.</p> * * @param throwable the exception to examine * @return The wrapped exception, or <code>null</code> if not * found. */ private static Throwable getCauseUsingWellKnownTypes( Throwable throwable ) { if ( throwable instanceof SQLException ) { return ( (SQLException) throwable ).getNextException(); } else if ( throwable instanceof InvocationTargetException ) { return ( (InvocationTargetException) throwable ).getTargetException(); } else { return null; } } /** * <p>Find a throwable by method name.</p> * * @param throwable the exception to examine * @param methodName the name of the method to find and invoke * @return The wrapped exception, or <code>null</code> if not * found. */ private static Throwable getCauseUsingMethodName( Throwable throwable, String methodName ) { Method method = null; try { method = throwable.getClass().getMethod( methodName, null ); } catch ( NoSuchMethodException ignored ) { } catch ( SecurityException ignored ) { } if ( method != null && Throwable.class.isAssignableFrom( method.getReturnType() ) ) { try { return (Throwable) method.invoke( throwable, new Object[0] ); } catch ( IllegalAccessException ignored ) { } catch ( IllegalArgumentException ignored ) { } catch ( InvocationTargetException ignored ) { } } return null; } /** * <p>Find a throwable by field name.</p> * * @param throwable the exception to examine * @param fieldName the name of the attribute to examine * @return The wrapped exception, or <code>null</code> if not * found. */ private static Throwable getCauseUsingFieldName( Throwable throwable, String fieldName ) { Field field = null; try { field = throwable.getClass().getField( fieldName ); } catch ( NoSuchFieldException ignored ) { } catch ( SecurityException ignored ) { } if ( field != null && Throwable.class.isAssignableFrom( field.getType() ) ) { try { return (Throwable) field.get( throwable ); } catch ( IllegalAccessException ignored ) { } catch ( IllegalArgumentException ignored ) { } } return null; } /** * <p>Returns the number of <code>Throwable</code> objects in the * exception chain.</p> * * @param throwable the exception to inspect * @return The throwable count. */ public static int getThrowableCount( Throwable throwable ) { // Count the number of throwables int count = 0; while ( throwable != null ) { count++; throwable = ExceptionUtils.getCause( throwable ); } return count; } /** * <p>Returns the list of <code>Throwable</code> objects in the * exception chain.</p> * * @param throwable the exception to inspect * @return The list of <code>Throwable</code> objects. */ public static Throwable[] getThrowables( Throwable throwable ) { List list = new ArrayList(); while ( throwable != null ) { list.add( throwable ); throwable = ExceptionUtils.getCause( throwable ); } return (Throwable[]) list.toArray( new Throwable[list.size()] ); } /** * <p>Delegates to {@link #indexOfThrowable(Throwable, Class, int)}, * starting the search at the beginning of the exception chain.</p> * * @see #indexOfThrowable(Throwable, Class, int) */ public static int indexOfThrowable( Throwable throwable, Class type ) { return indexOfThrowable( throwable, type, 0 ); } /** * <p>Returns the (zero based) index, of the first * <code>Throwable</code> that matches the specified type in the * exception chain of <code>Throwable</code> objects with an index * greater than or equal to the specified index, or * <code>-1</code> if the type is not found.</p> * * @param throwable the exception to inspect * @param type <code>Class</code> to look for * @param fromIndex the (zero based) index of the starting * position in the chain to be searched * @return the first occurrence of the type in the chain, or * <code>-1</code> if the type is not found * @throws IndexOutOfBoundsException If the <code>fromIndex</code> * argument is negative or not less than the count of * <code>Throwable</code>s in the chain. */ public static int indexOfThrowable( Throwable throwable, Class type, int fromIndex ) { if ( fromIndex < 0 ) { throw new IndexOutOfBoundsException( "Throwable index out of range: " + fromIndex ); } Throwable[] throwables = ExceptionUtils.getThrowables( throwable ); if ( fromIndex >= throwables.length ) { throw new IndexOutOfBoundsException( "Throwable index out of range: " + fromIndex ); } for ( int i = fromIndex; i < throwables.length; i++ ) { if ( throwables[i].getClass().equals( type ) ) { return i; } } return -1; } /** * Prints a compact stack trace for the root cause of a throwable. * The compact stack trace starts with the root cause and prints * stack frames up to the place where it was caught and wrapped. * Then it prints the wrapped exception and continues with stack frames * until the wrapper exception is caught and wrapped again, etc. * <p> * The method is equivalent to t.printStackTrace() for throwables * that don't have nested causes. */ public static void printRootCauseStackTrace( Throwable t, PrintStream stream ) { String trace[] = getRootCauseStackTrace( t ); for ( int i = 0; i < trace.length; i++ ) { stream.println( trace[i] ); } stream.flush(); } /** * Equivalent to printRootCauseStackTrace(t, System.err) */ public static void printRootCauseStackTrace( Throwable t ) { printRootCauseStackTrace( t, System.err ); } /** * Same as printRootCauseStackTrace(t, stream), except it takes * a PrintWriter as an argument. */ public static void printRootCauseStackTrace( Throwable t, PrintWriter writer ) { String trace[] = getRootCauseStackTrace( t ); for ( int i = 0; i < trace.length; i++ ) { writer.println( trace[i] ); } writer.flush(); } /** * Creates a compact stack trace for the root cause of the supplied * throwable. * * See <code>printRootCauseStackTrace(Throwable t, PrintStream s)</code> */ public static String[] getRootCauseStackTrace( Throwable t ) { Throwable throwables[] = getThrowables( t ); int count = throwables.length; ArrayList frames = new ArrayList(); List nextTrace = getStackFrameList( throwables[count - 1] ); for ( int i = count; --i >= 0; ) { List trace = nextTrace; if ( i != 0 ) { nextTrace = getStackFrameList( throwables[i - 1] ); removeCommonFrames( trace, nextTrace ); } if ( i == count - 1 ) { frames.add( throwables[i].toString() ); } else { frames.add( WRAPPED_MARKER + throwables[i].toString() ); } for ( int j = 0; j < trace.size(); j++ ) { frames.add( trace.get( j ) ); } } return (String[]) frames.toArray( new String[0] ); } /** * Given two stack traces, removes common frames from the cause trace. * * @param causeFrames stack trace of a cause throwable * @param wrapperFrames stack trace of a wrapper throwable */ private static void removeCommonFrames( List causeFrames, List wrapperFrames ) { int causeFrameIndex = causeFrames.size() - 1; int wrapperFrameIndex = wrapperFrames.size() - 1; while ( causeFrameIndex >= 0 && wrapperFrameIndex >= 0 ) { // Remove the frame from the cause trace if it is the same // as in the wrapper trace String causeFrame = (String) causeFrames.get( causeFrameIndex ); String wrapperFrame = (String) wrapperFrames.get( wrapperFrameIndex ); if ( causeFrame.equals( wrapperFrame ) ) { causeFrames.remove( causeFrameIndex ); } causeFrameIndex--; wrapperFrameIndex--; } } /** * A convenient way of extracting the stack trace from an * exception. * * @param t The <code>Throwable</code>. * @return The stack trace as generated by the exception's * <code>printStackTrace(PrintWriter)</code> method. */ public static String getStackTrace( Throwable t ) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter( sw, true ); t.printStackTrace( pw ); return sw.getBuffer().toString(); } /** * A way to get the entire nested stack-trace of an throwable. * * @param t The <code>Throwable</code>. * @return The nested stack trace, with the root cause first. */ public static String getFullStackTrace( Throwable t ) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter( sw, true ); Throwable[] ts = getThrowables( t ); for ( int i = 0; i < ts.length; i++ ) { ts[i].printStackTrace( pw ); if ( isNestedThrowable( ts[i] ) ) { break; } } return sw.getBuffer().toString(); } /** * Whether an Throwable is considered nested or not. * * @param throwable The <code>Throwable</code>. * @return boolean true/false */ public static boolean isNestedThrowable( Throwable throwable ) { if ( throwable == null ) { return false; } if ( throwable instanceof SQLException ) { return true; } else if ( throwable instanceof InvocationTargetException ) { return true; } int sz = CAUSE_METHOD_NAMES.length; for ( int i = 0; i < sz; i++ ) { try { Method method = throwable.getClass().getMethod( CAUSE_METHOD_NAMES[i], null ); if ( method != null ) { return true; } } catch ( NoSuchMethodException ignored ) { } catch ( SecurityException ignored ) { } } try { Field field = throwable.getClass().getField( "detail" ); if ( field != null ) { return true; } } catch ( NoSuchFieldException ignored ) { } catch ( SecurityException ignored ) { } return false; } /** * Captures the stack trace associated with the specified * <code>Throwable</code> object, decomposing it into a list of * stack frames. * * @param t The <code>Throwable</code>. * @return An array of strings describing each stack frame. */ public static String[] getStackFrames( Throwable t ) { return getStackFrames( getStackTrace( t ) ); } /** * Functionality shared between the * <code>getStackFrames(Throwable)</code> methods of this and the * classes. */ static String[] getStackFrames( String stackTrace ) { String linebreak = System.getProperty( "line.separator" ); StringTokenizer frames = new StringTokenizer( stackTrace, linebreak ); List list = new LinkedList(); while ( frames.hasMoreTokens() ) { list.add( frames.nextToken() ); } return (String[]) list.toArray( new String[]{ } ); } /** * Produces a List of stack frames - the message is not included. * This works in most cases - it will only fail if the exception message * contains a line that starts with: " at". * * @param t is any throwable * @return List of stack frames */ static List getStackFrameList( Throwable t ) { String stackTrace = getStackTrace( t ); String linebreak = System.getProperty( "line.separator" ); StringTokenizer frames = new StringTokenizer( stackTrace, linebreak ); List list = new LinkedList(); boolean traceStarted = false; while ( frames.hasMoreTokens() ) { String token = frames.nextToken(); // Determine if the line starts with <whitespace>at int at = token.indexOf( "at" ); if ( at != -1 && token.substring( 0, at ).trim().length() == 0 ) { traceStarted = true; list.add( token ); } else if ( traceStarted ) { break; } } return list; } }
// 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.impala.catalog.local; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocatedFileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RemoteIterator; import org.apache.hadoop.hive.common.FileUtils; import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj; import org.apache.hadoop.hive.metastore.api.Database; import org.apache.hadoop.hive.metastore.api.MetaException; import org.apache.hadoop.hive.metastore.api.NoSuchObjectException; import org.apache.hadoop.hive.metastore.api.Partition; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.hadoop.hive.metastore.api.UnknownDBException; import org.apache.impala.catalog.AuthorizationPolicy; import org.apache.impala.catalog.Function; import org.apache.impala.catalog.HdfsPartition.FileDescriptor; import org.apache.impala.catalog.HdfsTable; import org.apache.impala.catalog.MetaStoreClientPool; import org.apache.impala.catalog.MetaStoreClientPool.MetaStoreClient; import org.apache.impala.common.Pair; import org.apache.impala.service.BackendConfig; import org.apache.impala.thrift.TBackendGflags; import org.apache.impala.thrift.TNetworkAddress; import org.apache.impala.util.ListMap; import org.apache.impala.util.MetaStoreUtil; import org.apache.thrift.TException; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.errorprone.annotations.Immutable; /** * Metadata provider which calls out directly to the source systems * (filesystem, HMS, etc) with no caching. */ class DirectMetaProvider implements MetaProvider { private static MetaStoreClientPool msClientPool_; private static Configuration CONF = new Configuration(); DirectMetaProvider() { initMsClientPool(); } private static synchronized void initMsClientPool() { // Lazy-init the metastore client pool based on the backend configuration. // TODO(todd): this should probably be a process-wide singleton. if (msClientPool_ == null) { TBackendGflags cfg = BackendConfig.INSTANCE.getBackendCfg(); msClientPool_ = new MetaStoreClientPool(cfg.num_metadata_loading_threads, cfg.initial_hms_cnxn_timeout_s); } } @Override public AuthorizationPolicy getAuthPolicy() { throw new UnsupportedOperationException("not supported"); } @Override public boolean isReady() { // Direct provider is always ready since we don't need to wait for // an update from any external process. return true; } @Override public ImmutableList<String> loadDbList() throws TException { try (MetaStoreClient c = msClientPool_.getClient()) { return ImmutableList.copyOf(c.getHiveClient().getAllDatabases()); } } @Override public Database loadDb(String dbName) throws TException { try (MetaStoreClient c = msClientPool_.getClient()) { return c.getHiveClient().getDatabase(dbName); } } @Override public ImmutableList<String> loadTableNames(String dbName) throws MetaException, UnknownDBException, TException { try (MetaStoreClient c = msClientPool_.getClient()) { return ImmutableList.copyOf(c.getHiveClient().getAllTables(dbName)); } } @Override public Pair<Table, TableMetaRef> loadTable(String dbName, String tableName) throws MetaException, NoSuchObjectException, TException { Table msTable; try (MetaStoreClient c = msClientPool_.getClient()) { msTable = c.getHiveClient().getTable(dbName, tableName); } TableMetaRef ref = new TableMetaRefImpl(dbName, tableName, msTable); return Pair.create(msTable, ref); } @Override public String loadNullPartitionKeyValue() throws MetaException, TException { try (MetaStoreClient c = msClientPool_.getClient()) { return MetaStoreUtil.getNullPartitionKeyValue(c.getHiveClient()); } } @Override public List<PartitionRef> loadPartitionList(TableMetaRef table) throws MetaException, TException { Preconditions.checkArgument(table instanceof TableMetaRefImpl); TableMetaRefImpl ref = (TableMetaRefImpl)table; // If the table isn't partitioned, just return a single partition with no name. // In loadPartitionsByRefs() below, we'll detect this case and load the special // unpartitioned table. if (!ref.isPartitioned()) { return ImmutableList.of((PartitionRef)new PartitionRefImpl( PartitionRefImpl.UNPARTITIONED_NAME)); } List<String> partNames; try (MetaStoreClient c = msClientPool_.getClient()) { partNames = c.getHiveClient().listPartitionNames( ref.dbName_, ref.tableName_, /*max_parts=*/(short)-1); } List<PartitionRef> partRefs = Lists.newArrayListWithCapacity(partNames.size()); for (String name: partNames) { partRefs.add(new PartitionRefImpl(name)); } return partRefs; } @Override public Map<String, PartitionMetadata> loadPartitionsByRefs( TableMetaRef table, List<String> partitionColumnNames, ListMap<TNetworkAddress> hostIndex, List<PartitionRef> partitionRefs) throws MetaException, TException { Preconditions.checkNotNull(table); Preconditions.checkArgument(table instanceof TableMetaRefImpl); Preconditions.checkArgument(!partitionColumnNames.isEmpty()); Preconditions.checkNotNull(partitionRefs); TableMetaRefImpl tableImpl = (TableMetaRefImpl)table; String fullTableName = tableImpl.dbName_ + "." + tableImpl.tableName_; if (!((TableMetaRefImpl)table).isPartitioned()) { return loadUnpartitionedPartition((TableMetaRefImpl)table, partitionRefs, hostIndex); } Map<String, PartitionMetadata> ret = Maps.newHashMapWithExpectedSize( partitionRefs.size()); if (partitionRefs.isEmpty()) return ret; // Fetch the partitions. List<String> partNames = Lists.newArrayListWithCapacity(partitionRefs.size()); for (PartitionRef ref: partitionRefs) { partNames.add(ref.getName()); } List<Partition> parts; try (MetaStoreClient c = msClientPool_.getClient()) { parts = MetaStoreUtil.fetchPartitionsByName( c.getHiveClient(), partNames, tableImpl.dbName_, tableImpl.tableName_); } // HMS may return fewer partition objects than requested, and the // returned partition objects don't carry enough information to get their // names. So, we map the returned partitions back to the requested names // using the passed-in partition column names. Set<String> namesSet = ImmutableSet.copyOf(partNames); for (Partition p: parts) { List<String> vals = p.getValues(); if (vals.size() != partitionColumnNames.size()) { throw new MetaException("Unexpected number of partition values for " + "partition " + vals + " (expected " + partitionColumnNames.size() + ")"); } String partName = FileUtils.makePartName(partitionColumnNames, p.getValues()); if (!namesSet.contains(partName)) { throw new MetaException("HMS returned unexpected partition " + partName + " which was not requested. Requested: " + namesSet); } ImmutableList<FileDescriptor> fds = loadFileMetadata( fullTableName, partName, p, hostIndex); PartitionMetadata existing = ret.put(partName, new PartitionMetadataImpl(p, fds)); if (existing != null) { throw new MetaException("HMS returned multiple partitions with name " + partName); } } return ret; } /** * We model partitions slightly differently to Hive. So, in the case of an * unpartitioned table, we have to create a fake Partition object which has the * metadata of the table. */ private Map<String, PartitionMetadata> loadUnpartitionedPartition( TableMetaRefImpl table, List<PartitionRef> partitionRefs, ListMap<TNetworkAddress> hostIndex) { Preconditions.checkArgument(partitionRefs.size() == 1, "Expected exactly one partition to load for unpartitioned table"); PartitionRef ref = partitionRefs.get(0); Preconditions.checkArgument(ref.getName().isEmpty(), "Expected empty partition name for unpartitioned table"); Partition msPartition = msTableToPartition(table.msTable_); String fullName = table.dbName_ + "." + table.tableName_; ImmutableList<FileDescriptor> fds = loadFileMetadata(fullName, "default", msPartition, hostIndex); return ImmutableMap.of("", (PartitionMetadata)new PartitionMetadataImpl( msPartition, fds)); } static Partition msTableToPartition(Table msTable) { Partition msp = new Partition(); msp.setSd(msTable.getSd()); msp.setParameters(msTable.getParameters()); msp.setValues(Collections.<String>emptyList()); return msp; } @Override public List<String> loadFunctionNames(String dbName) throws TException { // NOTE: this is a bit tricky to implement since functions may be stored as // HMS functions or serialized functions in the DB parameters themselves. We // need to do some refactoring to support this in DirectMetaProvider. Some code // used to exist to do this in LocalDb -- look back in git history if you want to // revive the usefulness of DirectMetaProvider. throw new UnsupportedOperationException( "Functions not supported by DirectMetaProvider"); } @Override public ImmutableList<Function> loadFunction(String dbName, String functionName) throws TException { // See above. throw new UnsupportedOperationException( "Functions not supported by DirectMetaProvider"); } @Override public List<ColumnStatisticsObj> loadTableColumnStatistics(TableMetaRef table, List<String> colNames) throws TException { Preconditions.checkArgument(table instanceof TableMetaRefImpl); try (MetaStoreClient c = msClientPool_.getClient()) { return c.getHiveClient().getTableColumnStatistics( ((TableMetaRefImpl)table).dbName_, ((TableMetaRefImpl)table).tableName_, colNames); } } private ImmutableList<FileDescriptor> loadFileMetadata(String fullTableName, String partName, Partition msPartition, ListMap<TNetworkAddress> hostIndex) { Path partDir = new Path(msPartition.getSd().getLocation()); List<LocatedFileStatus> stats = new ArrayList<>(); try { FileSystem fs = partDir.getFileSystem(CONF); RemoteIterator<LocatedFileStatus> it = fs.listFiles(partDir, /*recursive=*/false); while (it.hasNext()) stats.add(it.next()); } catch (FileNotFoundException fnf) { // If the partition directory isn't found, this is treated as having no // files. return ImmutableList.of(); } catch (IOException ioe) { throw new LocalCatalogException(String.format( "Could not load files for partition %s of table %s", partName, fullTableName), ioe); } HdfsTable.FileMetadataLoadStats loadStats = new HdfsTable.FileMetadataLoadStats(partDir); try { FileSystem fs = partDir.getFileSystem(CONF); return ImmutableList.copyOf( HdfsTable.createFileDescriptors(fs, new FakeRemoteIterator<>(stats), hostIndex, loadStats)); } catch (IOException e) { throw new LocalCatalogException(String.format( "Could not convert files to descriptors for partition %s of table %s", partName, fullTableName), e); } } @Immutable private static class PartitionRefImpl implements PartitionRef { private static final String UNPARTITIONED_NAME = ""; private final String name_; public PartitionRefImpl(String name) { this.name_ = name; } @Override public String getName() { return name_; } } private static class PartitionMetadataImpl implements PartitionMetadata { private final Partition msPartition_; private final ImmutableList<FileDescriptor> fds_; public PartitionMetadataImpl(Partition msPartition, ImmutableList<FileDescriptor> fds) { this.msPartition_ = msPartition; this.fds_ = fds; } @Override public Partition getHmsPartition() { return msPartition_; } @Override public ImmutableList<FileDescriptor> getFileDescriptors() { return fds_; } @Override public boolean hasIncrementalStats() { return false; /* Incremental stats not supported in direct mode */ } @Override public byte[] getPartitionStats() { throw new UnsupportedOperationException("Incremental stats not supported with " + "DirectMetaProvider implementation."); } } private class TableMetaRefImpl implements TableMetaRef { private final String dbName_; private final String tableName_; private final Table msTable_; public TableMetaRefImpl(String dbName, String tableName, Table msTable) { this.dbName_ = dbName; this.tableName_ = tableName; this.msTable_ = msTable; } private boolean isPartitioned() { return msTable_.getPartitionKeysSize() != 0; } } /** * Wrapper for a normal Iterable<T> to appear like a Hadoop RemoteIterator<T>. * This is necessary because the existing code to convert file statuses to * descriptors consumes the remote iterator directly and thus avoids materializing * all of the LocatedFileStatus objects in memory at the same time. */ private static class FakeRemoteIterator<T> implements RemoteIterator<T> { private final Iterator<T> it_; FakeRemoteIterator(Iterable<T> it) { this.it_ = it.iterator(); } @Override public boolean hasNext() throws IOException { return it_.hasNext(); } @Override public T next() throws IOException { return it_.next(); } } }
package com.pardot.rhombus.cobject; import com.datastax.driver.core.Statement; import com.datastax.driver.core.querybuilder.Delete; import com.datastax.driver.core.querybuilder.QueryBuilder; import com.datastax.driver.core.utils.UUIDs; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Range; import com.pardot.rhombus.Criteria; import com.pardot.rhombus.cobject.shardingstrategy.ShardStrategyException; import com.pardot.rhombus.cobject.shardingstrategy.ShardingStrategyNone; import com.pardot.rhombus.cobject.statement.*; import org.apache.commons.codec.digest.DigestUtils; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.validation.constraints.NotNull; import java.math.BigInteger; import java.util.*; /** * Pardot, An ExactTarget Company * User: robrighter * Date: 4/8/13 */ public class CObjectCQLGenerator { private static Logger logger = LoggerFactory.getLogger(CObjectCQLGenerator.class); protected static final String KEYSPACE_DEFINITIONS_TABLE_NAME = "__keyspace_definitions"; protected static final String INDEX_UPDATES_TABLE_NAME = "__index_updates"; protected static final Integer MAX_CQL_STATEMENT_LIMIT = 1000; protected static final String TEMPLATE_CREATE_STATIC = "CREATE TABLE \"%s\".\"%s\" (id %s PRIMARY KEY, %s);"; protected static final String TEMPLATE_CREATE_WIDE = "CREATE TABLE \"%s\".\"%s\" (id %s, shardid bigint, %s, PRIMARY KEY ((shardid, %s),id) );"; protected static final String TEMPLATE_CREATE_KEYSPACE_LIST = "CREATE TABLE \"%s\".\"" + KEYSPACE_DEFINITIONS_TABLE_NAME + "\" (id uuid, name varchar, def varchar, PRIMARY KEY ((name), id));"; protected static final String TEMPLATE_CREATE_WIDE_INDEX = "CREATE TABLE \"%s\".\"%s\" (shardid bigint, tablename varchar, indexvalues varchar, targetrowkey varchar, PRIMARY KEY ((tablename, indexvalues),shardid) );"; protected static final String TEMPLATE_CREATE_INDEX_UPDATES = "CREATE TABLE \"%s\".\"" + INDEX_UPDATES_TABLE_NAME + "\" (id timeuuid, statictablename varchar, instanceid timeuuid, indexvalues varchar, PRIMARY KEY ((statictablename,instanceid),id))"; protected static final String TEMPLATE_TRUNCATE_INDEX_UPDATES = "TRUNCATE \"%s\".\"" + INDEX_UPDATES_TABLE_NAME + "\";"; protected static final String TEMPLATE_DROP = "DROP TABLE \"%s\".\"%s\";"; protected static final String TEMPLATE_TRUNCATE = "TRUNCATE \"%s\".\"%s\";"; protected static final String TEMPLATE_INSERT_STATIC = "INSERT INTO \"%s\".\"%s\" (%s) VALUES (%s)%s;";//"USING TIMESTAMP %s%s;";//Add back when timestamps become preparable protected static final String TEMPLATE_INSERT_WIDE = "INSERT INTO \"%s\".\"%s\" (%s) VALUES (%s)%s;";//"USING TIMESTAMP %s%s;";//Add back when timestamps become preparable protected static final String TEMPLATE_INSERT_KEYSPACE = "INSERT INTO \"%s\".\"" + KEYSPACE_DEFINITIONS_TABLE_NAME + "\" (id, name, def) values (?, ?, ?);"; protected static final String TEMPLATE_INSERT_WIDE_INDEX = "INSERT INTO \"%s\".\"%s\" (tablename, indexvalues, shardid, targetrowkey) VALUES (?, ?, ?, ?);";//"USING TIMESTAMP %s;";//Add back when timestamps become preparable protected static final String TEMPLATE_INSERT_INDEX_UPDATES = "INSERT INTO \"%s\".\"" + INDEX_UPDATES_TABLE_NAME + "\" (id, statictablename, instanceid, indexvalues) values (?, ?, ?, ?);"; protected static final String TEMPLATE_SELECT_STATIC = "SELECT * FROM \"%s\".\"%s\" WHERE %s;"; protected static final String TEMPLATE_SELECT_WIDE = "SELECT %s FROM \"%s\".\"%s\" WHERE shardid = %s AND %s ORDER BY id %s %s ALLOW FILTERING;"; protected static final String TEMPLATE_SELECT_KEYSPACE = "SELECT def FROM \"%s\".\"" + KEYSPACE_DEFINITIONS_TABLE_NAME + "\" WHERE name = ? ORDER BY id DESC LIMIT 1;"; protected static final String TEMPLATE_SELECT_WIDE_INDEX = "SELECT shardid FROM \"%s\".\"%s\" WHERE tablename = ? AND indexvalues = ?%s ORDER BY shardid %s ALLOW FILTERING;"; protected static final String TEMPLATE_DELETE = "DELETE FROM \"%s\".\"%s\" WHERE %s;";//"DELETE FROM %s USING TIMESTAMP %s WHERE %s;"; //Add back when timestamps become preparable protected static final String TEMPLATE_DELETE_OBSOLETE_UPDATE_INDEX_COLUMN = "DELETE FROM \"%s\".\"" + INDEX_UPDATES_TABLE_NAME + "\" WHERE statictablename = ? and instanceid = ? and id = ?"; protected static final String TEMPLATE_SELECT_FIRST_ELIGIBLE_INDEX_UPDATE = "SELECT statictablename,instanceid FROM \"%s\".\"" + INDEX_UPDATES_TABLE_NAME + "\" WHERE id < ? limit 1 allow filtering;"; protected static final String TEMPLATE_SELECT_NEXT_ELIGIBLE_INDEX_UPDATE = "SELECT statictablename,instanceid FROM \"%s\".\"" + INDEX_UPDATES_TABLE_NAME + "\" where token(statictablename,instanceid) > token(?,?) and id < ? limit 1 allow filtering;"; protected static final String TEMPLATE_SELECT_ROW_INDEX_UPDATE = "SELECT * FROM \"%s\".\"" + INDEX_UPDATES_TABLE_NAME + "\" where statictablename = ? and instanceid = ? order by id DESC;"; protected static final String TEMPLATE_SET_COMPACTION_LEVELED = "ALTER TABLE \"%s\".\"%s\" WITH compaction = { 'class' : 'LeveledCompactionStrategy', 'sstable_size_in_mb' : %d }"; protected static final String TEMPLATE_SET_COMPACTION_TIERED = "ALTER TABLE \"%s\".\"%s\" WITH compaction = { 'class' : 'SizeTieredCompactionStrategy', 'min_threshold' : %d }"; protected static final String TEMPLATE_TABLE_SCAN = "SELECT * FROM \"%s\".\"%s\";"; protected static final String TEMPLATE_ADD_FIELD = "ALTER TABLE \"%s\".\"%s\" add %s %s"; protected Map<String, CDefinition> definitions; protected CObjectShardList shardList; private Integer consistencyHorizon; private String keyspace; /** * Single Param constructor, mostly for testing convenience. Use the other constructor. */ public CObjectCQLGenerator(String keyspace, Integer consistencyHorizon){ this.definitions = Maps.newHashMap(); this.consistencyHorizon = consistencyHorizon; this.keyspace = keyspace; } /** * * @param objectDefinitions - A map where the key is the CDefinition.name and the value is the CDefinition. * This map should include a CDefinition for every object in the system. */ public CObjectCQLGenerator(String keyspace, Map<String, CDefinition> objectDefinitions, CObjectShardList shardList, Integer consistencyHorizon){ this.definitions = objectDefinitions; this.consistencyHorizon = consistencyHorizon; this.keyspace = keyspace; setShardList(shardList); } /** * Set the Definitions to be used * @param objectDefinitions - A map where the key is the CDefinition.name and the value is the CDefinition. * This map should include a CDefinition for every object in the system. */ public void setDefinitions(Map<String, CDefinition> objectDefinitions){ this.definitions = objectDefinitions; } /** * * @param objType - The name of the Object type aka CDefinition.name * @return Iterator of CQL statements that need to be executed for this task. */ public CQLStatementIterator makeCQLforCreate(String objType){ return makeCQLforCreate(this.definitions.get(objType)); } /** * * @return Iterator of CQL statements that need to be executed for this task. */ public CQLStatement makeCQLforCreateKeyspaceDefinitionsTable(){ return CQLStatement.make(String.format(TEMPLATE_CREATE_KEYSPACE_LIST, keyspace), KEYSPACE_DEFINITIONS_TABLE_NAME); } /** * * @param objType - The name of the Object type aka CDefinition.name * @return Iterator of CQL statements that need to be executed for this task. */ public CQLStatementIterator makeCQLforDrop(String objType){ return makeCQLforDrop(this.keyspace, this.definitions.get(objType)); } /** * * @param objType - The name of the Object type aka CDefinition.name * @return Iterator of CQL statements that need to be executed for this task. */ public CQLStatementIterator makeCQLforTruncate(String objType){ return makeCQLforTruncate(this.keyspace, this.definitions.get(objType)); } /** * * @param objType - The name of the Object type aka CDefinition.name * @return Iterator of CQL statements that need to be executed for this task. * @throws CQLGenerationException */ @NotNull public CQLStatement makeCQLforInsertNoValuesforStaticTable(String objType) throws CQLGenerationException { CDefinition definition = this.definitions.get(objType); Map<String, CField> fields = Maps.newHashMap(definition.getFields()); Object id = null; if (fields.containsKey("id")) { id = fields.get("id"); fields.remove("id"); } List<String> fieldNames = new ArrayList<String>(fields.keySet()); List<String> valuePlaceholders = new ArrayList<String>(fields.keySet()); return makeInsertStatementStatic(this.keyspace, definition.getName(), fieldNames, valuePlaceholders, id, null, null); } /** * @param definition The object definition of the wide table to insert into * @param tableName - The name of the wide table to insert into * @return CQL insert statement * @throws CQLGenerationException */ @NotNull public CQLStatement makeCQLforInsertNoValuesforWideTable(CDefinition definition, String tableName, Long shardId) throws CQLGenerationException { Map<String, CField> fields = Maps.newHashMap(definition.getFields()); Object id = null; if (fields.containsKey("id")) { id = fields.get("id"); fields.remove("id"); } List<String> fieldNames = new ArrayList<String>(fields.keySet()); List<Object> valuePlaceholders = new ArrayList<Object>(fields.keySet()); shardId = (shardId == null) ? 1L : shardId; return makeInsertStatementWide(this.keyspace, tableName, fieldNames, valuePlaceholders, id, shardId, null, null); } /** * @param tableName - The name of the wide table to insert into * @return CQL insert statement * @throws CQLGenerationException */ @NotNull public CQLStatement makeCQLforInsertNoValuesforShardIndex(String tableName) throws CQLGenerationException { return CQLStatement.make( String.format( TEMPLATE_INSERT_WIDE_INDEX, keyspace, tableName ), tableName, null); } /** * * @param objType - The name of the Object type aka CDefinition.name * @param data - A map of fieldnames to values representing the data to insert * @return Iterator of CQL statements that need to be executed for this task. * @throws CQLGenerationException */ @NotNull public CQLStatementIterator makeCQLforInsert(String objType, Map<String,Object> data) throws CQLGenerationException { return makeCQLforInsert(this.keyspace, this.definitions.get(objType), data); } /** * * @param keyspaceDefinition - The JSON keyspace definition * @return Iterator of CQL statements that need to be executed for this task. * @throws CQLGenerationException */ @NotNull public CQLStatementIterator makeCQLforInsertKeyspaceDefinition(String name, String keyspaceDefinition) throws CQLGenerationException { return makeCQLforInsertKeyspaceDefinition(keyspace, name, keyspaceDefinition, UUIDs.timeBased()); } /** * * @param objType - The name of the Object type aka CDefinition.name * @param data - A map of fieldnames to values representing the data to insert * @return Iterator of CQL statements that need to be executed for this task. * @throws CQLGenerationException */ @NotNull public CQLStatementIterator makeCQLforInsert(String objType, Map<String,Object> data, Object key, Long timestamp) throws CQLGenerationException { return makeCQLforInsert(this.keyspace, this.definitions.get(objType), data, key, timestamp, null); } /** * * @param objType - The name of the Object type aka CDefinition.name * @param key - The TimeUUID of the object to retrieve * @return Iterator of CQL statements that need to be executed for this task. (Should have a length of 1 for this particular method) */ @NotNull public CQLStatementIterator makeCQLforGet(String objType, Object key){ return makeCQLforGet(this.keyspace, this.definitions.get(objType), key); } protected static CQLStatementIterator makeCQLforGet(String keyspace, CDefinition def, Object key){ Object[] values = {key}; CQLStatement statement = CQLStatement.make(String.format(TEMPLATE_SELECT_STATIC, keyspace, def.getName(), "id = ?"), def.getName(), values); return new BoundedCQLStatementIterator(Lists.newArrayList(statement)); } /** * * @param objType - The name of the Object type aka CDefinition.name * @return Iterator of CQL statements that need to be executed for this task. (Should have a length of 1 for this particular method) */ @NotNull public CQLStatement makeCQLforTableScan(String objType){ return makeCQLforTableScan(this.keyspace, this.definitions.get(objType)); } /** * * @param objType - The name of the Object type aka CDefinition.name * @param criteria - The criteria object describing which rows to retrieve * @param countOnly - true means you want a count of rows, false means you want the rows themselves * @return Iterator of CQL statements that need to be executed for this task. */ @NotNull public CQLStatementIterator makeCQLforList(String objType, Criteria criteria, boolean countOnly) throws CQLGenerationException { CDefinition definition = this.definitions.get(objType); CObjectOrdering ordering = (criteria.getOrdering() != null ? criteria.getOrdering(): CObjectOrdering.DESCENDING); UUID endUuid = (criteria.getEndUuid() == null ? UUIDs.startOf(DateTime.now().getMillis()) : criteria.getEndUuid()); return makeCQLforList(this.keyspace, shardList, definition, criteria.getIndexKeys(), ordering, criteria.getStartUuid(), endUuid, criteria.getLimit(), criteria.getInclusive(), countOnly, criteria.getAllowFiltering()); } @NotNull protected static CQLStatementIterator makeCQLforList(String keyspace, CObjectShardList shardList, CDefinition def, SortedMap<String,Object> indexValues, CObjectOrdering ordering, @Nullable UUID start, @Nullable UUID end, Long limit, boolean inclusive, boolean countOnly, boolean allowFiltering) throws CQLGenerationException { // Get matching index from definition CIndex i = def.getIndex(indexValues, allowFiltering); if(i == null){ throw new CQLGenerationException(String.format("Could not find specified index on CDefinition %s",def.getName())); } // Determine client filters and fix index values Map<String, Object> clientFilters = null; if(i.getCompositeKeyList().size() < indexValues.keySet().size()) { clientFilters = Maps.newHashMap(); SortedMap<String, Object> newIndexValues = Maps.newTreeMap(); for(String key : indexValues.keySet()) { if(i.getCompositeKeyList().contains(key)) { newIndexValues.put(key, indexValues.get(key)); } else { // Index keys will always exactly match the criteria index values if allowFiltering is false, so this only happens if allowFiltering is true clientFilters.put(key, indexValues.get(key)); } } indexValues = newIndexValues; } boolean hasClientFilters = clientFilters != null && !clientFilters.isEmpty(); // Now validate the remaining index values if(!i.validateIndexKeys(indexValues)){ throw new CQLGenerationException(String.format("Cannot query index %s on CDefinition %s with the provided list of index values",i.getName(),def.getName())); } CQLStatement whereCQL = makeAndedEqualList(def,indexValues); String whereQuery = whereCQL.getQuery(); List<Object> values = new ArrayList<Object>(Arrays.asList(whereCQL.getValues())); if(start != null){ whereQuery += " AND id >" + (inclusive ? "= " : " ") + "?"; values.add(start); } if(end != null){ whereQuery += " AND id <" + (inclusive ? "= " : " ") + "?"; values.add(end); } String limitCQL; // If we have client side filters, apply a hard max limit here since the client specified criteria limit needs to be applied on the results that match the filters if(limit > 0 && !hasClientFilters && limit < CObjectCQLGenerator.MAX_CQL_STATEMENT_LIMIT){ limitCQL = "LIMIT %d"; } else { limitCQL = "LIMIT " + CObjectCQLGenerator.MAX_CQL_STATEMENT_LIMIT; } // TODO: if we feel like it's worth the trouble, for count queries with client side filters, only select the fields needed to satisfy the filters // note that doing so will also require modifying ObjectMapper.mapResult() so it only maps fields that exist in the row String CQLTemplate = String.format( TEMPLATE_SELECT_WIDE, // If this was a count query and filtering was allowed and client filters weren't defined, just do a count query because we don't need to apply filters // Otherwise if this was a count query, but allowFiltering was true and we have client-side filters to apply, do a full row query so we can apply the filters countOnly && !(allowFiltering && hasClientFilters) ? "count(*)":"*", keyspace, makeTableName(def, i), "?", whereQuery, ordering, limitCQL); CQLStatement templateCQLStatement = CQLStatement.make(CQLTemplate, makeTableName(def, i), values.toArray()); Long startTime = (start == null) ? null : UUIDs.unixTimestamp(start); Long endTime = (end == null) ? null : UUIDs.unixTimestamp(end); CQLStatementIterator returnIterator = null; if((startTime != null && endTime != null) || (i.getShardingStrategy() instanceof ShardingStrategyNone)) { //the query is either bounded or unsharded, so we do not need to check the shardindex try { Range<Long> shardIdRange = i.getShardingStrategy().getShardKeyRange(startTime,endTime); returnIterator = new UnboundableCQLStatementIterator(shardIdRange, limit, ordering, templateCQLStatement, def.getName()); } catch(ShardStrategyException e){ throw new CQLGenerationException(e.getMessage()); } } else { //we have an unbounded query returnIterator = new BoundedLazyCQLStatementIterator( shardList.getShardIdList(def,indexValues,ordering,start,end), templateCQLStatement, limit, def.getName() ); } // Set the client filters on the returned iterator so the client can take care of them returnIterator.setClientFilters(clientFilters); return returnIterator; } /** * * @return an iterator for getting all the keyspace definitions */ public CQLStatement makeCQLforGetKeyspaceDefinitions(String name){ return makeCQLforGetKeyspaceDefinitions(this.keyspace, name); } /** * * @param objType - The name of the Object type aka CDefinition.name * @param key - The TimeUUID of the object to delete * @param data - All the values of the fields existing in this object (or just the required fields will work) * @param timestamp - The timestamp for the request * @return Iterator of CQL statements that need to be executed for this task. */ @NotNull public CQLStatementIterator makeCQLforDelete(String objType, UUID key, Map<String,Object> data, Long timestamp){ return makeCQLforDelete(this.keyspace, this.definitions.get(objType), key, data, timestamp); } /** * * @param rowKey - Row key of the index_update row * @param id - Specific id of the item in the row to delete * @return Single CQLStatement that runs the delete */ @NotNull public CQLStatement makeCQLforDeleteObsoleteUpdateIndexColumn(IndexUpdateRowKey rowKey, UUID id){ return CQLStatement.make( String.format(TEMPLATE_DELETE_OBSOLETE_UPDATE_INDEX_COLUMN, this.keyspace), INDEX_UPDATES_TABLE_NAME, Arrays.asList(rowKey.getObjectName(), rowKey.getInstanceId(), id).toArray()); } /** * * @return String of single CQL statement required to create the Shard Index Table */ public CQLStatement makeCQLforShardIndexTableCreate(){ return CQLStatement.make(String.format(TEMPLATE_CREATE_WIDE_INDEX, this.keyspace, CObjectShardList.SHARD_INDEX_TABLE_NAME), CObjectShardList.SHARD_INDEX_TABLE_NAME); } private CQLStatement makeCQLforAddFieldToTable(String tableName, CField newField){ String query = String.format(TEMPLATE_ADD_FIELD, this.keyspace, tableName, newField.getName(), newField.getType()); return CQLStatement.make(query, tableName); } public CQLStatementIterator makeCQLforAddFieldToObject(CDefinition def, String newFieldName, List<CIndex> existingIndexes){ CField theNewField = def.getField(newFieldName); List<CQLStatement> ret = Lists.newArrayList(); //alter statement for the static table ret.add(makeCQLforAddFieldToTable(makeTableName(def,null), theNewField)); //now make the alter statements for the indexes for(CIndex i: existingIndexes){ ret.add(makeCQLforAddFieldToTable(makeTableName(def,i),theNewField)); } return new BoundedCQLStatementIterator(ret); } /** * * @return String of single CQL statement required to create the Shard Index Table */ public CQLStatement makeCQLforShardIndexTableDrop(){ return CQLStatement.make(String.format(TEMPLATE_DROP, this.keyspace, CObjectShardList.SHARD_INDEX_TABLE_NAME), CObjectShardList.SHARD_INDEX_TABLE_NAME); } /** * * @return String of single CQL statement required to create the Shard Index Table */ public CQLStatement makeCQLforShardIndexTableTruncate(){ return CQLStatement.make(String.format(TEMPLATE_TRUNCATE, this.keyspace, CObjectShardList.SHARD_INDEX_TABLE_NAME), CObjectShardList.SHARD_INDEX_TABLE_NAME); } /** * * @return CQLStatement of single CQL statement required to get the first update token */ public CQLStatement makeGetFirstEligibleIndexUpdate(){ return CQLStatement.make(String.format(TEMPLATE_SELECT_FIRST_ELIGIBLE_INDEX_UPDATE, keyspace), INDEX_UPDATES_TABLE_NAME, Arrays.asList(getTimeUUIDAtEndOfConsistencyHorizion()).toArray()); } /** * * @param lastInstanceKey - Row Key representing the position of the previous row key * @return CQLStatement of the single CQL statement required to get the next update token */ public CQLStatement makeGetNextEligibleIndexUpdate(IndexUpdateRowKey lastInstanceKey){ return CQLStatement.make(String.format(TEMPLATE_SELECT_NEXT_ELIGIBLE_INDEX_UPDATE, keyspace), INDEX_UPDATES_TABLE_NAME, Arrays.asList(lastInstanceKey.getObjectName(),lastInstanceKey.getInstanceId(),getTimeUUIDAtEndOfConsistencyHorizion()).toArray()); } /** * * @param instanceKey - Row Key representing the row key for the row to retrieve * @return CQLStatement of the single CQL statement required to get the Row corresponding to the token */ public static CQLStatement makeGetRowIndexUpdate(String keyspace, IndexUpdateRowKey instanceKey){ return CQLStatement.make(String.format(TEMPLATE_SELECT_ROW_INDEX_UPDATE, keyspace), INDEX_UPDATES_TABLE_NAME, Arrays.asList(instanceKey.getObjectName(),instanceKey.getInstanceId()).toArray()); } /** * * @param def - CIndex for the index for which to pull the shard list * @param indexValues - Values identifing the specific index for which to pull the shard list * @param ordering - ASC or DESC * @param start - Start UUID for bounding * @param end - End UUID for bounding * @return Single CQL statement needed to retrieve the list of shardids */ public static CQLStatement makeCQLforGetShardIndexList(String keyspace, CDefinition def, SortedMap<String,Object> indexValues, CObjectOrdering ordering,@Nullable UUID start, @Nullable UUID end) throws CQLGenerationException { CIndex i = def.getIndex(indexValues, false); String indexValueString = makeIndexValuesString(indexValues.values()); List values = Lists.newArrayList(); values.add(makeTableName(def,i)); values.add(indexValueString); String whereCQL = ""; if(start != null){ whereCQL += " AND shardid >= ?"; values.add(Long.valueOf(i.getShardingStrategy().getShardKey(start))); } if(end != null){ whereCQL += " AND shardid <= ?"; values.add(Long.valueOf(i.getShardingStrategy().getShardKey(end))); } String query = String.format( TEMPLATE_SELECT_WIDE_INDEX, keyspace, CObjectShardList.SHARD_INDEX_TABLE_NAME, whereCQL, ordering ); return CQLStatement.make(query, CObjectShardList.SHARD_INDEX_TABLE_NAME, values.toArray()); } private CQLStatementIterator makeCQLforLeveledCompaction(CKeyspaceDefinition keyspaceDefinition, Integer sstableSize){ List ret = Lists.newArrayList(); //global tables ret.add(makeCQLforLeveledCompaction(keyspaceDefinition.getName(), "__shardindex", sstableSize)); ret.add(makeCQLforLeveledCompaction(keyspaceDefinition.getName(), "__index_updates", sstableSize)); //CDefinition tables for(CDefinition def : keyspaceDefinition.getDefinitions().values()){ //static table ret.add(makeCQLforLeveledCompaction(keyspaceDefinition.getName(), makeTableName(def, null), sstableSize)); //indexes for(CIndex index : def.getIndexes().values()){ ret.add(makeCQLforLeveledCompaction(keyspaceDefinition.getName(), makeTableName(def,index), sstableSize)); } } return new BoundedCQLStatementIterator(ret); } private CQLStatementIterator makeCQLforTieredCompaction(CKeyspaceDefinition keyspaceDefinition, Integer minThreshold){ List ret = Lists.newArrayList(); //global tables ret.add(makeCQLforTieredCompaction(keyspaceDefinition.getName(), "__shardindex", minThreshold)); ret.add(makeCQLforTieredCompaction(keyspaceDefinition.getName(), "__index_updates", minThreshold)); //CDefinition tables for(CDefinition def : keyspaceDefinition.getDefinitions().values()){ //static table ret.add(makeCQLforTieredCompaction(keyspaceDefinition.getName(), makeTableName(def, null), minThreshold)); //indexes for(CIndex index : def.getIndexes().values()){ ret.add(makeCQLforTieredCompaction(keyspaceDefinition.getName(), makeTableName(def,index), minThreshold)); } } return new BoundedCQLStatementIterator(ret); } public CQLStatementIterator makeCQLforCompaction(CKeyspaceDefinition keyspaceDefinition, String strategy, Map<String,Object> options) throws CQLGenerationException { if(strategy.equals("LeveledCompactionStrategy")){ Integer sstableSize = (options.get("sstable_size_in_mb") == null) ? 5 : (Integer)options.get("sstable_size_in_mb"); return makeCQLforLeveledCompaction(keyspaceDefinition,sstableSize); } else if(strategy.equals("SizeTieredCompactionStrategy")){ Integer minThreshold = (options.get("min_threshold") == null) ? 6 : (Integer)options.get("min_threshold"); return makeCQLforTieredCompaction(keyspaceDefinition,minThreshold); } throw new CQLGenerationException("Unknown Strategy " + strategy); } /** * @param table - The table to update with the compaction strategy * @param sstableSize - the size in MB of the ss tables * @return String of single CQL statement required to set */ public static CQLStatement makeCQLforLeveledCompaction(String keyspace, String table, Integer sstableSize){ return CQLStatement.make(String.format(TEMPLATE_SET_COMPACTION_LEVELED, keyspace, table, sstableSize), table); } /** * @param table - The table to update with the compaction strategy * @param minThreshold - minimum number of SSTables to trigger a minor compaction * @return String of single CQL statement required to set */ public static CQLStatement makeCQLforTieredCompaction(String keyspace, String table, Integer minThreshold){ return CQLStatement.make(String.format(TEMPLATE_SET_COMPACTION_TIERED, keyspace, table, minThreshold), table); } public CQLStatement makeCQLforIndexUpdateTableCreate(){ return CQLStatement.make(String.format(TEMPLATE_CREATE_INDEX_UPDATES, this.keyspace), INDEX_UPDATES_TABLE_NAME); } public CQLStatement makeCQLforIndexUpdateTableTruncate(){ return CQLStatement.make(String.format(TEMPLATE_TRUNCATE_INDEX_UPDATES, this.keyspace), INDEX_UPDATES_TABLE_NAME); } public static CQLStatementIterator makeCQLforUpdate(String keyspace, CDefinition def, UUID key, Map<String,Object> oldValues, Map<String, Object> newValues) throws CQLGenerationException { List<CQLStatement> ret = Lists.newArrayList(); //(1) Detect if there are any changed index values in values List<CIndex> affectedIndexes = getAffectedIndexes(def, oldValues, newValues); List<CIndex> unaffectedIndexes = getUnaffectedIndexes(def, oldValues, newValues); //(2) Construct a complete copy of the object Map<String,Object> completeValues = Maps.newHashMap(oldValues); for(String k : newValues.keySet()){ completeValues.put(k, newValues.get(k)); } Map<String,ArrayList> fieldsAndValues = makeFieldAndValueList(def, completeValues); //(3) Delete from any indexes that are no longer applicable for(CIndex i : affectedIndexes){ Map<String,Object> compositeKeyToDelete = i.getIndexKeyAndValues(oldValues); //just ignore the delete if the old index values are the same as the new index values. //We will update with the new fields later on in the method. Ignoring the delete in this //case will solve the problem of async deletes and inserts happening in parallel Map<String,Object> compositeKeyOfCompleteValues = i.getIndexKeyAndValues(completeValues); if(compositeKeyOfCompleteValues.equals(compositeKeyToDelete)){ continue; } //ok we can move forward with the delete now if(def.isAllowNullPrimaryKeyInserts()){ //check if we have the necessary primary fields to delete on this index. If not just continue // because it would be ignored on insert if(!i.validateIndexKeys(compositeKeyToDelete)){ continue; } } ret.add(makeCQLforDeleteUUIDFromIndex(keyspace, def, i, key, compositeKeyToDelete, null)); } //(4) Add index values to the new values list Map<String,Object> newValuesAndIndexValues = Maps.newHashMap(newValues); for(String s: def.getRequiredFields()){ if(!newValuesAndIndexValues.containsKey(s)){ newValuesAndIndexValues.put(s, completeValues.get(s)); } } Map<String,ArrayList> fieldsAndValuesForNewValuesAndIndexValues = makeFieldAndValueList(def,newValuesAndIndexValues); //(5) Insert into the new indexes like a new insert for(CIndex i: affectedIndexes){ if(def.isAllowNullPrimaryKeyInserts()){ //check if we have the necessary primary fields to insert on this index. If not just continue; if(!i.validateIndexKeys(i.getIndexKeyAndValues(completeValues))){ continue; } } addCQLStatmentsForIndexInsert(keyspace, true, ret, def, completeValues, i, key, fieldsAndValues,null, null); } //(6) Insert into the existing indexes without the shard index addition for(CIndex i: unaffectedIndexes){ if(def.isAllowNullPrimaryKeyInserts()){ //check if we have the necessary primary fields to insert on this index. If not just continue; if(!i.validateIndexKeys(i.getIndexKeyAndValues(newValuesAndIndexValues))){ continue; } } addCQLStatmentsForIndexInsert(keyspace, false, ret, def, newValuesAndIndexValues, i, key, fieldsAndValuesForNewValuesAndIndexValues,null, null); } //(7) Update the static table (be sure to only update and not insert the completevalues just in case they are wrong, the background job will fix them later) Map<String,ArrayList> fieldsAndValuesOnlyForChanges = makeFieldAndValueList(def,newValues); ret.add(makeInsertStatementStatic( keyspace, makeTableName(def,null), (List<String>)fieldsAndValuesOnlyForChanges.get("fields").clone(), (List<Object>)fieldsAndValuesOnlyForChanges.get("values").clone(), key, null, null )); //(8) Insert a snapshot of the updated values for this id into the __index_updates ret.add(makeInsertUpdateIndexStatement(keyspace, def, key, def.makeIndexValues(completeValues))); return new BoundedCQLStatementIterator(ret); } public static List<CIndex> getAffectedIndexes(CDefinition def, Map<String,Object> oldValues, Map<String,Object> newValues){ List<CIndex> ret = Lists.newArrayList(); if(def.getIndexes() == null) { return ret; } for(CIndex i : def.getIndexes().values()){ if(i.areValuesAssociatedWithIndex(newValues)){ //This change does indeed effect this index ret.add(i); } } return ret; } public static List<CIndex> getUnaffectedIndexes(CDefinition def, Map<String,Object> oldValues, Map<String,Object> newValues){ List<CIndex> ret = Lists.newArrayList(); if(def.getIndexes() == null) { return ret; } for(CIndex i : def.getIndexes().values()){ if(!i.areValuesAssociatedWithIndex(newValues)){ //This change does not effect this index ret.add(i); } } return ret; } public CQLStatementIterator makeCQLforCreate(CDefinition def){ List<CQLStatement> ret = Lists.newArrayList(); ret.add(makeStaticTableCreate(def)); if(def.getIndexes() != null) { for(CIndex i : def.getIndexes().values()){ ret.add(makeWideTableCreate(def, i)); } } return new BoundedCQLStatementIterator(ret); } protected static CQLStatementIterator makeCQLforDrop(String keyspace, CDefinition def){ List<CQLStatement> ret = Lists.newArrayList(); ret.add(makeTableDrop(keyspace, def.getName())); if(def.getIndexes() != null) { for(CIndex i : def.getIndexes().values()){ ret.add(makeTableDrop(keyspace, makeTableName(def, i))); } } return new BoundedCQLStatementIterator(ret); } protected static CQLStatementIterator makeCQLforTruncate(String keyspace, CDefinition def){ List<CQLStatement> ret = Lists.newArrayList(); ret.add(makeTableTruncate(keyspace, def.getName())); if(def.getIndexes() != null) { for(CIndex i : def.getIndexes().values()){ ret.add(makeTableTruncate(keyspace, makeTableName(def, i))); } } return new BoundedCQLStatementIterator(ret); } protected static CQLStatement makeInsertStatementStatic(String keyspace, String tableName, List<String> fields, List values, Object id, Long timestamp, Integer ttl){ fields.add(0,"id"); values.add(0, id); String query = String.format( TEMPLATE_INSERT_STATIC, keyspace, tableName, makeCommaList(fields), makeCommaList(values, true), //timestamp.toString(), //add timestamp back when timestamps become preparable (ttl == null) ? "" : (" USING TTL "+ttl)//(" AND TTL "+ttl) //Revert this back to AND when timestamps are preparable ); return CQLStatement.make(query, tableName, values.toArray()); } public UUID getTimeUUIDAtEndOfConsistencyHorizion(){ UUID ret = UUIDs.startOf(DateTime.now().getMillis() - consistencyHorizon);//now minus 5 seconds return ret; } public static CQLStatement makeInsertUpdateIndexStatement(String keyspace, CDefinition def, UUID instanceId, Map<String,Object> indexvalues) throws CQLGenerationException { UUID id = UUIDs.timeBased(); String tableName = makeTableName(def,null); String indexValuesAsJson; try{ ObjectMapper om = new ObjectMapper(); indexValuesAsJson = om.writeValueAsString(indexvalues); } catch (Exception e){ throw new CQLGenerationException(e.getMessage()); } return CQLStatement.make(String.format(TEMPLATE_INSERT_INDEX_UPDATES,keyspace), tableName, Arrays.asList(id, tableName, instanceId, indexValuesAsJson).toArray() ); } protected static CQLStatement makeInsertStatementWide(String keyspace, String tableName, List<String> fields, List<Object> values, Object uuid, long shardid, Long timestamp, Integer ttl){ fields.add(0,"shardid"); values.add(0,Long.valueOf(shardid)); fields.add(0,"id"); values.add(0,uuid); String query = String.format( TEMPLATE_INSERT_WIDE, keyspace, tableName, makeCommaList(fields), makeCommaList(values,true), //timestamp.toString(), //add timestamp back when timestamps become preparable (ttl == null) ? "" : (" USING TTL "+ttl)//(" AND TTL "+ttl) //Revert this back to AND when timestamps are preparable ); return CQLStatement.make(query, tableName, values.toArray()); } protected static CQLStatement makeInsertStatementWideIndex(String keyspace, String tableName, String targetTableName, long shardId, List indexValues, Long timestamp) throws CQLGenerationException { String indexValuesString = makeIndexValuesString(indexValues); Object[] values = {targetTableName, indexValuesString, Long.valueOf(shardId), shardId+":"+indexValuesString}; return CQLStatement.make( String.format( TEMPLATE_INSERT_WIDE_INDEX, keyspace, tableName //timestamp.toString() //Add back timestamp when timestamps become preparable ), tableName, values); } public static CQLStatementIterator makeCQLforInsertKeyspaceDefinition(@NotNull String keyspace, @NotNull String name, @NotNull String keyspaceDefinition, @NotNull UUID id) throws CQLGenerationException{ ArrayList<CQLStatement> ret = Lists.newArrayList(); ret.add(CQLStatement.make(String.format(TEMPLATE_INSERT_KEYSPACE, keyspace), KEYSPACE_DEFINITIONS_TABLE_NAME, Arrays.asList(id, name, keyspaceDefinition).toArray())); return new BoundedCQLStatementIterator(ret); } protected static CQLStatementIterator makeCQLforInsert(@NotNull String keyspace, @NotNull CDefinition def, @NotNull Map<String,Object> data) throws CQLGenerationException{ return makeCQLforInsert(keyspace, def, data, null, null, null); } protected static CQLStatementIterator makeCQLforInsert(@NotNull String keyspace, @NotNull CDefinition def, @NotNull Map<String,Object> data, @Nullable Object uuid, Long timestamp, Integer ttl) throws CQLGenerationException{ List<CQLStatement> ret = Lists.newArrayList(); if(uuid == null){ uuid = UUIDs.timeBased(); } if(timestamp == 0){ timestamp = System.currentTimeMillis(); } if(!validateData(def, data)){ throw new CQLGenerationException("Invalid Insert Requested. Missing Field(s)"); } Map<String,ArrayList> fieldsAndValues = makeFieldAndValueList(def,data); //Static Table ret.add(makeInsertStatementStatic( keyspace, makeTableName(def,null), (List<String>)fieldsAndValues.get("fields").clone(), (List<Object>)fieldsAndValues.get("values").clone(), uuid, timestamp, ttl )); //Index Tables if(def.getIndexes() != null) { for(CIndex i : def.getIndexes().values()){ if(def.isAllowNullPrimaryKeyInserts()){ //check if we have the necessary primary fields to insert on this index. If not just continue; if(!i.validateIndexKeys(i.getIndexKeyAndValues(data))){ continue; } } //insert it into the index addCQLStatmentsForIndexInsert(keyspace, true, ret, def,data,i,uuid,fieldsAndValues,timestamp,ttl); } } return new BoundedCQLStatementIterator(ret); } public static void addCQLStatmentsForIndexInsert(String keyspace, boolean includeShardInsert, List<CQLStatement> statementListToAddTo, CDefinition def, @NotNull Map<String,Object> data, CIndex i, Object uuid, Map<String,ArrayList> fieldsAndValues,Long timestamp, Integer ttl) throws CQLGenerationException { //insert it into the index long shardId = i.getShardingStrategy().getShardKey(uuid); statementListToAddTo.add(makeInsertStatementWide( keyspace, makeTableName(def,i), (List<String>)fieldsAndValues.get("fields").clone(), (List<Object>)fieldsAndValues.get("values").clone(), uuid, shardId, timestamp, ttl )); if( includeShardInsert && (!(i.getShardingStrategy() instanceof ShardingStrategyNone))){ //record that we have made an insert into that shard statementListToAddTo.add(makeInsertStatementWideIndex( keyspace, CObjectShardList.SHARD_INDEX_TABLE_NAME, makeTableName(def,i), shardId, i.getIndexValues(data), timestamp )); } } protected static CQLStatement makeCQLforTableScan(String keyspace, CDefinition def){ return CQLStatement.make(String.format(TEMPLATE_TABLE_SCAN, keyspace, def.getName()), def.getName()); } public static CQLStatement makeCQLforGetKeyspaceDefinitions(String keyspace, String name){ String statement = String.format(TEMPLATE_SELECT_KEYSPACE, keyspace, name); Object[] values = {name}; return CQLStatement.make(statement, KEYSPACE_DEFINITIONS_TABLE_NAME, values); } protected static CQLStatementIterator makeCQLforDelete(String keyspace, CDefinition def, UUID key, Map<String,Object> data, Long timestamp){ if(timestamp == null){ timestamp = Long.valueOf(System.currentTimeMillis()); } List<CQLStatement> ret = Lists.newArrayList(); ret.add(makeCQLforDeleteUUIDFromStaticTable(keyspace, def, key, timestamp)); for(CIndex i : def.getIndexes().values()){ if(def.isAllowNullPrimaryKeyInserts()){ //check if we have the necessary primary fields to insert on this index. If not just continue; if(!i.validateIndexKeys(i.getIndexKeyAndValues(data))){ continue; } } ret.add(makeCQLforDeleteUUIDFromIndex(keyspace, def, i, key, i.getIndexKeyAndValues(data), timestamp)); } return new BoundedCQLStatementIterator(ret); } protected static CQLStatement makeCQLforDeleteUUIDFromStaticTable(String keyspace, CDefinition def, UUID uuid, Long timestamp){ Object[] values = {uuid}; return CQLStatement.make(String.format( TEMPLATE_DELETE, keyspace, makeTableName(def, null), //timestamp, //Add back when timestamps become preparable "id = ?"), makeTableName(def, null), values); } public static CQLStatement makeCQLforDeleteUUIDFromIndex(String keyspace, CDefinition def, CIndex index, UUID uuid, Map<String,Object> indexValues, Long timestamp){ List values = Lists.newArrayList( uuid, Long.valueOf(index.getShardingStrategy().getShardKey(uuid)) ); CQLStatement wheres = makeAndedEqualList(def, indexValues); values.addAll(Arrays.asList(wheres.getValues())); String whereCQL = String.format( "id = ? AND shardid = ? AND %s", wheres.getQuery()); String query = String.format( TEMPLATE_DELETE, keyspace, makeTableName(def,index), //timestamp, //Add back when timestamps become preparable whereCQL); return CQLStatement.make(query, makeTableName(def,index), values.toArray()); } public static Statement makeCQLforDeleteUUIDFromIndex_WorkaroundForUnpreparableTimestamp(String keyspace, CDefinition def, CIndex index, UUID uuid, Map<String,Object> indexValues, Long timestamp){ Statement ret = QueryBuilder.delete() .from(keyspace,makeIndexTableName(def,index)) .using(QueryBuilder.timestamp(timestamp)) .where(QueryBuilder.eq("id",uuid)) .and(QueryBuilder.eq("shardid", Long.valueOf(index.getShardingStrategy().getShardKey(uuid)))); for(String key : indexValues.keySet()){ ((Delete.Where)ret).and(QueryBuilder.eq(key,indexValues.get(key))); } return ret; } protected static CQLStatement makeTableDrop(String keyspace, String tableName){ return CQLStatement.make(String.format(TEMPLATE_DROP, keyspace, tableName), tableName); } protected static CQLStatement makeTableTruncate(String keyspace, String tableName){ return CQLStatement.make(String.format(TEMPLATE_TRUNCATE, keyspace, tableName), tableName); } public CQLStatement makeStaticTableCreate(CDefinition def){ String query = String.format( TEMPLATE_CREATE_STATIC, keyspace, def.getName(), def.getPrimaryKeyType(), makeFieldList(def.getFields().values(),true)); return CQLStatement.make(query, def.getName()); } public CQLStatement makeWideTableCreate(CDefinition def, CIndex index){ String query = String.format( TEMPLATE_CREATE_WIDE, keyspace, makeTableName(def,index), def.getPrimaryKeyType(), makeFieldList(def.getFields().values(), true), makeCommaList(index.getCompositeKeyList())); return CQLStatement.make(query, makeTableName(def, index)); } public static String makeIndexValuesString(Collection values) throws CQLGenerationException{ //note, this escaping mechanism can in very rare situations cause index collisions, for example //one:two as a value collides with another value one&#58;two List<String> escaped = Lists.newArrayList(); for(Object v : values){ escaped.add(coerceValueToString(v).replaceAll(":", "&#58;")); } return Joiner.on(":").join(escaped); } public static String coerceValueToString(Object value) throws CQLGenerationException { if(value instanceof String){ return (String)value; } if( (value instanceof UUID) || (value instanceof Long) || (value instanceof Boolean) || (value instanceof Float) || (value instanceof Double) || (value instanceof Integer) || (value instanceof BigInteger) ){ return value.toString(); } if( value instanceof java.util.Date){ return ((java.util.Date)value).getTime()+""; } throw new CQLGenerationException("Rhombus does not support indexes on fields of type " + value.getClass().toString()); } public static Map<String,ArrayList> makeFieldAndValueList(CDefinition def, Map<String,Object> data) throws CQLGenerationException{ ArrayList fieldList = Lists.newArrayList(); ArrayList valueList = Lists.newArrayList(); for(CField f : def.getFields().values()){ if( data.containsKey(f.getName()) && !f.getName().equals("id") ){ fieldList.add(f.getName()); valueList.add(data.get(f.getName())); } } Map<String,ArrayList> ret = Maps.newHashMap(); ret.put("fields", fieldList); ret.put("values", valueList); return ret; } protected static boolean validateData(CDefinition def, Map<String,Object> data){ if(def.isAllowNullPrimaryKeyInserts()){ return true; } Collection<String> fields = def.getRequiredFields(); for( String f : fields){ if(!data.containsKey(f)){ return false; } } return true; } protected static CQLStatement makeAndedEqualList(CDefinition def, Map<String,Object> data){ String query = ""; List values = Lists.newArrayList(); int count = 0; for(String key : data.keySet()){ CField f = def.getFields().get(key); query+=f.getName() + " = ?"; values.add(data.get(key)); if(++count < data.keySet().size()){ query += " AND "; } } return CQLStatement.make(query, def.getName(), values.toArray()); } protected static String makeCommaList(List strings, boolean onlyQuestionMarks){ Iterator<Object> it = strings.iterator(); String ret = ""; while(it.hasNext()){ Object thenext = it.next(); String thenextstring = thenext == null ? "null" : thenext.toString(); String s = onlyQuestionMarks ? "?" : thenextstring; ret = ret + s +(it.hasNext() ? ", " : ""); } return ret; } protected static String makeCommaList(List strings){ return makeCommaList(strings, false); } protected static String makeFieldList(Collection<CField> fields, boolean withType){ Iterator<CField> it = fields.iterator(); String ret = ""; while(it.hasNext()){ CField f = it.next(); if(f.getName().equals("id")){ continue; //ignore the id, if this definition specifies an id } ret = ret + f.getName() + (withType ? " " + f.getType() : "") + (it.hasNext() ? "," : ""); } return ret; } public static String makeTableName(CDefinition def, @Nullable CIndex index){ String objName = def.getName(); if(index == null){ return objName; } else{ return makeIndexTableName(def,index); } } protected static String makeIndexTableName(CDefinition def, CIndex index){ String indexName = Joiner.on('_').join(index.getCompositeKeyList()); String hash = DigestUtils.md5Hex(def.getName()+"|"+indexName); //md5 hashes (in hex) give us 32 chars. We have 48 chars available so that gives us 16 chars remaining for a pretty //display name for the object type. String objDisplayName = def.getName().length() > 15 ? def.getName().substring(0,16) : def.getName(); return objDisplayName+hash; } public void setShardList(CObjectShardList shardList) { this.shardList = shardList; } }
/* * Copyright (c) 2010-2016 Evolveum * * 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.evolveum.midpoint.test; import com.evolveum.icf.dummy.resource.DummyGroup; import com.evolveum.icf.dummy.resource.ScriptHistoryEntry; import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.match.MatchingRule; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.query.AndFilter; import com.evolveum.midpoint.prism.query.EqualFilter; import com.evolveum.midpoint.prism.query.ObjectFilter; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.query.RefFilter; import com.evolveum.midpoint.prism.query.builder.QueryBuilder; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.prism.util.PrismUtil; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.repo.cache.RepositoryCache; import com.evolveum.midpoint.schema.SearchResultList; import com.evolveum.midpoint.schema.constants.ConnectorTestOperation; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; import com.evolveum.midpoint.schema.processor.ResourceAttribute; import com.evolveum.midpoint.schema.processor.ResourceAttributeContainer; import com.evolveum.midpoint.schema.processor.ResourceAttributeContainerDefinition; import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; import com.evolveum.midpoint.schema.processor.ResourceSchema; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.schema.util.ShadowUtil; import com.evolveum.midpoint.schema.util.ResourceTypeUtil; import com.evolveum.midpoint.schema.util.SchemaDebugUtil; import com.evolveum.midpoint.schema.util.SchemaTestConstants; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.DebugDumpable; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.opends.server.types.Entry; import org.opends.server.types.SearchResultEntry; import org.testng.AssertJUnit; import org.w3c.dom.Element; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import static org.testng.AssertJUnit.*; /** * @author Radovan Semancik * */ public class IntegrationTestTools { public static final String DUMMY_CONNECTOR_TYPE = "com.evolveum.icf.dummy.connector.DummyConnector"; public static final String DBTABLE_CONNECTOR_TYPE = "org.identityconnectors.databasetable.DatabaseTableConnector"; public static final String NS_RESOURCE_DUMMY_CONFIGURATION = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.icf.dummy/com.evolveum.icf.dummy.connector.DummyConnector"; public static final QName RESOURCE_DUMMY_CONFIGURATION_USELESS_STRING_ELEMENT_NAME = new QName(NS_RESOURCE_DUMMY_CONFIGURATION ,"uselessString"); // public and not final - to allow changing it in tests public static Trace LOGGER = TraceManager.getTrace(IntegrationTestTools.class); private static final String OBJECT_TITLE_OUT_PREFIX = "\n*** "; private static final String OBJECT_TITLE_LOG_PREFIX = "*** "; private static final String LOG_MESSAGE_PREFIX = ""; private static final String OBJECT_LIST_SEPARATOR = "---"; private static final long WAIT_FOR_LOOP_SLEEP_MILIS = 500; public static void assertTestResourceSuccess(OperationResult testResult, ConnectorTestOperation operation) { OperationResult opResult = testResult.findSubresult(operation.getOperation()); assertNotNull("No result for "+operation, opResult); TestUtil.assertSuccess("Test resource failed (result): "+operation, opResult, 1); } public static void assertTestResourceFailure(OperationResult testResult, ConnectorTestOperation operation) { OperationResult opResult = testResult.findSubresult(operation.getOperation()); assertNotNull("No result for "+operation, opResult); TestUtil.assertFailure("Test resource succeeded while expected failure (result): "+operation, opResult); } public static void assertTestResourceNotApplicable(OperationResult testResult, ConnectorTestOperation operation) { OperationResult opResult = testResult.findSubresult(operation.getOperation()); assertNotNull("No result for "+operation, opResult); assertEquals("Test resource status is not 'not applicable', it is "+opResult.getStatus()+": "+operation, OperationResultStatus.NOT_APPLICABLE, opResult.getStatus()); } public static void assertNotEmpty(String message, String s) { assertNotNull(message, s); assertFalse(message, s.isEmpty()); } public static void assertNotEmpty(PolyString ps) { assertNotNull(ps); assertFalse(ps.isEmpty()); } public static void assertNotEmpty(PolyStringType ps) { assertNotNull(ps); assertFalse(PrismUtil.isEmpty(ps)); } public static void assertNotEmpty(String message, PolyString ps) { assertNotNull(message, ps); assertFalse(message, ps.isEmpty()); } public static void assertNotEmpty(String message, PolyStringType ps) { assertNotNull(message, ps); assertFalse(message, PrismUtil.isEmpty(ps)); } public static void assertNotEmpty(String s) { assertNotNull(s); assertFalse(s.isEmpty()); } public static void assertNotEmpty(String message, QName qname) { assertNotNull(message, qname); assertNotEmpty(message,qname.getNamespaceURI()); assertNotEmpty(message,qname.getLocalPart()); } public static void assertNotEmpty(QName qname) { assertNotNull(qname); assertNotEmpty(qname.getNamespaceURI()); assertNotEmpty(qname.getLocalPart()); } public static <T> void assertAttribute(ShadowType shadow, ResourceType resource, String name, T... expectedValues) { assertAttribute("Wrong attribute " + name + " in "+shadow, shadow, new QName(ResourceTypeUtil.getResourceNamespace(resource), name), expectedValues); } public static <T> void assertAttribute(PrismObject<? extends ShadowType> shadow, ResourceType resource, String name, T... expectedValues) { assertAttribute("Wrong attribute " + name + " in "+shadow, shadow, new QName(ResourceTypeUtil.getResourceNamespace(resource), name), expectedValues); } public static <T> void assertAttribute(ShadowType shadowType, QName name, T... expectedValues) { assertAttribute(shadowType.asPrismObject(), name, expectedValues); } public static <T> void assertAttribute(PrismObject<? extends ShadowType> shadow, QName name, T... expectedValues) { Collection<T> values = getAttributeValues(shadow, name); assertEqualsCollection("Wrong value for attribute "+name+" in "+shadow, expectedValues, values); } public static <T> void assertAttribute(String message, ShadowType repoShadow, QName name, T... expectedValues) { Collection<T> values = getAttributeValues(repoShadow, name); assertEqualsCollection(message, expectedValues, values); } public static <T> void assertAttribute(String message, PrismObject<? extends ShadowType> repoShadow, QName name, T... expectedValues) { Collection<T> values = getAttributeValues(repoShadow, name); assertEqualsCollection(message, expectedValues, values); } public static <T> void assertNoAttribute(PrismObject<? extends ShadowType> shadow, QName name) { assertNull("Found attribute "+name+" in "+shadow+" while not expecting it", getAttributeValues(shadow, name)); } public static <T> void assertEqualsCollection(String message, Collection<T> expectedValues, Collection<T> actualValues) { if (expectedValues == null && actualValues == null) { return; } assert !(expectedValues == null && actualValues != null) : "Expecting null values but got "+actualValues; assert actualValues != null : message+": Expecting "+expectedValues+" but got null"; assertEquals(message+": Wrong number of values in " + actualValues, expectedValues.size(), actualValues.size()); for (T actualValue: actualValues) { boolean found = false; for (T value: expectedValues) { if (value.equals(actualValue)) { found = true; } } if (!found) { fail(message + ": Unexpected value "+actualValue+"; expected "+expectedValues+"; has "+actualValues); } } } public static <T> void assertEqualsCollection(String message, Collection<T> expectedValues, T[] actualValues) { assertEqualsCollection(message, expectedValues, Arrays.asList(actualValues)); } public static <T> void assertEqualsCollection(String message, T[] expectedValues, Collection<T> actualValues) { assertEqualsCollection(message, Arrays.asList(expectedValues), actualValues); } public static String getIcfsNameAttribute(PrismObject<ShadowType> shadow) { return getIcfsNameAttribute(shadow.asObjectable()); } public static String getIcfsNameAttribute(ShadowType shadowType) { return getAttributeValue(shadowType, SchemaTestConstants.ICFS_NAME); } public static String getSecondaryIdentifier(PrismObject<ShadowType> shadow) { Collection<ResourceAttribute<?>> secondaryIdentifiers = ShadowUtil.getSecondaryIdentifiers(shadow); if (secondaryIdentifiers == null || secondaryIdentifiers.isEmpty()) { return null; } if (secondaryIdentifiers.size() > 1) { throw new IllegalArgumentException("Too many secondary indentifiers in "+shadow); } return (String) secondaryIdentifiers.iterator().next().getRealValue(); } public static void assertSecondaryIdentifier(PrismObject<ShadowType> repoShadow, String value) { assertEquals("Wrong secondary indetifier in "+repoShadow, value, getSecondaryIdentifier(repoShadow)); } public static void assertIcfsNameAttribute(ShadowType repoShadow, String value) { assertAttribute(repoShadow, SchemaTestConstants.ICFS_NAME, value); } public static void assertIcfsNameAttribute(PrismObject<ShadowType> repoShadow, String value) { assertAttribute(repoShadow, SchemaTestConstants.ICFS_NAME, value); } public static void assertAttributeNotNull(PrismObject<ShadowType> repoShadow, QName name) { Collection<String> values = getAttributeValues(repoShadow, name); assertFalse("No values for "+name+" in "+repoShadow, values == null || values.isEmpty()); assertEquals(1, values.size()); assertNotNull(values.iterator().next()); } public static void assertAttributeNotNull(ShadowType repoShadow, QName name) { Collection<String> values = getAttributeValues(repoShadow, name); assertFalse("No values for "+name+" in "+repoShadow, values == null || values.isEmpty()); assertEquals(1, values.size()); assertNotNull(values.iterator().next()); } public static void assertAttributeNotNull(String message, ShadowType repoShadow, QName name) { Collection<String> values = getAttributeValues(repoShadow, name); assertFalse("No values for "+name+" in "+repoShadow, values == null || values.isEmpty()); assertEquals(message, 1, values.size()); assertNotNull(message, values.iterator().next()); } public static void assertAttributeDefinition(ResourceAttribute<?> attr, QName expectedType, int minOccurs, int maxOccurs, boolean canRead, boolean canCreate, boolean canUpdate, Class<?> expectedAttributeDefinitionClass) { ResourceAttributeDefinition definition = attr.getDefinition(); QName attrName = attr.getElementName(); assertNotNull("No definition for attribute "+attrName, definition); //assertEquals("Wrong class of definition for attribute"+attrName, expetcedAttributeDefinitionClass, definition.getClass()); assertTrue("Wrong class of definition for attribute"+attrName+" (expected: " + expectedAttributeDefinitionClass + ", real: " + definition.getClass() + ")", expectedAttributeDefinitionClass.isAssignableFrom(definition.getClass())); assertEquals("Wrong type in definition for attribute"+attrName, expectedType, definition.getTypeName()); assertEquals("Wrong minOccurs in definition for attribute"+attrName, minOccurs, definition.getMinOccurs()); assertEquals("Wrong maxOccurs in definition for attribute"+attrName, maxOccurs, definition.getMaxOccurs()); assertEquals("Wrong canRead in definition for attribute"+attrName, canRead, definition.canRead()); assertEquals("Wrong canCreate in definition for attribute"+attrName, canCreate, definition.canAdd()); assertEquals("Wrong canUpdate in definition for attribute"+attrName, canUpdate, definition.canModify()); } public static void assertProvisioningAccountShadow(PrismObject<ShadowType> account, ResourceType resourceType, Class<?> expetcedAttributeDefinitionClass) { assertProvisioningShadow(account,resourceType,expetcedAttributeDefinitionClass, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME)); } public static void assertProvisioningShadow(PrismObject<ShadowType> account, ResourceType resourceType, Class<?> expetcedAttributeDefinitionClass, QName objectClass) { // Check attribute definition PrismContainer attributesContainer = account.findContainer(ShadowType.F_ATTRIBUTES); assertEquals("Wrong attributes container class", ResourceAttributeContainer.class, attributesContainer.getClass()); ResourceAttributeContainer rAttributesContainer = (ResourceAttributeContainer)attributesContainer; PrismContainerDefinition attrsDef = attributesContainer.getDefinition(); assertNotNull("No attributes container definition", attrsDef); assertTrue("Wrong attributes definition class "+attrsDef.getClass().getName(), attrsDef instanceof ResourceAttributeContainerDefinition); ResourceAttributeContainerDefinition rAttrsDef = (ResourceAttributeContainerDefinition)attrsDef; ObjectClassComplexTypeDefinition objectClassDef = rAttrsDef.getComplexTypeDefinition(); assertNotNull("No object class definition in attributes definition", objectClassDef); assertEquals("Wrong object class in attributes definition", objectClass, objectClassDef.getTypeName()); ResourceAttributeDefinition primaryIdDef = objectClassDef.getPrimaryIdentifiers().iterator().next(); ResourceAttribute<?> primaryIdAttr = rAttributesContainer.findAttribute(primaryIdDef.getName()); assertNotNull("No primary ID "+primaryIdDef.getName()+" in "+account, primaryIdAttr); assertAttributeDefinition(primaryIdAttr, DOMUtil.XSD_STRING, 0, 1, true, false, false, expetcedAttributeDefinitionClass); ResourceAttributeDefinition secondaryIdDef = objectClassDef.getSecondaryIdentifiers().iterator().next(); ResourceAttribute<Object> secondaryIdAttr = rAttributesContainer.findAttribute(secondaryIdDef.getName()); assertNotNull("No secondary ID "+secondaryIdDef.getName()+" in "+account, secondaryIdAttr); assertAttributeDefinition(secondaryIdAttr, DOMUtil.XSD_STRING, 1, 1, true, true, true, expetcedAttributeDefinitionClass); } public static <T> Collection<T> getAttributeValues(ShadowType shadowType, QName name) { return getAttributeValues(shadowType.asPrismObject(), name); } public static <T> Collection<T> getAttributeValues(PrismObject<? extends ShadowType> shadow, QName name) { if (shadow == null) { throw new IllegalArgumentException("No shadow"); } PrismContainer<?> attrCont = shadow.findContainer(ShadowType.F_ATTRIBUTES); if (attrCont == null) { return null; } PrismProperty<T> attrProp = attrCont.findProperty(name); if (attrProp == null) { return null; } return attrProp.getRealValues(); } public static String getAttributeValue(ShadowType repoShadow, QName name) { Collection<String> values = getAttributeValues(repoShadow, name); if (values == null || values.isEmpty()) { AssertJUnit.fail("Attribute "+name+" not found in shadow "+ObjectTypeUtil.toShortString(repoShadow)); } if (values.size() > 1) { AssertJUnit.fail("Too many values for attribute "+name+" in shadow "+ObjectTypeUtil.toShortString(repoShadow)); } return values.iterator().next(); } public static void waitFor(String message, Checker checker, int timeoutInterval) throws CommonException { waitFor(message, checker, timeoutInterval, WAIT_FOR_LOOP_SLEEP_MILIS); } public static void waitFor(String message, Checker checker, int timeoutInterval, long sleepInterval) throws CommonException { System.out.println(message); LOGGER.debug(LOG_MESSAGE_PREFIX + message); long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() < startTime + timeoutInterval) { boolean done = checker.check(); if (done) { System.out.println("... done"); LOGGER.trace(LOG_MESSAGE_PREFIX + "... done " + message); return; } try { Thread.sleep(sleepInterval); } catch (InterruptedException e) { LOGGER.warn("Sleep interrupted: {}", e.getMessage(), e); } } // we have timeout System.out.println("Timeout while "+message); LOGGER.error(LOG_MESSAGE_PREFIX + "Timeout while " + message); // Invoke callback checker.timeout(); throw new RuntimeException("Timeout while "+message); } public static void displayJaxb(String title, Object o, QName defaultElementName) throws SchemaException { String serialized = PrismTestUtil.serializeAnyData(o, defaultElementName); System.out.println(OBJECT_TITLE_OUT_PREFIX + title); System.out.println(serialized); LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + title + "\n" + serialized); } public static void display(String message) { System.out.println(OBJECT_TITLE_OUT_PREFIX + message); LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + message); } public static void display(String message, SearchResultEntry response) { System.out.println(OBJECT_TITLE_OUT_PREFIX + message); LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + message); display(response); } public static void display(Entry response) { System.out.println(response == null ? "null" : response.toLDIFString()); LOGGER.debug(response == null ? "null" : response.toLDIFString()); } public static void display(String message, Task task) { System.out.println(OBJECT_TITLE_OUT_PREFIX + message); System.out.println(task.debugDump()); LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + message + "\n" + task.debugDump()); } public static void display(String message, ObjectType o) { System.out.println(OBJECT_TITLE_OUT_PREFIX + message); System.out.println(ObjectTypeUtil.dump(o)); LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + message + "\n" + ObjectTypeUtil.dump(o)); } public static void display(String message, Collection collection) { String dump = DebugUtil.dump(collection); System.out.println(OBJECT_TITLE_OUT_PREFIX + message + "\n" + dump); LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + message + "\n" + dump); } public static void displayObjectTypeCollection(String message, Collection<? extends ObjectType> collection) { System.out.println(OBJECT_TITLE_OUT_PREFIX + message); LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + message); for (ObjectType o : collection) { System.out.println(ObjectTypeUtil.dump(o)); LOGGER.debug(ObjectTypeUtil.dump(o)); System.out.println(OBJECT_LIST_SEPARATOR); LOGGER.debug(OBJECT_LIST_SEPARATOR); } } public static void display(String title, Entry entry) { System.out.println(OBJECT_TITLE_OUT_PREFIX + title); String ldif = null; if (entry != null) { ldif = entry.toLDIFString(); } System.out.println(ldif); LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + title + "\n" + ldif); } public static void display(String message, PrismContainer<?> propertyContainer) { System.out.println(OBJECT_TITLE_OUT_PREFIX + message); System.out.println(propertyContainer == null ? "null" : propertyContainer.debugDump()); LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + message + "\n" + (propertyContainer == null ? "null" : propertyContainer.debugDump())); } public static void display(OperationResult result) { display("Result of "+result.getOperation(), result); } public static void display(String title, OperationResult result) { System.out.println(OBJECT_TITLE_OUT_PREFIX + title); System.out.println(result.debugDump()); LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + title + "\n" + result.debugDump()); } public static void display(String title, OperationResultType result) throws SchemaException { displayJaxb(title, result, SchemaConstants.C_RESULT); } public static void display(String title, List<Element> elements) { System.out.println(OBJECT_TITLE_OUT_PREFIX + title); LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + title); for(Element e : elements) { String s = DOMUtil.serializeDOMToString(e); System.out.println(s); LOGGER.debug(s); } } public static void display(String title, DebugDumpable dumpable) { System.out.println(OBJECT_TITLE_OUT_PREFIX + title); System.out.println(dumpable == null ? "null" : dumpable.debugDump()); LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + title + "\n" + (dumpable == null ? "null" : dumpable.debugDump())); } public static void display(String title, String value) { System.out.println(OBJECT_TITLE_OUT_PREFIX + title); System.out.println(value); LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + title + "\n" + value); } public static void display(String title, Object value) { System.out.println(OBJECT_TITLE_OUT_PREFIX + title); System.out.println(SchemaDebugUtil.prettyPrint(value)); LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + title + "\n" + SchemaDebugUtil.prettyPrint(value)); } public static void display(String title, Containerable value) { System.out.println(OBJECT_TITLE_OUT_PREFIX + title); System.out.println(SchemaDebugUtil.prettyPrint(value.asPrismContainerValue().debugDump())); LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + title + "\n" + SchemaDebugUtil.prettyPrint(value.asPrismContainerValue().debugDump())); } public static void display(String title, Throwable e) { String stackTrace = ExceptionUtils.getStackTrace(e); System.out.println(OBJECT_TITLE_OUT_PREFIX + title + ": "+e.getClass() + " " + e.getMessage()); System.out.println(stackTrace); LOGGER.debug("{}{}: {} {}\n{}", new Object[]{ OBJECT_TITLE_LOG_PREFIX, title, e.getClass(), e.getMessage(), stackTrace}); } public static <O extends ObjectType> void assertSearchResultNames(SearchResultList<PrismObject<O>> resultList, MatchingRule<String> matchingRule, String... expectedNames) throws SchemaException { List<String> names = new ArrayList<>(expectedNames.length); for(PrismObject<O> obj: resultList) { names.add(obj.asObjectable().getName().getOrig()); } PrismAsserts.assertSets("Unexpected search result", matchingRule, names, expectedNames); } public static <O extends ObjectType> void assertSearchResultNames(SearchResultList<PrismObject<O>> resultList, String... expectedNames) { List<String> names = new ArrayList<>(expectedNames.length); for(PrismObject<O> obj: resultList) { names.add(obj.asObjectable().getName().getOrig()); } PrismAsserts.assertSets("Unexpected search result", names, expectedNames); } public static void checkAllShadows(ResourceType resourceType, RepositoryService repositoryService, ObjectChecker<ShadowType> checker, PrismContext prismContext) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { OperationResult result = new OperationResult(IntegrationTestTools.class.getName() + ".checkAllShadows"); ObjectQuery query = createAllShadowsQuery(resourceType, prismContext); List<PrismObject<ShadowType>> allShadows = repositoryService.searchObjects(ShadowType.class, query, null, result); LOGGER.trace("Checking {} shadows, query:\n{}", allShadows.size(), query.debugDump()); for (PrismObject<ShadowType> shadow: allShadows) { checkShadow(shadow.asObjectable(), resourceType, repositoryService, checker, prismContext, result); } } public static ObjectQuery createAllShadowsQuery(ResourceType resourceType, PrismContext prismContext) throws SchemaException { return QueryBuilder.queryFor(ShadowType.class, prismContext) .item(ShadowType.F_RESOURCE_REF).ref(resourceType.getOid()) .build(); } public static ObjectQuery createAllShadowsQuery(ResourceType resourceType, QName objectClass, PrismContext prismContext) throws SchemaException { return QueryBuilder.queryFor(ShadowType.class, prismContext) .item(ShadowType.F_RESOURCE_REF).ref(resourceType.getOid()) .and().item(ShadowType.F_OBJECT_CLASS).eq(objectClass) .build(); } public static ObjectQuery createAllShadowsQuery(ResourceType resourceType, String objectClassLocalName, PrismContext prismContext) throws SchemaException { return createAllShadowsQuery(resourceType, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), objectClassLocalName), prismContext); } public static void checkAccountShadow(ShadowType shadowType, ResourceType resourceType, RepositoryService repositoryService, ObjectChecker<ShadowType> checker, PrismContext prismContext, OperationResult parentResult) throws SchemaException { checkAccountShadow(shadowType, resourceType, repositoryService, checker, null, prismContext, parentResult); } public static void checkAccountShadow(ShadowType shadowType, ResourceType resourceType, RepositoryService repositoryService, ObjectChecker<ShadowType> checker, MatchingRule<String> uidMatchingRule, PrismContext prismContext, OperationResult parentResult) throws SchemaException { checkShadow(shadowType, resourceType, repositoryService, checker, uidMatchingRule, prismContext, parentResult); assertEquals(new QName(ResourceTypeUtil.getResourceNamespace(resourceType), SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME), shadowType.getObjectClass()); } public static void checkEntitlementShadow(ShadowType shadowType, ResourceType resourceType, RepositoryService repositoryService, ObjectChecker<ShadowType> checker, String objectClassLocalName, PrismContext prismContext, OperationResult parentResult) throws SchemaException { checkEntitlementShadow(shadowType, resourceType, repositoryService, checker, objectClassLocalName, null, prismContext, parentResult); } public static void checkEntitlementShadow(ShadowType shadowType, ResourceType resourceType, RepositoryService repositoryService, ObjectChecker<ShadowType> checker, String objectClassLocalName, MatchingRule<String> uidMatchingRule, PrismContext prismContext, OperationResult parentResult) throws SchemaException { checkShadow(shadowType, resourceType, repositoryService, checker, uidMatchingRule, prismContext, parentResult); assertEquals(new QName(ResourceTypeUtil.getResourceNamespace(resourceType), objectClassLocalName), shadowType.getObjectClass()); } public static void checkShadow(ShadowType shadowType, ResourceType resourceType, RepositoryService repositoryService, ObjectChecker<ShadowType> checker, PrismContext prismContext, OperationResult parentResult) throws SchemaException { checkShadow(shadowType, resourceType, repositoryService, checker, null, prismContext, parentResult); } public static void checkShadow(ShadowType shadowType, ResourceType resourceType, RepositoryService repositoryService, ObjectChecker<ShadowType> checker, MatchingRule<String> uidMatchingRule, PrismContext prismContext, OperationResult parentResult) throws SchemaException { LOGGER.trace("Checking shadow:\n{}",shadowType.asPrismObject().debugDump()); shadowType.asPrismObject().checkConsistence(true, true, ConsistencyCheckScope.THOROUGH); assertNotNull("no OID",shadowType.getOid()); assertNotNull("no name",shadowType.getName()); assertEquals(resourceType.getOid(), shadowType.getResourceRef().getOid()); PrismContainer<?> attrs = shadowType.asPrismObject().findContainer(ShadowType.F_ATTRIBUTES); assertNotNull("no attributes",attrs); assertFalse("empty attributes",attrs.isEmpty()); RefinedResourceSchema rschema = RefinedResourceSchemaImpl.getRefinedSchema(resourceType); ObjectClassComplexTypeDefinition objectClassDef = rschema.findObjectClassDefinition(shadowType); assertNotNull("cannot determine object class for "+shadowType, objectClassDef); String icfUid = ShadowUtil.getSingleStringAttributeValue(shadowType, SchemaTestConstants.ICFS_UID); if (icfUid == null) { Collection<? extends ResourceAttributeDefinition> identifierDefs = objectClassDef.getPrimaryIdentifiers(); assertFalse("No identifiers for "+objectClassDef, identifierDefs == null || identifierDefs.isEmpty()); for (ResourceAttributeDefinition idDef: identifierDefs) { String id = ShadowUtil.getSingleStringAttributeValue(shadowType, idDef.getName()); assertNotNull("No identifier "+idDef.getName()+" in "+shadowType, id); } } String resourceOid = ShadowUtil.getResourceOid(shadowType); assertNotNull("No resource OID in "+shadowType, resourceOid); assertNotNull("Null OID in "+shadowType, shadowType.getOid()); PrismObject<ShadowType> repoShadow = null; try { repoShadow = repositoryService.getObject(ShadowType.class, shadowType.getOid(), null, parentResult); } catch (Exception e) { AssertJUnit.fail("Got exception while trying to read "+shadowType+ ": "+e.getCause()+": "+e.getMessage()); } checkShadowUniqueness(shadowType, objectClassDef, repositoryService, uidMatchingRule, prismContext, parentResult); String repoResourceOid = ShadowUtil.getResourceOid(repoShadow.asObjectable()); assertNotNull("No resource OID in the repository shadow "+repoShadow); assertEquals("Resource OID mismatch", resourceOid, repoResourceOid); try { repositoryService.getObject(ResourceType.class, resourceOid, null, parentResult); } catch (Exception e) { AssertJUnit.fail("Got exception while trying to read resource "+resourceOid+" as specified in current shadow "+shadowType+ ": "+e.getCause()+": "+e.getMessage()); } if (checker != null) { checker.check(shadowType); } } /** * Checks i there is only a single shadow in repo for this account. */ private static void checkShadowUniqueness(ShadowType resourceShadow, ObjectClassComplexTypeDefinition objectClassDef, RepositoryService repositoryService, MatchingRule<String> uidMatchingRule, PrismContext prismContext, OperationResult parentResult) { try { ObjectQuery query = createShadowQuery(resourceShadow, objectClassDef, uidMatchingRule, prismContext); List<PrismObject<ShadowType>> results = repositoryService.searchObjects(ShadowType.class, query, null, parentResult); LOGGER.trace("Shadow check with filter\n{}\n found {} objects", query.debugDump(), results.size()); if (results.size() == 0) { AssertJUnit.fail("No shadow found with query:\n"+query.debugDump()); } if (results.size() == 1) { return; } if (results.size() > 1) { for (PrismObject<ShadowType> result: results) { LOGGER.trace("Search result:\n{}", result.debugDump()); } LOGGER.error("More than one shadows found for " + resourceShadow); // TODO: Better error handling later throw new IllegalStateException("More than one shadows found for " + resourceShadow); } } catch (SchemaException e) { throw new SystemException(e); } } private static ObjectQuery createShadowQuery(ShadowType resourceShadow, ObjectClassComplexTypeDefinition objectClassDef, MatchingRule<String> uidMatchingRule, PrismContext prismContext) throws SchemaException { PrismContainer<?> attributesContainer = resourceShadow.asPrismObject().findContainer(ShadowType.F_ATTRIBUTES); QName identifierName = objectClassDef.getPrimaryIdentifiers().iterator().next().getName(); PrismProperty<String> identifier = attributesContainer.findProperty(identifierName); if (identifier == null) { throw new SchemaException("No identifier in "+resourceShadow); } String identifierValue = identifier.getRealValue(); if (uidMatchingRule != null) { identifierValue = uidMatchingRule.normalize(identifierValue); } PrismPropertyDefinition<String> identifierDef = identifier.getDefinition(); return QueryBuilder.queryFor(ShadowType.class, prismContext) .item(ShadowType.F_RESOURCE_REF).ref(ShadowUtil.getResourceOid(resourceShadow)) .and().item(new ItemPath(ShadowType.F_ATTRIBUTES, identifierDef.getName()), identifierDef).eq(identifierValue) .build(); } public static void applyResourceSchema(ShadowType accountType, ResourceType resourceType, PrismContext prismContext) throws SchemaException { ResourceSchema resourceSchema = RefinedResourceSchemaImpl.getResourceSchema(resourceType, prismContext); ShadowUtil.applyResourceSchema(accountType.asPrismObject(), resourceSchema); } public static void assertInMessageRecursive(Throwable e, String substring) { assert hasInMessageRecursive(e, substring) : "The substring '"+substring+"' was NOT found in the message of exception "+e+" (including cause exceptions)"; } public static boolean hasInMessageRecursive(Throwable e, String substring) { if (e.getMessage().contains(substring)) { return true; } if (e.getCause() != null) { return hasInMessageRecursive(e.getCause(), substring); } return false; } public static void assertNotInMessageRecursive(Throwable e, String substring) { assert !e.getMessage().contains(substring) : "The substring '"+substring+"' was found in the message of exception "+e+": "+e.getMessage(); if (e.getCause() != null) { assertNotInMessageRecursive(e.getCause(), substring); } } public static void assertNoRepoCache() { if (RepositoryCache.exists()) { AssertJUnit.fail("Cache exists! " + RepositoryCache.debugDump()); } } public static void assertScripts(List<ScriptHistoryEntry> scriptsHistory, ProvisioningScriptSpec... expectedScripts) { displayScripts(scriptsHistory); assertEquals("Wrong number of scripts executed", expectedScripts.length, scriptsHistory.size()); Iterator<ScriptHistoryEntry> historyIter = scriptsHistory.iterator(); for (ProvisioningScriptSpec expecedScript: expectedScripts) { ScriptHistoryEntry actualScript = historyIter.next(); assertEquals("Wrong script code", expecedScript.getCode(), actualScript.getCode()); if (expecedScript.getLanguage() == null) { assertEquals("We talk only gibberish here", "Gibberish", actualScript.getLanguage()); } else { assertEquals("Wrong script language", expecedScript.getLanguage(), actualScript.getLanguage()); } assertEquals("Wrong number of arguments", expecedScript.getArgs().size(), actualScript.getParams().size()); for (java.util.Map.Entry<String,Object> expectedEntry: expecedScript.getArgs().entrySet()) { Object expectedValue = expectedEntry.getValue(); Object actualVal = actualScript.getParams().get(expectedEntry.getKey()); assertEquals("Wrong value for argument '"+expectedEntry.getKey()+"'", expectedValue, actualVal); } } } public static void displayScripts(List<ScriptHistoryEntry> scriptsHistory) { for (ScriptHistoryEntry script : scriptsHistory) { display("Script", script); } } public static <T> void assertExtensionProperty(PrismObject<? extends ObjectType> object, QName propertyName, T... expectedValues) { PrismContainer<?> extension = object.getExtension(); PrismAsserts.assertPropertyValue(extension, propertyName, expectedValues); } public static <T> void assertNoExtensionProperty(PrismObject<? extends ObjectType> object, QName propertyName) { PrismContainer<?> extension = object.getExtension(); PrismAsserts.assertNoItem(extension, propertyName); } public static void assertIcfResourceSchemaSanity(ResourceSchema resourceSchema, ResourceType resourceType) { assertNotNull("No resource schema in "+resourceType, resourceSchema); QName objectClassQname = new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "AccountObjectClass"); ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findObjectClassDefinition(objectClassQname); assertNotNull("No object class definition for "+objectClassQname+" in resource schema", accountDefinition); ObjectClassComplexTypeDefinition accountDef = resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); assertTrue("Mismatched account definition: "+accountDefinition+" <-> "+accountDef, accountDefinition == accountDef); assertNotNull("No object class definition " + objectClassQname, accountDefinition); assertEquals("Object class " + objectClassQname + " is not account", ShadowKindType.ACCOUNT, accountDefinition.getKind()); assertTrue("Object class " + objectClassQname + " is not default account", accountDefinition.isDefaultInAKind()); assertFalse("Object class " + objectClassQname + " is empty", accountDefinition.isEmpty()); assertFalse("Object class " + objectClassQname + " is empty", accountDefinition.isIgnored()); Collection<? extends ResourceAttributeDefinition> identifiers = accountDefinition.getPrimaryIdentifiers(); assertNotNull("Null identifiers for " + objectClassQname, identifiers); assertFalse("Empty identifiers for " + objectClassQname, identifiers.isEmpty()); ResourceAttributeDefinition uidAttributeDefinition = accountDefinition.findAttributeDefinition(SchemaTestConstants.ICFS_UID); assertNotNull("No definition for attribute "+SchemaTestConstants.ICFS_UID, uidAttributeDefinition); assertTrue("Attribute "+SchemaTestConstants.ICFS_UID+" in not an identifier",uidAttributeDefinition.isIdentifier(accountDefinition)); assertTrue("Attribute "+SchemaTestConstants.ICFS_UID+" in not in identifiers list",identifiers.contains(uidAttributeDefinition)); assertEquals("Wrong displayName for attribute "+SchemaTestConstants.ICFS_UID, "ConnId UID", uidAttributeDefinition.getDisplayName()); assertEquals("Wrong displayOrder for attribute "+SchemaTestConstants.ICFS_UID, (Integer)100, uidAttributeDefinition.getDisplayOrder()); Collection<? extends ResourceAttributeDefinition> secondaryIdentifiers = accountDefinition.getSecondaryIdentifiers(); assertNotNull("Null secondary identifiers for " + objectClassQname, secondaryIdentifiers); assertFalse("Empty secondary identifiers for " + objectClassQname, secondaryIdentifiers.isEmpty()); ResourceAttributeDefinition nameAttributeDefinition = accountDefinition.findAttributeDefinition(SchemaTestConstants.ICFS_NAME); assertNotNull("No definition for attribute "+SchemaTestConstants.ICFS_NAME, nameAttributeDefinition); assertTrue("Attribute "+SchemaTestConstants.ICFS_NAME+" in not an identifier",nameAttributeDefinition.isSecondaryIdentifier(accountDefinition)); assertTrue("Attribute "+SchemaTestConstants.ICFS_NAME+" in not in identifiers list",secondaryIdentifiers.contains(nameAttributeDefinition)); assertEquals("Wrong displayName for attribute "+SchemaTestConstants.ICFS_NAME, "ConnId Name", nameAttributeDefinition.getDisplayName()); assertEquals("Wrong displayOrder for attribute "+SchemaTestConstants.ICFS_NAME, (Integer)110, nameAttributeDefinition.getDisplayOrder()); assertNotNull("Null identifiers in account", accountDef.getPrimaryIdentifiers()); assertFalse("Empty identifiers in account", accountDef.getPrimaryIdentifiers().isEmpty()); assertNotNull("Null secondary identifiers in account", accountDef.getSecondaryIdentifiers()); assertFalse("Empty secondary identifiers in account", accountDef.getSecondaryIdentifiers().isEmpty()); assertNotNull("No naming attribute in account", accountDef.getNamingAttribute()); assertFalse("No nativeObjectClass in account", StringUtils.isEmpty(accountDef.getNativeObjectClass())); ResourceAttributeDefinition uidDef = accountDef .findAttributeDefinition(SchemaTestConstants.ICFS_UID); assertEquals(1, uidDef.getMaxOccurs()); assertEquals(0, uidDef.getMinOccurs()); assertFalse("No UID display name", StringUtils.isBlank(uidDef.getDisplayName())); assertFalse("UID has create", uidDef.canAdd()); assertFalse("UID has update",uidDef.canModify()); assertTrue("No UID read",uidDef.canRead()); assertTrue("UID definition not in identifiers", accountDef.getPrimaryIdentifiers().contains(uidDef)); assertEquals("Wrong refined displayName for attribute "+SchemaTestConstants.ICFS_UID, "ConnId UID", uidDef.getDisplayName()); assertEquals("Wrong refined displayOrder for attribute "+SchemaTestConstants.ICFS_UID, (Integer)100, uidDef.getDisplayOrder()); ResourceAttributeDefinition nameDef = accountDef .findAttributeDefinition(SchemaTestConstants.ICFS_NAME); assertEquals(1, nameDef.getMaxOccurs()); assertEquals(1, nameDef.getMinOccurs()); assertFalse("No NAME displayName", StringUtils.isBlank(nameDef.getDisplayName())); assertTrue("No NAME create", nameDef.canAdd()); assertTrue("No NAME update",nameDef.canModify()); assertTrue("No NAME read",nameDef.canRead()); assertTrue("NAME definition not in identifiers", accountDef.getSecondaryIdentifiers().contains(nameDef)); assertEquals("Wrong refined displayName for attribute "+SchemaTestConstants.ICFS_NAME, "ConnId Name", nameDef.getDisplayName()); assertEquals("Wrong refined displayOrder for attribute "+SchemaTestConstants.ICFS_NAME, (Integer)110, nameDef.getDisplayOrder()); assertNull("The _PASSSWORD_ attribute sneaked into schema", accountDef.findAttributeDefinition(new QName(SchemaTestConstants.NS_ICFS,"password"))); } //TODO: add language parameter..for now, use xml serialization public static void displayXml(String message, PrismObject<? extends ObjectType> object) throws SchemaException { String xml = PrismTestUtil.serializeObjectToString(object, PrismContext.LANG_XML); display(message, xml); } public static ObjectDelta<ShadowType> createEntitleDelta(String accountOid, QName associationName, String groupOid, PrismContext prismContext) throws SchemaException { ShadowAssociationType association = new ShadowAssociationType(); association.setName(associationName); ObjectReferenceType shadowRefType = new ObjectReferenceType(); shadowRefType.setOid(groupOid); shadowRefType.setType(ShadowType.COMPLEX_TYPE); association.setShadowRef(shadowRefType); ItemPath entitlementAssociationPath = new ItemPath(ShadowType.F_ASSOCIATION); ObjectDelta<ShadowType> delta = ObjectDelta.createModificationAddContainer(ShadowType.class, accountOid, entitlementAssociationPath, prismContext, association); return delta; } public static ObjectDelta<ShadowType> createDetitleDelta(String accountOid, QName associationName, String groupOid, PrismContext prismContext) throws SchemaException { ShadowAssociationType association = new ShadowAssociationType(); association.setName(associationName); ObjectReferenceType shadowRefType = new ObjectReferenceType(); shadowRefType.setOid(groupOid); shadowRefType.setType(ShadowType.COMPLEX_TYPE); association.setShadowRef(shadowRefType); ItemPath entitlementAssociationPath = new ItemPath(ShadowType.F_ASSOCIATION); ObjectDelta<ShadowType> delta = ObjectDelta.createModificationDeleteContainer(ShadowType.class, accountOid, entitlementAssociationPath, prismContext, association); return delta; } public static void assertGroupMember(DummyGroup group, String accountId) { assertGroupMember(group, accountId, false); } public static void assertGroupMember(DummyGroup group, String accountId, boolean caseIgnore) { Collection<String> members = group.getMembers(); assertNotNull("No members in group "+group.getName()+", expected that "+accountId+" will be there", members); if (caseIgnore) { for (String member: members) { if (StringUtils.equalsIgnoreCase(accountId, member)) { return; } } AssertJUnit.fail("Account "+accountId+" is not member of group "+group.getName()+", members: "+members); } else { assertTrue("Account "+accountId+" is not member of group "+group.getName()+", members: "+members, members.contains(accountId)); } } public static void assertNoGroupMember(DummyGroup group, String accountId) { Collection<String> members = group.getMembers(); if (members == null) { return; } assertFalse("Account "+accountId+" IS member of group "+group.getName()+" while not expecting it, members: "+members, members.contains(accountId)); } public static void assertNoGroupMembers(DummyGroup group) { Collection<String> members = group.getMembers(); assertTrue("Group "+group.getName()+" has members while not expecting it, members: "+members, members == null || members.isEmpty()); } public static ShadowAssociationType assertAssociation(PrismObject<ShadowType> shadow, QName associationName, String entitlementOid) { ShadowType accountType = shadow.asObjectable(); List<ShadowAssociationType> associations = accountType.getAssociation(); assertNotNull("Null associations in "+shadow, associations); assertFalse("Empty associations in "+shadow, associations.isEmpty()); for (ShadowAssociationType association: associations) { if (associationName.equals(association.getName()) && association.getShadowRef() != null && entitlementOid.equals(association.getShadowRef().getOid())) { return association; } } AssertJUnit.fail("No association for entitlement "+entitlementOid+" in "+shadow); throw new IllegalStateException("not reached"); } public static void assertNoAssociation(PrismObject<ShadowType> shadow, QName associationName, String entitlementOid) { ShadowType accountType = shadow.asObjectable(); List<ShadowAssociationType> associations = accountType.getAssociation(); if (associations == null) { return; } for (ShadowAssociationType association: associations) { if (associationName.equals(association.getName()) && entitlementOid.equals(association.getShadowRef().getOid())) { AssertJUnit.fail("Unexpected association for entitlement "+entitlementOid+" in "+shadow); } } } public static void assertNoSchema(ResourceType resourceType) { assertNoSchema("Found schema in resource "+resourceType+" while not expecting it", resourceType); } public static void assertNoSchema(String message, ResourceType resourceType) { Element resourceXsdSchema = ResourceTypeUtil.getResourceXsdSchema(resourceType); AssertJUnit.assertNull(message, resourceXsdSchema); } }
/* * Autopsy Forensic Browser * * Copyright 2019-2020 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> 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.sleuthkit.autopsy.geolocation; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.EnumSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.logging.Level; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; import org.openide.filesystems.FileUtil; import org.openide.util.NbBundle.Messages; import org.openide.windows.RetainLocation; import org.openide.windows.TopComponent; import org.openide.windows.WindowManager; import org.sleuthkit.autopsy.casemodule.Case; import static org.sleuthkit.autopsy.casemodule.Case.Events.CURRENT_CASE; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil; import org.sleuthkit.autopsy.coreutils.ThreadConfined; import org.sleuthkit.autopsy.geolocation.datamodel.GeoLocationDataException; import org.sleuthkit.autopsy.ingest.IngestManager; import static org.sleuthkit.autopsy.ingest.IngestManager.IngestModuleEvent.DATA_ADDED; import org.sleuthkit.autopsy.ingest.ModuleDataEvent; import org.sleuthkit.autopsy.report.ReportProgressPanel; import org.sleuthkit.autopsy.report.modules.kml.KMLReport; import org.sleuthkit.datamodel.BlackboardArtifact; /** * Top component for the Geolocation Tool. * */ @TopComponent.Description(preferredID = "GeolocationTopComponent", persistenceType = TopComponent.PERSISTENCE_NEVER) @TopComponent.Registration(mode = "geolocation", openAtStartup = false) @RetainLocation("geolocation") @SuppressWarnings("PMD.SingularField") public final class GeolocationTopComponent extends TopComponent { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(GeolocationTopComponent.class.getName()); private static final Set<IngestManager.IngestModuleEvent> INGEST_MODULE_EVENTS_OF_INTEREST = EnumSet.of(DATA_ADDED); private final PropertyChangeListener ingestListener; private final PropertyChangeListener caseEventListener; private final GeoFilterPanel geoFilterPanel; final RefreshPanel refreshPanel = new RefreshPanel(); private static final String REPORT_PATH_FMT_STR = "%s" + File.separator + "%s %s %s" + File.separator; // This is the hardcoded report name from KMLReport.java private static final String REPORT_KML = "ReportKML.kml"; private boolean mapInitalized = false; @Messages({ "GLTopComponent_name=Geolocation", "GLTopComponent_initilzation_error=An error occurred during waypoint initilization. Geolocation data maybe incomplete.", "GLTopComponent_No_dataSource_message=There are no data sources with Geolocation artifacts found.", "GLTopComponent_No_dataSource_Title=No Geolocation artifacts found" }) /** * Constructs new GeoLocationTopComponent */ @ThreadConfined(type = ThreadConfined.ThreadType.AWT) @SuppressWarnings("deprecation") public GeolocationTopComponent() { initComponents(); setName(Bundle.GLTopComponent_name()); this.ingestListener = pce -> { String eventType = pce.getPropertyName(); if (eventType.equals(DATA_ADDED.toString())) { // Indicate that a refresh may be needed for GPS data. ModuleDataEvent eventData = (ModuleDataEvent) pce.getOldValue(); if (null != eventData && (eventData.getBlackboardArtifactType().getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_TRACKPOINT.getTypeID() || eventData.getBlackboardArtifactType().getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_SEARCH.getTypeID() || eventData.getBlackboardArtifactType().getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_LAST_KNOWN_LOCATION.getTypeID() || eventData.getBlackboardArtifactType().getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_ROUTE.getTypeID() || eventData.getBlackboardArtifactType().getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_METADATA_EXIF.getTypeID() || eventData.getBlackboardArtifactType().getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_BOOKMARK.getTypeID() || eventData.getBlackboardArtifactType().getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_TRACK.getTypeID() || eventData.getBlackboardArtifactType().getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_AREA.getTypeID())) { showRefreshPanel(true); } } }; this.caseEventListener = pce -> { mapPanel.clearWaypoints(); if (pce.getNewValue() != null) { updateWaypoints(); } }; refreshPanel.addCloseActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showRefreshPanel(false); } }); refreshPanel.addRefreshActionListner(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { geoFilterPanel.updateDataSourceList(); mapPanel.clearWaypoints(); showRefreshPanel(false); } }); geoFilterPanel = new GeoFilterPanel(); filterPane.setPanel(geoFilterPanel); geoFilterPanel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateWaypoints(); } }); geoFilterPanel.addPropertyChangeListener(GeoFilterPanel.INITPROPERTY, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (geoFilterPanel.hasDataSources()) { updateWaypoints(); } else { geoFilterPanel.setEnabled(false); setWaypointLoading(false); JOptionPane.showMessageDialog(GeolocationTopComponent.this, Bundle.GLTopComponent_No_dataSource_message(), Bundle.GLTopComponent_No_dataSource_Title(), JOptionPane.ERROR_MESSAGE); } } }); mapPanel.addPropertyChangeListener(MapPanel.CURRENT_MOUSE_GEOPOSITION, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { String label = ""; Object newValue = evt.getNewValue(); if (newValue != null) { label = newValue.toString(); } coordLabel.setText(label); } }); } @Override public void addNotify() { super.addNotify(); IngestManager.getInstance().addIngestModuleEventListener(INGEST_MODULE_EVENTS_OF_INTEREST, ingestListener); Case.addEventTypeSubscriber(EnumSet.of(CURRENT_CASE), caseEventListener); } @Override public void removeNotify() { super.removeNotify(); IngestManager.getInstance().removeIngestModuleEventListener(ingestListener); Case.removeEventTypeSubscriber(EnumSet.of(CURRENT_CASE), caseEventListener); } @Override public void componentOpened() { super.componentOpened(); WindowManager.getDefault().setTopComponentFloating(this, true); } /** * Sets the filter state that will be set when the panel is opened. If the * panel is already open, this has no effect. * * @param filter The filter to set in the GeoFilterPanel. */ public void setFilterState(GeoFilter filter) throws GeoLocationUIException { if (filter == null) { throw new GeoLocationUIException("Filter provided cannot be null."); } if (this.isOpened()) { geoFilterPanel.setupFilter(filter); updateWaypoints(); } else { geoFilterPanel.setInitialFilterState(filter); } } @Messages({ "GeolocationTC_connection_failure_message=Failed to connect to map title source.\nPlease review map source in Options dialog.", "GeolocationTC_connection_failure_message_title=Connection Failure" }) @Override public void open() { super.open(); // Let's make sure we only do this on the first open if (!mapInitalized) { try { mapPanel.initMap(); mapInitalized = true; } catch (GeoLocationDataException ex) { JOptionPane.showMessageDialog(this, Bundle.GeolocationTC_connection_failure_message(), Bundle.GeolocationTC_connection_failure_message_title(), JOptionPane.ERROR_MESSAGE); MessageNotifyUtil.Notify.error( Bundle.GeolocationTC_connection_failure_message_title(), Bundle.GeolocationTC_connection_failure_message()); logger.log(Level.SEVERE, ex.getMessage(), ex); return; // Doen't set the waypoints. } } mapPanel.clearWaypoints(); geoFilterPanel.clearDataSourceList(); geoFilterPanel.updateDataSourceList(); mapPanel.setWaypoints(new LinkedHashSet<>()); } /** * Set the state of the refresh panel at the top of the mapPanel. * * @param show Whether to show or hide the panel. */ private void showRefreshPanel(boolean show) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { boolean isShowing = false; Component[] comps = mapPanel.getComponents(); for (Component comp : comps) { if (comp.equals(refreshPanel)) { isShowing = true; break; } } if (show && !isShowing) { mapPanel.add(refreshPanel, BorderLayout.NORTH); mapPanel.revalidate(); } else if (!show && isShowing) { mapPanel.remove(refreshPanel); mapPanel.revalidate(); } } }); } /** * Filters the list of waypoints based on the user selections in the filter * pane. */ @Messages({ "GeoTopComponent_no_waypoints_returned_mgs=Applied filter failed to find waypoints that matched criteria.\nRevise filter options and try again.", "GeoTopComponent_no_waypoints_returned_Title=No Waypoints Found", "GeoTopComponent_filter_exception_msg=Exception occurred during waypoint filtering.", "GeoTopComponent_filter_exception_Title=Filter Failure", "GeoTopComponent_filer_data_invalid_msg=Unable to run waypoint filter.\nPlease select one or more data sources.", "GeoTopComponent_filer_data_invalid_Title=Filter Failure" }) private void updateWaypoints() { GeoFilter filters; // Show a warning message if the user has not selected a data source try { filters = geoFilterPanel.getFilterState(); } catch (GeoLocationUIException ex) { JOptionPane.showMessageDialog(this, ex.getMessage(), Bundle.GeoTopComponent_filer_data_invalid_Title(), JOptionPane.INFORMATION_MESSAGE); return; } setWaypointLoading(true); geoFilterPanel.setEnabled(false); Thread thread = new Thread(new Runnable() { @Override public void run() { try { (new WaypointFetcher(filters)).getWaypoints(); } catch (GeoLocationDataException ex) { logger.log(Level.SEVERE, "Failed to filter waypoints.", ex); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(GeolocationTopComponent.this, Bundle.GeoTopComponent_filter_exception_Title(), Bundle.GeoTopComponent_filter_exception_msg(), JOptionPane.ERROR_MESSAGE); setWaypointLoading(false); } }); } } }); thread.start(); } /** * Add the filtered set of waypoints to the map and set the various window * components to their proper state. * * @param waypointList */ void addWaypointsToMap(Set<MapWaypoint> waypointList, List<Set<MapWaypoint>> tracks, List<Set<MapWaypoint>> areas) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // If the list is empty, tell the user if (waypointList == null || waypointList.isEmpty()) { mapPanel.clearWaypoints(); JOptionPane.showMessageDialog(GeolocationTopComponent.this, Bundle.GeoTopComponent_no_waypoints_returned_Title(), Bundle.GeoTopComponent_no_waypoints_returned_mgs(), JOptionPane.INFORMATION_MESSAGE); setWaypointLoading(false); geoFilterPanel.setEnabled(true); return; } mapPanel.clearWaypoints(); mapPanel.setWaypoints(waypointList); mapPanel.setTracks(tracks); mapPanel.setAreas(areas); mapPanel.initializePainter(); setWaypointLoading(false); geoFilterPanel.setEnabled(true); } }); } /** * Show or hide the waypoint loading progress bar. * * @param loading */ void setWaypointLoading(boolean loading) { progressBar.setEnabled(true); progressBar.setVisible(loading); progressBar.setString("Loading Waypoints"); } /** * Create the directory path for the KML report. * * This is a modified version of the similar private function from * KMLReport. * * @return Path for the report * * @throws IOException */ private static String createReportDirectory() throws IOException { Case currentCase = Case.getCurrentCase(); // Create the root reports directory path of the form: <CASE DIRECTORY>/Reports/<Case fileName> <Timestamp>/ DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy-HH-mm-ss", Locale.US); Date date = new Date(); String dateNoTime = dateFormat.format(date); String reportPath = String.format(REPORT_PATH_FMT_STR, currentCase.getReportDirectory(), currentCase.getDisplayName(), "Google Earth KML", dateNoTime); // Create the root reports directory. try { FileUtil.createFolder(new File(reportPath)); } catch (IOException ex) { throw new IOException("Failed to make report folder, unable to generate reports.", ex); } return reportPath; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; filterPane = new org.sleuthkit.autopsy.geolocation.HidingPane(); statusBar = new javax.swing.JPanel(); reportButton = new javax.swing.JButton(); progressBar = new javax.swing.JProgressBar(); coordLabel = new javax.swing.JLabel(); mapPanel = new org.sleuthkit.autopsy.geolocation.MapPanel(); setLayout(new java.awt.BorderLayout()); add(filterPane, java.awt.BorderLayout.WEST); statusBar.setLayout(new java.awt.GridBagLayout()); org.openide.awt.Mnemonics.setLocalizedText(reportButton, org.openide.util.NbBundle.getMessage(GeolocationTopComponent.class, "GeolocationTopComponent.reportButton.text")); // NOI18N reportButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { reportButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); statusBar.add(reportButton, gridBagConstraints); progressBar.setIndeterminate(true); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; statusBar.add(progressBar, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(coordLabel, org.openide.util.NbBundle.getMessage(GeolocationTopComponent.class, "GeolocationTopComponent.coordLabel.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 0); statusBar.add(coordLabel, gridBagConstraints); add(statusBar, java.awt.BorderLayout.SOUTH); add(mapPanel, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents @Messages({ "GeolocationTC_empty_waypoint_message=Unable to generate KML report due to a lack of waypoints.\nPlease make sure there are waypoints visible before generating the KML report", "GeolocationTC_KML_report_title=KML Report", "GeolocationTC_report_progress_title=KML Report Progress" }) private void reportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_reportButtonActionPerformed List<MapWaypoint> visiblePoints = mapPanel.getVisibleWaypoints(); if (visiblePoints.isEmpty()) { JOptionPane.showConfirmDialog(this, Bundle.GeolocationTC_empty_waypoint_message(), Bundle.GeolocationTC_KML_report_title(), JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE); return; } try { ReportProgressPanel progressPanel = new ReportProgressPanel(); String reportBaseDir = createReportDirectory(); progressPanel.setLabels(REPORT_KML, reportBaseDir); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { KMLReport.getDefault().generateReport(reportBaseDir, progressPanel, MapWaypoint.getDataModelWaypoints(visiblePoints)); return null; } }; worker.execute(); JOptionPane.showConfirmDialog(this, progressPanel, Bundle.GeolocationTC_report_progress_title(), JOptionPane.CLOSED_OPTION, JOptionPane.PLAIN_MESSAGE); } catch (IOException ex) { logger.log(Level.WARNING, "Unable to create KML report", ex); } }//GEN-LAST:event_reportButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel coordLabel; private org.sleuthkit.autopsy.geolocation.HidingPane filterPane; private org.sleuthkit.autopsy.geolocation.MapPanel mapPanel; private javax.swing.JProgressBar progressBar; private javax.swing.JButton reportButton; private javax.swing.JPanel statusBar; // End of variables declaration//GEN-END:variables /** * Extends AbstractWaypointFetcher to handle the returning of the filters * set of MapWaypoints. */ @Messages({ "GeolocationTopComponent.WaypointFetcher.onErrorTitle=Error gathering GPS Track Data", "GeolocationTopComponent.WaypointFetcher.onErrorDescription=There was an error gathering some GPS Track Data. Some results have been excluded." }) final private class WaypointFetcher extends AbstractWaypointFetcher { WaypointFetcher(GeoFilter filters) { super(filters); } @Override protected void handleFilteredWaypointSet(Set<MapWaypoint> mapWaypoints, List<Set<MapWaypoint>> tracks, List<Set<MapWaypoint>> areas, boolean wasEntirelySuccessful) { addWaypointsToMap(mapWaypoints, tracks, areas); // if there is an error, present to the user. if (!wasEntirelySuccessful) { JOptionPane.showMessageDialog(GeolocationTopComponent.this, Bundle.GeolocationTopComponent_WaypointFetcher_onErrorDescription(), Bundle.GeolocationTopComponent_WaypointFetcher_onErrorTitle(), JOptionPane.ERROR_MESSAGE); } } } }
package com.microsoft.bingads.v12.bulk.entities; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer; import com.microsoft.bingads.internal.functionalinterfaces.Function; import com.microsoft.bingads.v12.bulk.BulkFileReader; import com.microsoft.bingads.v12.bulk.BulkFileWriter; import com.microsoft.bingads.v12.bulk.BulkOperation; import com.microsoft.bingads.v12.bulk.BulkServiceManager; import com.microsoft.bingads.v12.campaignmanagement.BidMultiplier; import com.microsoft.bingads.v12.campaignmanagement.BiddableCampaignCriterion; import com.microsoft.bingads.v12.campaignmanagement.CampaignCriterionStatus; import com.microsoft.bingads.v12.campaignmanagement.CriterionBid; import com.microsoft.bingads.v12.campaignmanagement.DistanceUnit; import com.microsoft.bingads.v12.campaignmanagement.RadiusCriterion; import com.microsoft.bingads.v12.internal.bulk.BulkMapping; import com.microsoft.bingads.v12.internal.bulk.MappingHelpers; import com.microsoft.bingads.v12.internal.bulk.RowValues; import com.microsoft.bingads.v12.internal.bulk.SimpleBulkMapping; import com.microsoft.bingads.v12.internal.bulk.StringExtensions; import com.microsoft.bingads.v12.internal.bulk.StringTable; import com.microsoft.bingads.v12.internal.bulk.entities.SingleRecordBulkEntity; /** * Represents a radius criterion that is assigned to a campaign. Each radius criterion can be read or written in a bulk file. * * <p> * For more information, see Campaign Radius Criterion at * <a href="https://go.microsoft.com/fwlink/?linkid=846127>https://go.microsoft.com/fwlink/?linkid=846127</a>. * </p> * * @see BulkServiceManager * @see BulkOperation * @see BulkFileReader * @see BulkFileWriter */ public class BulkCampaignRadiusCriterion extends SingleRecordBulkEntity { private BiddableCampaignCriterion biddableCampaignCriterion; private String campaignName; private static final List<BulkMapping<BulkCampaignRadiusCriterion>> MAPPINGS; static { List<BulkMapping<BulkCampaignRadiusCriterion>> m = new ArrayList<BulkMapping<BulkCampaignRadiusCriterion>>(); m.add(new SimpleBulkMapping<BulkCampaignRadiusCriterion, String>(StringTable.Status, new Function<BulkCampaignRadiusCriterion, String>() { @Override public String apply(BulkCampaignRadiusCriterion c) { CampaignCriterionStatus status = c.getBiddableCampaignCriterion().getStatus(); return status == null ? null : status.value(); } }, new BiConsumer<String, BulkCampaignRadiusCriterion>() { @Override public void accept(String v, BulkCampaignRadiusCriterion c) { c.getBiddableCampaignCriterion().setStatus(StringExtensions.parseOptional(v, new Function<String, CampaignCriterionStatus>() { @Override public CampaignCriterionStatus apply(String s) { return CampaignCriterionStatus.fromValue(s); } })); } } )); m.add(new SimpleBulkMapping<BulkCampaignRadiusCriterion, Long>(StringTable.Id, new Function<BulkCampaignRadiusCriterion, Long>() { @Override public Long apply(BulkCampaignRadiusCriterion c) { return c.getBiddableCampaignCriterion().getId(); } }, new BiConsumer<String, BulkCampaignRadiusCriterion>() { @Override public void accept(String v, BulkCampaignRadiusCriterion c) { c.getBiddableCampaignCriterion().setId(StringExtensions.parseOptional(v, new Function<String, Long>() { @Override public Long apply(String s) { return Long.parseLong(s); } })); } } )); m.add(new SimpleBulkMapping<BulkCampaignRadiusCriterion, Long>(StringTable.ParentId, new Function<BulkCampaignRadiusCriterion, Long>() { @Override public Long apply(BulkCampaignRadiusCriterion c) { return c.getBiddableCampaignCriterion().getCampaignId(); } }, new BiConsumer<String, BulkCampaignRadiusCriterion>() { @Override public void accept(String v, BulkCampaignRadiusCriterion c) { c.getBiddableCampaignCriterion().setCampaignId(StringExtensions.nullOrLong(v)); } } )); m.add(new SimpleBulkMapping<BulkCampaignRadiusCriterion, String>(StringTable.Campaign, new Function<BulkCampaignRadiusCriterion, String>() { @Override public String apply(BulkCampaignRadiusCriterion c) { return c.getCampaignName(); } }, new BiConsumer<String, BulkCampaignRadiusCriterion>() { @Override public void accept(String v, BulkCampaignRadiusCriterion c) { c.setCampaignName(v); } } )); m.add(new SimpleBulkMapping<BulkCampaignRadiusCriterion, String>(StringTable.BidAdjustment, new Function<BulkCampaignRadiusCriterion, String>() { @Override public String apply(BulkCampaignRadiusCriterion c) { if (c.getBiddableCampaignCriterion() instanceof BiddableCampaignCriterion) { CriterionBid bid = ((BiddableCampaignCriterion) c.getBiddableCampaignCriterion()).getCriterionBid(); if (bid == null) { return null; } else { return StringExtensions.toCriterionBidMultiplierBulkString(((BidMultiplier) bid).getMultiplier()); } } else { return null; } } }, new BiConsumer<String, BulkCampaignRadiusCriterion>() { @Override public void accept(String v, BulkCampaignRadiusCriterion c) { if (c.getBiddableCampaignCriterion() instanceof BiddableCampaignCriterion) { ((BidMultiplier) ((BiddableCampaignCriterion) c.getBiddableCampaignCriterion()).getCriterionBid()).setMultiplier( StringExtensions.nullOrDouble(v) ); } } } )); m.add(new SimpleBulkMapping<BulkCampaignRadiusCriterion, String>(StringTable.Name, new Function<BulkCampaignRadiusCriterion, String>() { @Override public String apply(BulkCampaignRadiusCriterion c) { if (c.getBiddableCampaignCriterion().getCriterion() instanceof RadiusCriterion) { return ((RadiusCriterion) c.getBiddableCampaignCriterion().getCriterion()).getName(); } return null; } }, new BiConsumer<String, BulkCampaignRadiusCriterion>() { @Override public void accept(String v, BulkCampaignRadiusCriterion c) { if (c.getBiddableCampaignCriterion().getCriterion() instanceof RadiusCriterion) { ((RadiusCriterion)c.getBiddableCampaignCriterion().getCriterion()).setName(v); } } } )); m.add(new SimpleBulkMapping<BulkCampaignRadiusCriterion, String>(StringTable.Latitude, new Function<BulkCampaignRadiusCriterion, String>() { @Override public String apply(BulkCampaignRadiusCriterion c) { if (c.getBiddableCampaignCriterion().getCriterion() instanceof RadiusCriterion) { Double latitude = ((RadiusCriterion) c.getBiddableCampaignCriterion().getCriterion()).getLatitudeDegrees(); return latitude == null ? null: latitude.toString(); } return null; } }, new BiConsumer<String, BulkCampaignRadiusCriterion>() { @Override public void accept(String v, BulkCampaignRadiusCriterion c) { if (c.getBiddableCampaignCriterion().getCriterion() instanceof RadiusCriterion) { ((RadiusCriterion)c.getBiddableCampaignCriterion().getCriterion()).setLatitudeDegrees(StringExtensions.nullOrDouble(v)); } } } )); m.add(new SimpleBulkMapping<BulkCampaignRadiusCriterion, String>(StringTable.Longitude, new Function<BulkCampaignRadiusCriterion, String>() { @Override public String apply(BulkCampaignRadiusCriterion c) { if (c.getBiddableCampaignCriterion().getCriterion() instanceof RadiusCriterion) { Double longitude = ((RadiusCriterion) c.getBiddableCampaignCriterion().getCriterion()).getLongitudeDegrees(); return longitude == null ? null: longitude.toString(); } return null; } }, new BiConsumer<String, BulkCampaignRadiusCriterion>() { @Override public void accept(String v, BulkCampaignRadiusCriterion c) { if (c.getBiddableCampaignCriterion().getCriterion() instanceof RadiusCriterion) { ((RadiusCriterion)c.getBiddableCampaignCriterion().getCriterion()).setLongitudeDegrees(StringExtensions.nullOrDouble(v)); } } } )); m.add(new SimpleBulkMapping<BulkCampaignRadiusCriterion, String>(StringTable.Radius, new Function<BulkCampaignRadiusCriterion, String>() { @Override public String apply(BulkCampaignRadiusCriterion c) { if (c.getBiddableCampaignCriterion().getCriterion() instanceof RadiusCriterion) { Long radius = ((RadiusCriterion) c.getBiddableCampaignCriterion().getCriterion()).getRadius(); return radius == null ? null: radius.toString(); } return null; } }, new BiConsumer<String, BulkCampaignRadiusCriterion>() { @Override public void accept(String v, BulkCampaignRadiusCriterion c) { if (c.getBiddableCampaignCriterion().getCriterion() instanceof RadiusCriterion) { ((RadiusCriterion)c.getBiddableCampaignCriterion().getCriterion()).setRadius(StringExtensions.nullOrLong(v)); } } } )); m.add(new SimpleBulkMapping<BulkCampaignRadiusCriterion, String>(StringTable.Unit, new Function<BulkCampaignRadiusCriterion, String>() { @Override public String apply(BulkCampaignRadiusCriterion c) { if (c.getBiddableCampaignCriterion().getCriterion() instanceof RadiusCriterion) { DistanceUnit radiusUnit = ((RadiusCriterion) c.getBiddableCampaignCriterion().getCriterion()).getRadiusUnit(); return radiusUnit == null ? null: radiusUnit.value(); } return null; } }, new BiConsumer<String, BulkCampaignRadiusCriterion>() { @Override public void accept(String v, BulkCampaignRadiusCriterion c) { if (c.getBiddableCampaignCriterion().getCriterion() instanceof RadiusCriterion) { ((RadiusCriterion)c.getBiddableCampaignCriterion().getCriterion()).setRadiusUnit(StringExtensions.parseOptional(v, new Function<String, DistanceUnit>() { @Override public DistanceUnit apply(String s) { return DistanceUnit.fromValue(s); } })); } } } )); MAPPINGS = Collections.unmodifiableList(m); } @Override public void processMappingsFromRowValues(RowValues values) { BiddableCampaignCriterion campaignCriterion = new BiddableCampaignCriterion(); BidMultiplier bidMultiplier = new BidMultiplier(); bidMultiplier.setType(BidMultiplier.class.getSimpleName()); RadiusCriterion radiusCriterion = new RadiusCriterion(); campaignCriterion.setCriterion(radiusCriterion); campaignCriterion.getCriterion().setType(RadiusCriterion.class.getSimpleName()); campaignCriterion.setCriterionBid(bidMultiplier); campaignCriterion.setType("BiddableCampaignCriterion"); setBiddableCampaignCriterion(campaignCriterion); MappingHelpers.convertToEntity(values, MAPPINGS, this); } @Override public void processMappingsToRowValues(RowValues values, boolean excludeReadonlyData) { validatePropertyNotNull(getBiddableCampaignCriterion(), BiddableCampaignCriterion.class.getSimpleName()); MappingHelpers.convertToValues(this, values, MAPPINGS); } /** * Gets an Campaign Criterion. */ public BiddableCampaignCriterion getBiddableCampaignCriterion() { return biddableCampaignCriterion; } /** * Sets an Campaign Criterion */ public void setBiddableCampaignCriterion(BiddableCampaignCriterion biddableCampaignCriterion) { this.biddableCampaignCriterion = biddableCampaignCriterion; } /** * Gets the name of the campaign. * Corresponds to the 'Campaign' field in the bulk file. */ public String getCampaignName() { return campaignName; } /** * Sets the name of the campaign. * Corresponds to the 'Campaign' field in the bulk file. */ public void setCampaignName(String campaignName) { this.campaignName = campaignName; } }
/** * 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.hadoop.hdfs.web; import static org.apache.hadoop.fs.permission.AclEntryScope.*; import static org.apache.hadoop.fs.permission.AclEntryType.*; import static org.apache.hadoop.fs.permission.FsAction.*; import static org.apache.hadoop.hdfs.server.namenode.AclTestHelpers.*; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.XAttr; import org.apache.hadoop.fs.XAttrCodec; import org.apache.hadoop.fs.permission.AclEntry; import org.apache.hadoop.fs.permission.AclStatus; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.DFSUtil; import org.apache.hadoop.hdfs.XAttrHelper; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.HdfsFileStatus; import org.apache.hadoop.hdfs.server.namenode.INodeId; import org.apache.hadoop.util.Time; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectReader; import org.junit.Assert; import org.junit.Test; import com.google.common.collect.Lists; public class TestJsonUtil { static FileStatus toFileStatus(HdfsFileStatus f, String parent) { return new FileStatus(f.getLen(), f.isDir(), f.getReplication(), f.getBlockSize(), f.getModificationTime(), f.getAccessTime(), f.getPermission(), f.getOwner(), f.getGroup(), f.isSymlink() ? new Path(f.getSymlink()) : null, new Path(f.getFullName(parent))); } @Test public void testHdfsFileStatus() throws IOException { final long now = Time.now(); final String parent = "/dir"; final HdfsFileStatus status = new HdfsFileStatus(1001L, false, 3, 1L << 26, now, now + 10, new FsPermission((short) 0644), "user", "group", DFSUtil.string2Bytes("bar"), DFSUtil.string2Bytes("foo"), INodeId.GRANDFATHER_INODE_ID, 0, null, (byte) 0); final FileStatus fstatus = toFileStatus(status, parent); System.out.println("status = " + status); System.out.println("fstatus = " + fstatus); final String json = JsonUtil.toJsonString(status, true); System.out.println("json = " + json.replace(",", ",\n ")); ObjectReader reader = new ObjectMapper().reader(Map.class); final HdfsFileStatus s2 = JsonUtil.toFileStatus((Map<?, ?>) reader.readValue(json), true); final FileStatus fs2 = toFileStatus(s2, parent); System.out.println("s2 = " + s2); System.out.println("fs2 = " + fs2); Assert.assertEquals(fstatus, fs2); } @Test public void testToDatanodeInfoWithoutSecurePort() throws Exception { Map<String, Object> response = new HashMap<String, Object>(); response.put("ipAddr", "127.0.0.1"); response.put("hostName", "localhost"); response.put("storageID", "fake-id"); response.put("xferPort", 1337l); response.put("infoPort", 1338l); // deliberately don't include an entry for "infoSecurePort" response.put("ipcPort", 1339l); response.put("capacity", 1024l); response.put("dfsUsed", 512l); response.put("remaining", 512l); response.put("blockPoolUsed", 512l); response.put("lastUpdate", 0l); response.put("xceiverCount", 4096l); response.put("networkLocation", "foo.bar.baz"); response.put("adminState", "NORMAL"); response.put("cacheCapacity", 123l); response.put("cacheUsed", 321l); JsonUtil.toDatanodeInfo(response); } @Test public void testToDatanodeInfoWithName() throws Exception { Map<String, Object> response = new HashMap<String, Object>(); // Older servers (1.x, 0.23, etc.) sends 'name' instead of ipAddr // and xferPort. String name = "127.0.0.1:1004"; response.put("name", name); response.put("hostName", "localhost"); response.put("storageID", "fake-id"); response.put("infoPort", 1338l); response.put("ipcPort", 1339l); response.put("capacity", 1024l); response.put("dfsUsed", 512l); response.put("remaining", 512l); response.put("blockPoolUsed", 512l); response.put("lastUpdate", 0l); response.put("xceiverCount", 4096l); response.put("networkLocation", "foo.bar.baz"); response.put("adminState", "NORMAL"); response.put("cacheCapacity", 123l); response.put("cacheUsed", 321l); DatanodeInfo di = JsonUtil.toDatanodeInfo(response); Assert.assertEquals(name, di.getXferAddr()); // The encoded result should contain name, ipAddr and xferPort. Map<String, Object> r = JsonUtil.toJsonMap(di); Assert.assertEquals(name, r.get("name")); Assert.assertEquals("127.0.0.1", r.get("ipAddr")); // In this test, it is Integer instead of Long since json was not actually // involved in constructing the map. Assert.assertEquals(1004, (int)(Integer)r.get("xferPort")); // Invalid names String[] badNames = {"127.0.0.1", "127.0.0.1:", ":", "127.0.0.1:sweet", ":123"}; for (String badName : badNames) { response.put("name", badName); checkDecodeFailure(response); } // Missing both name and ipAddr response.remove("name"); checkDecodeFailure(response); // Only missing xferPort response.put("ipAddr", "127.0.0.1"); checkDecodeFailure(response); } @Test public void testToAclStatus() throws IOException { String jsonString = "{\"AclStatus\":{\"entries\":[\"user::rwx\",\"user:user1:rw-\",\"group::rw-\",\"other::r-x\"],\"group\":\"supergroup\",\"owner\":\"testuser\",\"stickyBit\":false}}"; ObjectReader reader = new ObjectMapper().reader(Map.class); Map<?, ?> json = reader.readValue(jsonString); List<AclEntry> aclSpec = Lists.newArrayList(aclEntry(ACCESS, USER, ALL), aclEntry(ACCESS, USER, "user1", READ_WRITE), aclEntry(ACCESS, GROUP, READ_WRITE), aclEntry(ACCESS, OTHER, READ_EXECUTE)); AclStatus.Builder aclStatusBuilder = new AclStatus.Builder(); aclStatusBuilder.owner("testuser"); aclStatusBuilder.group("supergroup"); aclStatusBuilder.addEntries(aclSpec); aclStatusBuilder.stickyBit(false); Assert.assertEquals("Should be equal", aclStatusBuilder.build(), JsonUtil.toAclStatus(json)); } @Test public void testToJsonFromAclStatus() { String jsonString = "{\"AclStatus\":{\"entries\":[\"user:user1:rwx\",\"group::rw-\"],\"group\":\"supergroup\",\"owner\":\"testuser\",\"stickyBit\":false}}"; AclStatus.Builder aclStatusBuilder = new AclStatus.Builder(); aclStatusBuilder.owner("testuser"); aclStatusBuilder.group("supergroup"); aclStatusBuilder.stickyBit(false); List<AclEntry> aclSpec = Lists.newArrayList(aclEntry(ACCESS, USER,"user1", ALL), aclEntry(ACCESS, GROUP, READ_WRITE)); aclStatusBuilder.addEntries(aclSpec); Assert.assertEquals(jsonString, JsonUtil.toJsonString(aclStatusBuilder.build())); } @Test public void testToJsonFromXAttrs() throws IOException { String jsonString = "{\"XAttrs\":[{\"name\":\"user.a1\",\"value\":\"0x313233\"}," + "{\"name\":\"user.a2\",\"value\":\"0x313131\"}]}"; XAttr xAttr1 = (new XAttr.Builder()).setNameSpace(XAttr.NameSpace.USER). setName("a1").setValue(XAttrCodec.decodeValue("0x313233")).build(); XAttr xAttr2 = (new XAttr.Builder()).setNameSpace(XAttr.NameSpace.USER). setName("a2").setValue(XAttrCodec.decodeValue("0x313131")).build(); List<XAttr> xAttrs = Lists.newArrayList(); xAttrs.add(xAttr1); xAttrs.add(xAttr2); Assert.assertEquals(jsonString, JsonUtil.toJsonString(xAttrs, XAttrCodec.HEX)); } @Test public void testToXAttrMap() throws IOException { String jsonString = "{\"XAttrs\":[{\"name\":\"user.a1\",\"value\":\"0x313233\"}," + "{\"name\":\"user.a2\",\"value\":\"0x313131\"}]}"; ObjectReader reader = new ObjectMapper().reader(Map.class); Map<?, ?> json = reader.readValue(jsonString); XAttr xAttr1 = (new XAttr.Builder()).setNameSpace(XAttr.NameSpace.USER). setName("a1").setValue(XAttrCodec.decodeValue("0x313233")).build(); XAttr xAttr2 = (new XAttr.Builder()).setNameSpace(XAttr.NameSpace.USER). setName("a2").setValue(XAttrCodec.decodeValue("0x313131")).build(); List<XAttr> xAttrs = Lists.newArrayList(); xAttrs.add(xAttr1); xAttrs.add(xAttr2); Map<String, byte[]> xAttrMap = XAttrHelper.buildXAttrMap(xAttrs); Map<String, byte[]> parsedXAttrMap = JsonUtil.toXAttrs(json); Assert.assertEquals(xAttrMap.size(), parsedXAttrMap.size()); Iterator<Entry<String, byte[]>> iter = xAttrMap.entrySet().iterator(); while(iter.hasNext()) { Entry<String, byte[]> entry = iter.next(); Assert.assertArrayEquals(entry.getValue(), parsedXAttrMap.get(entry.getKey())); } } @Test public void testGetXAttrFromJson() throws IOException { String jsonString = "{\"XAttrs\":[{\"name\":\"user.a1\",\"value\":\"0x313233\"}," + "{\"name\":\"user.a2\",\"value\":\"0x313131\"}]}"; ObjectReader reader = new ObjectMapper().reader(Map.class); Map<?, ?> json = reader.readValue(jsonString); // Get xattr: user.a2 byte[] value = JsonUtil.getXAttr(json, "user.a2"); Assert.assertArrayEquals(XAttrCodec.decodeValue("0x313131"), value); } private void checkDecodeFailure(Map<String, Object> map) { try { JsonUtil.toDatanodeInfo(map); Assert.fail("Exception not thrown against bad input."); } catch (Exception e) { // expected } } }
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.lang; import com.intellij.openapi.util.io.DataInputOutputUtilRt; import com.intellij.openapi.util.text.StringHash; import com.intellij.util.ArrayUtilRt; import com.intellij.util.BloomFilterBase; import gnu.trove.TIntHashSet; import gnu.trove.TLongHashSet; import gnu.trove.TLongProcedure; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public final class ClasspathCache { static final int NUMBER_OF_ACCESSES_FOR_LAZY_CACHING = 1000; private final IntObjectHashMap myResourcePackagesCache = new IntObjectHashMap(); private final IntObjectHashMap myClassPackagesCache = new IntObjectHashMap(); private static final double PROBABILITY = 0.005d; static class LoaderData { private final int[] myResourcePackageHashes; private final int[] myClassPackageHashes; private final NameFilter myNameFilter; @Deprecated LoaderData() { this(new int[0], new int[0], new NameFilter(10000, PROBABILITY)); } LoaderData(@NotNull int[] resourcePackageHashes, @NotNull int[] classPackageHashes, @NotNull NameFilter nameFilter) { myResourcePackageHashes = resourcePackageHashes; myClassPackageHashes = classPackageHashes; myNameFilter = nameFilter; } LoaderData(@NotNull DataInput dataInput) throws IOException { this(readIntList(dataInput), readIntList(dataInput), new ClasspathCache.NameFilter(dataInput)); } @NotNull private static int[] readIntList(@NotNull DataInput reader) throws IOException { int numberOfElements = DataInputOutputUtilRt.readINT(reader); int[] ints = new int[numberOfElements]; for (int i = 0; i < numberOfElements; ++i) { ints[i] = DataInputOutputUtilRt.readINT(reader); } return ints; } void save(@NotNull DataOutput dataOutput) throws IOException { writeIntArray(dataOutput, myResourcePackageHashes); writeIntArray(dataOutput, myClassPackageHashes); myNameFilter.save(dataOutput); } private static void writeIntArray(@NotNull DataOutput writer, @NotNull int[] hashes) throws IOException { DataInputOutputUtilRt.writeINT(writer, hashes.length); for(int hash: hashes) DataInputOutputUtilRt.writeINT(writer, hash); } @NotNull NameFilter getNameFilter() { return myNameFilter; } } static class LoaderDataBuilder { private final TLongHashSet myUsedNameFingerprints = new TLongHashSet(); private final TIntHashSet myResourcePackageHashes = new TIntHashSet(); private final TIntHashSet myClassPackageHashes = new TIntHashSet(); LoaderDataBuilder() {} void addPossiblyDuplicateNameEntry(@NotNull String name) { name = transformName(name); myUsedNameFingerprints.add(NameFilter.toNameFingerprint(name)); } void addResourcePackageFromName(@NotNull String path) { myResourcePackageHashes.add(getPackageNameHash(path)); } void addClassPackageFromName(@NotNull String path) { myClassPackageHashes.add(getPackageNameHash(path)); } @NotNull LoaderData build() { int uniques = myUsedNameFingerprints.size(); if (uniques > 20000) { uniques += (int)(uniques * 0.03d); // allow some growth for Idea main loader } final NameFilter nameFilter = new NameFilter(uniques, PROBABILITY); myUsedNameFingerprints.forEach(new TLongProcedure() { @Override public boolean execute(long value) { nameFilter.addNameFingerprint(value); return true; } }); return new ClasspathCache.LoaderData(myResourcePackageHashes.toArray(), myClassPackageHashes.toArray(), nameFilter); } } private final ReadWriteLock myLock = new ReentrantReadWriteLock(); void applyLoaderData(@NotNull LoaderData loaderData, @NotNull Loader loader) { myLock.writeLock().lock(); try { for(int resourcePackageHash:loaderData.myResourcePackageHashes) { addResourceEntry(resourcePackageHash, myResourcePackagesCache, loader); } for(int classPackageHash:loaderData.myClassPackageHashes) { addResourceEntry(classPackageHash, myClassPackagesCache, loader); } loader.applyData(loaderData); } finally { myLock.writeLock().unlock(); } } abstract static class LoaderIterator <R, T1, T2> { @Nullable abstract R process(@NotNull Loader loader, @NotNull T1 parameter, @NotNull T2 parameter2, @NotNull String shortName); } @Nullable <R, T1, T2> R iterateLoaders(@NotNull String resourcePath, @NotNull LoaderIterator<R, T1, T2> iterator, @NotNull T1 parameter, @NotNull T2 parameter2, @NotNull String shortName) { myLock.readLock().lock(); Object o; try { IntObjectHashMap map = resourcePath.endsWith(UrlClassLoader.CLASS_EXTENSION) ? myClassPackagesCache : myResourcePackagesCache; o = map.get(getPackageNameHash(resourcePath)); } finally { myLock.readLock().unlock(); } if (o == null) return null; if (o instanceof Loader) return iterator.process((Loader)o, parameter, parameter2, shortName); Loader[] loaders = (Loader[])o; for (Loader l : loaders) { R result = iterator.process(l, parameter, parameter2, shortName); if (result != null) return result; } return null; } static int getPackageNameHash(@NotNull String resourcePath) { final int idx = resourcePath.lastIndexOf('/'); int h = 0; for (int off = 0; off < idx; off++) { h = 31 * h + resourcePath.charAt(off); } return h; } private static void addResourceEntry(int hash, @NotNull IntObjectHashMap map, @NotNull Loader loader) { Object o = map.get(hash); if (o == null) { map.put(hash, loader); } else if (o instanceof Loader) { if (ClassPath.ourClassLoadingInfo) assert loader != o; map.put(hash, new Loader[]{(Loader)o, loader}); } else { Loader[] loadersArray = (Loader[])o; if (ClassPath.ourClassLoadingInfo) assert ArrayUtilRt.find(loadersArray, loader) == -1; Loader[] newArray = new Loader[loadersArray.length + 1]; System.arraycopy(loadersArray, 0, newArray, 0, loadersArray.length); newArray[loadersArray.length] = loader; map.put(hash, newArray); } } @NotNull static String transformName(@NotNull String name) { int nameEnd = !name.isEmpty() && name.charAt(name.length() - 1) == '/' ? name.length() - 1 : name.length(); name = name.substring(name.lastIndexOf('/', nameEnd-1) + 1, nameEnd); if (name.endsWith(UrlClassLoader.CLASS_EXTENSION)) { String name1 = name; int $ = name1.indexOf('$'); if ($ != -1) { name1 = name1.substring(0, $); } else { int index = name1.lastIndexOf('.'); if (index >= 0) name1 = name1.substring(0, index); } name = name1; } return name; } static class NameFilter extends BloomFilterBase { private static final int SEED = 31; NameFilter(int _maxElementCount, double probability) { super(_maxElementCount, probability); } NameFilter(@NotNull DataInput input) throws IOException { super(input); } private void addNameFingerprint(long nameFingerprint) { int hash = (int)(nameFingerprint >> 32); int hash2 = (int)nameFingerprint; addIt(hash, hash2); } boolean maybeContains(@NotNull String name) { int hash = name.hashCode(); int hash2 = StringHash.murmur(name, SEED); return maybeContains(hash, hash2); } @Override protected void save(@NotNull DataOutput output) throws IOException { super.save(output); } private static long toNameFingerprint(@NotNull String name) { int hash = name.hashCode(); int hash2 = StringHash.murmur(name, SEED); return ((long)hash << 32) | (hash2 & 0xFFFFFFFFL); } } }
package org.afplib.samples; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.afplib.ResourceKey; import org.afplib.afplib.AfplibFactory; import org.afplib.afplib.BDG; import org.afplib.afplib.BFM; import org.afplib.afplib.BMM; import org.afplib.afplib.BRG; import org.afplib.afplib.BRS; import org.afplib.afplib.EDG; import org.afplib.afplib.EFM; import org.afplib.afplib.EMM; import org.afplib.afplib.ERG; import org.afplib.afplib.ERS; import org.afplib.afplib.FGD; import org.afplib.afplib.FullyQualifiedName; import org.afplib.afplib.FullyQualifiedNameFQNType; import org.afplib.afplib.IMM; import org.afplib.afplib.IOB; import org.afplib.afplib.IPG; import org.afplib.afplib.IPO; import org.afplib.afplib.IPS; import org.afplib.afplib.MCC; import org.afplib.afplib.MCF; import org.afplib.afplib.MCF1; import org.afplib.afplib.MCF1RG; import org.afplib.afplib.MCFRG; import org.afplib.afplib.MDD; import org.afplib.afplib.MDR; import org.afplib.afplib.MDRRG; import org.afplib.afplib.MFC; import org.afplib.afplib.MMC; import org.afplib.afplib.MMD; import org.afplib.afplib.MMO; import org.afplib.afplib.MMORG; import org.afplib.afplib.MMT; import org.afplib.afplib.MPG; import org.afplib.afplib.MPO; import org.afplib.afplib.MPORG; import org.afplib.afplib.MPS; import org.afplib.afplib.MPSRG; import org.afplib.afplib.ObjectClassification; import org.afplib.afplib.PEC; import org.afplib.afplib.PGP; import org.afplib.afplib.PGP1; import org.afplib.afplib.PMC; import org.afplib.afplib.ResourceObjectType; import org.afplib.afplib.ResourceObjectTypeObjType; import org.afplib.afplib.SFName; import org.afplib.base.SF; import org.afplib.base.Triplet; import org.afplib.io.AfpFilter; import org.afplib.io.AfpInputStream; import org.afplib.io.AfpOutputStream; import org.afplib.io.Filter; import org.afplib.io.Filter.STATE; import org.apache.commons.lang3.StringUtils; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AfpCombine { private static final Logger log = LoggerFactory.getLogger(AfpCombine.class); class Resource { long start, end, ersPos; byte[] content; String hash; } class MediumMap { long start, end; byte[] content; LinkedList<SF> sfs = new LinkedList<SF>(); String hash; } class InputFile { File file; List<ResourceKey> resources = new LinkedList<ResourceKey>(); Map<ResourceKey, Resource> filePos = new HashMap<ResourceKey, Resource>(); Map<ResourceKey, String> renamings = new HashMap<ResourceKey, String>(); Map<String, String> renameIMM = new HashMap<String, String>(); long documentStart; LinkedList<SF> formdef = new LinkedList<SF>(); LinkedList<String> mmNames = new LinkedList<String>(); Map<String, MediumMap> mediumMaps = new HashMap<String, MediumMap>(); } public static void main(String[] args) { log.info("starting..."); LinkedList<String> f = new LinkedList<String>(); String out = null; for(int i=0; i<args.length; i++) { if(args[i].equals("-o") && i+1<args.length) out = args[++i]; else f.add(args[i]); } log.debug("in: {}", StringUtils.join(f, ':')); log.debug("out: {}", out); try { new AfpCombine(out, (String[]) f.toArray(new String[f.size()])).run(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } log.info("done."); } private String outFile; private String[] inFiles; private InputFile[] files; private MessageDigest algorithm; private LinkedList<String> resourceNames = new LinkedList<String>(); private LinkedList<String> mmNames = new LinkedList<String>(); private SF[] formdef; private boolean checkResourceEquality = true; public AfpCombine(String outFile, String[] inFiles) { this.outFile = outFile; this.inFiles = inFiles; files = new InputFile[inFiles.length]; try { algorithm = MessageDigest.getInstance(System.getProperty("security.digest", "MD5")); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public void run() throws IOException { scanResources(); buildRenamingTable(); buildFormdef(); writeResourceGroup(); writeDocuments(); } private void scanResources() throws IOException, FileNotFoundException { for(int i=0; i<inFiles.length; i++) { files[i] = new InputFile(); files[i].file = new File(inFiles[i]); try(FileInputStream fin = new FileInputStream(files[i].file); AfpInputStream ain = new AfpInputStream(new BufferedInputStream(fin))) { SF sf; long filepos = 0, prevFilePos = 0; ByteArrayOutputStream buffer = null; ResourceKey key = null; Resource resource = null; String mmName = null; MediumMap mediumMap = null; boolean processingFormdef = false, isFirstFormdef = true; while((sf = ain.readStructuredField()) != null) { filepos = ain.getCurrentOffset(); if(sf instanceof ERG) { files[i].documentStart = filepos; break; } if(sf instanceof BRS) { key = ResourceKey.toResourceKey((BRS) sf); if(key.getType() == ResourceObjectTypeObjType.CONST_FORM_MAP_VALUE) { key = null; // do not save formdef resources } else { buffer = new ByteArrayOutputStream(); files[i].resources.add(key); files[i].filePos.put(key, resource = new Resource()); resource.start = prevFilePos; } } if(sf instanceof BFM && isFirstFormdef) { log.debug("processing formdef"); processingFormdef = true; } if(processingFormdef) files[i].formdef.add(sf); if(sf instanceof BMM && isFirstFormdef) { BMM bmm = (BMM) sf; mmName = bmm.getMMName(); log.debug("{}: found medium map {}", files[i].file, mmName); files[i].mmNames.add(mmName); files[i].mediumMaps.put(mmName, mediumMap = new MediumMap()); mediumMap.start = prevFilePos; buffer = new ByteArrayOutputStream(); } if(processingFormdef && mediumMap != null) { mediumMap.sfs.add(sf); } if(buffer != null) buffer.write(ain.getLastReadBuffer()); if(sf instanceof EMM && isFirstFormdef) { mediumMap.end = filepos; byte[] byteArray = buffer.toByteArray(); mediumMap.hash = getHash(byteArray); if(checkResourceEquality) mediumMap.content = byteArray; if(!mmNames.contains(mmName)) mmNames.add(mmName); log.debug("{}@{}-{}: found {}, hash {}", files[i].file, mediumMap.start, mediumMap.end, mmName, mediumMap.hash); mmName = null; mediumMap = null; buffer = null; } if(sf instanceof EFM) { processingFormdef = false; } if(sf instanceof ERS) { if(buffer == null) { // this is the end of a formdef, which we don't save isFirstFormdef = false; } else { resource.ersPos = prevFilePos; resource.end = filepos; byte[] byteArray = buffer.toByteArray(); resource.hash = getHash(byteArray); if(checkResourceEquality) resource.content = byteArray; if(!resourceNames.contains(key.getName())) resourceNames.add(key.getName()); log.debug("{}@{}-{}: found {}, hash {}", files[i].file, resource.start, resource.end, key, resource.hash); buffer = null; key = null; resource = null; } } prevFilePos = filepos; } } } } private void buildRenamingTable() { for(int i=0; i<files.length; i++) { for(int j=i+1; j<files.length; j++) { InputFile f1 = files[i]; InputFile f2 = files[j]; log.debug("comparing resources in {} and {}", f1.file.getName(), f2.file.getName()); for(ResourceKey k1 : f1.resources) { if(f2.resources.contains(k1) && !f2.renamings.containsKey(k1)) { // can this ever happen???? String h1 = f1.filePos.get(k1).hash; String h2 = f2.filePos.get(k1).hash; if(h1.equals(h2) && equals(f1.filePos.get(k1).content, f2.filePos.get(k1).content)) { if(f1.renamings.containsKey(k1)) { String newName = f1.renamings.get(k1); log.debug("resource {} is same in {} and {}, but being renamed to {}", k1.getName(), f1.file.getName(), f2.file.getName(), newName); f2.renamings.put(k1, newName); } else { log.debug("resource {} is same in {} and {}", k1.getName(), f1.file.getName(), f2.file.getName()); } } else { String newName = getNewResourceName(k1.getName(), h2); f2.renamings.put(k1, newName); resourceNames.add(newName); log.debug("{}: renaming resource {} to {}", f2.file.getName(), k1.getName(), newName ); } } } for(String mmName : f1.mmNames) { if(f2.mmNames.contains(mmName) && !f2.renameIMM.containsKey(mmName)) { String h1 = f1.mediumMaps.get(mmName).hash; String h2 = f2.mediumMaps.get(mmName).hash; if(h1.equals(h2) && equals(f1.mediumMaps.get(mmName).content, f2.mediumMaps.get(mmName).content)) { if(f1.renameIMM.containsKey(mmName)) { String newName = f1.renameIMM.get(mmName); log.debug("medium map {} is same in {} and {}, but being renamed to {}", mmName, f1.file.getName(), f2.file.getName(), newName); f2.renameIMM.put(mmName, newName); } else { log.debug("medium map {} is same in {} and {}", mmName, f1.file.getName(), f2.file.getName()); } } else { String newName = getNewFormdefName(mmName, h2); f2.renameIMM.put(mmName, newName); mmNames.add(newName); log.debug("{}: renaming medium map {} to {}", f2.file.getName(), mmName, newName); } } } } } } private boolean equals(byte[] b1, byte[] b2) { if(!checkResourceEquality) return true; return Arrays.equals(b1, b2); } private void buildFormdef() { LinkedList<SF> formdef = new LinkedList<SF>(); LinkedList<String> mmsWritten = new LinkedList<String>(); formdef.add(AfplibFactory.eINSTANCE.createBFM()); for(int i=0; i<inFiles.length; i++) { // build environment group LinkedList<SF> bdg = new LinkedList<SF>(); boolean isbdg = false; for(SF sf : files[i].formdef) { if(sf instanceof BDG) { isbdg = true; continue; } if(sf instanceof EDG) isbdg = false; if(isbdg) bdg.add(sf); } for(String mmName : files[i].mmNames) { MediumMap map = files[i].mediumMaps.get(mmName); Iterator<SF> it = map.sfs.iterator(); BMM bmm = (BMM) it.next(); if(files[i].renameIMM.containsKey(mmName)) { String newName = files[i].renameIMM.get(mmName); if(mmsWritten.contains(newName)) { log.debug("not writing resource {} as {} again", mmName, newName); continue; } bmm.setMMName(newName); log.debug("writing medium map {} as {} from {}", mmName, bmm.getMMName(), files[i].file.getName()); } else if(mmsWritten.contains(mmName)) { log.debug("not writing medium map {} again", mmName); continue; } else { log.debug("writing medium map {} from {}", mmName, files[i].file.getName()); } formdef.add(bmm); // add allowed sfs from the map inherited // by the environment group if needed add(formdef, bdg, map.sfs, FGD.class); add(formdef, bdg, map.sfs, MMO.class); add(formdef, bdg, map.sfs, MPO.class); add(formdef, bdg, map.sfs, MMT.class); add(formdef, bdg, map.sfs, MMD.class); add(formdef, bdg, map.sfs, MDR.class); add(formdef, bdg, map.sfs, PGP.class); add(formdef, bdg, map.sfs, MDD.class); add(formdef, bdg, map.sfs, MCC.class); add(formdef, bdg, map.sfs, MMC.class); add(formdef, bdg, map.sfs, PMC.class); add(formdef, bdg, map.sfs, MFC.class); add(formdef, bdg, map.sfs, PEC.class); formdef.add(AfplibFactory.eINSTANCE.createEMM()); mmsWritten.add(bmm.getMMName()); } } formdef.add(AfplibFactory.eINSTANCE.createEFM()); this.formdef = (SF[]) formdef.toArray(new SF[formdef.size()]); } @SuppressWarnings("unchecked") private <T extends SF> void add(LinkedList<SF> dest, LinkedList<SF> bdg, LinkedList<SF> map, Class<T> clazz) { LinkedList<T> result = new LinkedList<T>(); for(SF sf : map) { if(clazz.isInstance(sf) || (clazz.equals(PGP.class) && sf instanceof PGP1)) { result.add((T) sf); } } if(result.isEmpty()) { for(SF sf : bdg) { if(clazz.isInstance(sf) || (clazz.equals(PGP.class) && sf instanceof PGP1)) { result.add((T) sf); } } } dest.addAll(result); } private void writeResourceGroup() throws IOException { LinkedList<ResourceKey> resourcesWritten = new LinkedList<ResourceKey>(); try(AfpOutputStream aout = new AfpOutputStream(new BufferedOutputStream(new FileOutputStream(outFile, false)))) { BRG brg = AfplibFactory.eINSTANCE.createBRG(); aout.writeStructuredField(brg); { BRS brs = AfplibFactory.eINSTANCE.createBRS(); brs.setRSName("F1INLINE"); ResourceObjectType type = AfplibFactory.eINSTANCE.createResourceObjectType(); type.setConData(new byte[] {0,0,0,0}); type.setObjType(ResourceObjectTypeObjType.CONST_FORM_MAP_VALUE); brs.getTriplets().add(type); aout.writeStructuredField(brs); for(SF sf : formdef) aout.writeStructuredField(sf); ERS ers = AfplibFactory.eINSTANCE.createERS(); aout.writeStructuredField(ers); } log.info("writing resource group"); for(int i=0; i<inFiles.length; i++) { FileInputStream fin; try(AfpInputStream ain = new AfpInputStream(fin = new FileInputStream(inFiles[i]))) { for(ResourceKey key : files[i].resources) { if(key.getType() == ResourceObjectTypeObjType.CONST_FORM_MAP_VALUE) { log.debug("not writing formdef {}", key.getName()); continue; } ain.position(files[i].filePos.get(key).start); BRS brs = (BRS) ain.readStructuredField(); if(files[i].renamings.containsKey(key)) { String newName = files[i].renamings.get(key); ResourceKey newkey = new ResourceKey(key.getType(), newName, key.getObjId()); if(resourcesWritten.contains(newkey)) { log.debug("not writing resource {} as {} again", key.getName(), newName); continue; } renameBRSERS(brs, newName); resourcesWritten.add(newkey); log.debug("writing resource {} as {} from {}", key.getName(), newName, files[i].file.getName()); } else if(resourcesWritten.contains(key)) { log.debug("not writing resource {} again", key.getName()); continue; } else { resourcesWritten.add(key); log.debug("writing resource {} from {}", key.getName(), files[i].file.getName()); } aout.writeStructuredField(brs); byte[] buffer = new byte[8 * 1024]; int l; long left = files[i].filePos.get(key).ersPos - ain.getCurrentOffset(); while((l = fin.read(buffer, 0, left > buffer.length ? buffer.length : (int) left)) > 0) { aout.write(buffer, 0, l); left-=l; } if(left > 0) throw new IOException("couldn't copy resource from "+files[i].file.getName()); ERS ers = (ERS) ain.readStructuredField(); if(files[i].renamings.containsKey(key)) { String newName = files[i].renamings.get(key); renameBRSERS(ers, newName); } aout.writeStructuredField(ers); } } } ERG erg = AfplibFactory.eINSTANCE.createERG(); aout.writeStructuredField(erg); } } private void renameBRSERS(SF sf, String newName) { if(sf instanceof BRS) { ((BRS)sf).setRSName(newName); EList<Triplet> triplets = ((BRS)sf).getTriplets(); for(Object t : triplets) { if(t instanceof FullyQualifiedName) { FullyQualifiedName fqn = (FullyQualifiedName) t; if(fqn.getFQNType() == null) continue; if(FullyQualifiedNameFQNType.CONST_REPLACE_FIRST_GID_NAME_VALUE != fqn.getFQNType().intValue()) continue; fqn.setFQName(newName); break; } } } else { ((ERS)sf).setRSName(newName); } } private void writeDocuments() throws IOException { for(int i=0; i<inFiles.length; i++) { log.info("writing documents from {}", files[i].file.getName()); try (AfpInputStream in = new AfpInputStream(new FileInputStream(inFiles[i])); AfpOutputStream out = new AfpOutputStream( new BufferedOutputStream(new FileOutputStream(outFile, true)))) { in.position(files[i].documentStart); final InputFile file = files[i]; AfpFilter.filter(in, out, new Filter() { @Override public STATE onStructuredField(SF sf) { log.trace("{}", sf); switch(sf.getId()) { case SFName.IMM_VALUE: return rename(file, (IMM)sf); case SFName.IOB_VALUE: return rename(file, (IOB)sf); case SFName.IPG_VALUE: return rename(file, (IPG)sf); case SFName.IPO_VALUE: return rename(file, (IPO)sf); case SFName.IPS_VALUE: return rename(file, (IPS)sf); case SFName.MCF_VALUE: return rename(file, (MCF)sf); case SFName.MCF1_VALUE: return rename(file, (MCF1)sf); case SFName.MDR_VALUE: return rename(file, (MDR)sf); case SFName.MMO_VALUE: return rename(file, (MMO)sf); case SFName.MPG_VALUE: return rename(file, (MPG)sf); case SFName.MPO_VALUE: return rename(file, (MPO)sf); case SFName.MPS_VALUE: return rename(file, (MPS)sf); } return STATE.UNTOUCHED; } }); } } } private void overrideGid(EList<Triplet> triplets, String newName) { for(Object t : triplets) { if(t instanceof FullyQualifiedName) { FullyQualifiedName fqn = (FullyQualifiedName) t; if(fqn.getFQNType() == null) continue; if(FullyQualifiedNameFQNType.CONST_REPLACE_FIRST_GID_NAME_VALUE != fqn.getFQNType().intValue()) continue; fqn.setFQName(newName); break; } } } private Filter.STATE rename(InputFile file, IMM sf) { IMM imm = (IMM) sf; if(file.renameIMM.containsKey(imm.getMMPName())) { String newName = file.renameIMM.get(imm.getMMPName()); imm.setMMPName(newName); overrideGid(imm.getTriplets(), newName); log.trace("rename {}", newName); return Filter.STATE.MODIFIED; } return Filter.STATE.UNTOUCHED; } private Filter.STATE rename(InputFile file, IOB sf) { ResourceKey key = ResourceKey.toResourceKey(sf); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); sf.setObjName(newName); overrideGid(sf.getTriplets(), newName); log.trace("rename {}", newName); return Filter.STATE.MODIFIED; } return Filter.STATE.UNTOUCHED; } private Filter.STATE rename(InputFile file, IPG sf) { return Filter.STATE.UNTOUCHED; } private Filter.STATE rename(InputFile file, IPO sf) { ResourceKey key = ResourceKey.toResourceKey(sf); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); sf.setOvlyName(newName); overrideGid(sf.getTriplets(), newName); log.trace("rename {}", newName); return Filter.STATE.MODIFIED; } return Filter.STATE.UNTOUCHED; } private Filter.STATE rename(InputFile file, IPS sf) { ResourceKey key = ResourceKey.toResourceKey(sf); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); sf.setPsegName(newName); overrideGid(sf.getTriplets(), newName); log.trace("rename {}", newName); return Filter.STATE.MODIFIED; } return Filter.STATE.UNTOUCHED; } private Filter.STATE rename(InputFile file, MCF sf) { Filter.STATE result = Filter.STATE.UNTOUCHED; for(MCFRG rg : sf.getRG()) { for(Triplet t : rg.getTriplets()) { if(t instanceof FullyQualifiedName) { FullyQualifiedName fqn = (FullyQualifiedName) t; log.trace("{}", fqn); if(fqn.getFQNType() == FullyQualifiedNameFQNType.CONST_FONT_CHARACTER_SET_NAME_REFERENCE_VALUE) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_FONT_CHARACTER_SET, fqn.getFQName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); fqn.setFQName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } if(fqn.getFQNType() == FullyQualifiedNameFQNType.CONST_CODE_PAGE_NAME_REFERENCE_VALUE) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_CODE_PAGE, fqn.getFQName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); fqn.setFQName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } if(fqn.getFQNType() == FullyQualifiedNameFQNType.CONST_CODED_FONT_NAME_REFERENCE_VALUE) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_CODED_FONT, fqn.getFQName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); fqn.setFQName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } } } } return result; } private Filter.STATE rename(InputFile file, MCF1 sf) { STATE result = Filter.STATE.UNTOUCHED; for(MCF1RG rg : sf.getRG()) { log.trace("{}", rg); byte[] fcsname = rg.getFCSName().getBytes(Charset.forName("IBM500")); if(fcsname[0] != (byte) 0xff && fcsname[1] != (byte) 0xff) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_FONT_CHARACTER_SET, rg.getFCSName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); rg.setFCSName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } byte[] cfname = rg.getCFName().getBytes(Charset.forName("IBM500")); if(cfname[0] != (byte) 0xff && cfname[1] != (byte) 0xff) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_CODED_FONT, rg.getCFName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); rg.setCFName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } byte[] cpname = rg.getCPName().getBytes(Charset.forName("IBM500")); if(cpname[0] != (byte) 0xff && cpname[1] != (byte) 0xff) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_CODE_PAGE, rg.getCPName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); rg.setCPName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } } return result; } private Filter.STATE rename(InputFile file, MDR sf) { STATE result = Filter.STATE.UNTOUCHED; for(MDRRG rg : sf.getRG()) { EList<Triplet> mcfGroup = rg.getTriplets(); for(EObject triplet : mcfGroup) { if(triplet instanceof FullyQualifiedName) { log.trace("{}", triplet); int fqnType = ((FullyQualifiedName) triplet).getFQNType(); String name = ((FullyQualifiedName) triplet).getFQName(); ResourceKey key = null; if(fqnType == FullyQualifiedNameFQNType.CONST_RESOURCE_OBJECT_REFERENCE_VALUE) { key = new ResourceKey(ResourceObjectTypeObjType.CONST_IOCA, name); } else if(fqnType == FullyQualifiedNameFQNType.CONST_OTHER_OBJECT_DATA_REFERENCE_VALUE) { for(Triplet t : rg.getTriplets()) { if(t instanceof ObjectClassification) { ObjectClassification clazz = (ObjectClassification) t; key = new ResourceKey(ResourceObjectTypeObjType.CONST_OBJECT_CONTAINER, name, clazz.getRegObjId()); } } } else if(fqnType == FullyQualifiedNameFQNType.CONST_DATA_OBJECT_EXTERNAL_RESOURCE_REFERENCE_VALUE) { for(Triplet t : rg.getTriplets()) { if(t instanceof ObjectClassification) { ObjectClassification clazz = (ObjectClassification) t; key = new ResourceKey(ResourceObjectTypeObjType.CONST_OBJECT_CONTAINER, name, clazz.getRegObjId()); } } } if(key != null) { if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); ((FullyQualifiedName)triplet).setFQName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } } } } return result; } private Filter.STATE rename(InputFile file, MMO sf) { STATE result = Filter.STATE.UNTOUCHED; for(MMORG rg : sf.getRg()) { log.trace("{}", rg); ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_OVERLAY, rg.getOVLname()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); rg.setOVLname(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } return result; } private Filter.STATE rename(InputFile file, MPG sf) { log.warn("MPG is not supported: {}", sf); return Filter.STATE.UNTOUCHED; } private Filter.STATE rename(InputFile file, MPO sf) { STATE result = Filter.STATE.UNTOUCHED; for(MPORG rg : sf.getRG()) { log.trace("{}", rg); for(Triplet t : rg.getTriplets()) { if(t instanceof FullyQualifiedName) if(((FullyQualifiedName) t).getFQNType().intValue() == FullyQualifiedNameFQNType.CONST_RESOURCE_OBJECT_REFERENCE_VALUE) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_OVERLAY, ((FullyQualifiedName) t).getFQName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); ((FullyQualifiedName)t).setFQName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } } } return result; } private Filter.STATE rename(InputFile file, MPS sf) { STATE result = Filter.STATE.UNTOUCHED; for(MPSRG rg : sf.getFixedLengthRG()) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_PAGE_SEGMENT, rg.getPsegName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); rg.setPsegName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } return result; } private String getNewResourceName(String oldName, String hash) { for (int i = 0; i < hash.length() - 5; i++) { String res = oldName.substring(0, 2) + hash.substring(i, i + 6); if (!resourceNames.contains(res)) return res.toUpperCase(); } for(int i=0; i<999999; i++) { String res = oldName.substring(0, 2) + String.format("%06d", i); if (!resourceNames.contains(res)) return res.toUpperCase(); } log.error("unable to find a resource name for hash " + hash); throw new IllegalStateException( "unable to find a resource name for hash " + hash); } private String getNewFormdefName(String oldName, String hash) { for (int i = 0; i < hash.length() - 5; i++) { String res = oldName.substring(0, 2) + hash.substring(i, i + 6); if (!mmNames.contains(res)) return res.toUpperCase(); } for(int i=0; i<999999; i++) { String res = oldName.substring(0, 2) + String.format("%06d", i); if (!mmNames.contains(res)) return res.toUpperCase(); } log.error("unable to find a resource name for hash " + hash); throw new IllegalStateException( "unable to find a resource name for hash " + hash); } private String getHash(byte[] bytes) { algorithm.reset(); algorithm.update(bytes); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString(); } }
/** */ package CIM.IEC61970.Informative.InfCustomers.impl; import CIM.CIMPackage; import CIM.IEC61968.AssetModels.AssetModelsPackage; import CIM.IEC61968.AssetModels.impl.AssetModelsPackageImpl; import CIM.IEC61968.Assets.AssetsPackage; import CIM.IEC61968.Assets.impl.AssetsPackageImpl; import CIM.IEC61968.Common.CommonPackage; import CIM.IEC61968.Common.impl.CommonPackageImpl; import CIM.IEC61968.Customers.CustomersPackage; import CIM.IEC61968.Customers.impl.CustomersPackageImpl; import CIM.IEC61968.IEC61968Package; import CIM.IEC61968.LoadControl.LoadControlPackage; import CIM.IEC61968.LoadControl.impl.LoadControlPackageImpl; import CIM.IEC61968.Metering.MeteringPackage; import CIM.IEC61968.Metering.impl.MeteringPackageImpl; import CIM.IEC61968.PaymentMetering.PaymentMeteringPackage; import CIM.IEC61968.PaymentMetering.impl.PaymentMeteringPackageImpl; import CIM.IEC61968.WiresExt.WiresExtPackage; import CIM.IEC61968.WiresExt.impl.WiresExtPackageImpl; import CIM.IEC61968.Work.WorkPackage; import CIM.IEC61968.Work.impl.WorkPackageImpl; import CIM.IEC61968.impl.IEC61968PackageImpl; import CIM.IEC61970.Contingency.ContingencyPackage; import CIM.IEC61970.Contingency.impl.ContingencyPackageImpl; import CIM.IEC61970.ControlArea.ControlAreaPackage; import CIM.IEC61970.ControlArea.impl.ControlAreaPackageImpl; import CIM.IEC61970.Core.CorePackage; import CIM.IEC61970.Core.impl.CorePackageImpl; import CIM.IEC61970.Domain.DomainPackage; import CIM.IEC61970.Domain.impl.DomainPackageImpl; import CIM.IEC61970.Equivalents.EquivalentsPackage; import CIM.IEC61970.Equivalents.impl.EquivalentsPackageImpl; import CIM.IEC61970.Generation.GenerationDynamics.GenerationDynamicsPackage; import CIM.IEC61970.Generation.GenerationDynamics.impl.GenerationDynamicsPackageImpl; import CIM.IEC61970.Generation.Production.ProductionPackage; import CIM.IEC61970.Generation.Production.impl.ProductionPackageImpl; import CIM.IEC61970.IEC61970Package; import CIM.IEC61970.Informative.EnergyScheduling.EnergySchedulingPackage; import CIM.IEC61970.Informative.EnergyScheduling.impl.EnergySchedulingPackageImpl; import CIM.IEC61970.Informative.Financial.FinancialPackage; import CIM.IEC61970.Informative.Financial.impl.FinancialPackageImpl; import CIM.IEC61970.Informative.InfAssetModels.InfAssetModelsPackage; import CIM.IEC61970.Informative.InfAssetModels.impl.InfAssetModelsPackageImpl; import CIM.IEC61970.Informative.InfAssets.InfAssetsPackage; import CIM.IEC61970.Informative.InfAssets.impl.InfAssetsPackageImpl; import CIM.IEC61970.Informative.InfCommon.InfCommonPackage; import CIM.IEC61970.Informative.InfCommon.impl.InfCommonPackageImpl; import CIM.IEC61970.Informative.InfCore.InfCorePackage; import CIM.IEC61970.Informative.InfCore.impl.InfCorePackageImpl; import CIM.IEC61970.Informative.InfCustomers.InfCustomersFactory; import CIM.IEC61970.Informative.InfCustomers.InfCustomersPackage; import CIM.IEC61970.Informative.InfERPSupport.InfERPSupportPackage; import CIM.IEC61970.Informative.InfERPSupport.impl.InfERPSupportPackageImpl; import CIM.IEC61970.Informative.InfGMLSupport.InfGMLSupportPackage; import CIM.IEC61970.Informative.InfGMLSupport.impl.InfGMLSupportPackageImpl; import CIM.IEC61970.Informative.InfLoadControl.InfLoadControlPackage; import CIM.IEC61970.Informative.InfLoadControl.impl.InfLoadControlPackageImpl; import CIM.IEC61970.Informative.InfLocations.InfLocationsPackage; import CIM.IEC61970.Informative.InfLocations.impl.InfLocationsPackageImpl; import CIM.IEC61970.Informative.InfMetering.InfMeteringPackage; import CIM.IEC61970.Informative.InfMetering.impl.InfMeteringPackageImpl; import CIM.IEC61970.Informative.InfOperations.InfOperationsPackage; import CIM.IEC61970.Informative.InfOperations.impl.InfOperationsPackageImpl; import CIM.IEC61970.Informative.InfPaymentMetering.InfPaymentMeteringPackage; import CIM.IEC61970.Informative.InfPaymentMetering.impl.InfPaymentMeteringPackageImpl; import CIM.IEC61970.Informative.InfTypeAsset.InfTypeAssetPackage; import CIM.IEC61970.Informative.InfTypeAsset.impl.InfTypeAssetPackageImpl; import CIM.IEC61970.Informative.InfWork.InfWorkPackage; import CIM.IEC61970.Informative.InfWork.impl.InfWorkPackageImpl; import CIM.IEC61970.Informative.MarketOperations.MarketOperationsPackage; import CIM.IEC61970.Informative.MarketOperations.impl.MarketOperationsPackageImpl; import CIM.IEC61970.Informative.Reservation.ReservationPackage; import CIM.IEC61970.Informative.Reservation.impl.ReservationPackageImpl; import CIM.IEC61970.LoadModel.LoadModelPackage; import CIM.IEC61970.LoadModel.impl.LoadModelPackageImpl; import CIM.IEC61970.Meas.MeasPackage; import CIM.IEC61970.Meas.impl.MeasPackageImpl; import CIM.IEC61970.OperationalLimits.OperationalLimitsPackage; import CIM.IEC61970.OperationalLimits.impl.OperationalLimitsPackageImpl; import CIM.IEC61970.Outage.OutagePackage; import CIM.IEC61970.Outage.impl.OutagePackageImpl; import CIM.IEC61970.Protection.ProtectionPackage; import CIM.IEC61970.Protection.impl.ProtectionPackageImpl; import CIM.IEC61970.SCADA.SCADAPackage; import CIM.IEC61970.SCADA.impl.SCADAPackageImpl; import CIM.IEC61970.StateVariables.StateVariablesPackage; import CIM.IEC61970.StateVariables.impl.StateVariablesPackageImpl; import CIM.IEC61970.Topology.TopologyPackage; import CIM.IEC61970.Topology.impl.TopologyPackageImpl; import CIM.IEC61970.Wires.WiresPackage; import CIM.IEC61970.Wires.impl.WiresPackageImpl; import CIM.IEC61970.impl.IEC61970PackageImpl; import CIM.PackageDependencies.PackageDependenciesPackage; import CIM.PackageDependencies.impl.PackageDependenciesPackageImpl; import CIM.impl.CIMPackageImpl; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EEnum; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.impl.EPackageImpl; /** * <!-- begin-user-doc --> * An implementation of the model <b>Package</b>. * <!-- end-user-doc --> * @generated */ public class InfCustomersPackageImpl extends EPackageImpl implements InfCustomersPackage { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass standardIndustryCodeEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass customerBillingInfoEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass powerQualityPricingEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass outageHistoryEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass workBillingInfoEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass subscribePowerCurveEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass serviceGuaranteeEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass externalCustomerAgreementEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EEnum customerBillingKindEEnum = null; /** * Creates an instance of the model <b>Package</b>, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * <p>Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.emf.ecore.EPackage.Registry * @see CIM.IEC61970.Informative.InfCustomers.InfCustomersPackage#eNS_URI * @see #init() * @generated */ private InfCustomersPackageImpl() { super(eNS_URI, InfCustomersFactory.eINSTANCE); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends. * * <p>This method is used to initialize {@link InfCustomersPackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #eNS_URI * @generated */ public static InfCustomersPackage init() { if (isInited) return (InfCustomersPackage)EPackage.Registry.INSTANCE.getEPackage(InfCustomersPackage.eNS_URI); // Obtain or create and register package InfCustomersPackageImpl theInfCustomersPackage = (InfCustomersPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof InfCustomersPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new InfCustomersPackageImpl()); isInited = true; // Obtain or create and register interdependencies CIMPackageImpl theCIMPackage = (CIMPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(CIMPackage.eNS_URI) instanceof CIMPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(CIMPackage.eNS_URI) : CIMPackage.eINSTANCE); IEC61970PackageImpl theIEC61970Package = (IEC61970PackageImpl)(EPackage.Registry.INSTANCE.getEPackage(IEC61970Package.eNS_URI) instanceof IEC61970PackageImpl ? EPackage.Registry.INSTANCE.getEPackage(IEC61970Package.eNS_URI) : IEC61970Package.eINSTANCE); OperationalLimitsPackageImpl theOperationalLimitsPackage = (OperationalLimitsPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(OperationalLimitsPackage.eNS_URI) instanceof OperationalLimitsPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(OperationalLimitsPackage.eNS_URI) : OperationalLimitsPackage.eINSTANCE); EnergySchedulingPackageImpl theEnergySchedulingPackage = (EnergySchedulingPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(EnergySchedulingPackage.eNS_URI) instanceof EnergySchedulingPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(EnergySchedulingPackage.eNS_URI) : EnergySchedulingPackage.eINSTANCE); InfERPSupportPackageImpl theInfERPSupportPackage = (InfERPSupportPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(InfERPSupportPackage.eNS_URI) instanceof InfERPSupportPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(InfERPSupportPackage.eNS_URI) : InfERPSupportPackage.eINSTANCE); InfAssetModelsPackageImpl theInfAssetModelsPackage = (InfAssetModelsPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(InfAssetModelsPackage.eNS_URI) instanceof InfAssetModelsPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(InfAssetModelsPackage.eNS_URI) : InfAssetModelsPackage.eINSTANCE); InfAssetsPackageImpl theInfAssetsPackage = (InfAssetsPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(InfAssetsPackage.eNS_URI) instanceof InfAssetsPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(InfAssetsPackage.eNS_URI) : InfAssetsPackage.eINSTANCE); InfGMLSupportPackageImpl theInfGMLSupportPackage = (InfGMLSupportPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(InfGMLSupportPackage.eNS_URI) instanceof InfGMLSupportPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(InfGMLSupportPackage.eNS_URI) : InfGMLSupportPackage.eINSTANCE); InfCorePackageImpl theInfCorePackage = (InfCorePackageImpl)(EPackage.Registry.INSTANCE.getEPackage(InfCorePackage.eNS_URI) instanceof InfCorePackageImpl ? EPackage.Registry.INSTANCE.getEPackage(InfCorePackage.eNS_URI) : InfCorePackage.eINSTANCE); MarketOperationsPackageImpl theMarketOperationsPackage = (MarketOperationsPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(MarketOperationsPackage.eNS_URI) instanceof MarketOperationsPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(MarketOperationsPackage.eNS_URI) : MarketOperationsPackage.eINSTANCE); InfOperationsPackageImpl theInfOperationsPackage = (InfOperationsPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(InfOperationsPackage.eNS_URI) instanceof InfOperationsPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(InfOperationsPackage.eNS_URI) : InfOperationsPackage.eINSTANCE); InfWorkPackageImpl theInfWorkPackage = (InfWorkPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(InfWorkPackage.eNS_URI) instanceof InfWorkPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(InfWorkPackage.eNS_URI) : InfWorkPackage.eINSTANCE); InfPaymentMeteringPackageImpl theInfPaymentMeteringPackage = (InfPaymentMeteringPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(InfPaymentMeteringPackage.eNS_URI) instanceof InfPaymentMeteringPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(InfPaymentMeteringPackage.eNS_URI) : InfPaymentMeteringPackage.eINSTANCE); InfCommonPackageImpl theInfCommonPackage = (InfCommonPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(InfCommonPackage.eNS_URI) instanceof InfCommonPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(InfCommonPackage.eNS_URI) : InfCommonPackage.eINSTANCE); InfLocationsPackageImpl theInfLocationsPackage = (InfLocationsPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(InfLocationsPackage.eNS_URI) instanceof InfLocationsPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(InfLocationsPackage.eNS_URI) : InfLocationsPackage.eINSTANCE); FinancialPackageImpl theFinancialPackage = (FinancialPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(FinancialPackage.eNS_URI) instanceof FinancialPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(FinancialPackage.eNS_URI) : FinancialPackage.eINSTANCE); ReservationPackageImpl theReservationPackage = (ReservationPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(ReservationPackage.eNS_URI) instanceof ReservationPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(ReservationPackage.eNS_URI) : ReservationPackage.eINSTANCE); InfMeteringPackageImpl theInfMeteringPackage = (InfMeteringPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(InfMeteringPackage.eNS_URI) instanceof InfMeteringPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(InfMeteringPackage.eNS_URI) : InfMeteringPackage.eINSTANCE); InfLoadControlPackageImpl theInfLoadControlPackage = (InfLoadControlPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(InfLoadControlPackage.eNS_URI) instanceof InfLoadControlPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(InfLoadControlPackage.eNS_URI) : InfLoadControlPackage.eINSTANCE); InfTypeAssetPackageImpl theInfTypeAssetPackage = (InfTypeAssetPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(InfTypeAssetPackage.eNS_URI) instanceof InfTypeAssetPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(InfTypeAssetPackage.eNS_URI) : InfTypeAssetPackage.eINSTANCE); MeasPackageImpl theMeasPackage = (MeasPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(MeasPackage.eNS_URI) instanceof MeasPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(MeasPackage.eNS_URI) : MeasPackage.eINSTANCE); GenerationDynamicsPackageImpl theGenerationDynamicsPackage = (GenerationDynamicsPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(GenerationDynamicsPackage.eNS_URI) instanceof GenerationDynamicsPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(GenerationDynamicsPackage.eNS_URI) : GenerationDynamicsPackage.eINSTANCE); ProductionPackageImpl theProductionPackage = (ProductionPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(ProductionPackage.eNS_URI) instanceof ProductionPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(ProductionPackage.eNS_URI) : ProductionPackage.eINSTANCE); SCADAPackageImpl theSCADAPackage = (SCADAPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(SCADAPackage.eNS_URI) instanceof SCADAPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(SCADAPackage.eNS_URI) : SCADAPackage.eINSTANCE); WiresPackageImpl theWiresPackage = (WiresPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(WiresPackage.eNS_URI) instanceof WiresPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(WiresPackage.eNS_URI) : WiresPackage.eINSTANCE); CorePackageImpl theCorePackage = (CorePackageImpl)(EPackage.Registry.INSTANCE.getEPackage(CorePackage.eNS_URI) instanceof CorePackageImpl ? EPackage.Registry.INSTANCE.getEPackage(CorePackage.eNS_URI) : CorePackage.eINSTANCE); StateVariablesPackageImpl theStateVariablesPackage = (StateVariablesPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(StateVariablesPackage.eNS_URI) instanceof StateVariablesPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(StateVariablesPackage.eNS_URI) : StateVariablesPackage.eINSTANCE); EquivalentsPackageImpl theEquivalentsPackage = (EquivalentsPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(EquivalentsPackage.eNS_URI) instanceof EquivalentsPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(EquivalentsPackage.eNS_URI) : EquivalentsPackage.eINSTANCE); DomainPackageImpl theDomainPackage = (DomainPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(DomainPackage.eNS_URI) instanceof DomainPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(DomainPackage.eNS_URI) : DomainPackage.eINSTANCE); LoadModelPackageImpl theLoadModelPackage = (LoadModelPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(LoadModelPackage.eNS_URI) instanceof LoadModelPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(LoadModelPackage.eNS_URI) : LoadModelPackage.eINSTANCE); ProtectionPackageImpl theProtectionPackage = (ProtectionPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(ProtectionPackage.eNS_URI) instanceof ProtectionPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(ProtectionPackage.eNS_URI) : ProtectionPackage.eINSTANCE); OutagePackageImpl theOutagePackage = (OutagePackageImpl)(EPackage.Registry.INSTANCE.getEPackage(OutagePackage.eNS_URI) instanceof OutagePackageImpl ? EPackage.Registry.INSTANCE.getEPackage(OutagePackage.eNS_URI) : OutagePackage.eINSTANCE); ControlAreaPackageImpl theControlAreaPackage = (ControlAreaPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(ControlAreaPackage.eNS_URI) instanceof ControlAreaPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(ControlAreaPackage.eNS_URI) : ControlAreaPackage.eINSTANCE); ContingencyPackageImpl theContingencyPackage = (ContingencyPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(ContingencyPackage.eNS_URI) instanceof ContingencyPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(ContingencyPackage.eNS_URI) : ContingencyPackage.eINSTANCE); TopologyPackageImpl theTopologyPackage = (TopologyPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(TopologyPackage.eNS_URI) instanceof TopologyPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(TopologyPackage.eNS_URI) : TopologyPackage.eINSTANCE); PackageDependenciesPackageImpl thePackageDependenciesPackage = (PackageDependenciesPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(PackageDependenciesPackage.eNS_URI) instanceof PackageDependenciesPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(PackageDependenciesPackage.eNS_URI) : PackageDependenciesPackage.eINSTANCE); IEC61968PackageImpl theIEC61968Package = (IEC61968PackageImpl)(EPackage.Registry.INSTANCE.getEPackage(IEC61968Package.eNS_URI) instanceof IEC61968PackageImpl ? EPackage.Registry.INSTANCE.getEPackage(IEC61968Package.eNS_URI) : IEC61968Package.eINSTANCE); MeteringPackageImpl theMeteringPackage = (MeteringPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(MeteringPackage.eNS_URI) instanceof MeteringPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(MeteringPackage.eNS_URI) : MeteringPackage.eINSTANCE); WiresExtPackageImpl theWiresExtPackage = (WiresExtPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(WiresExtPackage.eNS_URI) instanceof WiresExtPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(WiresExtPackage.eNS_URI) : WiresExtPackage.eINSTANCE); CommonPackageImpl theCommonPackage = (CommonPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(CommonPackage.eNS_URI) instanceof CommonPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(CommonPackage.eNS_URI) : CommonPackage.eINSTANCE); AssetModelsPackageImpl theAssetModelsPackage = (AssetModelsPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(AssetModelsPackage.eNS_URI) instanceof AssetModelsPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(AssetModelsPackage.eNS_URI) : AssetModelsPackage.eINSTANCE); PaymentMeteringPackageImpl thePaymentMeteringPackage = (PaymentMeteringPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(PaymentMeteringPackage.eNS_URI) instanceof PaymentMeteringPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(PaymentMeteringPackage.eNS_URI) : PaymentMeteringPackage.eINSTANCE); CustomersPackageImpl theCustomersPackage = (CustomersPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(CustomersPackage.eNS_URI) instanceof CustomersPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(CustomersPackage.eNS_URI) : CustomersPackage.eINSTANCE); LoadControlPackageImpl theLoadControlPackage = (LoadControlPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(LoadControlPackage.eNS_URI) instanceof LoadControlPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(LoadControlPackage.eNS_URI) : LoadControlPackage.eINSTANCE); AssetsPackageImpl theAssetsPackage = (AssetsPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(AssetsPackage.eNS_URI) instanceof AssetsPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(AssetsPackage.eNS_URI) : AssetsPackage.eINSTANCE); WorkPackageImpl theWorkPackage = (WorkPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(WorkPackage.eNS_URI) instanceof WorkPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(WorkPackage.eNS_URI) : WorkPackage.eINSTANCE); // Load packages theCIMPackage.loadPackage(); // Fix loaded packages theInfCustomersPackage.fixPackageContents(); theCIMPackage.fixPackageContents(); theIEC61970Package.fixPackageContents(); theOperationalLimitsPackage.fixPackageContents(); theEnergySchedulingPackage.fixPackageContents(); theInfERPSupportPackage.fixPackageContents(); theInfAssetModelsPackage.fixPackageContents(); theInfAssetsPackage.fixPackageContents(); theInfGMLSupportPackage.fixPackageContents(); theInfCorePackage.fixPackageContents(); theMarketOperationsPackage.fixPackageContents(); theInfOperationsPackage.fixPackageContents(); theInfWorkPackage.fixPackageContents(); theInfPaymentMeteringPackage.fixPackageContents(); theInfCommonPackage.fixPackageContents(); theInfLocationsPackage.fixPackageContents(); theFinancialPackage.fixPackageContents(); theReservationPackage.fixPackageContents(); theInfMeteringPackage.fixPackageContents(); theInfLoadControlPackage.fixPackageContents(); theInfTypeAssetPackage.fixPackageContents(); theMeasPackage.fixPackageContents(); theGenerationDynamicsPackage.fixPackageContents(); theProductionPackage.fixPackageContents(); theSCADAPackage.fixPackageContents(); theWiresPackage.fixPackageContents(); theCorePackage.fixPackageContents(); theStateVariablesPackage.fixPackageContents(); theEquivalentsPackage.fixPackageContents(); theDomainPackage.fixPackageContents(); theLoadModelPackage.fixPackageContents(); theProtectionPackage.fixPackageContents(); theOutagePackage.fixPackageContents(); theControlAreaPackage.fixPackageContents(); theContingencyPackage.fixPackageContents(); theTopologyPackage.fixPackageContents(); thePackageDependenciesPackage.fixPackageContents(); theIEC61968Package.fixPackageContents(); theMeteringPackage.fixPackageContents(); theWiresExtPackage.fixPackageContents(); theCommonPackage.fixPackageContents(); theAssetModelsPackage.fixPackageContents(); thePaymentMeteringPackage.fixPackageContents(); theCustomersPackage.fixPackageContents(); theLoadControlPackage.fixPackageContents(); theAssetsPackage.fixPackageContents(); theWorkPackage.fixPackageContents(); // Mark meta-data to indicate it can't be changed theInfCustomersPackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(InfCustomersPackage.eNS_URI, theInfCustomersPackage); return theInfCustomersPackage; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getStandardIndustryCode() { if (standardIndustryCodeEClass == null) { standardIndustryCodeEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(InfCustomersPackage.eNS_URI).getEClassifiers().get(0); } return standardIndustryCodeEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getStandardIndustryCode_CustomerAgreements() { return (EReference)getStandardIndustryCode().getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getStandardIndustryCode_Code() { return (EAttribute)getStandardIndustryCode().getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getCustomerBillingInfo() { if (customerBillingInfoEClass == null) { customerBillingInfoEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(InfCustomersPackage.eNS_URI).getEClassifiers().get(1); } return customerBillingInfoEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getCustomerBillingInfo_DueDate() { return (EAttribute)getCustomerBillingInfo().getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getCustomerBillingInfo_PymtPlanAmt() { return (EAttribute)getCustomerBillingInfo().getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getCustomerBillingInfo_CustomerAccount() { return (EReference)getCustomerBillingInfo().getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getCustomerBillingInfo_LastPaymentDate() { return (EAttribute)getCustomerBillingInfo().getEStructuralFeatures().get(3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getCustomerBillingInfo_BillingDate() { return (EAttribute)getCustomerBillingInfo().getEStructuralFeatures().get(4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getCustomerBillingInfo_LastPaymentAmt() { return (EAttribute)getCustomerBillingInfo().getEStructuralFeatures().get(5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getCustomerBillingInfo_PymtPlanType() { return (EAttribute)getCustomerBillingInfo().getEStructuralFeatures().get(6); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getCustomerBillingInfo_OutBalance() { return (EAttribute)getCustomerBillingInfo().getEStructuralFeatures().get(7); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getCustomerBillingInfo_ErpInvoiceLineItems() { return (EReference)getCustomerBillingInfo().getEStructuralFeatures().get(8); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getCustomerBillingInfo_Kind() { return (EAttribute)getCustomerBillingInfo().getEStructuralFeatures().get(9); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getPowerQualityPricing() { if (powerQualityPricingEClass == null) { powerQualityPricingEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(InfCustomersPackage.eNS_URI).getEClassifiers().get(3); } return powerQualityPricingEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getPowerQualityPricing_PricingStructure() { return (EReference)getPowerQualityPricing().getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getPowerQualityPricing_ValueUninterruptedServiceEnergy() { return (EAttribute)getPowerQualityPricing().getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getPowerQualityPricing_VoltImbalanceViolCost() { return (EAttribute)getPowerQualityPricing().getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getPowerQualityPricing_VoltLimitViolCost() { return (EAttribute)getPowerQualityPricing().getEStructuralFeatures().get(3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getPowerQualityPricing_EmergencyLowVoltLimit() { return (EAttribute)getPowerQualityPricing().getEStructuralFeatures().get(4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getPowerQualityPricing_ValueUninterruptedServiceP() { return (EAttribute)getPowerQualityPricing().getEStructuralFeatures().get(5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getPowerQualityPricing_EmergencyHighVoltLimit() { return (EAttribute)getPowerQualityPricing().getEStructuralFeatures().get(6); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getPowerQualityPricing_PowerFactorMin() { return (EAttribute)getPowerQualityPricing().getEStructuralFeatures().get(7); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getPowerQualityPricing_ServiceDeliveryPoints() { return (EReference)getPowerQualityPricing().getEStructuralFeatures().get(8); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getPowerQualityPricing_NormalLowVoltLimit() { return (EAttribute)getPowerQualityPricing().getEStructuralFeatures().get(9); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getPowerQualityPricing_NormalHighVoltLimit() { return (EAttribute)getPowerQualityPricing().getEStructuralFeatures().get(10); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getOutageHistory() { if (outageHistoryEClass == null) { outageHistoryEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(InfCustomersPackage.eNS_URI).getEClassifiers().get(4); } return outageHistoryEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getOutageHistory_OutageReports() { return (EReference)getOutageHistory().getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getWorkBillingInfo() { if (workBillingInfoEClass == null) { workBillingInfoEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(InfCustomersPackage.eNS_URI).getEClassifiers().get(5); } return workBillingInfoEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getWorkBillingInfo_CustomerAccount() { return (EReference)getWorkBillingInfo().getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getWorkBillingInfo_ReceivedDateTime() { return (EAttribute)getWorkBillingInfo().getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getWorkBillingInfo_Discount() { return (EAttribute)getWorkBillingInfo().getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getWorkBillingInfo_IssueDateTime() { return (EAttribute)getWorkBillingInfo().getEStructuralFeatures().get(3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getWorkBillingInfo_ErpLineItems() { return (EReference)getWorkBillingInfo().getEStructuralFeatures().get(4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getWorkBillingInfo_DueDateTime() { return (EAttribute)getWorkBillingInfo().getEStructuralFeatures().get(5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getWorkBillingInfo_Deposit() { return (EAttribute)getWorkBillingInfo().getEStructuralFeatures().get(6); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getWorkBillingInfo_Works() { return (EReference)getWorkBillingInfo().getEStructuralFeatures().get(7); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getWorkBillingInfo_WorkPrice() { return (EAttribute)getWorkBillingInfo().getEStructuralFeatures().get(8); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getWorkBillingInfo_CostEstimate() { return (EAttribute)getWorkBillingInfo().getEStructuralFeatures().get(9); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getSubscribePowerCurve() { if (subscribePowerCurveEClass == null) { subscribePowerCurveEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(InfCustomersPackage.eNS_URI).getEClassifiers().get(6); } return subscribePowerCurveEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getSubscribePowerCurve_PricingStructure() { return (EReference)getSubscribePowerCurve().getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getServiceGuarantee() { if (serviceGuaranteeEClass == null) { serviceGuaranteeEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(InfCustomersPackage.eNS_URI).getEClassifiers().get(7); } return serviceGuaranteeEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getServiceGuarantee_PayAmount() { return (EAttribute)getServiceGuarantee().getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getServiceGuarantee_ApplicationPeriod() { return (EReference)getServiceGuarantee().getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getServiceGuarantee_AutomaticPay() { return (EAttribute)getServiceGuarantee().getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getServiceGuarantee_ServiceRequirement() { return (EAttribute)getServiceGuarantee().getEStructuralFeatures().get(3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getExternalCustomerAgreement() { if (externalCustomerAgreementEClass == null) { externalCustomerAgreementEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(InfCustomersPackage.eNS_URI).getEClassifiers().get(8); } return externalCustomerAgreementEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EEnum getCustomerBillingKind() { if (customerBillingKindEEnum == null) { customerBillingKindEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(InfCustomersPackage.eNS_URI).getEClassifiers().get(2); } return customerBillingKindEEnum; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public InfCustomersFactory getInfCustomersFactory() { return (InfCustomersFactory)getEFactoryInstance(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private boolean isFixed = false; /** * Fixes up the loaded package, to make it appear as if it had been programmatically built. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void fixPackageContents() { if (isFixed) return; isFixed = true; fixEClassifiers(); } /** * Sets the instance class on the given classifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void fixInstanceClass(EClassifier eClassifier) { if (eClassifier.getInstanceClassName() == null) { eClassifier.setInstanceClassName("CIM.IEC61970.Informative.InfCustomers." + eClassifier.getName()); setGeneratedClassName(eClassifier); } } } //InfCustomersPackageImpl
package com.linkedin.thirdeye.anomaly.database; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.google.common.base.Joiner; import com.linkedin.thirdeye.anomaly.api.AnomalyDatabaseConfig; import com.linkedin.thirdeye.anomaly.api.ResultProperties; import com.linkedin.thirdeye.anomaly.util.ResourceUtils; import com.linkedin.thirdeye.api.TimeRange; /** * */ public class AnomalyTable { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final Logger LOGGER = LoggerFactory.getLogger(AnomalyTable.class); private static final Joiner COMMA = Joiner.on(','); private static final Joiner AND = Joiner.on(" AND "); /** * @param dbConfig * @param collection * Collection conatining anomalies * @param functionName * SQL pattern for function name to match * @param functionDescription * SQL pattern for description to match * @param metrics * The list of metrics used * @param topLevelOnly * Only anomalies with all * dimensions * @param orderBy * Components of orderBy clause * @param startTimeWindow * @param endTimeWindow * @return * List of rows based on query produced * @throws SQLException */ public static List<AnomalyTableRow> selectRows( AnomalyDatabaseConfig dbConfig, String collection, String functionName, String functionDescription, Set<String> metrics, boolean topLevelOnly, List<String> orderBy, long startTimeWindow, long endTimeWindow) throws SQLException { return selectRows(dbConfig, collection, null, functionName, functionDescription, null, metrics, topLevelOnly, orderBy, new TimeRange(startTimeWindow, endTimeWindow)); } public static List<AnomalyTableRow> selectRows(AnomalyDatabaseConfig dbConfig, int functionId, TimeRange timeRange) throws SQLException { List<String> orderBy = Arrays.asList(new String[]{"time_window"}); return selectRows(dbConfig, null, functionId, null, null, null, null, false, orderBy, null); } public static List<AnomalyTableRow> selectRows( AnomalyDatabaseConfig dbConfig, String collection, Integer functionId, String functionName, String functionDescription, Map<String, String> dimensions, Set<String> metrics, boolean topLevelOnly, List<String> orderBy, TimeRange timeRange) throws SQLException { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { String sql = buildAnomalyTableSelectStatement(dbConfig, functionId, functionName, functionDescription, collection, topLevelOnly, orderBy, timeRange); conn = dbConfig.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); List<AnomalyTableRow> results = new LinkedList<AnomalyTableRow>(); while (rs.next()) { AnomalyTableRow row = new AnomalyTableRow(); row.setId(rs.getInt("id")); row.setFunctionTable(rs.getString("function_table")); row.setFunctionId(rs.getInt("function_id")); row.setFunctionName(rs.getString("function_name")); row.setFunctionDescription(rs.getString("function_description")); row.setCollection(rs.getString("collection")); row.setTimeWindow(rs.getLong("time_window")); row.setNonStarCount(rs.getInt("non_star_count")); row.setDimensions(deserializeDimensions(rs.getString("dimensions"))); row.setDimensionsContribution(rs.getDouble("dimensions_contribution")); row.setMetrics(deserializeMetrics(rs.getString("metrics"))); row.setAnomalyScore(rs.getDouble("anomaly_score")); row.setAnomalyVolume(rs.getDouble("anomaly_volume")); ResultProperties properties = new ResultProperties(); try { properties.load(new StringReader(rs.getString("properties"))); } catch (IOException e) { LOGGER.warn("unable to deserialize anomaly result properties", e); properties = null; } row.setProperties(properties); // filter on dimensions if (dimensions != null) { if (row.getDimensions() == null || row.getDimensions().size() != dimensions.size() || !row.compareDimensions(dimensions)) { continue; } } // filter on metrics if (metrics != null) { if (row.getMetrics() == null || row.getMetrics().size() != metrics.size() || !metrics.containsAll(row.getMetrics())) { continue; } } results.add(row); } return results; } catch (SQLException e) { LOGGER.error("there was a problem retrieving rows", e); throw e; } finally { try { if (conn != null) { conn.close(); } if (stmt != null) { stmt.close(); } if (rs != null) { rs.close(); } } catch (SQLException e) { LOGGER.error("close exception", e); } } } /** * Create anomaly table if it does not exist * * @param dbConfig * @throws IOException * @throws SQLException */ public static void createTable(AnomalyDatabaseConfig dbConfig) throws IOException { dbConfig.runSQL(buildAnomalyTableCreateStmt(dbConfig.getAnomalyTableName())); } /** * Adds the row to the anomaly table referenced in dbConfig * * @param dbConfig * @param row * @throws IOException */ public static void insertRow(AnomalyDatabaseConfig dbConfig, AnomalyTableRow row) throws IOException { Connection conn = null; PreparedStatement preparedStmt = null; try { conn = dbConfig.getConnection(); preparedStmt = conn.prepareStatement(buildAnomlayTableInsertStmt(dbConfig.getAnomalyTableName())); preparedStmt.setString(1, row.getFunctionTable()); preparedStmt.setInt(2, row.getFunctionId()); preparedStmt.setString(3, row.getFunctionDescription()); preparedStmt.setString(4, row.getFunctionName()); preparedStmt.setString(5, row.getCollection()); preparedStmt.setLong(6, row.getTimeWindow()); preparedStmt.setInt(7, row.getNonStarCount()); preparedStmt.setString(8, serializeDimensions(row.getDimensions())); preparedStmt.setDouble(9, row.getDimensionsContribution()); preparedStmt.setString(10, serializeMetrics(row.getMetrics())); preparedStmt.setDouble(11, row.getAnomalyScore()); preparedStmt.setDouble(12, row.getAnomalyVolume()); StringWriter writer = new StringWriter(); row.getProperties().store(new PrintWriter(writer), "ResultProperties"); preparedStmt.setString(13, writer.getBuffer().toString()); preparedStmt.executeUpdate(); } catch (SQLException | JsonProcessingException e) { LOGGER.error("unable to insert row", e); } finally { try { if (conn != null) { conn.close(); } if (preparedStmt != null) { preparedStmt.close(); } } catch (SQLException e) { LOGGER.error("close exception", e); } } } /** * @param dbconfig * @param functionName * @param functionDescription * @param collection * @param metric * @param topLevelOnly * @param startTimeWindow * @param endTimeWidnow * @return * @throws JsonProcessingException */ private static String buildAnomalyTableSelectStatement(AnomalyDatabaseConfig dbconfig, Integer functionId, String functionName, String functionDescription, String collection, boolean topLevelOnly, List<String> orderBy, TimeRange timeRange) { StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM ").append(dbconfig.getAnomalyTableName()).append(" WHERE "); List<String> whereClause = new LinkedList<>(); if (dbconfig.getFunctionTableName() != null) { whereClause.add("function_table = '" + dbconfig.getFunctionTableName() + "'"); } if (functionId != null) { whereClause.add("function_id = '" + functionId + "'"); } if (collection != null) { whereClause.add("collection = '" + collection + "'"); } if (functionName != null) { whereClause.add("function_name = '" + functionName + "'"); } if (functionDescription != null) { whereClause.add("function_description LIKE '" + functionDescription + "'"); } if (topLevelOnly) { whereClause.add("non_star_count = 0"); } if (timeRange != null) { whereClause.add("time_window BETWEEN '" + timeRange.getStart() + "' AND '" + timeRange.getEnd() + "'"); } sb.append(AND.join(whereClause)); if (orderBy != null && orderBy.size() > 0) { sb.append(" ORDER BY ").append(COMMA.join(orderBy)); } sb.append(";"); return sb.toString(); } private static String buildAnomalyTableCreateStmt(String anomalyTableName) throws IOException { String formatString = ResourceUtils.getResourceAsString("database/anomaly/create-anomaly-table-template.sql"); return String.format(formatString, anomalyTableName); } private static String buildAnomlayTableInsertStmt(String tableName) throws IOException { String formatString = ResourceUtils.getResourceAsString("database/anomaly/insert-into-anomaly-table-template.sql"); return String.format(formatString, tableName); } private static Map<String, String> deserializeDimensions(String dimensionsString) { ObjectReader reader = OBJECT_MAPPER.reader(Map.class); try { return reader.readValue(dimensionsString); } catch (IOException e) { return null; } } private static String serializeDimensions(Map<String, String> dimensionsMap) throws JsonProcessingException { return OBJECT_MAPPER.writeValueAsString(dimensionsMap); } private static Set<String> deserializeMetrics(String metricsString) { ObjectReader reader = OBJECT_MAPPER.reader(Set.class); try { return reader.readValue(metricsString); } catch (IOException e) { return null; } } private static String serializeMetrics(Set<String> metrics) throws JsonProcessingException { return OBJECT_MAPPER.writeValueAsString(metrics); } }
package liquibase.change.core; import liquibase.change.ChangeFactory; import liquibase.change.StandardChangeTest; import liquibase.database.core.MockDatabase; import liquibase.statement.SqlStatement; import liquibase.statement.DatabaseFunction; import liquibase.statement.core.AddDefaultValueStatement; import static org.junit.Assert.*; import org.junit.Test; public class AddDefaultValueChangeTest extends StandardChangeTest { @Override @Test public void generateStatement() throws Exception { AddDefaultValueChange change = new AddDefaultValueChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COLUMN_NAME"); change.setDefaultValue("New default value"); change.setColumnDataType("VARCHAR(255)"); SqlStatement[] statements = change.generateStatements(new MockDatabase()); assertEquals(1, statements.length); AddDefaultValueStatement statement = (AddDefaultValueStatement) statements[0]; assertEquals("TABLE_NAME", statement.getTableName()); assertEquals("COLUMN_NAME", statement.getColumnName()); assertEquals("New default value", statement.getDefaultValue()); assertEquals("VARCHAR(255)", statement.getColumnDataType()); } @Test public void generateStatements_intDefaultValue() throws Exception { AddDefaultValueChange change = new AddDefaultValueChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COLUMN_NAME"); change.setDefaultValueNumeric("42"); SqlStatement[] statements = change.generateStatements(new MockDatabase()); assertEquals(1, statements.length); AddDefaultValueStatement statement = (AddDefaultValueStatement) statements[0]; assertEquals("TABLE_NAME", statement.getTableName()); assertEquals("COLUMN_NAME", statement.getColumnName()); assertTrue(statement.getDefaultValue() instanceof Number); assertEquals("42", statement.getDefaultValue().toString()); } @Test public void generateStatements_decimalDefaultValue() throws Exception { AddDefaultValueChange change = new AddDefaultValueChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COLUMN_NAME"); change.setDefaultValueNumeric("42.56"); SqlStatement[] statements = change.generateStatements(new MockDatabase()); assertEquals(1, statements.length); AddDefaultValueStatement statement = (AddDefaultValueStatement) statements[0]; assertEquals("TABLE_NAME", statement.getTableName()); assertEquals("COLUMN_NAME", statement.getColumnName()); assertTrue(statement.getDefaultValue() instanceof Number); assertEquals("42.56", statement.getDefaultValue().toString()); } @Test public void generateStatements_computedNumeric() throws Exception { AddDefaultValueChange change = new AddDefaultValueChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COLUMN_NAME"); change.setDefaultValueNumeric("Math.random()"); SqlStatement[] statements = change.generateStatements(new MockDatabase()); assertEquals(1, statements.length); AddDefaultValueStatement statement = (AddDefaultValueStatement) statements[0]; assertEquals("TABLE_NAME", statement.getTableName()); assertEquals("COLUMN_NAME", statement.getColumnName()); assertTrue(statement.getDefaultValue() instanceof DatabaseFunction); assertEquals("Math.random()", statement.getDefaultValue().toString()); } @Test public void generateStatements_computedDate() throws Exception { AddDefaultValueChange change = new AddDefaultValueChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COLUMN_NAME"); change.setDefaultValueDate("NOW()"); SqlStatement[] statements = change.generateStatements(new MockDatabase()); assertEquals(1, statements.length); AddDefaultValueStatement statement = (AddDefaultValueStatement) statements[0]; assertEquals("TABLE_NAME", statement.getTableName()); assertEquals("COLUMN_NAME", statement.getColumnName()); assertTrue(statement.getDefaultValue() instanceof DatabaseFunction); assertEquals("NOW()", statement.getDefaultValue().toString()); } @Test public void generateStatements_booleanDefaultValue_true() throws Exception { AddDefaultValueChange change = new AddDefaultValueChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COLUMN_NAME"); change.setDefaultValueBoolean(Boolean.TRUE); SqlStatement[] statements = change.generateStatements(new MockDatabase()); assertEquals(1, statements.length); AddDefaultValueStatement statement = (AddDefaultValueStatement) statements[0]; assertEquals("TABLE_NAME", statement.getTableName()); assertEquals("COLUMN_NAME", statement.getColumnName()); assertTrue(statement.getDefaultValue() instanceof Boolean); assertEquals(Boolean.TRUE, statement.getDefaultValue()); } @Test public void generateStatements_booleanDefaultValue_false() throws Exception { AddDefaultValueChange change = new AddDefaultValueChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COLUMN_NAME"); change.setDefaultValueBoolean(Boolean.FALSE); SqlStatement[] statements = change.generateStatements(new MockDatabase()); assertEquals(1, statements.length); AddDefaultValueStatement statement = (AddDefaultValueStatement) statements[0]; assertEquals("TABLE_NAME", statement.getTableName()); assertEquals("COLUMN_NAME", statement.getColumnName()); assertTrue(statement.getDefaultValue() instanceof Boolean); assertEquals(Boolean.FALSE, statement.getDefaultValue()); } // @Test // public void generateStatements_dateDefaultValue() throws Exception { // new DatabaseTestTemplate().testOnAllDatabases(new DatabaseTest() { // // public void performTest(Database database) throws Exception { // java.sql.Date date = new java.sql.Date(new Date().getTime()); // // AddDefaultValueChange change = new AddDefaultValueChange(); // change.setTableName("TABLE_NAME"); // change.setColumnName("COLUMN_NAME"); // ISODateFormat dateFormat = new ISODateFormat(); // change.setDefaultValueDate(dateFormat.format(date)); // // SqlStatement[] statements = change.generateStatements(new MockDatabase()); // assertEquals(1, statements.length); // AddDefaultValueStatement statement = (AddDefaultValueStatement) statements[0]; // // // assertEquals("TABLE_NAME", statement.getTableName()); // assertEquals("COLUMN_NAME", statement.getColumnName()); // assertTrue(statement.getDefaultValue() instanceof java.sql.Date); // assertEquals(date.toString(), statement.getDefaultValue().toString()); // } // }); // } @Override public void getRefactoringName() throws Exception { assertEquals("addDefaultValue", ChangeFactory.getInstance().getChangeMetaData(new AddDefaultValueChange()).getName()); } @Override @Test public void getConfirmationMessage() throws Exception { AddDefaultValueChange change = new AddDefaultValueChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setColumnName("COLUMN_NAME"); assertEquals("Default value added to TABLE_NAME.COLUMN_NAME", change.getConfirmationMessage()); } @Test public void getMD5Sum() throws Exception { AddDefaultValueChange change = new AddDefaultValueChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setColumnName("COLUMN_NAME"); change.setDefaultValue("DEF STRING"); change.setDefaultValueNumeric("42"); change.setDefaultValueBoolean(true); change.setDefaultValueDate("2007-01-02"); String md5sum1 = change.generateCheckSum().toString(); change.setSchemaName("SCHEMA_NAME2"); String md5Sum2 = change.generateCheckSum().toString(); assertFalse(md5sum1.equals(md5Sum2)); change.setSchemaName("SCHEMA_NAME"); String md5Sum3 = change.generateCheckSum().toString(); assertTrue(md5sum1.equals(md5Sum3)); } }
/* * Copyright (C) 2012 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.swift.codec.metadata; import static org.fest.assertions.Assertions.assertThat; import static org.testng.Assert.fail; import com.facebook.swift.codec.ThriftConstructor; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; import com.google.common.reflect.TypeToken; import org.testng.annotations.Test; import java.lang.reflect.Type; import java.util.concurrent.locks.Lock; import com.facebook.swift.codec.ComponentWithMultipleAnnotatedInterfaces; import com.facebook.swift.codec.ComponentWithSetterAndNoBuilder; import com.facebook.swift.codec.DiscreteComponent; import com.facebook.swift.codec.ThriftField.Requiredness; public class TestThriftStructMetadataBuilder { @Test public void testNoId() throws Exception { ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder(new ThriftCatalog(), NoId.class); MetadataErrors metadataErrors = builder.getMetadataErrors(); assertThat(metadataErrors.getErrors()) .as("metadata errors") .hasSize(1); assertThat(metadataErrors.getWarnings()) .as("metadata warnings") .isEmpty(); assertThat(metadataErrors.getErrors().get(0).getMessage()) .as("error message") .containsIgnoringCase("not have an id"); } @ThriftStruct public final static class NoId { @ThriftField public String getField1() { return null; } @ThriftField public void setField1(String value) { } } @Test public void testMultipleIds() throws Exception { ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder(new ThriftCatalog(), MultipleIds.class); MetadataErrors metadataErrors = builder.getMetadataErrors(); assertThat(metadataErrors.getErrors()) .as("metadata errors") .hasSize(1); assertThat(metadataErrors.getWarnings()) .as("metadata warnings") .isEmpty(); assertThat(metadataErrors.getErrors().get(0).getMessage()) .as("error message") .containsIgnoringCase("multiple ids"); } @ThriftStruct public final static class MultipleIds { @ThriftField(name = "foo", value = 1) public void setField1(String value) { } @ThriftField(name = "foo", value = 2) public void setField2(String value) { } @ThriftField(name = "foo") public String getField1() { return null; } @ThriftField(name = "foo") public String getField2() { return null; } } @Test public void testMultipleNames() throws Exception { ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder(new ThriftCatalog(), MultipleNames.class); MetadataErrors metadataErrors = builder.getMetadataErrors(); assertThat(metadataErrors.getErrors()) .as("metadata errors") .isEmpty(); assertThat(metadataErrors.getWarnings()) .as("metadata warnings") .hasSize(1); assertThat(metadataErrors.getWarnings().get(0).getMessage()) .as("error message") .containsIgnoringCase("multiple names"); } @ThriftStruct public final static class MultipleNames { @ThriftField(value = 1, name = "foo") public String getFoo() { return null; } @ThriftField(value = 1, name = "bar") public void setFoo(String value) { } } @Test public void testUnsupportedType() throws Exception { ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder(new ThriftCatalog(), UnsupportedJavaType.class); MetadataErrors metadataErrors = builder.getMetadataErrors(); assertThat(metadataErrors.getErrors()) .as("metadata errors") .hasSize(1); assertThat(metadataErrors.getWarnings()) .as("metadata warnings") .isEmpty(); assertThat(metadataErrors.getErrors().get(0).getMessage()) .as("error message") .containsIgnoringCase("not a supported Java type"); } @ThriftStruct public final static class UnsupportedJavaType { @ThriftField(1) public Lock unsupportedJavaType; } @Test public void testMultipleTypes() throws Exception { ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder(new ThriftCatalog(), MultipleTypes.class); MetadataErrors metadataErrors = builder.getMetadataErrors(); assertThat(metadataErrors.getErrors()) .as("metadata errors") .hasSize(1); assertThat(metadataErrors.getWarnings()) .as("metadata warnings") .isEmpty(); assertThat(metadataErrors.getErrors().get(0).getMessage()) .as("error message") .containsIgnoringCase("multiple types"); } @ThriftStruct public final static class MultipleTypes { @ThriftField(1) public int getFoo() { return 0; } @ThriftField public void setFoo(short value) { } } @Test public void testGenericBuilder() { Type structType = new TypeToken<GenericStruct<String>>() {}.getType(); ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder(new ThriftCatalog(), structType); builder.build(); } @ThriftStruct(builder = GenericStruct.GenericBuilder.class) public final static class GenericStruct<T> { private T fieldValue; private GenericStruct(T fieldValue) { this.fieldValue = fieldValue; } @ThriftField(1) public T getFieldValue() { return fieldValue; } public static class GenericBuilder<T> { private T fieldValue; @ThriftField(1) public GenericBuilder<T> setFieldValue(T fieldValue) { this.fieldValue = fieldValue; return this; } @ThriftConstructor public GenericStruct<T> build() { return new GenericStruct<>(fieldValue); } } } @Test(expectedExceptions = { MetadataErrorException.class }) public void testGenericBuilderForNonGenericStruct() { Type structType = new TypeToken<NonGenericStruct>() {}.getType(); ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder(new ThriftCatalog(), structType); builder.build(); } @ThriftStruct(builder = NonGenericStruct.GenericBuilder.class) public static class NonGenericStruct { private NonGenericStruct() { } public static class GenericBuilder<T> { @ThriftConstructor public NonGenericStruct build() { return new NonGenericStruct(); } } } @Test public void testMulitpleRequiredness() { ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder(new ThriftCatalog(), MultipleRequiredness.class); MetadataErrors metadataErrors = builder.getMetadataErrors(); assertThat(metadataErrors.getErrors()) .as("metadata errors") .hasSize(1); assertThat(metadataErrors.getWarnings()) .as("metadata warnings") .isEmpty(); assertThat(metadataErrors.getErrors().get(0).getMessage()) .as("error message") .containsIgnoringCase("multiple requiredness"); } @ThriftStruct public static final class MultipleRequiredness { @ThriftField(value = 1, requiredness = Requiredness.OPTIONAL) public int getFoo() { return 0; } @ThriftField(value = 1, requiredness = Requiredness.NONE) public void setFoo(int value) { } } @Test public void testMergeableRequiredness() { ThriftStructMetadata metadata = new ThriftStructMetadataBuilder(new ThriftCatalog(), MergeableRequiredness.class).build(); assertThat(metadata.getField(1).getRequiredness()) .as("requiredness of field 'foo'") .isEqualTo(Requiredness.OPTIONAL); } @ThriftStruct public static final class MergeableRequiredness { @ThriftField(value = 1, requiredness = Requiredness.OPTIONAL) public int getFoo() { return 0; } @ThriftField public void setFoo(int value) { } } @Test public void testStructInterface() { ThriftStructMetadata metadata = new ThriftStructMetadataBuilder( new ThriftCatalog(), DiscreteComponent.class).build(); assertThat(metadata.getFields()) .as("metadata for a valid struct interface") .hasSize(3); } @Test public void testInvalidStructWithMultipleAnnotatedInterfaces() { ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder( new ThriftCatalog(), ComponentWithMultipleAnnotatedInterfaces.class); MetadataErrors errors = builder.getMetadataErrors(); assertThat(errors.getErrors()).as("metadata errors").isNotEmpty(); for (MetadataErrorException e : errors.getErrors()) { String msg = e.getMessage(); if (msg.contains("is annotated with @ThriftStruct, however there is also a @ThriftStruct annotation on")) { return; } } fail("should have had an error about multiple annotations."); } @Test public void testInvalidStructClassImplementsAnnotatedInterface() { ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder( new ThriftCatalog(), ComponentWithMultipleAnnotatedInterfaces.class); MetadataErrors errors = builder.getMetadataErrors(); assertThat(errors.getErrors()).as("metadata errors").isNotEmpty(); for (MetadataErrorException e : errors.getErrors()) { String msg = e.getMessage(); if (msg.contains("is annotated with @ThriftStruct, however there is also a @ThriftStruct annotation on")) { return; } } fail("should have had an error about multiple annotations."); } @Test public void testInvalidInterfaceStructWithNoBuilder() { ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder( new ThriftCatalog(), ComponentWithSetterAndNoBuilder.class); MetadataErrors errors = builder.getMetadataErrors(); assertThat(errors.getErrors()).as("metadata errors").isNotEmpty(); for (MetadataErrorException e : errors.getErrors()) { String msg = e.getMessage(); if (msg.contains("Interface structs must define a builder")) { return; } } fail("should have had an error saying that interface structs must define a builder."); } @Test public void testNonFinalStructsOk() { ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder(new ThriftCatalog(), NotFinalStruct.class); builder.build(); } @ThriftStruct public static class NotFinalStruct { } }
/** * Copyright 2014-16 by Riccardo Massera (TheCoder4.Eu) and Stephan Rauh (http://www.beyondjava.net). * * This file is part of BootsFaces. * * 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 net.bootsfaces.component.inputText; import java.io.IOException; import javax.el.ValueExpression; import javax.faces.component.UIComponent; import javax.faces.component.ValueHolder; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.render.FacesRenderer; import net.bootsfaces.C; import net.bootsfaces.component.ajax.AJAXRenderer; import net.bootsfaces.component.inputSecret.InputSecret; import net.bootsfaces.render.CoreRenderer; import net.bootsfaces.render.H; import net.bootsfaces.render.R; import net.bootsfaces.render.Responsive; import net.bootsfaces.render.Tooltip; @FacesRenderer(componentFamily = C.BSFCOMPONENT, rendererType = "net.bootsfaces.component.inputText.InputText") public class InputTextRenderer extends CoreRenderer { @Override public void decode(FacesContext context, UIComponent component) { InputText inputText = (InputText) component; if (inputText.isDisabled() || inputText.isReadonly()) { return; } decodeBehaviors(context, inputText); String clientId = inputText.getClientId(context); String name = inputText.getName(); if (null == name) { name = "input_" + clientId; } String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(name); if (submittedValue != null) { inputText.setSubmittedValue(submittedValue); } new AJAXRenderer().decode(context, component, name); } /** * This method is called by the JSF framework to get the type-safe value of the attribute. Do not delete this * method. */ @Override public Object getConvertedValue(FacesContext fc, UIComponent c, Object sval) throws ConverterException { Converter cnv = resolveConverter(fc, c); if (cnv != null) { return cnv.getAsObject(fc, c, (String) sval); } else { return sval; } } protected Converter resolveConverter(FacesContext context, UIComponent c) { if (!(c instanceof ValueHolder)) { return null; } Converter cnv = ((ValueHolder) c).getConverter(); if (cnv != null) { return cnv; } else { ValueExpression ve = c.getValueExpression("value"); if (ve != null) { Class<?> valType = ve.getType(context.getELContext()); if (valType != null) { return context.getApplication().createConverter(valType); } } return null; } } @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { if (!component.isRendered()) { return; } InputText inputText = (InputText) component; ResponseWriter rw = context.getResponseWriter(); String clientId = inputText.getClientId(); String responsiveLabelClass=null; String label = inputText.getLabel(); { if (!inputText.isRenderLabel()) { label = null; } } if (null != label) { responsiveLabelClass = Responsive.getResponsiveLabelClass(inputText); } String responsiveStyleClass = Responsive.getResponsiveStyleClass(inputText, false).trim(); if (responsiveStyleClass.length() > 0 && responsiveLabelClass == null) { rw.startElement("div", component); rw.writeAttribute("class", responsiveStyleClass, "class"); } // "Prepend" facet UIComponent prep = inputText.getFacet("prepend"); // "Append" facet UIComponent app = inputText.getFacet("append"); boolean prepend = (prep != null); boolean append = (app != null); // Define TYPE ( if null set default = text ) // support for b:inputSecret String t; if (component instanceof InputSecret) { t = "password"; } else { // ordinary input fields t = inputText.getType(); if (t == null) t = "text"; } rw.startElement("div", component); if (null != inputText.getDir()) { rw.writeAttribute("dir", inputText.getDir(), "dir"); } Tooltip.generateTooltip(context, inputText, rw); rw.writeAttribute("id", clientId, "id"); // clientId if (inputText.isInline()) { rw.writeAttribute("class", "form-inline", "class"); } else { rw.writeAttribute("class", "form-group", "class"); } if (label != null) { rw.startElement("label", component); rw.writeAttribute("for", "input_" + clientId, "for"); // "input_" + clientId generateErrorAndRequiredClass(inputText, rw, clientId, inputText.getLabelStyleClass(), responsiveLabelClass, "control-label"); writeAttribute(rw, "style", inputText.getLabelStyle()); rw.writeText(label, null); rw.endElement("label"); } if (responsiveStyleClass.length() > 0 && responsiveLabelClass != null) { rw.startElement("div", component); rw.writeAttribute("class", responsiveStyleClass, "class"); } if (append || prepend) { rw.startElement("div", component); rw.writeAttribute("class", "input-group", "class"); } if (prepend) { R.decorateFacetComponent(inputText, prep, context, rw); } // Input rw.startElement("input", inputText); String fieldId = inputText.getFieldId(); if (null == fieldId) { fieldId = "input_" + clientId; } rw.writeAttribute("id", fieldId, null); // "input_" + clientId String name = inputText.getName(); // System.out.println(name); if (null == name) { name = "input_" + clientId; } rw.writeAttribute("name", name, null); rw.writeAttribute("type", t, null); generateStyleClass(inputText, rw); String ph = inputText.getPlaceholder(); if (ph != null) { rw.writeAttribute("placeholder", ph, null); } if (inputText.isDisabled()) { rw.writeAttribute("disabled", "disabled", null); } if (inputText.isReadonly()) { rw.writeAttribute("readonly", "readonly", null); } // Encode attributes (HTML 4 pass-through + DHTML) renderPassThruAttributes(context, component, H.INPUT_TEXT); String autocomplete = inputText.getAutocomplete(); if ((autocomplete != null) && (autocomplete.equals("off"))) { rw.writeAttribute("autocomplete", "off", null); } if (inputText.isTags() && (!inputText.isTypeahead())) { rw.writeAttribute("data-role", "tagsinput", null); } String v = getValue2Render(context, component); rw.writeAttribute("value", v, null); // Render Ajax Capabilities AJAXRenderer.generateBootsFacesAJAXAndJavaScript(FacesContext.getCurrentInstance(), inputText, rw); rw.endElement("input"); if (append) { R.decorateFacetComponent(inputText, app, context, rw); } if (append || prepend) { rw.endElement("div"); } // input-group rw.endElement("div"); // form-group if (responsiveStyleClass.length() > 0) { rw.endElement("div"); } Tooltip.activateTooltips(context, inputText); if (inputText.isTypeahead()) { String id = component.getClientId(); id = id.replace(":", "_"); // we need to escape the id for jQuery rw.startElement("script", component); String typeaheadname = id + "_typeahead"; if (inputText.isTags()) { String js = "var engine = new Bloodhound({" + // "name: '" + typeaheadname + "'," + // "local: " + getTypeaheadObjectArray(inputText) + "," + // "datumTokenizer: function(d) {" + // " return Bloodhound.tokenizers.whitespace(d.val);" + // "}," + // "queryTokenizer: Bloodhound.tokenizers.whitespace" + // "});"; js += "$('." + id + "').tagsinput({" + // "typeaheadjs: {" + // " name: 'animals'," + // " displayKey: 'val'," + // " valueKey: 'val'," + // " source: engine.ttAdapter()" + // "}" + // "});";// rw.writeText(js, null); } else { String options = ""; options = addOption(options, "hint:" + inputText.isTypeaheadHint()); options = addOption(options, "highlight:" + inputText.isTypeaheadHighlight()); options = addOption(options, "minLength:" + inputText.getTypeaheadMinLength()); String options2 = ""; options2 = addOption(options2, "limit:" + inputText.getTypeaheadLimit()); options2 = addOption(options2, "name:'" + typeaheadname + "'"); options2 = addOption(options2, "source: BsF.substringMatcher(" + getTypeaheadValueArray(inputText) + ")"); rw.writeText("$('." + id + "').typeahead({" + options + "},{" + options2 + "});", null); } rw.endElement("script"); } } private String addOption(String options, String newOption) { if (options.length() > 0) { options += ","; } return options + newOption; } private String getTypeaheadValueArray(InputText inputText) { String s = inputText.getTypeaheadValues(); if (null == s) return null; s = s.trim(); if (!s.contains("\'")) { String[] parts = s.split(","); StringBuilder b = new StringBuilder(s.length() * 2); for (String p : parts) { if (b.length() > 0) { b.append(','); } b.append('\''); b.append(p.trim()); b.append('\''); } s = b.toString(); } return "[" + s + "]"; } private String getTypeaheadObjectArray(InputText inputText) { String s = inputText.getTypeaheadValues(); if (null == s) return null; s = s.trim(); if (!s.contains("\'")) { String[] parts = s.split(","); StringBuilder b = new StringBuilder(s.length() * 2); for (String p : parts) { if (b.length() > 0) { b.append(','); } b.append("{val:"); b.append('\''); b.append(p.trim()); b.append('\''); b.append('}'); } s = b.toString(); } return "[" + s + "]"; } private void generateStyleClass(InputText inputText, ResponseWriter rw) throws IOException { StringBuilder sb; String s; sb = new StringBuilder(20); // optimize int sb.append("form-control"); String fsize = inputText.getFieldSize(); if (fsize != null) { sb.append(" input-").append(fsize); } // styleClass and class support String sclass = inputText.getStyleClass(); if (sclass != null) { sb.append(" ").append(sclass); } sb.append(" ").append(getErrorAndRequiredClass(inputText, inputText.getClientId())); if (inputText.isTypeahead()) { sb.append(" ").append(inputText.getClientId().replace(":","_")); } s = sb.toString().trim(); if (s != null && s.length() > 0) { rw.writeAttribute("class", s, "class"); } } }
/** * Licensed to Apereo under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright ownership. Apereo * 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 the * following location: * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <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.apereo.portal.portlets.lookup; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.annotation.PostConstruct; import javax.portlet.PortletPreferences; import javax.portlet.PortletRequest; import org.apereo.portal.EntityIdentifier; import org.apereo.portal.portlets.search.DisplayNameComparator; import org.apereo.portal.security.IAuthorizationPrincipal; import org.apereo.portal.security.IPermission; import org.apereo.portal.security.IPerson; import org.apereo.portal.services.AuthorizationService; import org.jasig.services.persondir.IPersonAttributeDao; import org.jasig.services.persondir.IPersonAttributes; import org.jasig.services.persondir.support.NamedPersonImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.webflow.context.ExternalContext; /** Implements logic and helper methods for the person-lookup web flow. */ public class PersonLookupHelperImpl implements IPersonLookupHelper { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); private IPersonAttributeDao personAttributeDao; public IPersonAttributeDao getPersonAttributeDao() { return personAttributeDao; } /** The {@link IPersonAttributeDao} used to perform lookups. */ public void setPersonAttributeDao(IPersonAttributeDao personLookupDao) { this.personAttributeDao = personLookupDao; } private int maxResults = 10; public void setMaxResults(int maxResults) { this.maxResults = maxResults; } public int getMaxResults() { return maxResults; } private int searchThreadCount = 10; // Default to a high enough value that it doesn't cause issues during a load test private long searchThreadTimeoutSeconds = 60; /** * Set the number of concurrent threads process person search results in parallel. * * @param searchThreadCount number of concurrent threads for processing search results */ public void setSearchThreadCount(int searchThreadCount) { this.searchThreadCount = searchThreadCount; } /** * Set the max number of seconds the threads doing the person search results should wait for a * result. <br> * TODO This is to prevent waiting indefinitely on a hung worker thread. In the future, would be * nice to get the portlet's timeout value and set this to a second or two fewer. * * @param searchThreadTimeoutSeconds Maximum number of seconds to wait for thread to respond */ public void setSearchThreadTimeoutSeconds(long searchThreadTimeoutSeconds) { this.searchThreadTimeoutSeconds = searchThreadTimeoutSeconds; } private ExecutorService executor; @PostConstruct public void initializeSearchExecutor() { executor = Executors.newFixedThreadPool(searchThreadCount); } /* (non-Javadoc) * @see org.apereo.portal.portlets.swapper.IPersonLookupHelper#getQueryAttributes(org.springframework.webflow.context.ExternalContext) */ @Override public Set<String> getQueryAttributes(ExternalContext externalContext) { final PortletRequest portletRequest = (PortletRequest) externalContext.getNativeRequest(); final PortletPreferences preferences = portletRequest.getPreferences(); final Set<String> queryAttributes; final String[] configuredAttributes = preferences.getValues(PERSON_LOOKUP_PERSON_LOOKUP_QUERY_ATTRIBUTES, null); final String[] excludedAttributes = preferences.getValues(PERSON_LOOKUP_PERSON_LOOKUP_QUERY_ATTRIBUTES_EXCLUDES, null); //If attributes are configured in portlet prefs just use them if (configuredAttributes != null) { queryAttributes = new LinkedHashSet<String>(Arrays.asList(configuredAttributes)); } //Otherwise provide all available attributes from the IPersonAttributeDao else { final Set<String> availableAttributes = this.personAttributeDao.getAvailableQueryAttributes(); queryAttributes = new TreeSet<String>(availableAttributes); } //Remove excluded attributes if (excludedAttributes != null) { for (final String excludedAttribute : excludedAttributes) { queryAttributes.remove(excludedAttribute); } } return queryAttributes; } /* (non-Javadoc) * @see org.apereo.portal.portlets.swapper.IPersonLookupHelper#getDisplayAttributes(org.springframework.webflow.context.ExternalContext) */ @Override public Set<String> getDisplayAttributes(ExternalContext externalContext) { final PortletRequest portletRequest = (PortletRequest) externalContext.getNativeRequest(); final PortletPreferences preferences = portletRequest.getPreferences(); final Set<String> displayAttributes; final String[] configuredAttributes = preferences.getValues(PERSON_LOOKUP_PERSON_DETAILS_DETAILS_ATTRIBUTES, null); final String[] excludedAttributes = preferences.getValues( PERSON_LOOKUP_PERSON_DETAILS_DETAILS_ATTRIBUTES_EXCLUDES, null); //If attributes are configured in portlet prefs use those the user has if (configuredAttributes != null) { displayAttributes = new LinkedHashSet<String>(); displayAttributes.addAll(Arrays.asList(configuredAttributes)); } //Otherwise provide all available attributes from the IPersonAttributes else { displayAttributes = new TreeSet<String>(personAttributeDao.getPossibleUserAttributeNames()); } //Remove any excluded attributes if (excludedAttributes != null) { for (final String excludedAttribute : excludedAttributes) { displayAttributes.remove(excludedAttribute); } } return displayAttributes; } /* (non-Javadoc) * @see org.apereo.portal.portlets.lookup.IPersonLookupHelper#getSelf(org.springframework.webflow.context.ExternalContext) */ @Override public IPersonAttributes getSelf(ExternalContext externalContext) { final PortletRequest portletRequest = (PortletRequest) externalContext.getNativeRequest(); final String username = portletRequest.getRemoteUser(); return this.personAttributeDao.getPerson(username); } /* (non-Javadoc) * @see org.apereo.portal.portlets.lookup.IPersonLookupHelper#searchForPeople(org.apereo.portal.security.IPerson, java.util.Map) */ @Override public List<IPersonAttributes> searchForPeople( final IPerson searcher, final Map<String, Object> query) { // get the IAuthorizationPrincipal for the searching user final IAuthorizationPrincipal principal = getPrincipalForUser(searcher); // build a set of all possible user attributes the current user has // permission to view final Set<String> permittedAttributes = getPermittedAttributes(principal); // remove any query attributes that the user does not have permission // to view final Map<String, Object> inUseQuery = new HashMap<>(); for (Map.Entry<String, Object> queryEntry : query.entrySet()) { final String attr = queryEntry.getKey(); if (permittedAttributes.contains(attr)) { inUseQuery.put(attr, queryEntry.getValue()); } else { this.logger.warn( "User '" + searcher.getName() + "' attempted searching on attribute '" + attr + "' which is not allowed in the current configuration. The attribute will be ignored."); } } // ensure the query has at least one search attribute defined if (inUseQuery.keySet().size() == 0) { throw new IllegalArgumentException("Search query is empty"); } // get the set of people matching the search query final Set<IPersonAttributes> people = this.personAttributeDao.getPeople(inUseQuery); if (people == null) { return Collections.emptyList(); } // To improve efficiency and not do as many permission checks or person directory searches, // if we have too many results and all people in the returned set of personAttributes have // a displayName, pre-sort the set and limit it to maxResults. The typical use case is that // LDAP returns results that have the displayName populated. Note that a disadvantage of this // approach is that the smaller result set may have entries that permissions prevent the // current users from viewing the person and thus reduce the number of final results, but // that is rare (typical use case is users can't view administrative internal accounts or the // system account, none of which tend to be in LDAP). We could retain a few more than maxResults // to offset that chance, but IMHO not worth the cost of extra external queries. List<IPersonAttributes> peopleList = new ArrayList<>(people); if (peopleList.size() > maxResults && allListItemsHaveDisplayName(peopleList)) { logger.debug( "All items contained displayName; pre-sorting list of size {} and truncating to", peopleList.size(), maxResults); // sort the list by display name Collections.sort(peopleList, new DisplayNameComparator()); peopleList = peopleList.subList(0, maxResults); } // Construct a new representation of the persons limited to attributes the searcher // has permissions to view. Will change order of the list. List<IPersonAttributes> list = getVisiblePersons(principal, permittedAttributes, peopleList); // Sort the list by display name Collections.sort(list, new DisplayNameComparator()); // limit the list to a maximum number of returned results if (list.size() > maxResults) { list = list.subList(0, maxResults); } return list; } /** * Returns a list of the personAttributes that this principal has permission to view. This * implementation does the check on the list items in parallel because personDirectory is * consulted for non-admin principals to get the person attributes which is really slow if done * on N entries in parallel because personDirectory often goes out to LDAP or another external * source for additional attributes. This processing will not retain list order. * * @param principal user performing the search * @param permittedAttributes set of attributes the principal has permission to view * @param peopleList list of people returned from the search * @return UNORDERED list of visible persons */ private List<IPersonAttributes> getVisiblePersons( final IAuthorizationPrincipal principal, final Set<String> permittedAttributes, List<IPersonAttributes> peopleList) { List<Future<IPersonAttributes>> futures = new ArrayList<>(); List<IPersonAttributes> list = new ArrayList<>(); // Ugly. PersonDirectory requires RequestContextHolder to be set for each thread, so pass it // into the callable. RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); // For each person in the list, check to see if the current user has permission to view this user for (IPersonAttributes person : peopleList) { Callable<IPersonAttributes> worker = new FetchVisiblePersonCallable( principal, person, permittedAttributes, requestAttributes); Future<IPersonAttributes> task = executor.submit(worker); futures.add(task); } for (Future<IPersonAttributes> future : futures) { try { final IPersonAttributes visiblePerson = future.get(searchThreadTimeoutSeconds, TimeUnit.SECONDS); if (visiblePerson != null) { list.add(visiblePerson); } } catch (InterruptedException e) { logger.error("Processing person search interrupted", e); } catch (ExecutionException e) { logger.error("Error Processing person search", e); } catch (TimeoutException e) { future.cancel(true); logger.warn( "Exceeded {} ms waiting for getVisiblePerson to return result", searchThreadTimeoutSeconds); } } logger.debug("Found {} results", list.size()); return list; } /** * Utility class for executor framework for search persons processing. Ugly - person directory * needs the requestAttributes in the RequestContextHolder set for each thread from the caller. */ private class FetchVisiblePersonCallable implements Callable<IPersonAttributes> { private IAuthorizationPrincipal principal; private IPersonAttributes person; private Set<String> permittedAttributes; private RequestAttributes requestAttributes; public FetchVisiblePersonCallable( IAuthorizationPrincipal principal, IPersonAttributes person, Set<String> permittedAttributes, RequestAttributes requestAttributes) { this.principal = principal; this.person = person; this.permittedAttributes = permittedAttributes; this.requestAttributes = requestAttributes; } /** * If the current user has permission to view this person, construct a new representation of * the person limited to attributes the searcher has permissions to view, else return null * if user cannot view. * * @return person attributes user can view. Null if user can't view person. * @throws Exception */ @Override public IPersonAttributes call() throws Exception { RequestContextHolder.setRequestAttributes(requestAttributes); return getVisiblePerson(principal, person, permittedAttributes); } } /** * Utility class to determine if all items in the list of people have a displayName. * * @param people list of personAttributes * @return true if all list items have an attribute displayName */ private boolean allListItemsHaveDisplayName(List<IPersonAttributes> people) { for (IPersonAttributes person : people) { if (person.getAttributeValue("displayName") == null) { return false; } } return true; } /* (non-Javadoc) * @see org.apereo.portal.portlets.lookup.IPersonLookupHelper#findPerson(org.apereo.portal.security.IPerson, java.lang.String) */ @Override public IPersonAttributes findPerson(final IPerson searcher, final String username) { // get the IAuthorizationPrincipal for the searching user final IAuthorizationPrincipal principal = getPrincipalForUser(searcher); // build a set of all possible user attributes the current user has // permission to view final Set<String> permittedAttributes = getPermittedAttributes(principal); // get the set of people matching the search query final IPersonAttributes person = this.personAttributeDao.getPerson(username); if (person == null) { logger.info("No user found with username matching " + username); return null; } // if the current user has permission to view this person, construct // a new representation of the person limited to attributes the // searcher has permissions to view return getVisiblePerson(principal, person, permittedAttributes); } /** * Get the authoriztaion principal matching the supplied IPerson. * * @param person * @return */ protected IAuthorizationPrincipal getPrincipalForUser(final IPerson person) { final EntityIdentifier ei = person.getEntityIdentifier(); return AuthorizationService.instance().newPrincipal(ei.getKey(), ei.getType()); } /** * Get the set of all user attribute names defined in the portal for which the specified * principal has the attribute viewing permission. * * @param principal * @return */ protected Set<String> getPermittedAttributes(final IAuthorizationPrincipal principal) { final Set<String> attributeNames = personAttributeDao.getPossibleUserAttributeNames(); return getPermittedAttributes(principal, attributeNames); } /** * Filter the specified set of user attribute names to contain only those that the specified * principal may perform <code>IPermission.VIEW_USER_ATTRIBUTE_ACTIVITY</code>. These are user * attributes the user has general permission to view, for all visible users. * * @param principal * @param attributeNames * @return */ protected Set<String> getPermittedAttributes( final IAuthorizationPrincipal principal, final Set<String> attributeNames) { final Set<String> permittedAttributes = new HashSet<>(); for (String attr : attributeNames) { if (principal.hasPermission( IPermission.PORTAL_USERS, IPermission.VIEW_USER_ATTRIBUTE_ACTIVITY, attr)) { permittedAttributes.add(attr); } } return permittedAttributes; } /** * Provide a complete set of user attribute names that the specified principal may view within * his or her own collection. These will be attributes for which the user has <em>either</em> * <code>IPermission.VIEW_USER_ATTRIBUTE_ACTIVITY</code> or <code> * IPermission.VIEW_OWN_USER_ATTRIBUTE_ACTIVITY</code>. * * @param principal Represents a portal user who wishes to view user attributes * @param generallyPermittedAttributes The collection of user attribute name this user may view * for any visible user * @since 5.0 */ protected Set<String> getPermittedOwnAttributes( final IAuthorizationPrincipal principal, final Set<String> generallyPermittedAttributes) { // The permttedOwnAttributes collection includes all the generallyPermittedAttributes final Set<String> rslt = new HashSet<>(generallyPermittedAttributes); for (String attr : personAttributeDao.getPossibleUserAttributeNames()) { if (principal.hasPermission( IPermission.PORTAL_USERS, IPermission.VIEW_OWN_USER_ATTRIBUTE_ACTIVITY, attr)) { rslt.add(attr); } } return rslt; } /** * Filter an IPersonAttributes for a specified viewing principal. The returned person will * contain only the attributes provided in the permitted attributes list. <code>null</code> if * the principal does not have permission to view the user. * * @param principal * @param person * @param generallyPermittedAttributes * @return */ protected IPersonAttributes getVisiblePerson( final IAuthorizationPrincipal principal, final IPersonAttributes person, final Set<String> generallyPermittedAttributes) { // first check to see if the principal has permission to view this person. Unfortunately for // non-admin users, this will result in a call to PersonDirectory (which may go out to LDAP or // other external systems) to find out what groups the person is in to see if the principal // has permission or deny through one of the contained groups. if (person.getName() != null && principal.hasPermission( IPermission.PORTAL_USERS, IPermission.VIEW_USER_ACTIVITY, person.getName())) { // If the user has permission, filter the person attributes according // to the specified permitted attributes; the collection of permitted // attributes can be different based on whether the user is trying to // access information about him/herself. final Set<String> permittedAttributes = person.getName().equals(principal.getKey()) ? getPermittedOwnAttributes(principal, generallyPermittedAttributes) : generallyPermittedAttributes; final Map<String, List<Object>> visibleAttributes = new HashMap<>(); for (String attr : person.getAttributes().keySet()) { if (permittedAttributes.contains(attr)) { visibleAttributes.put(attr, person.getAttributeValues(attr)); } } // use the filtered attribute list to create and return a new // person object final IPersonAttributes visiblePerson = new NamedPersonImpl(person.getName(), visibleAttributes); return visiblePerson; } else { logger.debug( "Principal " + principal.getKey() + " does not have permissions to view user " + person.getName()); return null; } } }
/** * Copyright Pravega 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 * * 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.pravega.controller.task.KeyValueTable; import com.google.common.annotations.VisibleForTesting; import io.pravega.client.EventStreamClientFactory; import io.pravega.client.stream.EventWriterConfig; import io.pravega.client.tables.KeyValueTableConfiguration; import io.pravega.common.Exceptions; import io.pravega.common.concurrent.Futures; import io.pravega.common.tracing.TagLogger; import io.pravega.controller.retryable.RetryableException; import io.pravega.controller.server.SegmentHelper; import io.pravega.controller.server.eventProcessor.ControllerEventProcessors; import io.pravega.controller.server.security.auth.GrpcAuthHelper; import io.pravega.controller.store.kvtable.AbstractKVTableMetadataStore; import io.pravega.controller.store.kvtable.KVTableMetadataStore; import io.pravega.controller.store.kvtable.KVTableState; import io.pravega.controller.store.stream.OperationContext; import io.pravega.controller.store.stream.StoreException; import io.pravega.controller.stream.api.grpc.v1.Controller.CreateKeyValueTableStatus; import io.pravega.controller.stream.api.grpc.v1.Controller.DeleteKVTableStatus; import io.pravega.controller.task.EventHelper; import io.pravega.controller.util.RetryHelper; import io.pravega.shared.controller.event.kvtable.CreateTableEvent; import io.pravega.shared.controller.event.kvtable.DeleteTableEvent; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; import lombok.Synchronized; import org.slf4j.LoggerFactory; import static io.pravega.controller.task.Stream.TaskStepsRetryHelper.withRetries; import static io.pravega.shared.NameUtils.getQualifiedTableSegmentName; /** * Collection of metadata update tasks on KeyValueTable. * <p> * Any update to the task method signature should be avoided, since it can cause problems during upgrade. * Instead, a new overloaded method may be created with the same task annotation name but a new version. */ public class TableMetadataTasks implements AutoCloseable { private static final TagLogger log = new TagLogger(LoggerFactory.getLogger(TableMetadataTasks.class)); private static final int NUM_RETRIES = 10; private final KVTableMetadataStore kvtMetadataStore; private final SegmentHelper segmentHelper; private final ScheduledExecutorService executor; private final ScheduledExecutorService eventExecutor; private final String hostId; private final GrpcAuthHelper authHelper; private EventHelper eventHelper; public TableMetadataTasks(final KVTableMetadataStore kvtMetadataStore, final SegmentHelper segmentHelper, final ScheduledExecutorService executor, final ScheduledExecutorService eventExecutor, final String hostId, GrpcAuthHelper authHelper) { this.kvtMetadataStore = kvtMetadataStore; this.segmentHelper = segmentHelper; this.executor = executor; this.eventExecutor = eventExecutor; this.hostId = hostId; this.authHelper = authHelper; } @VisibleForTesting public TableMetadataTasks(final KVTableMetadataStore kvtMetadataStore, final SegmentHelper segmentHelper, final ScheduledExecutorService executor, final ScheduledExecutorService eventExecutor, final String hostId, GrpcAuthHelper authHelper, EventHelper helper) { this.kvtMetadataStore = kvtMetadataStore; this.segmentHelper = segmentHelper; this.executor = executor; this.eventExecutor = eventExecutor; this.hostId = hostId; this.authHelper = authHelper; this.eventHelper = helper; } @Synchronized public void initializeStreamWriters(final EventStreamClientFactory clientFactory, final String streamName) { if (this.eventHelper != null) { this.eventHelper.close(); } this.eventHelper = new EventHelper(clientFactory.createEventWriter(streamName, ControllerEventProcessors.CONTROLLER_EVENT_SERIALIZER, EventWriterConfig.builder().enableConnectionPooling(true).retryAttempts(Integer.MAX_VALUE).build()), this.executor, this.eventExecutor, hostId, ((AbstractKVTableMetadataStore) this.kvtMetadataStore).getHostTaskIndex()); } /** * Create a Key-Value Table. * * @param scope scope name. * @param kvtName KVTable name. * @param kvtConfig KVTable configuration. * @param createTimestamp KVTable creation timestamp. * @param requestId request id * @return update status. */ public CompletableFuture<CreateKeyValueTableStatus.Status> createKeyValueTable(String scope, String kvtName, KeyValueTableConfiguration kvtConfig, final long createTimestamp, long requestId) { OperationContext context = kvtMetadataStore.createContext(scope, kvtName, requestId); return RetryHelper.withRetriesAsync(() -> { // 1. check if scope with this name exists... return kvtMetadataStore.checkScopeExists(scope, context, executor) .thenCompose(exists -> { if (!exists) { return CompletableFuture.completedFuture(CreateKeyValueTableStatus.Status.SCOPE_NOT_FOUND); } return kvtMetadataStore.isScopeSealed(scope, context, executor).thenCompose(isScopeSealed -> { if (isScopeSealed) { return CompletableFuture.completedFuture(CreateKeyValueTableStatus.Status.SCOPE_NOT_FOUND); } //2. check state of the KVTable, if found return Futures.exceptionallyExpecting(kvtMetadataStore.getState(scope, kvtName, true, context, executor), e -> Exceptions.unwrap(e) instanceof StoreException.DataNotFoundException, KVTableState.UNKNOWN) .thenCompose(state -> { if (state.equals(KVTableState.UNKNOWN) || state.equals(KVTableState.CREATING)) { //3. get a new UUID for the KVTable we will be creating. UUID id = kvtMetadataStore.newScope(scope).newId(); CreateTableEvent event = new CreateTableEvent(scope, kvtName, kvtConfig.getPartitionCount(), kvtConfig.getPrimaryKeyLength(), kvtConfig.getSecondaryKeyLength(), createTimestamp, requestId, id, kvtConfig.getRolloverSizeBytes()); //4. Update ScopeTable with the entry for this KVT and Publish the event for creation return eventHelper.addIndexAndSubmitTask(event, () -> kvtMetadataStore.createEntryForKVTable(scope, kvtName, id, context, executor)) .thenCompose(x -> isCreateProcessed(scope, kvtName, kvtConfig, createTimestamp, executor, context)); } log.info(requestId, "KeyValue table {}/{} already exists", scope, kvtName); return isCreateProcessed(scope, kvtName, kvtConfig, createTimestamp, executor, context); }); }); }); }, e -> Exceptions.unwrap(e) instanceof RetryableException, NUM_RETRIES, executor); } /** * Delete a KeyValueTable. * * @param scope scope. * @param kvtName KeyValueTable name. * @param requestId request id. * @return delete status. */ public CompletableFuture<DeleteKVTableStatus.Status> deleteKeyValueTable(final String scope, final String kvtName, long requestId) { OperationContext context = kvtMetadataStore.createContext(scope, kvtName, requestId); return RetryHelper.withRetriesAsync(() -> { return Futures.exceptionallyExpecting(kvtMetadataStore.getState(scope, kvtName, false, context, executor), e -> Exceptions.unwrap(e) instanceof StoreException.DataNotFoundException, KVTableState.UNKNOWN) .thenCompose(state -> { if (KVTableState.UNKNOWN.equals(state)) { return CompletableFuture.completedFuture(DeleteKVTableStatus.Status.TABLE_NOT_FOUND); } else { return kvtMetadataStore.getKVTable(scope, kvtName, context).getId(context) .thenCompose(id -> { DeleteTableEvent deleteEvent = new DeleteTableEvent(scope, kvtName, requestId, UUID.fromString(id)); return eventHelper.addIndexAndSubmitTask(deleteEvent, () -> kvtMetadataStore.setState(scope, kvtName, KVTableState.DELETING, context, executor)) .thenCompose(x -> eventHelper.checkDone(() -> isDeleted(scope, kvtName, context))) .thenApply(y -> DeleteKVTableStatus.Status.SUCCESS); }); } }); }, e -> Exceptions.unwrap(e) instanceof RetryableException, NUM_RETRIES, executor); } public CompletableFuture<Void> deleteSegments(String scope, String kvt, Set<Long> segmentsToDelete, String delegationToken, long requestId) { log.debug(requestId, "{}/{} deleting {} segments", scope, kvt, segmentsToDelete.size()); return Futures.allOf(segmentsToDelete .stream() .parallel() .map(segment -> deleteSegment(scope, kvt, segment, delegationToken, requestId)) .collect(Collectors.toList())); } public CompletableFuture<Void> deleteSegment(String scope, String kvt, long segmentId, String delegationToken, long requestId) { final String qualifiedTableSegmentName = getQualifiedTableSegmentName(scope, kvt, segmentId); log.debug(requestId, "Deleting segment {} with Id {}", qualifiedTableSegmentName, segmentId); return Futures.toVoid(withRetries(() -> segmentHelper.deleteTableSegment(qualifiedTableSegmentName, false, delegationToken, requestId), executor)); } @VisibleForTesting CompletableFuture<Boolean> isDeleted(String scope, String kvtName, OperationContext context) { return Futures.exceptionallyExpecting(kvtMetadataStore.getState(scope, kvtName, true, context, executor), e -> Exceptions.unwrap(e) instanceof StoreException.DataNotFoundException, KVTableState.UNKNOWN) .thenCompose(state -> { if (state.equals(KVTableState.UNKNOWN)) { return CompletableFuture.completedFuture(Boolean.TRUE); } else { return CompletableFuture.completedFuture(Boolean.FALSE); } }); } private CompletableFuture<CreateKeyValueTableStatus.Status> isCreateProcessed(String scope, String kvtName, KeyValueTableConfiguration kvtConfig, final long createTimestamp, Executor executor, OperationContext context) { return eventHelper.checkDone(() -> isCreated(scope, kvtName, executor, context)) .thenCompose(y -> isSameCreateRequest(scope, kvtName, kvtConfig, createTimestamp, executor, context)) .thenCompose(same -> { if (same) { return CompletableFuture.completedFuture(CreateKeyValueTableStatus.Status.SUCCESS); } else { return CompletableFuture.completedFuture(CreateKeyValueTableStatus.Status.TABLE_EXISTS); } }); } private CompletableFuture<Boolean> isCreated(String scope, String kvtName, Executor executor, OperationContext context) { return Futures.exceptionallyExpecting(kvtMetadataStore.getState(scope, kvtName, true, context, executor), e -> Exceptions.unwrap(e) instanceof StoreException.DataNotFoundException, KVTableState.UNKNOWN) .thenApply(state -> { log.debug(context.getRequestId(), "KVTable State is {}", state.toString()); return state.equals(KVTableState.ACTIVE); }); } private CompletableFuture<Boolean> isSameCreateRequest(final String requestScopeName, final String requestKVTName, final KeyValueTableConfiguration requestKVTConfig, final long requestCreateTimestamp, Executor executor, final OperationContext context) { return kvtMetadataStore.getCreationTime(requestScopeName, requestKVTName, context, executor) .thenCompose(creationTime -> { if (creationTime == requestCreateTimestamp) { return kvtMetadataStore.getConfiguration(requestScopeName, requestKVTName, context, executor) .thenCompose(cfg -> { if (cfg.getPartitionCount() == requestKVTConfig.getPartitionCount()) { return CompletableFuture.completedFuture(Boolean.TRUE); } else { return CompletableFuture.completedFuture(Boolean.FALSE); } }); } return CompletableFuture.completedFuture(Boolean.FALSE); }); } public String retrieveDelegationToken() { return authHelper.retrieveMasterToken(); } public CompletableFuture<Void> createNewSegments(String scope, String kvt, List<Long> segmentIds, int keyLength, long requestId, long rolloverSizeBytes) { return Futures.toVoid(Futures.allOfWithResults(segmentIds .stream() .parallel() .map(segment -> createNewSegment(scope, kvt, segment, keyLength, retrieveDelegationToken(), requestId, rolloverSizeBytes)) .collect(Collectors.toList()))); } private CompletableFuture<Void> createNewSegment(String scope, String kvt, long segmentId, int keyLength, String controllerToken, long requestId, long rolloverSizeBytes) { final String qualifiedTableSegmentName = getQualifiedTableSegmentName(scope, kvt, segmentId); log.debug("Creating segment {}", qualifiedTableSegmentName); return Futures.toVoid(withRetries(() -> segmentHelper.createTableSegment(qualifiedTableSegmentName, controllerToken, requestId, false, keyLength, rolloverSizeBytes), executor)); } @Override public void close() { if (eventHelper != null) { eventHelper.close(); } } }
/** * This file is part of Billund - http://www.computercraft.info/billund * Copyright Daniel Ratcliffe, 2013-2014. See LICENSE for license details. */ package dan200.billund.shared; import java.util.List; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraft.block.Block; import net.minecraft.util.Facing; import net.minecraft.util.Vec3; import net.minecraft.util.MathHelper; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.ForgeDirection; import dan200.Billund; public class ItemBrick extends Item { public ItemBrick(int i) { super(i); setMaxStackSize( 64 ); setHasSubtypes( true ); setUnlocalizedName( "billbrick" ); setCreativeTab( Billund.getCreativeTab() ); } public static ItemStack create( int colour, int width, int depth, int quantity ) { int damage = ((width - 1) & 0x1) + (((depth - 1) & 0x7) << 1) + ((colour & 0xf) << 4); return new ItemStack( Billund.Items.brick.itemID, quantity, damage ); } @Override public void getSubItems( int itemID, CreativeTabs tabs, List list ) { for( int colour=0; colour<StudColour.Count; ++colour ) { list.add( create( colour, 1, 1, 1 ) ); list.add( create( colour, 1, 2, 1 ) ); list.add( create( colour, 1, 3, 1 ) ); list.add( create( colour, 1, 4, 1 ) ); list.add( create( colour, 1, 6, 1 ) ); list.add( create( colour, 2, 2, 1 ) ); list.add( create( colour, 2, 3, 1 ) ); list.add( create( colour, 2, 4, 1 ) ); list.add( create( colour, 2, 6, 1 ) ); } } public static TileEntityBillund.StudRaycastResult raycastFromPlayer( World world, EntityPlayer player, float f ) { // Calculate the raycast origin and direction double yOffset2 = ( !world.isRemote && player.isSneaking() ) ? -0.08 : 0.0; // TODO: Improve float pitch = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * f; float yaw = player.prevRotationYaw + (player.rotationYaw - player.prevRotationYaw) * f; double x = player.prevPosX + (player.posX - player.prevPosX) * (double)f; double y = player.prevPosY + (player.posY - player.prevPosY) * (double)f + 1.62 - player.yOffset + yOffset2; // TODO: Improve double z = player.prevPosZ + (player.posZ - player.prevPosZ) * (double)f; Vec3 position = world.getWorldVec3Pool().getVecFromPool( x, y, z ); float f3 = MathHelper.cos( -yaw * 0.017453292F - (float)Math.PI ); float f4 = MathHelper.sin( -yaw * 0.017453292F - (float)Math.PI ); float f5 = -MathHelper.cos( -pitch * 0.017453292F ); float f6 = MathHelper.sin( -pitch * 0.017453292F ); float f7 = f4 * f5; float f8 = f3 * f5; float distance = 5.0f; if( player instanceof EntityPlayerMP ) { distance = (float)((EntityPlayerMP)player).theItemInWorldManager.getBlockReachDistance(); } Vec3 direction = world.getWorldVec3Pool().getVecFromPool( (double)f7, (double)f6, (double)f8 ); // Do the raycast return TileEntityBillund.raycastStuds( world, position, direction, distance ); } public static Brick getPotentialBrick( ItemStack stack, World world, EntityPlayer player, float f ) { // Do the raycast TileEntityBillund.StudRaycastResult result = raycastFromPlayer( world, player, f ); if( result != null ) { // Calculate where to place the brick int width = getWidth( stack ); int depth = getDepth( stack ); int height = 1; if( player.isSneaking() ) { int temp = depth; depth = width; width = temp; } int placeX = result.hitX; int placeY = result.hitY; int placeZ = result.hitZ; switch( result.hitSide ) { case 0: placeY -= height; break; case 1: placeY++; break; case 2: placeZ -= depth; break; case 3: placeZ++; break; case 4: placeX -= width; break; case 5: placeX++; break; } // Try a few positions nearby Brick brick = new Brick( getColour( stack ), placeX, placeY, placeZ, width, height, depth ); for( int x=0; x<width; ++x ) { for( int z=0; z<depth; ++z ) { for( int y=0; y<height; ++y ) { brick.XOrigin = placeX - x; brick.YOrigin = placeY - y; brick.ZOrigin = placeZ - z; if( TileEntityBillund.canAddBrick( world, brick ) ) { return brick; } } } } } return null; } public static Brick getExistingBrick( World world, EntityPlayer player, float f ) { // Do the raycast TileEntityBillund.StudRaycastResult result = raycastFromPlayer( world, player, f ); if( result != null ) { Stud stud = TileEntityBillund.getStud( world, result.hitX, result.hitY, result.hitZ ); if( stud != null && stud.Colour != StudColour.Wall) { return new Brick( stud.Colour, stud.XOrigin, stud.YOrigin, stud.ZOrigin, stud.BrickWidth, stud.BrickHeight, stud.BrickDepth ); } } return null; } @Override public boolean onItemUseFirst( ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ ) { // Brick brick = getPotentialBrick( stack, world, player, 1.0f ); // if( brick != null ) // { // return true; // } return false; } @Override public boolean onItemUse( ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ ) { // Brick brick = getPotentialBrick( stack, world, player, 1.0f ); // if( brick != null ) // { // return true; // } return false; } @Override public ItemStack onItemRightClick( ItemStack stack, World world, EntityPlayer player ) { Brick brick = getPotentialBrick( stack, world, player, 1.0f ); if( brick != null ) { if( !world.isRemote ) { // Place the brick TileEntityBillund.addBrick( world, brick ); if( !player.capabilities.isCreativeMode ) { // Decrement stackSize stack.stackSize--; } } } return stack; } public static int getWidth( ItemStack stack ) { int damage = stack.getItemDamage(); return (damage & 0x1) + 1; } public static int getHeight( ItemStack stack ) { return 1; } public static int getDepth( ItemStack stack ) { int damage = stack.getItemDamage(); return ((damage >> 1) & 0x7) + 1; } public static int getColour( ItemStack stack ) { int damage = stack.getItemDamage(); return ((damage >> 4) & 0xf); } }
/* * Copyright (c) 2015, SRI International * All rights reserved. * Licensed under the The BSD 3-Clause License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/BSD-3-Clause * * 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 aic-praise 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 com.sri.ai.praise.core.representation.classbased.expressionbased.core; import static com.sri.ai.expresso.helper.Expressions.ONE; import static com.sri.ai.expresso.helper.Expressions.ZERO; import static com.sri.ai.expresso.helper.Expressions.apply; import static com.sri.ai.expresso.helper.Expressions.parse; import static com.sri.ai.grinder.helper.GrinderUtil.getTypeExpressionOfExpression; import static com.sri.ai.grinder.helper.GrinderUtil.getTypeOfExpression; import static com.sri.ai.grinder.library.FunctorConstants.EQUAL; import static com.sri.ai.grinder.library.FunctorConstants.EQUIVALENCE; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.function.Predicate; import com.sri.ai.expresso.api.Expression; import com.sri.ai.expresso.api.Type; import com.sri.ai.grinder.api.Context; import com.sri.ai.grinder.library.controlflow.IfThenElse; import com.sri.ai.praise.core.representation.classbased.expressionbased.api.ExpressionBasedModel; import com.sri.ai.praise.core.representation.classbased.expressionbased.api.ExpressionBasedProblem; import com.sri.ai.praise.other.integration.proceduralattachment.api.ProceduralAttachments; /** * An {@link ExpressionBasedProblem} based on a {@link ExpressionBasedModel} and a (possibly compound) query expression. * <p> * In the case of compound queries, it introduces a new variable, "query", and a factor * defining "query" to be equal to the original compound query. * Because of that, it also provides a method for replacing the compound query back into a given expression containing * the variable query. */ public class DefaultExpressionBasedProblem implements ExpressionBasedProblem { private static final Expression QUERY_SYMBOL = parse("query"); /** The original {@link ExpressionBasedModel}. */ private ExpressionBasedModel originalExpressionBasedModel; /** The variable query to be used ("query" if original query was compound). */ private Expression querySymbol; /** The list of factors to be used (including the variable query definition if original query was compound). */ private List<Expression> factorExpressionsIncludingQueryDefinitionIfAny; private List<Expression> originalRandomVariables; private Predicate<Expression> isParameterPredicate; /** The original query. */ private Expression queryExpression; /** Whether the list of factors represents a Bayesian network. */ private boolean modelIsKnownToBeBayesianNetwork; /** Whether the original query was compound. */ private boolean queryIsCompound; /** The context to be used, possibly including the symbol "query" and its type. */ private Context context; /** Procedural attachments. */ private ProceduralAttachments proceduralAttachments; public DefaultExpressionBasedProblem(Expression queryExpression, ExpressionBasedModel model) { this.originalExpressionBasedModel = model; this.queryExpression = queryExpression; this.originalRandomVariables = originalExpressionBasedModel.getRandomVariables(); this.isParameterPredicate = e -> model.getMapFromNonUniquelyNamedConstantNameToTypeName().containsKey(e.toString()); this.modelIsKnownToBeBayesianNetwork = originalExpressionBasedModel.isKnownToBeBayesianNetwork(); this.proceduralAttachments = originalExpressionBasedModel.getProceduralAttachments(); if (decideIfQueryIsCompound()) { processCompoundQuery(); } else { processVariableQuery(); } } /** * Replaces variable query ("query") by original query in given expression, * and simplifies it with original model's context. */ @Override public Expression replaceQuerySymbolByQueryExpressionIfNeeded(Expression expression) { Expression result; if (queryIsCompound) { result = expression.replaceAllOccurrences(QUERY_SYMBOL, queryExpression, originalExpressionBasedModel.getContext()); } else { result = expression; } return result; } private boolean decideIfQueryIsCompound() { Map<String, String> mapFromRandomVariableNameToTypeName = originalExpressionBasedModel.getMapFromRandomVariableNameToTypeName(); boolean queryIsOneOfTheRandomVariables = mapFromRandomVariableNameToTypeName.containsKey(queryExpression.toString()); queryIsCompound = ! queryIsOneOfTheRandomVariables; return queryIsCompound; } private void processVariableQuery() { querySymbol = queryExpression; factorExpressionsIncludingQueryDefinitionIfAny = originalExpressionBasedModel.getFactors(); context = originalExpressionBasedModel.getContext(); } private void processCompoundQuery() { querySymbol = QUERY_SYMBOL; factorExpressionsIncludingQueryDefinitionIfAny = getListOfFactorsAndQueryFactor(); context = extendContextWithQuerySymbol(queryExpression); } private List<Expression> getListOfFactorsAndQueryFactor() { Expression queryFactor = makeQueryDefinitionFactor(queryExpression); List<Expression> originalFactorsAndQueryFactor = makeListOfOriginalFactorsAndQueryDefinitionFactor(queryFactor); return originalFactorsAndQueryFactor; } private Expression makeQueryDefinitionFactor(Expression queryExpression) { boolean queryIsBoolean = queryIsBoolean(queryExpression); String typeAppropriateEquality = queryIsBoolean? EQUIVALENCE : EQUAL; Expression queryFactorCondition = apply(typeAppropriateEquality, QUERY_SYMBOL, queryExpression); Expression queryFactor = IfThenElse.make(queryFactorCondition, ONE, ZERO); return queryFactor; } private boolean queryIsBoolean(Expression queryExpression) { Type typeOfQueryExpression = getTypeOfExpression(queryExpression, originalExpressionBasedModel.getContext()); boolean queryIsBoolean = typeOfQueryExpression.toString().equals("Boolean"); return queryIsBoolean; } private List<Expression> makeListOfOriginalFactorsAndQueryDefinitionFactor(Expression queryFactor) { List<Expression> originalFactorsAndQueryFactor = getCopyOfOriginalFactors(); originalFactorsAndQueryFactor.add(queryFactor); return originalFactorsAndQueryFactor; } private List<Expression> getCopyOfOriginalFactors() { LinkedList<Expression> result = new LinkedList<>(originalExpressionBasedModel.getFactors()); return result; } private Context extendContextWithQuerySymbol(Expression queryExpression) { Context originalContext = originalExpressionBasedModel.getContext(); Expression queryType = getTypeExpressionOfExpression(queryExpression, originalContext); String queryTypeName = queryType.toString(); Context result = originalContext.extendWithSymbolsAndTypes("query", queryTypeName); return result; } public ExpressionBasedModel getOriginalExpressionBasedModel() { return originalExpressionBasedModel; } @Override public Expression getQuerySymbol() { return querySymbol; } @Override public List<Expression> getFactorExpressionsIncludingQueryDefinitionIfAny() { return Collections.unmodifiableList(factorExpressionsIncludingQueryDefinitionIfAny); } @Override public List<Expression> getRandomVariablesExcludingQuerySymbol() { return Collections.unmodifiableList(originalRandomVariables); } @Override public Predicate<Expression> getIsParameterPredicate() { return isParameterPredicate; } @Override public Expression getQueryExpression() { return queryExpression; } @Override public boolean modelIsKnownToBeBayesianNetwork() { return modelIsKnownToBeBayesianNetwork; } @Override public boolean getQueryIsCompound() { return queryIsCompound; } @Override public ProceduralAttachments getProceduralAttachments() { return proceduralAttachments; } @Override public void setProceduralAttachments(ProceduralAttachments proceduralAttachments) { this.proceduralAttachments = proceduralAttachments; } @Override public Context getContext() { return context; } }
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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.intellij.ui; import com.intellij.ide.ui.LafManager; import com.intellij.ide.ui.LafManagerListener; import com.intellij.notification.EventLog; import com.intellij.notification.Notification; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.wm.impl.IdeRootPane; import com.intellij.util.Alarm; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.JBInsets; import consulo.desktop.util.awt.migration.AWTComponentProviderUtil; import consulo.disposer.Disposable; import consulo.disposer.Disposer; import consulo.ui.impl.BalloonLayoutEx; import consulo.ui.impl.ToolWindowPanelImplEx; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.util.List; import java.util.*; public class DesktopBalloonLayoutImpl implements BalloonLayoutEx { private final ComponentAdapter myResizeListener = new ComponentAdapter() { @Override public void componentResized(@Nonnull ComponentEvent e) { queueRelayout(); } }; protected JLayeredPane myLayeredPane; private final Insets myInsets; protected final List<Balloon> myBalloons = new ArrayList<>(); private final Map<Balloon, BalloonLayoutData> myLayoutData = new HashMap<>(); private GetInt myWidth; private final Alarm myRelayoutAlarm = new Alarm(); private final Runnable myRelayoutRunnable = () -> { if (myLayeredPane == null) { return; } relayout(); fireRelayout(); }; private JRootPane myParent; private final Runnable myCloseAll = () -> { for (Balloon balloon : new ArrayList<>(myBalloons)) { remove(balloon, true); } }; private final Runnable myLayoutRunnable = () -> { calculateSize(); relayout(); fireRelayout(); }; private LafManagerListener myLafListener; private final List<Runnable> myListeners = new ArrayList<>(); public DesktopBalloonLayoutImpl(@Nonnull JRootPane parent, @Nonnull Insets insets) { myParent = parent; myLayeredPane = parent.getLayeredPane(); myInsets = insets; myLayeredPane.addComponentListener(myResizeListener); } public void dispose() { myLayeredPane.removeComponentListener(myResizeListener); if (myLafListener != null) { LafManager.getInstance().removeLafManagerListener(myLafListener); myLafListener = null; } for (Balloon balloon : new ArrayList<>(myBalloons)) { Disposer.dispose(balloon); } myRelayoutAlarm.cancelAllRequests(); myBalloons.clear(); myLayoutData.clear(); myListeners.clear(); myLayeredPane = null; myParent = null; } @Override public void addListener(Runnable listener) { myListeners.add(listener); } @Override public void removeListener(Runnable listener) { myListeners.remove(listener); } private void fireRelayout() { for (Runnable listener : myListeners) { listener.run(); } } @Override @Nullable public Component getTopBalloonComponent() { BalloonImpl balloon = (BalloonImpl)ContainerUtil.getLastItem(myBalloons); return balloon == null ? null : balloon.getComponent(); } @Override public void add(@Nonnull Balloon balloon) { add(balloon, null); } @Override public void add(@Nonnull final Balloon balloon, @Nullable Object layoutData) { ApplicationManager.getApplication().assertIsDispatchThread(); Balloon merge = merge(layoutData); if (merge == null) { if (!myBalloons.isEmpty() && myBalloons.size() == getVisibleCount()) { remove(myBalloons.get(0)); } myBalloons.add(balloon); } else { int index = myBalloons.indexOf(merge); remove(merge); myBalloons.add(index, balloon); } if (layoutData instanceof BalloonLayoutData) { BalloonLayoutData balloonLayoutData = (BalloonLayoutData)layoutData; balloonLayoutData.closeAll = myCloseAll; balloonLayoutData.doLayout = myLayoutRunnable; myLayoutData.put(balloon, balloonLayoutData); } Disposer.register(balloon, new Disposable() { @Override public void dispose() { clearNMore(balloon); remove(balloon, false); queueRelayout(); } }); if (myLafListener == null && layoutData != null) { myLafListener = new LafManagerListener() { @Override public void lookAndFeelChanged(LafManager source) { for (BalloonLayoutData layoutData : myLayoutData.values()) { if (layoutData.lafHandler != null) { layoutData.lafHandler.run(); } } } }; LafManager.getInstance().addLafManagerListener(myLafListener); } calculateSize(); relayout(); if (!balloon.isDisposed()) { balloon.show(myLayeredPane); } fireRelayout(); } @Nullable private Balloon merge(@Nullable Object data) { String mergeId = null; if (data instanceof String) { mergeId = (String)data; } else if (data instanceof BalloonLayoutData) { mergeId = ((BalloonLayoutData)data).groupId; } if (mergeId != null) { for (Map.Entry<Balloon, BalloonLayoutData> e : myLayoutData.entrySet()) { if (mergeId.equals(e.getValue().groupId)) { return e.getKey(); } } } return null; } @Override @Nullable public BalloonLayoutData.MergeInfo preMerge(@Nonnull Notification notification) { Balloon balloon = merge(notification.getGroupId()); if (balloon != null) { BalloonLayoutData layoutData = myLayoutData.get(balloon); if (layoutData != null) { return layoutData.merge(); } } return null; } @Override public void remove(@Nonnull Notification notification) { Balloon balloon = merge(notification.getGroupId()); if (balloon != null) { remove(balloon, true); } } private void remove(@Nonnull Balloon balloon) { remove(balloon, false); balloon.hide(true); fireRelayout(); } private void clearNMore(@Nonnull Balloon balloon) { BalloonLayoutData layoutData = myLayoutData.get(balloon); if (layoutData != null && layoutData.project != null && layoutData.mergeData != null) { EventLog.clearNMore(layoutData.project, Collections.singleton(layoutData.groupId)); } } private void remove(@Nonnull Balloon balloon, boolean hide) { myBalloons.remove(balloon); BalloonLayoutData layoutData = myLayoutData.remove(balloon); if (layoutData != null) { layoutData.mergeData = null; } if (hide) { balloon.hide(); fireRelayout(); } } public void closeAll() { myCloseAll.run(); } public void closeFirst() { if (!myBalloons.isEmpty()) { remove(myBalloons.get(0), true); } } public int getBalloonCount() { return myBalloons.size(); } private static int getVisibleCount() { return 2; } @Nonnull private Dimension getSize(@Nonnull Balloon balloon) { BalloonLayoutData layoutData = myLayoutData.get(balloon); if (layoutData == null) { Dimension size = balloon.getPreferredSize(); return myWidth == null ? size : new Dimension(myWidth.i(), size.height); } return new Dimension(myWidth.i(), layoutData.height); } public boolean isEmpty() { return myBalloons.isEmpty(); } public void queueRelayout() { myRelayoutAlarm.cancelAllRequests(); myRelayoutAlarm.addRequest(myRelayoutRunnable, 200); } private void calculateSize() { myWidth = null; for (Balloon balloon : myBalloons) { BalloonLayoutData layoutData = myLayoutData.get(balloon); if (layoutData != null) { layoutData.height = balloon.getPreferredSize().height; } } myWidth = BalloonLayoutConfiguration::FixedWidth; } private void relayout() { final Dimension size = myLayeredPane.getSize(); JBInsets.removeFrom(size, myInsets); final Rectangle layoutRec = new Rectangle(new Point(myInsets.left, myInsets.top), size); List<ArrayList<Balloon>> columns = createColumns(layoutRec); while (columns.size() > 1) { remove(myBalloons.get(0), true); columns = createColumns(layoutRec); } ToolWindowPanelImplEx pane = AWTComponentProviderUtil.findChild(myParent, ToolWindowPanelImplEx.class); JComponent layeredPane = pane != null ? pane.getMyLayeredPane() : null; int eachColumnX = (layeredPane == null ? myLayeredPane.getWidth() : layeredPane.getX() + layeredPane.getWidth()) - 4; doLayout(columns.get(0), eachColumnX + 4, (int)myLayeredPane.getBounds().getMaxY()); } private void doLayout(List<Balloon> balloons, int startX, int bottomY) { int y = bottomY; ToolWindowPanelImplEx pane = AWTComponentProviderUtil.findChild(myParent, ToolWindowPanelImplEx.class); if (pane != null) { y -= pane.getBottomHeight(); } if (myParent instanceof IdeRootPane) { y -= ((IdeRootPane)myParent).getStatusBarHeight(); } for (Balloon balloon : balloons) { Rectangle bounds = new Rectangle(getSize(balloon)); y -= bounds.height; bounds.setLocation(startX - bounds.width, y); balloon.setBounds(bounds); } } private List<ArrayList<Balloon>> createColumns(Rectangle layoutRec) { List<ArrayList<Balloon>> columns = new ArrayList<>(); ArrayList<Balloon> eachColumn = new ArrayList<>(); columns.add(eachColumn); int eachColumnHeight = 0; for (Balloon each : myBalloons) { final Dimension eachSize = getSize(each); if (eachColumnHeight + eachSize.height > layoutRec.getHeight()) { eachColumn = new ArrayList<>(); columns.add(eachColumn); eachColumnHeight = 0; } eachColumn.add(each); eachColumnHeight += eachSize.height; } return columns; } private interface GetInt { int i(); } }
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2012 MIT, All rights reserved // Released under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 package com.google.appinventor.client.widgets.boxes; import com.google.appinventor.client.widgets.boxes.Box.BoxDescriptor; import com.google.appinventor.common.utils.StringUtils; import com.google.appinventor.shared.properties.json.JSONObject; import com.google.appinventor.shared.properties.json.JSONUtil; import com.google.appinventor.shared.properties.json.JSONValue; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.allen_sauer.gwt.dnd.client.DragEndEvent; import com.allen_sauer.gwt.dnd.client.DragHandler; import com.allen_sauer.gwt.dnd.client.DragStartEvent; import com.allen_sauer.gwt.dnd.client.drop.IndexedDropController; import java.util.ArrayList; import java.util.Set; import java.util.List; import java.util.Map; /** * Defines a column-based layout for the boxes on a work area panel. * */ public final class ColumnLayout extends Layout { /** * Drag handler for detecting changes to the layout. */ public class ChangeDetector implements DragHandler { @Override public void onDragEnd(DragEndEvent event) { fireLayoutChange(); } @Override public void onDragStart(DragStartEvent event) { } @Override public void onPreviewDragEnd(DragEndEvent event) { } @Override public void onPreviewDragStart(DragStartEvent event) { } } /** * Represents a column in the layout. */ public static final class Column extends IndexedDropController { // Field names for JSON object encoding of layout private static final String NAME_WIDTH = "width"; private static final String NAME_BOXES = "boxes"; // Associated column container (this is the state of the layout when it is active) private final VerticalPanel columnPanel; // Relative column width (in percent of work area width) private int relativeWidth; // Absolute width (in pixel) private int absoluteWidth; // List of box description (this is the state of the layout when it is inactive) private final List<BoxDescriptor> boxes; /** * Creates new column. */ private Column(int relativeWidth) { this(new VerticalPanel(), relativeWidth); } /** * Creates new column. */ private Column(VerticalPanel columnPanel, int relativeWidth) { super(columnPanel); boxes = new ArrayList<BoxDescriptor>(); this.columnPanel = columnPanel; this.relativeWidth = relativeWidth; columnPanel.setWidth(relativeWidth + "%"); columnPanel.setSpacing(SPACING); } @Override protected void insert(Widget widget, int beforeIndex) { // columnPanel always contains at least one widget: the 'invisible' end marker. Therefore // beforeIndex cannot become negative. if (beforeIndex == columnPanel.getWidgetCount()) { beforeIndex--; } super.insert(widget, beforeIndex); if (widget instanceof Box) { ((Box) widget).onResize(absoluteWidth); } } /** * Invoked upon resizing of the work area panel. * * @see WorkAreaPanel#onResize(int, int) * * @param width column width in pixel */ public void onResize(int width) { absoluteWidth = width * relativeWidth / 100; columnPanel.setWidth(absoluteWidth + "px"); for (Widget w : columnPanel) { if (w instanceof Box) { ((Box) w).onResize(absoluteWidth); } else { // Top-of-column marker (otherwise invisible widget) w.setWidth(absoluteWidth + "px"); } } } /** * Add a new box to the column. * * @param type type of box * @param height height of box in pixels if not minimized * @param minimized indicates whether box is minimized */ public void add(Class<? extends Box> type, int height, boolean minimized) { boxes.add(new BoxDescriptor(type, absoluteWidth, height, minimized)); } /** * Updates the box descriptors for the boxes in the column. */ private void updateBoxDescriptors() { boxes.clear(); for (Widget w : columnPanel) { if (w instanceof Box) { boxes.add(((Box) w).getLayoutSettings()); } } } /** * Returns JSON encoding for the boxes in a column. */ private String toJson() { List<String> jsonBoxes = new ArrayList<String>(); for (int i = 0; i < columnPanel.getWidgetCount(); i++) { Widget w = columnPanel.getWidget(i); if (w instanceof Box) { jsonBoxes.add(((Box) w).getLayoutSettings().toJson()); } } return "{" + "\"" + NAME_WIDTH + "\":" + JSONUtil.toJson(relativeWidth) + "," + "\"" + NAME_BOXES + "\":[" + StringUtils.join(",", jsonBoxes) + "]" + "}"; } /** * Creates a new column from a JSON encoded layout. * * @param columnIndex index of column * @param object column in JSON format */ private static Column fromJson(int columnIndex, JSONObject object) { Column column = new Column(columnIndex); Map<String, JSONValue> properties = object.getProperties(); column.relativeWidth = JSONUtil.intFromJsonValue(properties.get(NAME_WIDTH)); for (JSONValue boxObject : properties.get(NAME_BOXES).asArray().getElements()) { column.boxes.add(BoxDescriptor.fromJson(boxObject.asObject())); } return column; } /** * Collects box types encoded in the JSON. * * @param object column in JSON format * @param boxTypes set of box types encountered so far */ private static void boxTypesFromJson(JSONObject object, Set<String> boxTypes) { Map<String, JSONValue> properties = object.getProperties(); for (JSONValue boxObject : properties.get(NAME_BOXES).asArray().getElements()) { boxTypes.add(BoxDescriptor.boxTypeFromJson(boxObject.asObject())); } } } // Spacing between columns in pixels private static final int SPACING = 5; // Field names for JSON object encoding of layout private static final String NAME_NAME = "name"; private static final String NAME_COLUMNS = "columns"; // List of columns private final List<Column> columns; // Drag handler for detecting changes to the layout private final DragHandler changeDetector; /** * Creates a new layout. */ public ColumnLayout(String name) { super(name); columns = new ArrayList<Column>(); changeDetector = new ChangeDetector(); } /** * Clears the layout (removes all existing columns etc). */ private void clear(WorkAreaPanel workArea) { for (Column column : columns) { workArea.getWidgetDragController().unregisterDropController(column); } workArea.getWidgetDragController().removeDragHandler(changeDetector); columns.clear(); } /** * Adds a new column to the layout. * * @param relativeWidth relative width of column (width of all columns * should add up to 100) * @return new layout column */ public Column addColumn(int relativeWidth) { Column column = new Column(relativeWidth); columns.add(column); return column; } @Override public void apply(WorkAreaPanel workArea) { // Clear base panel workArea.clear(); // Horizontal panel to hold columns HorizontalPanel horizontalPanel = new HorizontalPanel(); horizontalPanel.setSize("100%", "100%"); workArea.add(horizontalPanel); // Initialize columns for (Column column : columns) { horizontalPanel.add(column.columnPanel); workArea.getWidgetDragController().registerDropController(column); // Add invisible dummy widget to prevent column from collapsing when it contains no boxes column.columnPanel.add(new Label()); // Add boxes from layout List<BoxDescriptor> boxes = column.boxes; for (int index = 0; index < boxes.size(); index++) { BoxDescriptor bd = boxes.get(index); Box box = workArea.createBox(bd); if (box != null) { column.insert(box, index); box.restoreLayoutSettings(bd); } } } workArea.getWidgetDragController().addDragHandler(changeDetector); } @Override public void onResize(int width, int height) { // Calculate the usable width for the columns (which is the width of the browser client area // minus the spacing on each side of the boxes). int usableWidth = (width - ((columns.size() + 1) * SPACING)); // On startup it can happen that we receive a window resize event before the boxes are attached // to the DOM. In that case, width and height are 0, we can safely ignore because there will // soon be another resize event after the boxes are attached to the DOM. if (width > 0) { for (Column column : columns) { column.onResize(usableWidth); } } } @Override public String toJson() { List<String> jsonColumns = new ArrayList<String>(columns.size()); for (Column column : columns) { jsonColumns.add(column.toJson()); } return "{" + "\"" + NAME_NAME + "\":" + JSONUtil.toJson(getName()) + "," + "\"" + NAME_COLUMNS + "\":[" + StringUtils.join(",", jsonColumns) + "]" + "}"; } /** * Creates a new layout from a JSON encoded layout. * * @param object layout in JSON format */ public static Layout fromJson(JSONObject object, WorkAreaPanel workArea) { Map<String, JSONValue> properties = object.getProperties(); String name = properties.get(NAME_NAME).asString().getString(); ColumnLayout layout = (ColumnLayout) workArea.getLayouts().get(name); if (layout == null) { layout = new ColumnLayout(name); } layout.clear(workArea); for (JSONValue columnObject : properties.get(NAME_COLUMNS).asArray().getElements()) { layout.columns.add(Column.fromJson(layout.columns.size(), columnObject.asObject())); } return layout; } /** * Collects box types encoded in the JSON. * * @param object layout in JSON format * @param boxTypes box types encountered so far */ public static void boxTypesFromJson(JSONObject object, Set<String> boxTypes) { Map<String, JSONValue> properties = object.getProperties(); for (JSONValue columnObject : properties.get(NAME_COLUMNS).asArray().getElements()) { Column.boxTypesFromJson(columnObject.asObject(), boxTypes); } } @Override protected void fireLayoutChange() { // Need to update box descriptors before firing change event. // It is easier (maintenance-wise) to do this here instead of doing this in multiple places. for (Column column : columns) { column.updateBoxDescriptors(); } super.fireLayoutChange(); } }
/******************************************************************************* * Copyright 2013-2015 alladin-IT GmbH * * 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 at.alladin.rmbt.android.fragments.result; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import android.content.Context; import android.os.Bundle; import android.os.Parcelable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.SimpleAdapter; import android.widget.TextView; import at.alladin.openrmbt.android.R; import at.alladin.rmbt.android.main.RMBTMainActivity; import at.alladin.rmbt.client.v2.task.result.QoSServerResult; import at.alladin.rmbt.client.v2.task.result.QoSServerResult.DetailType; import at.alladin.rmbt.client.v2.task.result.QoSServerResultDesc; import at.alladin.rmbt.client.v2.task.result.QoSTestResultEnum; public class QoSTestDetailView extends ScrollView { public enum QoSResultListType { FAIL (R.string.result_details_qos_failure, R.color.result_red, DetailType.FAIL), SUCCESS (R.string.result_details_qos_success, R.color.result_green, DetailType.OK), INFO (R.string.result_details_qos_info, R.color.result_info, DetailType.INFO); final int titleResourceId; final int colorResourceId; final DetailType detailType; private QoSResultListType(final int titleResourceId, final int colorResourceId, final DetailType detailType) { this.titleResourceId = titleResourceId; this.colorResourceId = colorResourceId; this.detailType = detailType; } public int getTitleResourceId() { return titleResourceId; } public int getColorResourceId() { return colorResourceId; } public DetailType getDetailType() { return detailType; } } public class QoSResultListAdapter { private SimpleAdapter listAdapter; private final ViewGroup viewGroup; private final LinearLayout listView; private final List<HashMap<String, String>> descMap = new ArrayList<HashMap<String, String>>(); public QoSResultListAdapter(final ViewGroup container) { this.viewGroup = container; listView = (LinearLayout) viewGroup.findViewById(R.id.value_list); } public void build() { if (this.listAdapter == null) { this.listAdapter = new SimpleAdapter(activity, descMap, R.layout.qos_category_test_desc_item, new String[] { "name"}, new int[] { R.id.name }); } for (int i = 0; i < descMap.size(); i++) { View v = listAdapter.getView(i, null, null); listView.addView(v); } listView.invalidate(); } public ViewGroup getViewGroup() { return viewGroup; } public LinearLayout getListView() { return listView; } public List<HashMap<String, String>> getDescMap() { return descMap; } } public static final String OPTION_TEST_CATEGORY = "test_category"; public static final String BUNDLE_QOS_RESULT = "qos_result"; public static final String BUNDLE_QOS_DESC_LIST = "qos_desc_list"; QoSTestResultEnum curTestResult; private QoSServerResult result; private List<QoSServerResultDesc> descList; private Map<DetailType, QoSResultListAdapter> resultViewList; private RMBTMainActivity activity; public QoSTestDetailView(Context context, RMBTMainActivity activity, QoSServerResult result, List<QoSServerResultDesc> descList) { super(context); this.activity = activity; this.result = result; this.descList = descList; setFillViewport(true); final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); createView(inflater, this); } public View createView(LayoutInflater inflater, ViewGroup container) { View view = null; view = inflater.inflate(R.layout.qos_test_view, this); System.out.println(result); resultViewList = new TreeMap<QoSServerResult.DetailType, QoSTestDetailView.QoSResultListAdapter>(new Comparator<QoSServerResult.DetailType>() { @Override public int compare(DetailType lhs, DetailType rhs) { // TODO Auto-generated method stub if (lhs.ordinal()>rhs.ordinal()) return 1; else if (lhs.ordinal()<rhs.ordinal()) return -1; return 0; } }); for (QoSResultListType type : QoSResultListType.values()) { final View v = inflater.inflate(R.layout.qos_test_view_result_list, null); final TextView titleTest = (TextView) v.findViewById(R.id.subheader_text); titleTest.setText(type.getTitleResourceId()); v.setBackgroundResource(type.getColorResourceId()); resultViewList.put(type.getDetailType(), new QoSResultListAdapter((ViewGroup) v)); } HashMap<String, String> viewItem; if (descList != null) { for (int i = 0; i < descList.size(); i++) { QoSServerResultDesc desc = descList.get(i); if (desc.getUidSet().contains(result.getUid())) { viewItem = new HashMap<String, String>(); viewItem.put("name", desc.getDesc()); resultViewList.get(desc.getStatus()).getDescMap().add(viewItem); } } } final LinearLayout descContainerView = (LinearLayout) view.findViewById(R.id.result_desc_container); int posIndex = 1; for (Entry<DetailType, QoSResultListAdapter> e : resultViewList.entrySet()) { if (e.getValue().getDescMap().size() > 0) { e.getValue().build(); descContainerView.addView(e.getValue().getViewGroup(), posIndex++); switch(e.getKey()) { case OK: if (resultViewList.get(DetailType.FAIL) != null && resultViewList.get(DetailType.FAIL).getDescMap().size() > 0) { if (QoSServerResult.ON_FAILURE_BEHAVIOUR_INFO_SUCCESS.equals(result.getOnFailureBehaviour())) { e.getValue().getViewGroup().setBackgroundResource(R.color.result_info); } else if(QoSServerResult.ON_FAILURE_BEHAVIOUR_HIDE_SUCCESS.equals(result.getOnFailureBehaviour())) { e.getValue().getViewGroup().setVisibility(View.GONE); } } default: } } } LinearLayout headerList = (LinearLayout) view.findViewById(R.id.value_list_header); View headerView = inflater.inflate(R.layout.qos_category_test_desc_item, container, false); TextView header = (TextView) headerView.findViewById(R.id.name); header.setText(result.getTestSummary()); headerList.addView(headerView); LinearLayout infoList = (LinearLayout) view.findViewById(R.id.value_list_test); View infoView = inflater.inflate(R.layout.qos_category_test_desc_item, container, false); TextView info = (TextView) infoView.findViewById(R.id.name); info.setText(result.getTestDescription()); infoList.addView(infoView); return view; } @SuppressWarnings("unchecked") @Override protected void onRestoreInstanceState(Parcelable state) { super.onRestoreInstanceState(state); if (state != null) { curTestResult = QoSTestResultEnum.values()[((Bundle) state).getInt(OPTION_TEST_CATEGORY, 0)]; if (((Bundle) state).containsKey(BUNDLE_QOS_RESULT)) { result = (QoSServerResult) ((Bundle) state).getSerializable(BUNDLE_QOS_RESULT); descList = (List<QoSServerResultDesc>) ((Bundle) state).getSerializable(BUNDLE_QOS_DESC_LIST); } } } @Override protected Parcelable onSaveInstanceState() { Bundle outState = new Bundle(); outState.putSerializable(BUNDLE_QOS_DESC_LIST, (Serializable) descList); outState.putSerializable(BUNDLE_QOS_RESULT, (Serializable) result); outState.putInt(OPTION_TEST_CATEGORY, curTestResult.ordinal()); return outState; } public void setResult(QoSServerResult result) { this.result = result; } public void setResultDescList(List<QoSServerResultDesc> list) { this.descList = list; } }
/* * 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.geode.connectors.jdbc.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.sql.Blob; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.Date; import junitparams.Parameters; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.apache.geode.connectors.jdbc.JdbcConnectorException; import org.apache.geode.pdx.FieldType; import org.apache.geode.pdx.PdxInstance; import org.apache.geode.pdx.WritablePdxInstance; import org.apache.geode.test.junit.runners.GeodeParamsRunner; @RunWith(GeodeParamsRunner.class) public class SqlToPdxInstanceTest { private static final String COLUMN_NAME_1 = "columnName1"; private static final String COLUMN_NAME_2 = "columnName2"; private static final String PDX_FIELD_NAME_1 = "pdxFieldName1"; private static final String PDX_FIELD_NAME_2 = "pdxFieldName2"; private SqlToPdxInstance sqlToPdxInstance; private final WritablePdxInstance writablePdxInstance = mock(WritablePdxInstance.class); private ResultSet resultSet; private ResultSetMetaData metaData = mock(ResultSetMetaData.class); @Before public void setup() throws Exception { resultSet = mock(ResultSet.class); when(resultSet.next()).thenReturn(true).thenReturn(false); when(resultSet.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); sqlToPdxInstance = new SqlToPdxInstance(); PdxInstance pdxTemplate = mock(PdxInstance.class); when(pdxTemplate.createWriter()).thenReturn(writablePdxInstance); sqlToPdxInstance.setPdxTemplate(pdxTemplate); } @Test @Parameters(source = FieldType.class) public void createPdxInstanceFromSqlDataTest(FieldType fieldType) throws SQLException { int columnIndex = 1; sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, fieldType); Object columnValue = setupGetFieldValueResultSet(fieldType, columnIndex); Object expectedFieldValue = getFieldValueFromColumnValue(columnValue, fieldType); PdxInstance result = sqlToPdxInstance.create(resultSet); assertThat(result).isSameAs(writablePdxInstance); verify((WritablePdxInstance) result).setField(PDX_FIELD_NAME_1, expectedFieldValue); verifyNoMoreInteractions(result); } @Test public void createReturnsNullIfNoResultsReturned() throws Exception { when(resultSet.next()).thenReturn(false); PdxInstance pdxInstance = createPdxInstance(); assertThat(pdxInstance).isNull(); } @Test public void readReturnsDataFromAllResultColumns() throws Exception { when(metaData.getColumnCount()).thenReturn(2); when(metaData.getColumnName(2)).thenReturn(COLUMN_NAME_2); when(resultSet.getString(1)).thenReturn("column1"); when(resultSet.getString(2)).thenReturn("column2"); sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, FieldType.STRING); sqlToPdxInstance.addMapping(COLUMN_NAME_2, PDX_FIELD_NAME_2, FieldType.STRING); PdxInstance result = createPdxInstance(); assertThat(result).isSameAs(writablePdxInstance); verify((WritablePdxInstance) result).setField(PDX_FIELD_NAME_1, "column1"); verify((WritablePdxInstance) result).setField(PDX_FIELD_NAME_2, "column2"); verifyNoMoreInteractions(result); } @Test public void skipsUnmappedColumns() throws Exception { when(metaData.getColumnCount()).thenReturn(2); when(metaData.getColumnName(2)).thenReturn(COLUMN_NAME_2); when(resultSet.getString(1)).thenReturn("column1"); when(resultSet.getString(2)).thenReturn("column2"); sqlToPdxInstance.addMapping(COLUMN_NAME_2, PDX_FIELD_NAME_2, FieldType.STRING); assertThatThrownBy(() -> createPdxInstance()).isInstanceOf(JdbcConnectorException.class) .hasMessageContaining("The jdbc-mapping does not contain the column name \"" + COLUMN_NAME_1 + "\". This is probably caused by a column being added to the table after the jdbc-mapping was created."); } @Test public void fieldsAreNotWrittenIfNoColumns() throws Exception { FieldType fieldType = FieldType.CHAR; when(metaData.getColumnCount()).thenReturn(0); sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, fieldType); PdxInstance result = createPdxInstance(); assertThat(result).isSameAs(writablePdxInstance); verifyNoMoreInteractions(result); } @Test public void readOfCharFieldWithEmptyStringWritesCharZero() throws Exception { char expectedValue = 0; FieldType fieldType = FieldType.CHAR; when(metaData.getColumnType(1)).thenReturn(Types.CHAR); when(resultSet.getString(1)).thenReturn(""); sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, fieldType); PdxInstance result = createPdxInstance(); verifyResult(expectedValue, result); } @Test public void readOfDateFieldWithDateColumnWritesDate() throws Exception { FieldType fieldType = FieldType.DATE; when(metaData.getColumnType(1)).thenReturn(Types.DATE); java.sql.Date sqlDate = java.sql.Date.valueOf("1979-09-11"); Date expectedValue = new Date(sqlDate.getTime()); when(resultSet.getDate(1)).thenReturn(sqlDate); sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, fieldType); PdxInstance result = createPdxInstance(); verifyResult(expectedValue, result); } @Test public void readOfByteArrayFieldWithBlob() throws Exception { FieldType fieldType = FieldType.BYTE_ARRAY; when(metaData.getColumnType(1)).thenReturn(Types.BLOB); byte[] expectedValue = new byte[] {1, 2, 3}; Blob blob = mock(Blob.class); when(blob.length()).thenReturn((long) expectedValue.length); when(blob.getBytes(1, expectedValue.length)).thenReturn(expectedValue); when(resultSet.getBlob(1)).thenReturn(blob); sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, fieldType); PdxInstance result = createPdxInstance(); verifyResult(expectedValue, result); } @Test public void readOfByteArrayFieldWithNullBlob() throws Exception { FieldType fieldType = FieldType.BYTE_ARRAY; when(metaData.getColumnType(1)).thenReturn(Types.BLOB); when(resultSet.getBlob(1)).thenReturn(null); sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, fieldType); PdxInstance result = createPdxInstance(); verifyResult(null, result); verify(resultSet).getBlob(1); } @Test public void readOfByteArrayFieldWithHugeBlobThrows() throws Exception { FieldType fieldType = FieldType.BYTE_ARRAY; when(metaData.getColumnType(1)).thenReturn(Types.BLOB); Blob blob = mock(Blob.class); when(blob.length()).thenReturn((long) Integer.MAX_VALUE + 1); when(resultSet.getBlob(1)).thenReturn(blob); sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, fieldType); assertThatThrownBy(() -> createPdxInstance()).isInstanceOf(JdbcConnectorException.class) .hasMessageContaining( "Blob of length 2147483648 is too big to be converted to a byte array."); } @Test public void readOfObjectFieldWithBlob() throws Exception { FieldType fieldType = FieldType.OBJECT; when(metaData.getColumnType(1)).thenReturn(Types.BLOB); byte[] expectedValue = new byte[] {1, 2, 3}; Blob blob = mock(Blob.class); when(blob.length()).thenReturn((long) expectedValue.length); when(blob.getBytes(1, expectedValue.length)).thenReturn(expectedValue); when(resultSet.getBlob(1)).thenReturn(blob); sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, fieldType); PdxInstance result = createPdxInstance(); verifyResult(expectedValue, result); } @Test public void readOfDateFieldWithTimeColumnWritesDate() throws Exception { FieldType fieldType = FieldType.DATE; when(metaData.getColumnType(1)).thenReturn(Types.TIME); java.sql.Time sqlTime = java.sql.Time.valueOf("22:33:44"); Date expectedValue = new Date(sqlTime.getTime()); when(resultSet.getTime(1)).thenReturn(sqlTime); sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, fieldType); PdxInstance result = createPdxInstance(); verifyResult(expectedValue, result); } @Test public void readOfDateFieldWithTimestampColumnWritesDate() throws Exception { FieldType fieldType = FieldType.DATE; when(metaData.getColumnType(1)).thenReturn(Types.TIMESTAMP); java.sql.Timestamp sqlTimestamp = java.sql.Timestamp.valueOf("1979-09-11 22:33:44.567"); Date expectedValue = new Date(sqlTimestamp.getTime()); when(resultSet.getTimestamp(1)).thenReturn(sqlTimestamp); sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, fieldType); PdxInstance result = createPdxInstance(); verifyResult(expectedValue, result); } @Test public void readOfObjectFieldWithDateColumnWritesDate() throws Exception { FieldType fieldType = FieldType.OBJECT; java.sql.Date sqlDate = java.sql.Date.valueOf("1979-09-11"); Date expectedValue = new Date(sqlDate.getTime()); when(resultSet.getObject(1)).thenReturn(sqlDate); sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, fieldType); PdxInstance result = createPdxInstance(); verifyResult(expectedValue, result); } @Test public void readOfObjectFieldWithJavaUtilDateWritesDate() throws Exception { FieldType fieldType = FieldType.OBJECT; sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, fieldType); Date expectedValue = new Date(); when(resultSet.getObject(1)).thenReturn(expectedValue); PdxInstance result = createPdxInstance(); verifyResult(expectedValue, result); } @Test public void readOfObjectFieldWithTimeColumnWritesDate() throws Exception { FieldType fieldType = FieldType.OBJECT; sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, fieldType); java.sql.Time sqlTime = java.sql.Time.valueOf("22:33:44"); Date expectedValue = new Date(sqlTime.getTime()); when(resultSet.getObject(1)).thenReturn(sqlTime); PdxInstance result = createPdxInstance(); verifyResult(expectedValue, result); } @Test public void readOfObjectFieldWithTimestampColumnWritesDate() throws Exception { FieldType fieldType = FieldType.OBJECT; sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, fieldType); java.sql.Timestamp sqlTimestamp = java.sql.Timestamp.valueOf("1979-09-11 22:33:44.567"); Date expectedValue = new Date(sqlTimestamp.getTime()); when(resultSet.getObject(1)).thenReturn(sqlTimestamp); PdxInstance result = createPdxInstance(); verifyResult(expectedValue, result); } @Test @Parameters({"BOOLEAN_ARRAY", "OBJECT_ARRAY", "CHAR_ARRAY", "SHORT_ARRAY", "INT_ARRAY", "LONG_ARRAY", "FLOAT_ARRAY", "DOUBLE_ARRAY", "STRING_ARRAY", "ARRAY_OF_BYTE_ARRAYS"}) public void throwsExceptionWhenReadWritesUnsupportedType(FieldType fieldType) throws Exception { sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, fieldType); String returnValue = "ReturnValue"; when(resultSet.getObject(1)).thenReturn(returnValue); assertThatThrownBy(() -> createPdxInstance()).isInstanceOf(JdbcConnectorException.class) .hasMessageContaining("Could not convert "); } @Test public void throwsExceptionIfMoreThanOneResultReturned() throws Exception { when(metaData.getColumnCount()).thenReturn(2); when(metaData.getColumnName(2)).thenReturn(COLUMN_NAME_2); sqlToPdxInstance.addMapping(COLUMN_NAME_1, PDX_FIELD_NAME_1, FieldType.STRING); sqlToPdxInstance.addMapping(COLUMN_NAME_2, PDX_FIELD_NAME_2, FieldType.STRING); when(resultSet.next()).thenReturn(true); assertThatThrownBy(() -> createPdxInstance()).isInstanceOf(JdbcConnectorException.class) .hasMessageContaining("Multiple rows returned for query: "); } private PdxInstance createPdxInstance() throws SQLException { return sqlToPdxInstance.create(resultSet); } private void verifyResult(Object expectedValue, PdxInstance result) { assertThat(result).isSameAs(writablePdxInstance); verify((WritablePdxInstance) result).setField(PDX_FIELD_NAME_1, expectedValue); verifyNoMoreInteractions(result); } private Object getFieldValueFromColumnValue(Object columnValue, FieldType fieldType) { Object result = columnValue; if (fieldType == FieldType.CHAR) { String columnString = (String) columnValue; result = columnString.charAt(0); } else if (fieldType == FieldType.DATE) { java.sql.Timestamp columnTimestamp = (java.sql.Timestamp) columnValue; result = new java.util.Date(columnTimestamp.getTime()); } return result; } private Object setupGetFieldValueResultSet(FieldType fieldType, int columnIndex) throws SQLException { Object value = getValueByFieldType(fieldType); switch (fieldType) { case STRING: when(resultSet.getString(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case CHAR: when(resultSet.getString(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case SHORT: when(resultSet.getShort(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case INT: when(resultSet.getInt(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case LONG: when(resultSet.getLong(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case FLOAT: when(resultSet.getFloat(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case DOUBLE: when(resultSet.getDouble(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case BYTE: when(resultSet.getByte(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case BOOLEAN: when(resultSet.getBoolean(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case DATE: when(resultSet.getTimestamp(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case BYTE_ARRAY: when(resultSet.getBytes(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case BOOLEAN_ARRAY: when(resultSet.getObject(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case CHAR_ARRAY: when(resultSet.getObject(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case SHORT_ARRAY: when(resultSet.getObject(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case INT_ARRAY: when(resultSet.getObject(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case LONG_ARRAY: when(resultSet.getObject(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case FLOAT_ARRAY: when(resultSet.getObject(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case DOUBLE_ARRAY: when(resultSet.getObject(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case STRING_ARRAY: when(resultSet.getObject(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case OBJECT_ARRAY: when(resultSet.getObject(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case ARRAY_OF_BYTE_ARRAYS: when(resultSet.getObject(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; case OBJECT: when(resultSet.getObject(columnIndex)).thenReturn(getValueByFieldType(fieldType)); break; default: throw new IllegalStateException("unhandled fieldType " + fieldType); } return value; } private static byte[][] arrayOfByteArray = new byte[][] {{1, 2}, {3, 4}}; @SuppressWarnings("unchecked") private <T> T getValueByFieldType(FieldType fieldType) { switch (fieldType) { case STRING: return (T) "stringValue"; case CHAR: return (T) "charValue"; case SHORT: return (T) Short.valueOf((short) 36); case INT: return (T) Integer.valueOf(36); case LONG: return (T) Long.valueOf(36); case FLOAT: return (T) Float.valueOf(36); case DOUBLE: return (T) Double.valueOf(36); case BYTE: return (T) Byte.valueOf((byte) 36); case BOOLEAN: return (T) Boolean.TRUE; case DATE: return (T) new java.sql.Timestamp(1000); case BYTE_ARRAY: return (T) new byte[] {1, 2}; case BOOLEAN_ARRAY: return (T) new boolean[] {true, false}; case CHAR_ARRAY: return (T) new char[] {1, 2}; case SHORT_ARRAY: return (T) new short[] {1, 2}; case INT_ARRAY: return (T) new int[] {1, 2}; case LONG_ARRAY: return (T) new long[] {1, 2}; case FLOAT_ARRAY: return (T) new float[] {1, 2}; case DOUBLE_ARRAY: return (T) new double[] {1, 2}; case STRING_ARRAY: return (T) new String[] {"1", "2"}; case OBJECT_ARRAY: return (T) new Object[] {1, 2}; case ARRAY_OF_BYTE_ARRAYS: return (T) arrayOfByteArray; case OBJECT: return (T) "objectValue"; default: throw new IllegalStateException("unhandled fieldType " + fieldType); } } }
package com.dlsu.getbetter.getbetter; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.provider.MediaStore; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.InputType; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import android.widget.MediaController; import com.dlsu.getbetter.getbetter.activities.ViewImageActivity; import com.dlsu.getbetter.getbetter.adapters.FileAttachmentsAdapter; import com.dlsu.getbetter.getbetter.database.DataAdapter; import com.dlsu.getbetter.getbetter.objects.Attachment; import com.dlsu.getbetter.getbetter.objects.DividerItemDecoration; import com.dlsu.getbetter.getbetter.objects.Patient; import com.dlsu.getbetter.getbetter.sessionmanagers.NewPatientSessionManager; import com.dlsu.getbetter.getbetter.sessionmanagers.SystemSessionManager; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Locale; /** * A simple {@link Fragment} subclass. */ public class SummaryPageFragment extends Fragment implements View.OnClickListener, MediaController.MediaPlayerControl { private String patientName; private String patientAgeGender; private String patientProfileImage; private String patientFirstName; private String patientMiddleName; private String patientLastName; private String patientBirthdate; private String patientGender; private String patientCivilStatus; private String patientBloodType; private String chiefComplaint; private String controlNumber; private String uploadedDate; private String attachmentName; private static final int REQUEST_IMAGE_ATTACHMENT = 100; private static final int REQUEST_VIDEO_ATTACHMENT = 200; private static final int REQUEST_AUDIO_ATTACHMENT = 300; private static final int MEDIA_TYPE_IMAGE = 1; private static final int MEDIA_TYPE_VIDEO = 2; private static final int MEDIA_TYPE_AUDIO = 3; private long patientId; private int caseRecordId; private int healthCenterId; private int userId; private ArrayList<Attachment> attachments; private FileAttachmentsAdapter fileAdapter; private RecyclerView.LayoutManager fileListLayoutManager; private ImageView summaryProfileImage; private CardView recordSoundContainer; private Button recordSoundbBtn; private Button stopRecordBtn; private Button playSoundBtn; private Button doneRecordBtn; private Button cancelRecordBtn; private MediaRecorder hpiRecorder; private MediaPlayer nMediaPlayer; private MediaController nMediaController; private Handler nHandler = new Handler(); private Uri fileUri; private String audioOutputFile; private DataAdapter getBetterDb; private NewPatientSessionManager newPatientDetails; public SummaryPageFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SystemSessionManager systemSessionManager = new SystemSessionManager(getActivity()); if(systemSessionManager.checkLogin()) getActivity().finish(); HashMap<String, String> user = systemSessionManager.getUserDetails(); HashMap<String, String> hc = systemSessionManager.getHealthCenter(); HashMap<String, String> patientDetails = newPatientDetails.getNewPatientDetails(); healthCenterId = Integer.parseInt(hc.get(SystemSessionManager.HEALTH_CENTER_ID)); initializeDatabase(); getUserId(user.get(SystemSessionManager.LOGIN_USER_NAME)); newPatientDetails = new NewPatientSessionManager(getActivity()); patientProfileImage = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_PROFILE_IMAGE); patientFirstName = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_FIRST_NAME); patientMiddleName = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_MIDDLE_NAME); patientLastName = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_LAST_NAME); patientBirthdate = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_BIRTHDATE); patientGender = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_GENDER); patientCivilStatus = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_CIVIL_STATUS); patientBloodType = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_BLOOD_TYPE); chiefComplaint = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_CHIEF_COMPLAINT); String recordedHpiOutputFile = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_DOC_HPI_RECORD); Patient patient = new Patient(patientFirstName, patientMiddleName, patientLastName, patientBirthdate, patientGender, patientCivilStatus, patientProfileImage); String patientInfoFormImage = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_DOC_IMAGE1); String familySocialHistoryFormImage = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_DOC_IMAGE2); String chiefComplaintFormImage = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_DOC_IMAGE3); String patientInfoFormImageTitle = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_DOC_IMAGE1_TITLE); String familySocialHistoryFormImageTitle = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_DOC_IMAGE2_TITLE); String chiefComplaintFormImageTitle = patientDetails.get(NewPatientSessionManager.NEW_PATIENT_DOC_IMAGE3_TITLE); if(!newPatientDetails.isActivityNewPatient()) { HashMap<String, String> pId = newPatientDetails.getPatientInfo(); patientId = Long.valueOf(pId.get(NewPatientSessionManager.PATIENT_ID)); patientFirstName = pId.get(NewPatientSessionManager.NEW_PATIENT_FIRST_NAME); patientLastName = pId.get(NewPatientSessionManager.NEW_PATIENT_LAST_NAME); caseRecordId = generateCaseRecordId(patientId); controlNumber = generateControlNumber(patientId); } attachments = new ArrayList<>(); uploadedDate = getTimeStamp(); fileAdapter = new FileAttachmentsAdapter(attachments); //encrypt here addPhotoAttachment(patientInfoFormImage, patientInfoFormImageTitle, uploadedDate); addPhotoAttachment(familySocialHistoryFormImage, familySocialHistoryFormImageTitle, uploadedDate); addPhotoAttachment(chiefComplaintFormImage, chiefComplaintFormImageTitle, uploadedDate); addHPIAttachment(recordedHpiOutputFile, chiefComplaint, uploadedDate); fileListLayoutManager = new LinearLayoutManager(this.getContext()); patientName = patientFirstName + " " + patientMiddleName + " " + patientLastName; patientAgeGender = patient.getAge() + " yrs. old, " + patientGender; nMediaPlayer = new MediaPlayer(); nMediaController = new MediaController(this.getContext()) { @Override public void hide() { } }; //Uri hpiRecordingUri = Uri.parse(recordedHpiOutputFile); nMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { //encrypt here nMediaPlayer.setDataSource(recordedHpiOutputFile); nMediaPlayer.prepare(); } catch (IOException e) { e.printStackTrace(); } } private void initializeDatabase () { getBetterDb = new DataAdapter(this.getContext()); try { getBetterDb.createDatabase(); } catch (SQLException e) { e.printStackTrace(); } } private void getUserId(String username) { try { getBetterDb.openDatabase(); } catch (SQLException e) { e.printStackTrace(); } userId = getBetterDb.getUserId(username); getBetterDb.closeDatabase(); } private void addPhotoAttachment (String path, String title, String uploadedOn) { Attachment attachment = new Attachment(path, title, 1, uploadedOn); attachments.add(fileAdapter.getItemCount(), attachment); fileAdapter.notifyItemInserted(fileAdapter.getItemCount() - 1); } private void addVideoAttachment (String path, String title, String uploadedOn) { Attachment attachment = new Attachment(path, title, 2, uploadedOn); attachments.add(fileAdapter.getItemCount(), attachment); fileAdapter.notifyItemInserted(fileAdapter.getItemCount() - 1); } private void addAudioAttachment (String path, String title, String uploadedOn) { Attachment attachment = new Attachment(path, title, 3, uploadedOn); attachments.add(attachment); } private void addHPIAttachment(String path, String title, String uploadedOn) { Attachment attachment = new Attachment(path, title, 5, uploadedOn); attachments.add(attachment); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_summary_page, container, false); TextView summaryChiefComplaint = (TextView)rootView.findViewById(R.id.summary_page_chief_complaint); TextView summaryPatientName = (TextView) rootView.findViewById(R.id.summary_page_patient_name); TextView summaryAgeGender = (TextView) rootView.findViewById(R.id.summary_page_age_gender); Button summarySubmitBtn = (Button) rootView.findViewById(R.id.summary_page_submit_btn); Button summaryTakePicBtn = (Button)rootView.findViewById(R.id.summary_page_take_pic_btn); Button summaryRecordVideo = (Button)rootView.findViewById(R.id.summary_page_rec_video_btn); Button summaryRecordAudio = (Button)rootView.findViewById(R.id.summary_page_rec_sound_btn); Button summaryTakePicDocBtn = (Button)rootView.findViewById(R.id.summary_page_take_pic_doc_btn); Button summaryUpdatePatientRecBtn = (Button)rootView.findViewById(R.id.summary_update_patient_rec_btn); Button summaryEstethoscopeBtn = (Button)rootView.findViewById(R.id.summary_page_estethoscope_btn); Button summarySelectFileBtn = (Button)rootView.findViewById(R.id.summary_page_select_file_btn); RecyclerView attachmentFileList = (RecyclerView) rootView.findViewById(R.id.summary_page_files_list); RecyclerView.ItemDecoration dividerItemDecoration = new DividerItemDecoration(getContext()); recordSoundContainer = (CardView)rootView.findViewById(R.id.summary_page_record_sound_container); recordSoundbBtn = (Button)rootView.findViewById(R.id.summary_page_audio_record_btn); stopRecordBtn = (Button)rootView.findViewById(R.id.summary_page_audio_stop_record_btn); playSoundBtn = (Button)rootView.findViewById(R.id.summary_page_audio_play_recorded_btn); doneRecordBtn = (Button)rootView.findViewById(R.id.summary_page_record_audio_done_btn); cancelRecordBtn = (Button)rootView.findViewById(R.id.summary_page_record_audio_cancel_btn); summaryProfileImage = (ImageView) rootView.findViewById(R.id.profile_picture_display); nMediaController.setMediaPlayer(SummaryPageFragment.this); nMediaController.setAnchorView(rootView.findViewById(R.id.hpi_media_player)); summaryPatientName.setText(patientName); summaryAgeGender.setText(patientAgeGender); summaryChiefComplaint.setText(chiefComplaint); recordSoundContainer.setVisibility(View.GONE); stopRecordBtn.setEnabled(false); playSoundBtn.setEnabled(false); summarySubmitBtn.setOnClickListener(this); summaryTakePicBtn.setOnClickListener(this); summaryTakePicDocBtn.setOnClickListener(this); summaryRecordVideo.setOnClickListener(this); summaryRecordAudio.setOnClickListener(this); summaryUpdatePatientRecBtn.setOnClickListener(this); summaryEstethoscopeBtn.setOnClickListener(this); summarySelectFileBtn.setOnClickListener(this); recordSoundbBtn.setOnClickListener(this); stopRecordBtn.setOnClickListener(this); playSoundBtn.setOnClickListener(this); doneRecordBtn.setOnClickListener(this); cancelRecordBtn.setOnClickListener(this); attachmentFileList.setHasFixedSize(true); attachmentFileList.setLayoutManager(fileListLayoutManager); attachmentFileList.setAdapter(fileAdapter); attachmentFileList.addItemDecoration(dividerItemDecoration); fileAdapter.SetOnItemClickListener(new FileAttachmentsAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Intent intent = new Intent(getActivity(), ViewImageActivity.class); intent.putExtra("imageUrl", attachments.get(position).getAttachmentPath()); intent.putExtra("imageTitle", attachments.get(position).getAttachmentDescription()); startActivity(intent); } }); nMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { nHandler.post(new Runnable() { public void run() { nMediaController.show(0); nMediaPlayer.start(); } }); } }); return rootView; } @Override public void onResume() { super.onResume(); setPic(summaryProfileImage, patientProfileImage); } @Override public void onClick(View v) { int id = v.getId(); if(id == R.id.summary_page_submit_btn) { if(newPatientDetails.isActivityNewPatient()) { new InsertPatientTask().execute(patientFirstName, patientMiddleName, patientLastName, patientBirthdate, patientGender, patientCivilStatus, patientBloodType, patientProfileImage); } else { new InsertCaseRecordTask().execute(); } if(nMediaPlayer.isPlaying()) { nMediaPlayer.stop(); nMediaPlayer.release(); } if(nMediaController.isShowing()) { nMediaController.hide(); } newPatientDetails.endSession(); getActivity().finish(); } else if (id == R.id.summary_page_take_pic_btn) { takePicture(); } else if (id == R.id.summary_page_take_pic_doc_btn) { takePicture(); } else if (id == R.id.summary_page_rec_video_btn) { recordVideo(); } else if (id == R.id.summary_page_estethoscope_btn) { featureAlertMessage(); } else if (id == R.id.summary_page_select_file_btn) { featureAlertMessage(); } else if (id == R.id.summary_page_rec_sound_btn) { audioOutputFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath() + "/" + "hpi_recording_" + getTimeStamp().substring(0,9) + ".3gp"; hpiRecorder = new MediaRecorder(); hpiRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); hpiRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); hpiRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB); hpiRecorder.setOutputFile(audioOutputFile); recordSoundContainer.setVisibility(View.VISIBLE); } else if (id == R.id.summary_page_audio_record_btn) { try { hpiRecorder.prepare(); hpiRecorder.start(); } catch (IllegalStateException | IOException e) { e.printStackTrace(); } stopRecordBtn.setEnabled(true); } else if (id == R.id.summary_page_audio_stop_record_btn) { hpiRecorder.stop(); hpiRecorder.release(); hpiRecorder = null; stopRecordBtn.setEnabled(false); playSoundBtn.setEnabled(true); } else if (id == R.id.summary_page_audio_play_recorded_btn) { MediaPlayer mp = new MediaPlayer(); try { mp.setDataSource(audioOutputFile); } catch (IOException e ) { e.printStackTrace(); } try { mp.prepare(); } catch (IOException e) { e.printStackTrace(); } mp.start(); } else if (id == R.id.summary_page_record_audio_done_btn) { } else if (id == R.id.summary_page_record_audio_cancel_btn) { } } @Override public boolean canPause() { return true; } @Override public boolean canSeekBackward() { return false; } @Override public boolean canSeekForward() { return false; } @Override public int getAudioSessionId() { return 0; } @Override public int getBufferPercentage() { return (nMediaPlayer.getCurrentPosition() * 100) / nMediaPlayer.getDuration(); } @Override public int getCurrentPosition() { return nMediaPlayer.getCurrentPosition(); } @Override public int getDuration() { return nMediaPlayer.getDuration(); } @Override public boolean isPlaying() { return nMediaPlayer.isPlaying(); } @Override public void pause() { if(nMediaPlayer.isPlaying()) nMediaPlayer.pause(); } @Override public void seekTo(int pos) { nMediaPlayer.seekTo(pos); } @Override public void start() { nMediaPlayer.start(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == REQUEST_IMAGE_ATTACHMENT) { if(resultCode == Activity.RESULT_OK) { editAttachmentName(MEDIA_TYPE_IMAGE); } else if(resultCode == Activity.RESULT_CANCELED) { } else { } } else if(requestCode == REQUEST_VIDEO_ATTACHMENT) { if(resultCode == Activity.RESULT_OK) { editAttachmentName(MEDIA_TYPE_VIDEO); // addVideoAttachment(videoAttachmentPath, "video", uploadedDate); } else if (resultCode == Activity.RESULT_CANCELED) { } else { } } else if(requestCode == REQUEST_AUDIO_ATTACHMENT) { } } @Override public void onDestroy() { super.onDestroy(); if(nMediaPlayer.isPlaying()) { nMediaPlayer.stop(); nMediaPlayer.release(); } if(nMediaController.isShowing()) { nMediaController.hide(); } } private void editAttachmentName (final int type) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle("Image Filename"); // Set up the input final EditText input = new EditText(getContext()); // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text input.setInputType(InputType.TYPE_CLASS_TEXT); builder.setView(input); // Set up the buttons builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { attachmentName = input.getText().toString(); InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(input.getWindowToken(), 0); if(type == MEDIA_TYPE_IMAGE) { addPhotoAttachment(fileUri.getPath(), attachmentName, uploadedDate); } else if(type == MEDIA_TYPE_VIDEO) { addVideoAttachment(fileUri.getPath(), attachmentName, uploadedDate); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } private class InsertPatientTask extends AsyncTask<String, Void, Long> { private final ProgressDialog progressDialog = new ProgressDialog(SummaryPageFragment.this.getContext()); @Override protected void onPreExecute() { this.progressDialog.setMessage("Inserting Patient Info..."); this.progressDialog.show(); } @Override protected Long doInBackground(String... params) { long rowId; try { getBetterDb.openDatabase(); } catch (SQLException e) { e.printStackTrace(); } rowId = getBetterDb.insertPatientInfo(params[0], params[1], params[2], params[3], params[4], params[5], params[6], params[7], healthCenterId); getBetterDb.closeDatabase(); return rowId; } @Override protected void onPostExecute(Long result) { if (this.progressDialog.isShowing()) { this.progressDialog.dismiss(); } Toast.makeText(SummaryPageFragment.this.getContext(), "Patient ID: " + result + " inserted.", Toast.LENGTH_LONG).show(); patientId = result; caseRecordId = generateCaseRecordId(result); Log.e("case record id", caseRecordId+""); controlNumber = generateControlNumber(result); new InsertCaseRecordTask().execute(); } } // private class InsertNewAttachment extends AsyncTask<Void, Void, String> { // // @Override // protected void onPreExecute() { // super.onPreExecute(); // // } // // @Override // protected String doInBackground(Void... params) { // // editAttachmentName(); // return attachmentName; // } // // @Override // protected void onPostExecute(String result) { // super.onPostExecute(result); // // addPhotoAttachment(imageAttachmentPath, result, uploadedDate); // // } // } private void insertCaseRecord() { try { getBetterDb.openDatabase(); } catch (SQLException e) { e.printStackTrace(); } Log.e("id", caseRecordId + ""); Log.e("patientId", patientId + ""); Log.e("chiefComplaint", chiefComplaint); getBetterDb.insertCaseRecord(caseRecordId, patientId, healthCenterId, chiefComplaint, controlNumber); getBetterDb.closeDatabase(); } private void insertCaseRecordHistory() { try { getBetterDb.openDatabase(); } catch (SQLException e) { e.printStackTrace(); } Log.e("history id", caseRecordId + ""); getBetterDb.insertCaseRecordHistory(caseRecordId, userId, uploadedDate); getBetterDb.closeDatabase(); } private void insertCaseRecordAttachments() { try { getBetterDb.openDatabase(); } catch (SQLException e) { e.printStackTrace(); } for(int i = 0; i < attachments.size(); i++) { Log.e("attachment id", caseRecordId + ""); attachments.get(i).setCaseRecordId(caseRecordId); getBetterDb.insertCaseRecordAttachments(attachments.get(i)); } getBetterDb.closeDatabase(); } private String generateControlNumber(long pId) { String result; String firstChar = patientFirstName.substring(0, 1).toUpperCase(); String secondChar = patientLastName.substring(0, 1).toUpperCase(); String patientIdChar = String.valueOf(pId); result = firstChar + secondChar + patientIdChar + "-" + caseRecordId; Log.e("control number", result); return result; } private int generateCaseRecordId(long patientId) { ArrayList<Integer> storedIds; int caseRecordId; int a = 251; int c = 134; int m = 312; int generatedRandomId = m / 2; generatedRandomId = (a * generatedRandomId + c) % m; caseRecordId = Integer.parseInt(patientId + Integer.toString(generatedRandomId)); try { getBetterDb.openDatabase(); } catch (SQLException e) { e.printStackTrace(); } storedIds = getBetterDb.getCaseRecordIds(); getBetterDb.closeDatabase(); if(storedIds.isEmpty()) { return caseRecordId; } else { while(storedIds.contains(caseRecordId)) { generatedRandomId = (a * generatedRandomId + c) % m; caseRecordId = Integer.parseInt(Long.toString(patientId) + Integer.toString(generatedRandomId)); } return caseRecordId; } } private class InsertCaseRecordTask extends AsyncTask<Void, Void, Void> { private ProgressDialog progressDialog = new ProgressDialog(SummaryPageFragment.this.getContext()); @Override protected void onPreExecute() { progressDialog.setMessage("Inserting case record..."); progressDialog.show(); } @Override protected Void doInBackground(Void... params) { insertCaseRecord(); insertCaseRecordAttachments(); insertCaseRecordHistory(); return null; } @Override protected void onPostExecute(Void unused) { if(progressDialog.isShowing()) { progressDialog.hide(); progressDialog.dismiss(); } } } /** * Here we store the file url as it will be null after returning from camera * app */ @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // save file url in bundle as it will be null on screen orientation // changes outState.putParcelable("file_uri", fileUri); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if(savedInstanceState != null) { fileUri = savedInstanceState.getParcelable("file_uri"); } } private File createMediaFile(int type) { String timeStamp = getTimeStamp().substring(0, 9); File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), DirectoryConstants.CASE_RECORD_ATTACHMENT_DIRECTORY_NAME); if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("Debug", "Oops! Failed create " + DirectoryConstants.CASE_RECORD_ATTACHMENT_DIRECTORY_NAME + " directory"); return null; } } File mediaFile; if(type == MEDIA_TYPE_IMAGE) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); } else if (type == MEDIA_TYPE_VIDEO) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4"); } else if (type == MEDIA_TYPE_AUDIO) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "AUD_" + timeStamp + ".3gp"); } else { return null; } return mediaFile; } private Uri getOutputMediaFileUri(int type) { return Uri.fromFile(createMediaFile(type)); } private void takePicture() { //encrypt here Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); startActivityForResult(intent, REQUEST_IMAGE_ATTACHMENT); } private void recordVideo() { //encrypt here Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO); intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 5491520L); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); startActivityForResult(intent, REQUEST_VIDEO_ATTACHMENT); } private void recordSound() { } private void setPic(ImageView mImageView, String mCurrentPhotoPath) { //decrypt here // Get the dimensions of the View int targetW = 255;//mImageView.getWidth(); int targetH = 200;// mImageView.getHeight(); Log.e("width and height", targetW + targetH + ""); // Get the dimensions of the bitmap BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); int photoW = bmOptions.outWidth; int photoH = bmOptions.outHeight; // Determine how much to scale down the patientProfileImage int scaleFactor = Math.min(photoW/targetW, photoH/targetH); // Decode the patientProfileImage file into a Bitmap sized to fill the View bmOptions.inJustDecodeBounds = false; bmOptions.inSampleSize = scaleFactor; Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); mImageView.setImageBitmap(bitmap); } private String getTimeStamp() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()); } private void featureAlertMessage() { AlertDialog.Builder builder = new AlertDialog.Builder(SummaryPageFragment.this.getActivity()); builder.setTitle("Feature Not Available!"); builder.setMessage("Sorry! This feature is still under construction. :)"); builder.setNeutralButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } }
/* * Copyright 2012 Shared Learning Collaborative, LLC * * 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.slc.sli.dashboard.manager.impl; import java.io.File; import java.io.FileReader; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.slc.sli.dashboard.client.APIClient; import org.slc.sli.dashboard.entity.Config; import org.slc.sli.dashboard.entity.ConfigMap; import org.slc.sli.dashboard.entity.EdOrgKey; import org.slc.sli.dashboard.entity.GenericEntity; import org.slc.sli.dashboard.manager.ApiClientManager; import org.slc.sli.dashboard.manager.ConfigManager; import org.slc.sli.dashboard.util.CacheableConfig; import org.slc.sli.dashboard.util.Constants; import org.slc.sli.dashboard.util.DashboardException; import org.slc.sli.dashboard.util.JsonConverter; /** * * ConfigManager allows other classes, such as controllers, to access and * persist view configurations. * Given a user, it will obtain view configuration at each level of the user's * hierarchy, and merge them into one set for the user. * * @author dwu */ public class ConfigManagerImpl extends ApiClientManager implements ConfigManager { private Logger logger = LoggerFactory.getLogger(getClass()); private String driverConfigLocation; private String userConfigLocation; private static final String LAYOUT_NAME = "layoutName"; private static final String LAYOUT = "layout"; private static final String DEFAULT = "default"; private static final String TYPE = "type"; public ConfigManagerImpl() { } /** * this method should be called by Spring Framework * set location of config file to be read. If the directory does not exist, * create it. * * @param configLocation * reading from properties file panel.config.driver.dir */ public void setDriverConfigLocation(String configLocation) { URL url = Config.class.getClassLoader().getResource(configLocation); if (url == null) { File f = new File(Config.class.getClassLoader().getResource("") + "/" + configLocation); f.mkdir(); this.driverConfigLocation = f.getAbsolutePath(); } else { this.driverConfigLocation = url.getPath(); } } /** * this method should be called by Spring Framework * set location of config file to be read. If the directory does not exist, * create it. * * @param configLocation * reading from properties file panel.config.custom.dir */ public void setUserConfigLocation(String configLocation) { if (!configLocation.startsWith("/")) { URL url = Config.class.getClassLoader().getResource(configLocation); if (url == null) { File f = new File(Config.class.getClassLoader().getResource("").getPath() + configLocation); f.mkdir(); configLocation = f.getAbsolutePath(); } else { configLocation = url.getPath(); } } this.userConfigLocation = configLocation; } /** * return the absolute file path of domain specific config file * * @param path * can be district ID name or state ID name * @param componentId * profile name * @return the absolute file path of domain specific config file */ public String getComponentConfigLocation(String path, String componentId) { return userConfigLocation + "/" + path + "/" + componentId + ".json"; } /** * return the absolute file path of default config file * * @param path * can be district ID name or state ID name * @param componentId * profile name * @return the absolute file path of default config file */ public String getDriverConfigLocation(String componentId) { return this.driverConfigLocation + "/" + componentId + ".json"; } /** * Find the lowest organization hierarchy config file. If the lowest * organization hierarchy * config file does not exist, it returns default (Driver) config file. * If the Driver config file does not exist, it is in a critical situation. * It will throw an * exception. * * @param apiCustomConfig * custom configuration uploaded by admininistrator. * @param customPath * abslute directory path where a config file exist. * @param componentId * name of the profile * @return proper Config to be used for the dashboard */ private Config getConfigByPath(Config customConfig, String componentId) { Config driverConfig = null; try { String driverId = componentId; // if custom config exist, read the config file if (customConfig != null) { driverId = customConfig.getParentId(); } // read Driver (default) config. File f = new File(getDriverConfigLocation(driverId)); driverConfig = loadConfig(f); if (customConfig != null) { return driverConfig.overWrite(customConfig); } return driverConfig; } catch (Exception ex) { logger.error("Unable to read config for " + componentId, ex); throw new DashboardException("Unable to read config for " + componentId); } } private Config loadConfig(File f) throws Exception { if (f.exists()) { FileReader fr = new FileReader(f); try { return JsonConverter.fromJson(fr, Config.class); } finally { IOUtils.closeQuietly(fr); } } return null; } @Override @CacheableConfig public Config getComponentConfig(String token, EdOrgKey edOrgKey, String componentId) { Config customComponentConfig = null; GenericEntity edOrg = null; GenericEntity parentEdOrg = null; EdOrgKey parentEdOrgKey = null; String id = edOrgKey.getSliId(); List<EdOrgKey> edOrgKeys = new ArrayList<EdOrgKey>(); edOrgKeys.add(edOrgKey); // keep reading EdOrg until it hits the top. APIClient apiClient = getApiClient(); do { if (apiClient != null) { edOrg = apiClient.getEducationalOrganization(token, id); if (edOrg != null) { parentEdOrg = apiClient.getParentEducationalOrganization(token, edOrg); if (parentEdOrg != null) { id = parentEdOrg.getId(); parentEdOrgKey = new EdOrgKey(id); edOrgKeys.add(parentEdOrgKey); } } else { // if edOrg is null, it means no parent edOrg either. parentEdOrg = null; } } } while (parentEdOrg != null); for (EdOrgKey key : edOrgKeys) { ConfigMap configMap = getCustomConfig(token, key); // if api has config if (configMap != null && !configMap.isEmpty()) { Config edOrgComponentConfig = configMap.getComponentConfig(componentId); if (edOrgComponentConfig != null) { if (customComponentConfig == null) { customComponentConfig = edOrgComponentConfig; } else { // edOrgComponentConfig overwrites customComponentConfig customComponentConfig = edOrgComponentConfig.overWrite(customComponentConfig); } } } } return getConfigByPath(customComponentConfig, componentId); } @Override @Cacheable(value = Constants.CACHE_USER_WIDGET_CONFIG) public Collection<Config> getWidgetConfigs(String token, EdOrgKey edOrgKey) { Map<String, String> attrs = new HashMap<String, String>(); attrs.put("type", Config.Type.WIDGET.toString()); return getConfigsByAttribute(token, edOrgKey, attrs); } @Override public Collection<Config> getConfigsByAttribute(String token, EdOrgKey edOrgKey, Map<String, String> attrs) { return getConfigsByAttribute(token, edOrgKey, attrs, true); } @Override public Collection<Config> getConfigsByAttribute(String token, EdOrgKey edOrgKey, Map<String, String> attrs, boolean overwriteCustomConfig) { // id to config map Map<String, Config> configs = new HashMap<String, Config>(); Config config; // list files in driver dir File driverConfigDir = new File(this.driverConfigLocation); File[] driverConfigFiles = driverConfigDir.listFiles(); if (driverConfigFiles == null) { logger.error("Unable to read config directory"); throw new DashboardException("Unable to read config directory!!!!"); } for (File f : driverConfigFiles) { try { config = loadConfig(f); } catch (Exception e) { logger.error("Unable to read config " + f.getName() + ". Skipping file", e); continue; } // check the config params. if they all match, add to the config map. boolean matchAll = true; for (String attrName : attrs.keySet()) { String methodName = ""; try { // use reflection to call the right config object method methodName = "get" + Character.toUpperCase(attrName.charAt(0)) + attrName.substring(1); Method method = config.getClass().getDeclaredMethod(methodName, new Class[] {}); Object ret = method.invoke(config, new Object[] {}); // compare the result to the desired result if (!(ret.toString().equals(attrs.get(attrName)))) { matchAll = false; break; } } catch (Exception e) { matchAll = false; logger.error("Error calling config method: " + methodName); } } // add to config map if (matchAll) { configs.put(config.getId(), config); } } // get custom configs if (overwriteCustomConfig) { for (String id : configs.keySet()) { configs.put(id, getComponentConfig(token, edOrgKey, id)); } } return configs.values(); } /** * Get the user's educational organization's custom configuration. * * @param token * The user's authentication token. * @return The education organization's custom configuration */ @Override public ConfigMap getCustomConfig(String token, EdOrgKey edOrgKey) { try { return getApiClient().getEdOrgCustomData(token, edOrgKey.getSliId()); } catch (Exception e) { // it's a valid scenario when there is no district specific config. Default will be used // in this case. logger.debug( "No district specific config is available, the default config will be used" ); return null; } } /** * Put or save the user's educational organization's custom configuration. * * @param token * The user's authentication token. * @param customConfigJson * The education organization's custom configuration JSON. */ @Override @CacheEvict(value = Constants.CACHE_USER_PANEL_CONFIG, allEntries = true) public void putCustomConfig(String token, EdOrgKey edOrgKey, ConfigMap configMap) { getApiClient().putEdOrgCustomData(token, edOrgKey.getSliId(), configMap); } /** * Save one custom configuration for an ed-org * */ @Override @CacheEvict(value = Constants.CACHE_USER_PANEL_CONFIG, allEntries = true) public void putCustomConfig(String token, EdOrgKey edOrgKey, Config config) { // get current custom config map from api ConfigMap configMap = getCustomConfig(token, edOrgKey); if (configMap == null) { configMap = new ConfigMap(); configMap.setConfig(new HashMap<String, Config>()); } // update with new config ConfigMap newConfigMap = configMap.cloneWithNewConfig(config); // write new config map getApiClient().putEdOrgCustomData(token, edOrgKey.getSliId(), newConfigMap); } /** * To find Config is PANEL types and belong to the layout. * * @param config * @param layoutName * @return */ private boolean doesBelongToLayout(Config config, String layoutName) { boolean belongConfig = true; // first filter by type. // Target TYPEs are PANEL, GRID, TREE, and REPEAT_HEADER_GRID Config.Type type = config.getType(); if (type != null && (type.equals(Config.Type.PANEL) || type.equals(Config.Type.GRID) || type.equals(Config.Type.TREE) || type .equals(Config.Type.REPEAT_HEADER_GRID))) { // if a client requests specific layout, // then filter layout. if (layoutName != null) { belongConfig = false; Map<String, Object> configParams = config.getParams(); if (configParams != null) { List<String> layouts = (List<String>) configParams.get(LAYOUT); if (layouts != null) { if (layouts.contains(layoutName)) { belongConfig = true; } } } } } else { belongConfig = false; } return belongConfig; } @Override public Map<String, Collection<Config>> getAllConfigByType(String token, EdOrgKey edOrgKey, Map<String, String> params) { Map<String, Collection<Config>> allConfigs = new HashMap<String, Collection<Config>>(); // configIdLookup is used to check parentId from Custom Config exists in Driver Config Set<String> configIdLookup = new HashSet<String>(); Map<String, String> attribute = new HashMap<String, String>(); String layoutName = params.get(LAYOUT_NAME); if (params.containsKey(TYPE)) { attribute.put(TYPE, params.get(TYPE)); } // get Driver Config by specified attribute Collection<Config> driverConfigs = getConfigsByAttribute(token, edOrgKey, attribute, false); // filter config by layout name // and // build lookup index Iterator<Config> configIterator = driverConfigs.iterator(); while (configIterator.hasNext()) { Config driverConfig = configIterator.next(); if (doesBelongToLayout(driverConfig, layoutName)) { configIdLookup.add(driverConfig.getId()); } else { configIterator.remove(); } } // add DriverConfig to a returning object allConfigs.put(DEFAULT, driverConfigs); // read edOrg custom config recursively APIClient apiClient = getApiClient(); while (edOrgKey != null) { // customConfigByType will be added to a returning object Collection<Config> customConfigByType = new LinkedList<Config>(); // get current edOrg custom config ConfigMap customConfigMap = getCustomConfig(token, edOrgKey); if (customConfigMap != null) { Map<String, Config> configByMap = customConfigMap.getConfig(); if (configByMap != null) { Collection<Config> customConfigs = configByMap.values(); if (customConfigs != null) { for (Config customConfig : customConfigs) { // if parentId from customConfig does not exist in DriverConfig, // then ignore. String parentId = customConfig.getParentId(); if (parentId != null && configIdLookup.contains(parentId)) { if (doesBelongToLayout(customConfig, layoutName)) { customConfigByType.add(customConfig); } } } } } } // find current EdOrg entity GenericEntity edOrg = apiClient.getEducationalOrganization(token, edOrgKey.getSliId()); List<String> organizationCategories = (List<String>) edOrg.get(Constants.ATTR_ORG_CATEGORIES); if (organizationCategories != null && !organizationCategories.isEmpty()) { for (String educationAgency : organizationCategories) { if (educationAgency != null) { allConfigs.put(educationAgency, customConfigByType); break; } } } // find parent EdOrg edOrgKey = null; edOrg = apiClient.getParentEducationalOrganization(token, edOrg); if (edOrg != null) { String id = edOrg.getId(); if (id != null && !id.isEmpty()) { edOrgKey = new EdOrgKey(id); } } } return allConfigs; } }
/** * 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.tests.integration.aerogear; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.api.core.Message; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; import org.apache.activemq.artemis.api.core.client.SendAcknowledgementHandler; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.tests.util.ServiceTestBase; import org.apache.activemq.artemis.tests.util.UnitTestCase; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.config.ConnectorServiceConfiguration; import org.apache.activemq.artemis.core.config.CoreQueueConfiguration; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.integration.aerogear.AeroGearConnectorServiceFactory; import org.apache.activemq.artemis.integration.aerogear.AeroGearConstants; import org.apache.activemq.artemis.utils.json.JSONArray; import org.apache.activemq.artemis.utils.json.JSONException; import org.apache.activemq.artemis.utils.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mortbay.jetty.Request; import org.mortbay.jetty.Server; import org.mortbay.jetty.handler.AbstractHandler; import org.mortbay.jetty.nio.SelectChannelConnector; public class AeroGearBasicServerTest extends ServiceTestBase { private ActiveMQServer server; private ServerLocator locator; private Server jetty; @Override @Before public void setUp() throws Exception { super.setUp(); /* * there will be a thread kept alive by the http connection, we could disable the thread check but this means that the tests * interfere with one another, we just have to wait for it to be killed * */ jetty = new Server(); SelectChannelConnector connector0 = new SelectChannelConnector(); connector0.setPort(8080); connector0.setMaxIdleTime(30000); connector0.setHost("localhost"); jetty.addConnector(connector0); jetty.start(); HashMap<String, Object> params = new HashMap(); params.put(AeroGearConstants.QUEUE_NAME, "testQueue"); params.put(AeroGearConstants.ENDPOINT_NAME, "http://localhost:8080"); params.put(AeroGearConstants.APPLICATION_ID_NAME, "9d646a12-e601-4452-9e05-efb0fccdfd08"); params.put(AeroGearConstants.APPLICATION_MASTER_SECRET_NAME, "ed75f17e-cf3c-4c9b-a503-865d91d60d40"); params.put(AeroGearConstants.RETRY_ATTEMPTS_NAME, 2); params.put(AeroGearConstants.RETRY_INTERVAL_NAME, 1); params.put(AeroGearConstants.BADGE_NAME, "99"); params.put(AeroGearConstants.ALIASES_NAME, "me,him,them"); params.put(AeroGearConstants.DEVICE_TYPE_NAME, "android,ipad"); params.put(AeroGearConstants.SOUND_NAME, "sound1"); params.put(AeroGearConstants.VARIANTS_NAME, "variant1,variant2"); Configuration configuration = createDefaultConfig() .addConnectorServiceConfiguration( new ConnectorServiceConfiguration() .setFactoryClassName(AeroGearConnectorServiceFactory.class.getName()) .setParams(params) .setName("TestAeroGearService")) .addQueueConfiguration(new CoreQueueConfiguration() .setAddress("testQueue") .setName("testQueue")); server = createServer(configuration); server.start(); } @Override @After public void tearDown() throws Exception { if (jetty != null) { jetty.stop(); } if (locator != null) { locator.close(); } if (server != null) { server.stop(); } super.tearDown(); } @Test public void aerogearSimpleReceiveTest() throws Exception { CountDownLatch latch = new CountDownLatch(1); AeroGearHandler aeroGearHandler = new AeroGearHandler(latch); jetty.addHandler(aeroGearHandler); TransportConfiguration tpconf = new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY); locator = ActiveMQClient.createServerLocatorWithoutHA(tpconf); ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); ClientProducer producer = session.createProducer("testQueue"); ClientMessage m = session.createMessage(true); m.putStringProperty(AeroGearConstants.AEROGEAR_ALERT.toString(), "hello from ActiveMQ!"); m.putStringProperty("AEROGEAR_PROP1", "prop1"); m.putBooleanProperty("AEROGEAR_PROP2", true); producer.send(m); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertNotNull(aeroGearHandler.jsonObject); JSONObject body = (JSONObject) aeroGearHandler.jsonObject.get("message"); assertNotNull(body); String prop1 = body.getString("AEROGEAR_PROP1"); assertNotNull(prop1); assertEquals(prop1, "prop1"); prop1 = body.getString("AEROGEAR_PROP2"); assertNotNull(prop1); assertEquals(prop1, "true"); String alert = body.getString("alert"); assertNotNull(alert); assertEquals(alert, "hello from ActiveMQ!"); String sound = body.getString("sound"); assertNotNull(sound); assertEquals(sound, "sound1"); String badge = body.getString("badge"); assertNotNull(badge); assertEquals(badge, "99"); JSONArray jsonArray = (JSONArray) aeroGearHandler.jsonObject.get("variants"); assertNotNull(jsonArray); assertEquals(jsonArray.getString(0), "variant1"); assertEquals(jsonArray.getString(1), "variant2"); jsonArray = (JSONArray) aeroGearHandler.jsonObject.get("alias"); assertNotNull(jsonArray); assertEquals(jsonArray.getString(0), "me"); assertEquals(jsonArray.getString(1), "him"); assertEquals(jsonArray.getString(2), "them"); jsonArray = (JSONArray) aeroGearHandler.jsonObject.get("deviceType"); assertNotNull(jsonArray); assertEquals(jsonArray.getString(0), "android"); assertEquals(jsonArray.getString(1), "ipad"); Integer ttl = (Integer) aeroGearHandler.jsonObject.get("ttl"); assertNotNull(ttl); assertEquals(ttl.intValue(), 3600); latch = new CountDownLatch(1); aeroGearHandler.resetLatch(latch); //now override the properties m = session.createMessage(true); m.putStringProperty(AeroGearConstants.AEROGEAR_ALERT.toString(), "another hello from ActiveMQ!"); m.putStringProperty(AeroGearConstants.AEROGEAR_BADGE.toString(), "111"); m.putStringProperty(AeroGearConstants.AEROGEAR_SOUND.toString(), "s1"); m.putIntProperty(AeroGearConstants.AEROGEAR_TTL.toString(), 10000); m.putStringProperty(AeroGearConstants.AEROGEAR_ALIASES.toString(), "alias1,alias2"); m.putStringProperty(AeroGearConstants.AEROGEAR_DEVICE_TYPES.toString(), "dev1,dev2"); m.putStringProperty(AeroGearConstants.AEROGEAR_VARIANTS.toString(), "v1,v2"); producer.send(m); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertNotNull(aeroGearHandler.jsonObject); body = (JSONObject) aeroGearHandler.jsonObject.get("message"); assertNotNull(body); alert = body.getString("alert"); assertNotNull(alert); assertEquals(alert, "another hello from ActiveMQ!"); sound = body.getString("sound"); assertNotNull(sound); assertEquals(sound, "s1"); badge = body.getString("badge"); assertNotNull(badge); assertEquals(badge, "111"); jsonArray = (JSONArray) aeroGearHandler.jsonObject.get("variants"); assertNotNull(jsonArray); assertEquals(jsonArray.getString(0), "v1"); assertEquals(jsonArray.getString(1), "v2"); jsonArray = (JSONArray) aeroGearHandler.jsonObject.get("alias"); assertNotNull(jsonArray); assertEquals(jsonArray.getString(0), "alias1"); assertEquals(jsonArray.getString(1), "alias2"); jsonArray = (JSONArray) aeroGearHandler.jsonObject.get("deviceType"); assertNotNull(jsonArray); assertEquals(jsonArray.getString(0), "dev1"); assertEquals(jsonArray.getString(1), "dev2"); ttl = (Integer) aeroGearHandler.jsonObject.get("ttl"); assertNotNull(ttl); assertEquals(ttl.intValue(), 10000); session.start(); ClientMessage message = session.createConsumer("testQueue").receiveImmediate(); assertNull(message); } class AeroGearHandler extends AbstractHandler { JSONObject jsonObject; private CountDownLatch latch; public AeroGearHandler(CountDownLatch latch) { this.latch = latch; } @Override public void handle(String target, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { Request request = (Request) httpServletRequest; httpServletResponse.setContentType("text/html"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); request.setHandled(true); byte[] bytes = new byte[httpServletRequest.getContentLength()]; httpServletRequest.getInputStream().read(bytes); String json = new String(bytes); try { jsonObject = new JSONObject(json); } catch (JSONException e) { jsonObject = null; } latch.countDown(); } public void resetLatch(CountDownLatch latch) { this.latch = latch; } } @Test public void aerogearReconnectTest() throws Exception { jetty.stop(); final CountDownLatch reconnectLatch = new CountDownLatch(1); jetty.addHandler(new AbstractHandler() { @Override public void handle(String target, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { Request request = (Request) httpServletRequest; httpServletResponse.setContentType("text/html"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); request.setHandled(true); reconnectLatch.countDown(); } }); TransportConfiguration tpconf = new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY); locator = ActiveMQClient.createServerLocatorWithoutHA(tpconf); ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); ClientProducer producer = session.createProducer("testQueue"); final CountDownLatch latch = new CountDownLatch(2); ClientMessage m = session.createMessage(true); m.putStringProperty(AeroGearConstants.AEROGEAR_ALERT.toString(), "hello from ActiveMQ!"); producer.send(m, new SendAcknowledgementHandler() { @Override public void sendAcknowledged(Message message) { latch.countDown(); } }); m = session.createMessage(true); m.putStringProperty(AeroGearConstants.AEROGEAR_ALERT.toString(), "another hello from ActiveMQ!"); producer.send(m, new SendAcknowledgementHandler() { @Override public void sendAcknowledged(Message message) { latch.countDown(); } }); latch.await(5, TimeUnit.SECONDS); Thread.sleep(1000); jetty.start(); reconnectLatch.await(5, TimeUnit.SECONDS); session.start(); ClientMessage message = session.createConsumer("testQueue").receiveImmediate(); assertNull(message); } @Test public void aerogear401() throws Exception { final CountDownLatch latch = new CountDownLatch(1); jetty.addHandler(new AbstractHandler() { @Override public void handle(String target, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { Request request = (Request) httpServletRequest; httpServletResponse.setContentType("text/html"); httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); request.setHandled(true); latch.countDown(); } }); TransportConfiguration tpconf = new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY); locator = ActiveMQClient.createServerLocatorWithoutHA(tpconf); ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); ClientProducer producer = session.createProducer("testQueue"); ClientMessage m = session.createMessage(true); m.putStringProperty(AeroGearConstants.AEROGEAR_ALERT.toString(), "hello from ActiveMQ!"); producer.send(m); m = session.createMessage(true); m.putStringProperty(AeroGearConstants.AEROGEAR_ALERT.toString(), "another hello from ActiveMQ!"); producer.send(m); assertTrue(latch.await(5, TimeUnit.SECONDS)); session.start(); ClientConsumer consumer = session.createConsumer("testQueue"); ClientMessage message = consumer.receive(5000); assertNotNull(message); message = consumer.receive(5000); assertNotNull(message); } @Test public void aerogear404() throws Exception { jetty.addHandler(new AbstractHandler() { @Override public void handle(String target, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { Request request = (Request) httpServletRequest; httpServletResponse.setContentType("text/html"); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); request.setHandled(true); } }); TransportConfiguration tpconf = new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY); locator = ActiveMQClient.createServerLocatorWithoutHA(tpconf); ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); ClientProducer producer = session.createProducer("testQueue"); ClientMessage m = session.createMessage(true); m.putStringProperty(AeroGearConstants.AEROGEAR_ALERT.toString(), "hello from ActiveMQ!"); producer.send(m); m = session.createMessage(true); m.putStringProperty(AeroGearConstants.AEROGEAR_ALERT.toString(), "another hello from ActiveMQ!"); producer.send(m); session.start(); ClientConsumer consumer = session.createConsumer("testQueue"); ClientMessage message = consumer.receive(5000); assertNotNull(message); message = consumer.receive(5000); assertNotNull(message); } }
/* * Copyright 2015 ctakesoft.com<[email protected]> * * 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.ctakesoft.ctassistant; import android.app.Activity; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.customtabs.CustomTabsCallback; import android.support.customtabs.CustomTabsClient; import android.support.customtabs.CustomTabsServiceConnection; import android.support.customtabs.CustomTabsSession; import android.text.TextUtils; import android.util.Log; import org.chromium.customtabsclient.shared.CustomTabsHelper; import org.chromium.customtabsclient.shared.ServiceConnection; import org.chromium.customtabsclient.shared.ServiceConnectionCallback; /** * Chrome Custom Tabs Assistant main class */ public final class Assistant implements ServiceConnectionCallback { @SuppressWarnings("unused") private static final String TAG = Assistant.class.getSimpleName(); @SuppressWarnings("unused") private final Assistant self = this; private static class NavigationCallback extends CustomTabsCallback { @Override public void onNavigationEvent(int navigationEvent, Bundle extras) { // Log.i(TAG, "onNavigationEvent: Code = " + navigationEvent); } } private Context mContext; private ConnectionCallback mCallback; private CustomTabsSession mCustomTabsSession; private CustomTabsClient mClient; private CustomTabsServiceConnection mConnection; private String mPackageNameToBind; /** * constructor * * @param context Activity to start the Chrome Custom Tabs * @param callback It will be set if you want to be notified of the connection result. */ public Assistant(@NonNull Activity context, @Nullable ConnectionCallback callback) { mContext = context; mCallback = callback; } /** * Service connection request for preload */ public void connect() { if (!bindCustomTabsService()) { if (mCallback != null) { mCallback.onFailed(); } } } /** * Service disconnection request */ public void disConnect() { unbindCustomTabsService(); } public void destroy() { mCallback = null; } public void preLoad(@NonNull String urlString) { // pre load CustomTabsSession session = getSession(); if (session == null || !session.mayLaunchUrl(Uri.parse(urlString), null, null)) { Log.w(TAG, "createIntentBuilder: mayLaunchUrl failed"); } } /** * Creating builder for generating Chrome Custom Tabs. * * @return {@link AssistantIntent.Builder} */ public AssistantIntent.Builder createIntentBuilder() { return new AssistantIntent.Builder(mContext, getSession()); } /** * Launch the Chrome Custom Tabs. * * @param assistantIntent The resulting AssistantIntent * @param urlString url string */ public void launch(@NonNull AssistantIntent assistantIntent, @NonNull String urlString) { openCustomTab((Activity) mContext, assistantIntent, Uri.parse(urlString), new AssistantWebView()); } /* ----- internals ----- */ private boolean bindCustomTabsService() { if (mClient != null) { return false; } if (TextUtils.isEmpty(mPackageNameToBind)) { mPackageNameToBind = CustomTabsHelper.getPackageNameToUse(mContext); if (mPackageNameToBind == null) { return false; } } mConnection = new ServiceConnection(this); boolean ok = CustomTabsClient.bindCustomTabsService(mContext, mPackageNameToBind, mConnection); if (!ok) { mConnection = null; } return ok; } private void unbindCustomTabsService() { if (mConnection == null) { // not connected. return; } mContext.unbindService(mConnection); mClient = null; mCustomTabsSession = null; } private CustomTabsSession getSession() { if (mClient == null) { mCustomTabsSession = null; } else if (mCustomTabsSession == null) { mCustomTabsSession = mClient.newSession(new NavigationCallback()); } return mCustomTabsSession; } @Override public void onServiceConnected(CustomTabsClient client) { Log.d(TAG, "onServiceConnected() called with " + "client = [" + client + "]"); mClient = client; if (mClient != null) { if (!mClient.warmup(0)) { Log.w(TAG, "onServiceConnected: WarmUp failed"); } } if (mCallback != null) { mCallback.onConnected(); } } @Override public void onServiceDisconnected() { Log.d(TAG, "onServiceDisconnected() called with " + ""); mClient = null; if (mCallback != null) { mCallback.onDisconnected(); } } /** * Opens the URL on a Custom Tab if possible. Otherwise fallsback to opening it on a WebView. * * @param activity The host activity. * @param assistantIntent a CustomTabsIntent to be used if Custom Tabs is available. * @param uri the Uri to be opened. * @param fallback a CustomTabFallback to be used if Custom Tabs is not available. */ static void openCustomTab(Activity activity, AssistantIntent assistantIntent, Uri uri, CustomTabFallback fallback) { String packageName = CustomTabsHelper.getPackageNameToUse(activity); //If we cant find a package name, it means theres no browser that supports //Chrome Custom Tabs installed. So, we fallback to the webview if (packageName == null) { if (fallback != null) { fallback.openUri(activity, uri); } } else { assistantIntent.setPackage(packageName); assistantIntent.launchUrl(activity, uri); } } /** * To be used as a fallback to open the Uri when Custom Tabs is not available. */ interface CustomTabFallback { /** * @param activity The Activity that wants to open the Uri. * @param uri The uri to be opened by the fallback. */ void openUri(Activity activity, Uri uri); } }
/* * Copyright (C) 2013 salesforce.com, 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 org.auraframework.components.perf; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import javax.inject.Inject; import org.apache.log4j.Logger; import org.auraframework.adapter.ServletUtilAdapter; import org.auraframework.annotations.Annotations.ServiceComponent; import org.auraframework.def.ApplicationDef; import org.auraframework.def.BaseComponentDef; import org.auraframework.def.ClientLibraryDef; import org.auraframework.def.ComponentDef; import org.auraframework.def.ControllerDef; import org.auraframework.def.DefDescriptor; import org.auraframework.def.DefDescriptor.DefType; import org.auraframework.def.Definition; import org.auraframework.def.DescriptorFilter; import org.auraframework.def.HelperDef; import org.auraframework.def.IncludeDefRef; import org.auraframework.def.LibraryDef; import org.auraframework.def.ProviderDef; import org.auraframework.def.RendererDef; import org.auraframework.def.StyleDef; import org.auraframework.def.module.ModuleDef; import org.auraframework.def.module.ModuleDef.CodeType; import org.auraframework.ds.servicecomponent.Controller; import org.auraframework.http.resource.AppJs; import org.auraframework.impl.util.AuraUtil; import org.auraframework.service.ContextService; import org.auraframework.service.DefinitionService; import org.auraframework.system.Annotations.ActionGroup; import org.auraframework.system.Annotations.AuraEnabled; import org.auraframework.system.Annotations.Key; import org.auraframework.throwable.ClientOutOfSyncException; import org.auraframework.throwable.quickfix.DefinitionNotFoundException; import org.auraframework.throwable.quickfix.QuickFixException; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.gson.Gson; @ServiceComponent public class DependenciesController implements Controller { private static final Logger logger = Logger.getLogger(DependenciesController.class); @Inject private DefinitionService definitionService; @Inject AppJs appJs; @Inject ContextService contextService; @Inject ServletUtilAdapter servletUtilAdapter; @AuraEnabled @ActionGroup(value = "dependencies-app") public Map<String, Node> createGraph(@Key("app")String app) throws Exception { DescriptorFilter matcher = new DescriptorFilter(app, DefType.APPLICATION); Set<DefDescriptor<?>> descriptors = definitionService.find(matcher); if (descriptors == null || descriptors.size() == 0) { return null; } DefDescriptor<?> root = (DefDescriptor<?>)descriptors.toArray()[0]; Node rootNode = new Node(root); Graph graph = new Graph(rootNode); Set<String> visited = new HashSet<>(); buildGraph(graph, rootNode, visited); return graph.getNodes(); } @AuraEnabled @ActionGroup(value = "dependencies-app") public Map<String, Map<String, String>> getClientLibraryDependencies(@Key("app")String app) throws Exception { Map<String, Map<String, String>> result = new HashMap<>(); Map<String, List<String>> consumers = new HashMap<>(); DescriptorFilter matcher = new DescriptorFilter(app, DefType.APPLICATION); Set<DefDescriptor<?>> descriptors = definitionService.find(matcher); if (descriptors == null || descriptors.size() == 0) { return null; } DefDescriptor<?> appDesc = (DefDescriptor<?>)descriptors.toArray()[0]; String uid = definitionService.getUid(null, appDesc); List<ClientLibraryDef> clientLibDefs = definitionService.getClientLibraries(uid); for (ClientLibraryDef clientLibDef : clientLibDefs) { String clientLibName = clientLibDef.getLibraryName(); Map<String, String> info = new HashMap<>(); info.put("prefetch", Boolean.toString(clientLibDef.shouldPrefetch())); result.put(clientLibName, info); consumers.put(clientLibName, new ArrayList<>()); } // find all components which include the client library to the app for (DefDescriptor<?> dependency : definitionService.getDependencies(uid)) { Definition def = definitionService.getDefinition(dependency); if (def instanceof BaseComponentDef) { List<ClientLibraryDef> clientLibDeps = ((BaseComponentDef)def).getClientLibraries(); for (ClientLibraryDef clientLibDep : clientLibDeps) { List<String> list = consumers.get(clientLibDep.getLibraryName()); list.add(dependency.getQualifiedName()); } } } for (ClientLibraryDef clientLibDef : clientLibDefs) { String clientLibName = clientLibDef.getLibraryName(); result.get(clientLibName).put("consumers", consumers.get(clientLibName).toString()); } return result; } @AuraEnabled @ActionGroup(value = "dependencies-app") public Set<String> getAllDescriptors() { // Note: DescriptorFilter with all DefTypes does not seem to work, so doing all separate DescriptorFilter matcher = new DescriptorFilter("markup://*:*", DefType.COMPONENT); Set<DefDescriptor<?>> descriptors = definitionService.find(matcher); matcher = new DescriptorFilter("markup://*:*", DefType.APPLICATION); descriptors.addAll(definitionService.find(matcher)); matcher = new DescriptorFilter("markup://*:*", DefType.LIBRARY); descriptors.addAll(definitionService.find(matcher)); Set<String> list = new HashSet<>(); for (DefDescriptor<?> descriptor : descriptors) { list.add(descriptor.toString() + "@" + descriptor.getDefType()); } return list; } @AuraEnabled @ActionGroup(value = "dependencies-app") public Map<String, Object> getDependencies(@Key("component")String component) { DefDescriptor<?> descriptor; SortedSet<DefDescriptor<?>> sorted; Map<String, Object> dependencies = Maps.newHashMap(); ArrayList<String> list = Lists.newArrayList(); String uid; int pos = component.indexOf("@"); if (pos != -1) { component = component.substring(0, pos); } DescriptorFilter filter = new DescriptorFilter(component, Lists.newArrayList(DefType.LIBRARY,DefType.COMPONENT,DefType.APPLICATION)); Set<DefDescriptor<?>> descriptors = definitionService.find(filter); if (descriptors.size() != 1) { return null; } descriptor = descriptors.iterator().next(); try { Definition def = definitionService.getDefinition(descriptor); if (def == null) { return null; } descriptor = def.getDescriptor(); uid = definitionService.getUid(null, descriptor); sorted = Sets.newTreeSet(definitionService.getDependencies(uid)); for (DefDescriptor<?> dep : sorted) { def = definitionService.getDefinition(dep); DefType type = dep.getDefType(); if (type != DefType.EVENT && type != DefType.COMPONENT && type != DefType.INTERFACE && type != DefType.LIBRARY || (def.getDescriptor().getNamespace().equals("aura") || def.getDescriptor().getNamespace().equals("auradev"))) { continue; } list.add(dep.toString() + "@" + dep.getDefType()); } dependencies.put("dependencies", list); dependencies.put("def", component); return dependencies; } catch (Throwable t) { return null; } } /** * Used by the traceDependencies.app application. * Returns a similar set of data to getDependencies method, but also includes UIDs and HashCodes which help us diagnose * COOS issues. * * @param component * @return */ @SuppressWarnings("unchecked") @AuraEnabled @ActionGroup(value = "dependencies-app") public Map<String, Object> getDependenciesWithHashCodes(@Key("component")String component) { DefDescriptor<?> descriptor = null; SortedSet<DefDescriptor<?>> sorted; Map<String, Object> dependencies = Maps.newHashMap(); ArrayList<Map<String, String>> dependenciesData = Lists.newArrayList(); String uid; String specifiedDefType = null; // Allows specifying what type you want, since descriptor isn't enough. @SuppressWarnings({ "serial", "rawtypes" }) final Map<String, Class> prefixToTypeMap = new HashMap<String, Class>() {{ put("templatecss", StyleDef.class); put("js@helper", HelperDef.class); put("js@controller", ControllerDef.class); put("js@renderer", RendererDef.class); put("js@provider", ProviderDef.class); }}; if (component.contains("@")) { final String[] descriptorPair = component.split("@"); component = descriptorPair[0]; specifiedDefType = descriptorPair[1].toLowerCase(); } try { if(component.contains("://")) { final String[] pair = component.split("://"); final String prefix = pair[0].toLowerCase(); final String key = (specifiedDefType != null) ? prefix + "@" + specifiedDefType : prefix; if(prefixToTypeMap.containsKey(key)) { descriptor = definitionService.getDefDescriptor(component, prefixToTypeMap.get(key)); } } if(descriptor == null) { final DescriptorFilter filter = new DescriptorFilter(component, Lists.newArrayList(DefType.LIBRARY,DefType.COMPONENT,DefType.APPLICATION,DefType.FLAVORED_STYLE,DefType.HELPER,DefType.CONTROLLER,DefType.STYLE,DefType.EVENT,DefType.RENDERER)); final Set<DefDescriptor<?>> descriptors = definitionService.find(filter); if (descriptors.size() != 1) { return null; } descriptor = descriptors.iterator().next(); } if(descriptor==null) { return null; } Definition definition = definitionService.getDefinition(descriptor); if (definition == null) { dependencies.put("error", "No Definition found for '" + descriptor.toString() + "'"); return dependencies; } descriptor = definition.getDescriptor(); uid = definitionService.getUid(null, descriptor); sorted = Sets.newTreeSet(definitionService.getDependencies(uid)); for (DefDescriptor<?> dependency : sorted) { definition = definitionService.getDefinition(dependency); DefType type = dependency.getDefType(); Map<String, String> returnData = Maps.newHashMap(); try { String bundle = dependency.getBundle() != null ? dependency.getBundle().getQualifiedName() : ""; returnData.put("descriptor", dependency.toString()); returnData.put("defType", type.toString()); returnData.put("uid", definitionService.getUid(null, dependency)); returnData.put("bundleName", bundle); returnData.put("hash", definitionService.getDefinition(dependency).getOwnHash()); } catch(ClientOutOfSyncException | QuickFixException ex) { returnData.put("descriptor", dependency.toString()); returnData.put("defType", type.toString()); returnData.put("error", ex.getMessage()); } dependenciesData.add(returnData); } dependencies.put("dependencies", dependenciesData); dependencies.put("def", component); return dependencies; } catch (Throwable t) { dependencies.put("error", t.getMessage()); return dependencies; } } /** * Used by the dependencyTracker.app application. Returns a similar set of data to getDependencies method, but also * includes dependency code sizes which help us analyze app.js * * @param component * @return */ @SuppressWarnings("unchecked") @AuraEnabled @ActionGroup(value = "dependencies-app") public Map<String, Object> getDependencyMetrics(@Key("component") String component) { DefDescriptor<?> descriptor = null; Map<String, Object> dependencies = Maps.newHashMap(); String specifiedDefType = null; // Allows specifying what type you want, since descriptor isn't enough. @SuppressWarnings({ "serial", "rawtypes" }) final Map<String, Class> prefixToTypeMap = new HashMap<String, Class>() { { put("templatecss", StyleDef.class); put("js@helper", HelperDef.class); put("js@controller", ControllerDef.class); put("js@renderer", RendererDef.class); put("js@provider", ProviderDef.class); } }; if (component.contains("@")) { final String[] descriptorPair = component.split("@"); component = descriptorPair[0]; specifiedDefType = descriptorPair[1].toLowerCase(); } try { if (component.contains("://")) { final String[] pair = component.split("://"); final String prefix = pair[0].toLowerCase(); final String key = (specifiedDefType != null) ? prefix + "@" + specifiedDefType : prefix; if (prefixToTypeMap.containsKey(key)) { descriptor = definitionService.getDefDescriptor(component, prefixToTypeMap.get(key)); } } if (descriptor == null) { final DescriptorFilter filter = new DescriptorFilter(component, Lists.newArrayList(DefType.LIBRARY, DefType.COMPONENT, DefType.APPLICATION, DefType.MODULE)); final Set<DefDescriptor<?>> descriptors = definitionService.find(filter); if (descriptors.size() != 1) { return null; } descriptor = descriptors.iterator().next(); } if (descriptor == null) { return null; } Definition definition = definitionService.getDefinition(descriptor); if (definition == null) { dependencies.put("error", "No Definition found for '" + descriptor.toString() + "'"); return dependencies; } dependencies.put("dependencies", getDependenciesData(definition)); dependencies.put("def", component); return dependencies; } catch (Throwable t) { dependencies.put("error", t.getMessage()); return dependencies; } } @AuraEnabled @ActionGroup(value = "dependencies-app") public Boolean writeAllDependencies(@Key("file")String file) { Set<String> descriptors = getAllDescriptors(); Map<String, Object> dependencies = Maps.newHashMap(); for (String rawDescriptor : descriptors) { Map<String, Object> list = getDependencies(rawDescriptor); if (list != null) { list.remove("def"); } dependencies.put(rawDescriptor, list); } Gson gson = new Gson(); String json = gson.toJson(dependencies); String path = AuraUtil.getAuraHome() + "/aura-resources/src/main/resources/aura/resources/"; try(PrintWriter out = new PrintWriter( path + file )) { out.println(json); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } private ArrayList<Map<String, String>> getDependenciesData(Definition definition) throws DefinitionNotFoundException, QuickFixException { Set<DefDescriptor<?>> dependencies = definition.getDependencySet(); ArrayList<Map<String, String>> dependenciesData = Lists.newArrayList(); for (DefDescriptor<?> dependency : dependencies) { String key = dependency.toString(); // ignore itself // ignore aura dependencies if (key.equals(definition.getDescriptor().toString()) || dependency.getNamespace() == null || dependency.getNamespace().toLowerCase().equals("aura")) { continue; } DefType type = dependency.getDefType(); if (type.equals(DefType.APPLICATION) || type.equals(DefType.COMPONENT) || type.equals(DefType.LIBRARY) || type.equals(DefType.MODULE)) { Map<String, String> returnData = getDependencyDetails(dependency); dependenciesData.add(returnData); } } return dependenciesData; } private Map<String, String> getDependencyDetails(DefDescriptor<?> dependency) throws DefinitionNotFoundException, QuickFixException { Map<String, String> returnData = Maps.newHashMap(); DefType type = dependency.getDefType(); try { returnData.put("descriptor", dependency.toString()); returnData.put("defType", type.toString()); String dependencyUid = definitionService.getUid(null, dependency); int size = 0; int prodSize = 0; boolean outputDependencyMetric = false; // output file size if defType has it if (type.equals(DefType.APPLICATION)) { ApplicationDef applicationDef = (ApplicationDef)definitionService.getDefinition(dependency); size = applicationDef.getCode(false).getBytes().length; prodSize = applicationDef.getCode(true).getBytes().length; outputDependencyMetric = true; } else if (type.equals(DefType.COMPONENT)) { ComponentDef componentDef = (ComponentDef)definitionService.getDefinition(dependency); size = componentDef.getCode(false).getBytes().length; prodSize = componentDef.getCode(true).getBytes().length; outputDependencyMetric = true; } else if (type.equals(DefType.LIBRARY)) { LibraryDef libDef = (LibraryDef)definitionService.getDefinition(dependency); for (IncludeDefRef includeDefRef : libDef.getIncludes()) { size += includeDefRef.getCode(false).getBytes().length; prodSize += includeDefRef.getCode(true).getBytes().length; } outputDependencyMetric = true; } else if (type.equals(DefType.MODULE)) { ModuleDef moduleDef = (ModuleDef)definitionService.getDefinition(dependency); size = moduleDef.getCode(CodeType.DEV).getBytes().length; prodSize = moduleDef.getCode(CodeType.PROD).getBytes().length; outputDependencyMetric = true; } if (size > 0) { returnData.put("fileSize", String.valueOf(size)); } if (prodSize > 0) { returnData.put("prodFileSize", String.valueOf(prodSize)); } if (outputDependencyMetric) { int innerDependencySize = 0; int prodInnerDependencySize = 0; int numberOfDeps = 0; SortedSet<DefDescriptor<?>> dependencies = Sets.newTreeSet(definitionService.getDependencies(dependencyUid)); for (DefDescriptor<?> innerDependency : dependencies) { String key = innerDependency.toString(); // ignore itself // ignore aura dependencies if (key.equals(dependency.toString()) || innerDependency.getNamespace() == null || innerDependency.getNamespace().equals("aura")) { continue; } type = innerDependency.getDefType(); boolean outputInnerDependencyMetrics = false; if (type.equals(DefType.COMPONENT)) { ComponentDef componentDef = (ComponentDef)definitionService.getDefinition(innerDependency); innerDependencySize += componentDef.getCode(false).getBytes().length; prodInnerDependencySize += componentDef.getCode(true).getBytes().length; outputInnerDependencyMetrics = true; } else if (type.equals(DefType.LIBRARY)) { LibraryDef libDef = (LibraryDef)definitionService.getDefinition(innerDependency); for (IncludeDefRef includeDefRef : libDef.getIncludes()) { innerDependencySize += includeDefRef.getCode(false).getBytes().length; prodInnerDependencySize += includeDefRef.getCode(true).getBytes().length; } outputInnerDependencyMetrics = true; } if (outputInnerDependencyMetrics) { numberOfDeps++; } } returnData.put("numberOfDependency", String.valueOf(numberOfDeps)); returnData.put("innerDependencySize", String.valueOf(innerDependencySize)); returnData.put("innerDependencyProdSize", String.valueOf(prodInnerDependencySize)); } } catch (ClientOutOfSyncException | QuickFixException ex) { returnData.put("descriptor", dependency.toString()); returnData.put("defType", type.toString()); returnData.put("error", ex.getMessage()); } return returnData; } private void buildGraph(Graph graph, Node current, Set<String> visited) throws DefinitionNotFoundException, QuickFixException { if (visited.contains(current.getDescriptor().getQualifiedName())) { return; } Definition def; try { def = definitionService.getDefinition(current.getDescriptor()); } catch(Exception e) { // If it fails to get definition, have to drop it for now... logger.error("Failed to get defnition for " + current, e); return; } Set<DefDescriptor<?>> hardDependencies = def.getDependencySet(); //TODO: figure out if we can add the serialized def size as well current.setOwnSize(getCodeSize(def)); visited.add(current.getDescriptor().getQualifiedName()); logger.info("Visiting : " + current.getDescriptor() ); logger.info("Found Deps: " + hardDependencies.toString() + " " + hardDependencies.size()); for (DefDescriptor<?> depDescr : hardDependencies) { if (isWantedDescriptor(depDescr)) { Node toNode = graph.findNode(depDescr.getQualifiedName()); if (toNode == null) { toNode = new Node(depDescr); graph.addNodeIfAbsent(toNode); } graph.addEdge(current, toNode); buildGraph(graph, toNode, visited); } } } private final static Set<String> namespaceBlackList = new HashSet<>(Arrays.asList("aura", "auradev")); private final static Set<DefType> defTypeWhitelist = new HashSet<>(Arrays.asList( DefType.APPLICATION, DefType.COMPONENT, DefType.LIBRARY, DefType.INTERFACE, DefType.MODULE)); private boolean isWantedDescriptor(DefDescriptor<? extends Definition> descriptor) { return defTypeWhitelist.contains(descriptor.getDefType()) && !namespaceBlackList.contains(descriptor.getNamespace()); } private int getCodeSize(Definition def) { DefType type = def.getDescriptor().getDefType(); switch (type) { case APPLICATION : return ((ApplicationDef) def).getCode(true).getBytes().length; case COMPONENT: return ((ComponentDef) def).getCode(true).getBytes().length; case LIBRARY: int libSize = 0; for (IncludeDefRef includeDefRef : ((LibraryDef) def).getIncludes()) { libSize += includeDefRef.getCode(true).getBytes().length; } return libSize; case MODULE: return ((ModuleDef)def).getCode(CodeType.PROD).getBytes().length; default: return 0; } } }
/* * 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.flink.runtime.blob; import org.apache.flink.configuration.Configuration; import org.apache.flink.api.common.JobID; import org.apache.flink.runtime.concurrent.Future; import org.apache.flink.runtime.concurrent.FutureUtils; import org.apache.flink.runtime.concurrent.impl.FlinkCompletableFuture; import org.apache.flink.util.OperatingSystem; import org.apache.flink.util.Preconditions; import org.apache.flink.util.TestLogger; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static org.junit.Assert.*; import static org.junit.Assume.assumeTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * Tests for successful and failing PUT operations against the BLOB server, * and successful GET operations. */ public class BlobServerPutTest extends TestLogger { private final Random rnd = new Random(); @Test public void testPutBufferSuccessful() throws IOException { BlobServer server = null; BlobClient client = null; try { Configuration config = new Configuration(); server = new BlobServer(config, new VoidBlobStore()); InetSocketAddress serverAddress = new InetSocketAddress("localhost", server.getPort()); client = new BlobClient(serverAddress, config); byte[] data = new byte[2000000]; rnd.nextBytes(data); // put content addressable (like libraries) BlobKey key1 = client.put(data); assertNotNull(key1); BlobKey key2 = client.put(data, 10, 44); assertNotNull(key2); // put under job and name scope JobID jid = new JobID(); String stringKey = "my test key"; client.put(jid, stringKey, data); // --- GET the data and check that it is equal --- // one get request on the same client InputStream is1 = client.get(key2); byte[] result1 = new byte[44]; BlobUtils.readFully(is1, result1, 0, result1.length, null); is1.close(); for (int i = 0, j = 10; i < result1.length; i++, j++) { assertEquals(data[j], result1[i]); } // close the client and create a new one for the remaining requests client.close(); client = new BlobClient(serverAddress, config); InputStream is2 = client.get(key1); byte[] result2 = new byte[data.length]; BlobUtils.readFully(is2, result2, 0, result2.length, null); is2.close(); assertArrayEquals(data, result2); InputStream is3 = client.get(jid, stringKey); byte[] result3 = new byte[data.length]; BlobUtils.readFully(is3, result3, 0, result3.length, null); is3.close(); assertArrayEquals(data, result3); } finally { if (client != null) { client.close(); } if (server != null) { server.close(); } } } @Test public void testPutStreamSuccessful() throws IOException { BlobServer server = null; BlobClient client = null; try { Configuration config = new Configuration(); server = new BlobServer(config, new VoidBlobStore()); InetSocketAddress serverAddress = new InetSocketAddress("localhost", server.getPort()); client = new BlobClient(serverAddress, config); byte[] data = new byte[2000000]; rnd.nextBytes(data); // put content addressable (like libraries) { BlobKey key1 = client.put(new ByteArrayInputStream(data)); assertNotNull(key1); } // put under job and name scope { JobID jid = new JobID(); String stringKey = "my test key"; client.put(jid, stringKey, new ByteArrayInputStream(data)); } } finally { if (client != null) { try { client.close(); } catch (Throwable t) { t.printStackTrace(); } } if (server != null) { server.close(); } } } @Test public void testPutChunkedStreamSuccessful() throws IOException { BlobServer server = null; BlobClient client = null; try { Configuration config = new Configuration(); server = new BlobServer(config, new VoidBlobStore()); InetSocketAddress serverAddress = new InetSocketAddress("localhost", server.getPort()); client = new BlobClient(serverAddress, config); byte[] data = new byte[2000000]; rnd.nextBytes(data); // put content addressable (like libraries) { BlobKey key1 = client.put(new ChunkedInputStream(data, 19)); assertNotNull(key1); } // put under job and name scope { JobID jid = new JobID(); String stringKey = "my test key"; client.put(jid, stringKey, new ChunkedInputStream(data, 17)); } } finally { if (client != null) { client.close(); } if (server != null) { server.close(); } } } @Test public void testPutBufferFails() throws IOException { assumeTrue(!OperatingSystem.isWindows()); //setWritable doesn't work on Windows. BlobServer server = null; BlobClient client = null; File tempFileDir = null; try { Configuration config = new Configuration(); server = new BlobServer(config, new VoidBlobStore()); // make sure the blob server cannot create any files in its storage dir tempFileDir = server.createTemporaryFilename().getParentFile().getParentFile(); assertTrue(tempFileDir.setExecutable(true, false)); assertTrue(tempFileDir.setReadable(true, false)); assertTrue(tempFileDir.setWritable(false, false)); InetSocketAddress serverAddress = new InetSocketAddress("localhost", server.getPort()); client = new BlobClient(serverAddress, config); byte[] data = new byte[2000000]; rnd.nextBytes(data); // put content addressable (like libraries) try { client.put(data); fail("This should fail."); } catch (IOException e) { assertTrue(e.getMessage(), e.getMessage().contains("Server side error")); } try { client.put(data); fail("Client should be closed"); } catch (IllegalStateException e) { // expected } } finally { // set writable again to make sure we can remove the directory if (tempFileDir != null) { tempFileDir.setWritable(true, false); } if (client != null) { client.close(); } if (server != null) { server.close(); } } } @Test public void testPutNamedBufferFails() throws IOException { assumeTrue(!OperatingSystem.isWindows()); //setWritable doesn't work on Windows. BlobServer server = null; BlobClient client = null; File tempFileDir = null; try { Configuration config = new Configuration(); server = new BlobServer(config, new VoidBlobStore()); // make sure the blob server cannot create any files in its storage dir tempFileDir = server.createTemporaryFilename().getParentFile().getParentFile(); assertTrue(tempFileDir.setExecutable(true, false)); assertTrue(tempFileDir.setReadable(true, false)); assertTrue(tempFileDir.setWritable(false, false)); InetSocketAddress serverAddress = new InetSocketAddress("localhost", server.getPort()); client = new BlobClient(serverAddress, config); byte[] data = new byte[2000000]; rnd.nextBytes(data); // put under job and name scope try { JobID jid = new JobID(); String stringKey = "my test key"; client.put(jid, stringKey, data); fail("This should fail."); } catch (IOException e) { assertTrue(e.getMessage(), e.getMessage().contains("Server side error")); } try { JobID jid = new JobID(); String stringKey = "another key"; client.put(jid, stringKey, data); fail("Client should be closed"); } catch (IllegalStateException e) { // expected } } finally { // set writable again to make sure we can remove the directory if (tempFileDir != null) { tempFileDir.setWritable(true, false); } if (client != null) { client.close(); } if (server != null) { server.close(); } } } /** * FLINK-6020 * * Tests that concurrent put operations will only upload the file once to the {@link BlobStore}. */ @Test public void testConcurrentPutOperations() throws IOException, ExecutionException, InterruptedException { final Configuration configuration = new Configuration(); BlobStore blobStore = mock(BlobStore.class); int concurrentPutOperations = 2; int dataSize = 1024; final CountDownLatch countDownLatch = new CountDownLatch(concurrentPutOperations); final byte[] data = new byte[dataSize]; ArrayList<Future<BlobKey>> allFutures = new ArrayList(concurrentPutOperations); ExecutorService executor = Executors.newFixedThreadPool(concurrentPutOperations); try ( final BlobServer blobServer = new BlobServer(configuration, blobStore)) { for (int i = 0; i < concurrentPutOperations; i++) { Future<BlobKey> putFuture = FlinkCompletableFuture.supplyAsync(new Callable<BlobKey>() { @Override public BlobKey call() throws Exception { try (BlobClient blobClient = blobServer.createClient()) { return blobClient.put(new BlockingInputStream(countDownLatch, data)); } } }, executor); allFutures.add(putFuture); } FutureUtils.ConjunctFuture<Collection<BlobKey>> conjunctFuture = FutureUtils.combineAll(allFutures); // wait until all operations have completed and check that no exception was thrown Collection<BlobKey> blobKeys = conjunctFuture.get(); Iterator<BlobKey> blobKeyIterator = blobKeys.iterator(); assertTrue(blobKeyIterator.hasNext()); BlobKey blobKey = blobKeyIterator.next(); // make sure that all blob keys are the same while(blobKeyIterator.hasNext()) { assertEquals(blobKey, blobKeyIterator.next()); } // check that we only uploaded the file once to the blob store verify(blobStore, times(1)).put(any(File.class), eq(blobKey)); } finally { executor.shutdownNow(); } } private static final class BlockingInputStream extends InputStream { private final CountDownLatch countDownLatch; private final byte[] data; private int index = 0; public BlockingInputStream(CountDownLatch countDownLatch, byte[] data) { this.countDownLatch = Preconditions.checkNotNull(countDownLatch); this.data = Preconditions.checkNotNull(data); } @Override public int read() throws IOException { countDownLatch.countDown(); try { countDownLatch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Blocking operation was interrupted.", e); } if (index >= data.length) { return -1; } else { return data[index++]; } } } // -------------------------------------------------------------------------------------------- private static final class ChunkedInputStream extends InputStream { private final byte[][] data; private int x = 0, y = 0; private ChunkedInputStream(byte[] data, int numChunks) { this.data = new byte[numChunks][]; int bytesPerChunk = data.length / numChunks; int bytesTaken = 0; for (int i = 0; i < numChunks - 1; i++, bytesTaken += bytesPerChunk) { this.data[i] = new byte[bytesPerChunk]; System.arraycopy(data, bytesTaken, this.data[i], 0, bytesPerChunk); } this.data[numChunks - 1] = new byte[data.length - bytesTaken]; System.arraycopy(data, bytesTaken, this.data[numChunks - 1], 0, this.data[numChunks - 1].length); } @Override public int read() { if (x < data.length) { byte[] curr = data[x]; if (y < curr.length) { byte next = curr[y]; y++; return next; } else { y = 0; x++; return read(); } } else { return -1; } } @Override public int read(byte[] b, int off, int len) throws IOException { if (len == 0) { return 0; } if (x < data.length) { byte[] curr = data[x]; if (y < curr.length) { int toCopy = Math.min(len, curr.length - y); System.arraycopy(curr, y, b, off, toCopy); y += toCopy; return toCopy; } else { y = 0; x++; return read(b, off, len); } } else { return -1; } } } }
package com.intellij.jps.cache.loader; import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.compiler.server.BuildManager; import com.intellij.compiler.server.PortableCachesLoadListener; import com.intellij.ide.util.PropertiesComponent; import com.intellij.jps.cache.JpsCacheBundle; import com.intellij.jps.cache.client.JpsServerClient; import com.intellij.jps.cache.git.GitCommitsIterator; import com.intellij.jps.cache.git.GitRepositoryUtil; import com.intellij.jps.cache.loader.JpsOutputLoader.LoaderStatus; import com.intellij.jps.cache.model.BuildTargetState; import com.intellij.jps.cache.model.JpsLoaderContext; import com.intellij.jps.cache.ui.SegmentedProgressIndicatorManager; import com.intellij.notification.NotificationAction; import com.intellij.notification.NotificationType; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.ContainerUtil; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.model.serialization.JDomSerializationUtil; import org.jetbrains.jps.model.serialization.JpsLoaderBase; import org.jetbrains.jps.model.serialization.PathMacroUtil; import org.jetbrains.jps.util.JpsPathUtil; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicBoolean; import static com.intellij.execution.process.ProcessIOExecutorService.INSTANCE; import static com.intellij.jps.cache.statistics.JpsCacheUsagesCollector.DOWNLOAD_DURATION_EVENT_ID; import static com.intellij.jps.cache.ui.JpsLoaderNotifications.*; import static org.jetbrains.jps.model.serialization.java.JpsJavaModelSerializerExtension.OUTPUT_TAG; import static org.jetbrains.jps.model.serialization.java.JpsJavaModelSerializerExtension.URL_ATTRIBUTE; public class JpsOutputLoaderManager implements Disposable { private static final Logger LOG = Logger.getInstance("com.intellij.jps.cache.loader.JpsOutputLoaderManager"); private static final String LATEST_COMMIT_ID = "JpsOutputLoaderManager.latestCommitId"; private static final double SEGMENT_SIZE = 0.33; private final AtomicBoolean hasRunningTask; private final CompilerWorkspaceConfiguration myWorkspaceConfiguration; private List<JpsOutputLoader<?>> myJpsOutputLoadersLoaders; private final JpsMetadataLoader myMetadataLoader; private final JpsServerClient myServerClient; private final String myBuildOutDir; private final Project myProject; @Override public void dispose() { } @NotNull public static JpsOutputLoaderManager getInstance(@NotNull Project project) { return project.getService(JpsOutputLoaderManager.class); } public JpsOutputLoaderManager(@NotNull Project project) { myProject = project; hasRunningTask = new AtomicBoolean(); myBuildOutDir = getBuildOutDir(myProject); myServerClient = JpsServerClient.getServerClient(); myMetadataLoader = new JpsMetadataLoader(project, myServerClient); myWorkspaceConfiguration = CompilerWorkspaceConfiguration.getInstance(myProject); // Configure build manager BuildManager buildManager = BuildManager.getInstance(); if (!buildManager.isGeneratePortableCachesEnabled()) buildManager.setGeneratePortableCachesEnabled(true); } public void load(boolean isForceUpdate, boolean verbose) { Task.Backgroundable task = new Task.Backgroundable(myProject, JpsCacheBundle.message("progress.title.updating.compiler.caches")) { @Override public void run(@NotNull ProgressIndicator indicator) { Pair<String, Integer> commitInfo = getNearestCommit(isForceUpdate, verbose); if (commitInfo != null) { assert myProject != null; myProject.getMessageBus().syncPublisher(PortableCachesLoadListener.TOPIC).loadingStarted(); // Drop JPS metadata to force plugin for downloading all compilation outputs if (isForceUpdate) { myMetadataLoader.dropCurrentProjectMetadata(); File outDir = new File(myBuildOutDir); if (outDir.exists()) { indicator.setText(JpsCacheBundle.message("progress.text.clean.output.directories")); FileUtil.delete(outDir); } LOG.info("Compilation output folder empty"); } startLoadingForCommit(commitInfo.first); } hasRunningTask.set(false); } }; if (!canRunNewLoading()) return; BackgroundableProcessIndicator processIndicator = new BackgroundableProcessIndicator(task); processIndicator.setIndeterminate(false); ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, processIndicator); } public void notifyAboutNearestCache() { Pair<String, Integer> commitInfo = getNearestCommit(false, false); if (commitInfo == null) return; String notificationContent = commitInfo.second == 1 ? JpsCacheBundle.message("notification.content.caches.are.for.current.commit") : JpsCacheBundle .message("notification.content.caches.are.for.commit.commits.prior.to.yours", commitInfo.second - 1); ApplicationManager.getApplication().invokeLater(() -> { STANDARD .createNotification(JpsCacheBundle.message("notification.title.compiler.caches.available"), notificationContent, NotificationType.INFORMATION) .addAction(NotificationAction.createSimpleExpiring(JpsCacheBundle.message("action.NotificationAction.JpsOutputLoaderManager.text.update.caches"), () -> load(false, false))) .notify(myProject); }); } @Nullable private Pair<String, Integer> getNearestCommit(boolean isForceUpdate, boolean verbose) { Map<String, Set<String>> availableCommitsPerRemote = myServerClient.getCacheKeysPerRemote(myProject); String previousCommitId = PropertiesComponent.getInstance().getValue(LATEST_COMMIT_ID); List<GitCommitsIterator> repositoryList = GitRepositoryUtil.getCommitsIterator(myProject, availableCommitsPerRemote.keySet()); String commitId = ""; int commitsBehind = 0; Set<String> availableCommitsForRemote = new HashSet<>(); for (GitCommitsIterator commitsIterator : repositoryList) { availableCommitsForRemote = availableCommitsPerRemote.get(commitsIterator.getRemote()); if (availableCommitsForRemote.contains(commitId)) continue; commitsBehind = 0; while (commitsIterator.hasNext() && !availableCommitsForRemote.contains(commitId)) { commitId = commitsIterator.next(); commitsBehind++; } } var group = verbose ? STANDARD : EVENT_LOG; if (!availableCommitsForRemote.contains(commitId)) { String warning = JpsCacheBundle.message("notification.content.not.found.any.caches.for.latest.commits.in.branch"); LOG.warn(warning); ApplicationManager.getApplication().invokeLater(() -> { group.createNotification(JpsCacheBundle.message("notification.title.jps.caches.downloader"), warning, NotificationType.WARNING).notify(myProject); }); return null; } if (previousCommitId != null && commitId.equals(previousCommitId) && !isForceUpdate) { String info = JpsCacheBundle.message("notification.content.system.contains.up.to.date.caches"); LOG.info(info); ApplicationManager.getApplication().invokeLater(() -> { group.createNotification(JpsCacheBundle.message("notification.title.jps.caches.downloader"), info, NotificationType.INFORMATION).notify(myProject); }); return null; } return Pair.create(commitId, commitsBehind); } private void startLoadingForCommit(@NotNull String commitId) { long startTime = System.currentTimeMillis(); ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); indicator.setText(JpsCacheBundle.message("progress.text.fetching.cache.for.commit", commitId)); // Loading metadata for commit Map<String, Map<String, BuildTargetState>> commitSourcesState = myMetadataLoader.loadMetadataForCommit(commitId); if (commitSourcesState == null) { LOG.warn("Couldn't load metadata for commit: " + commitId); myProject.getMessageBus().syncPublisher(PortableCachesLoadListener.TOPIC).loadingFinished(false); return; } // Calculate downloads Map<String, Map<String, BuildTargetState>> currentSourcesState = myMetadataLoader.loadCurrentProjectMetadata(); int totalDownloads = getLoaders(myProject).stream().mapToInt(loader -> loader.calculateDownloads(commitSourcesState, currentSourcesState)).sum(); indicator.setFraction(0.01); try { // Computation with loaders results. If at least one of them failed rollback all job initLoaders(commitId, indicator, totalDownloads, commitSourcesState, currentSourcesState).thenAccept(loaderStatus -> { LOG.info("Loading finished with " + loaderStatus + " status"); try { SegmentedProgressIndicatorManager indicatorManager = new SegmentedProgressIndicatorManager(indicator, totalDownloads, SEGMENT_SIZE); CompletableFuture.allOf(getLoaders(myProject).stream() .map(loader -> applyChanges(loaderStatus, loader, indicator, indicatorManager)) .toArray(CompletableFuture[]::new)) .thenRun(() -> saveStateAndNotify(loaderStatus, commitId, startTime)) .get(); } catch (InterruptedException | ExecutionException e) { LOG.warn("Unexpected exception rollback all progress", e); onFail(); getLoaders(myProject).forEach(loader -> loader.rollback()); myProject.getMessageBus().syncPublisher(PortableCachesLoadListener.TOPIC).loadingFinished(false); indicator.setText(JpsCacheBundle.message("progress.text.rolling.back.downloaded.caches")); } }).handle((result, ex) -> handleExceptions(result, ex, indicator)).get(); } catch (InterruptedException | ExecutionException e) { LOG.warn("Couldn't fetch jps compilation caches", e); onFail(); myProject.getMessageBus().syncPublisher(PortableCachesLoadListener.TOPIC).loadingFinished(false); } } @Nullable private static String getBuildOutDir(@NotNull Project project) { VirtualFile projectFile = project.getProjectFile(); String projectBasePath = project.getBasePath(); if (projectFile == null || projectBasePath == null) { LOG.warn("Project files doesn't exist"); return null; } String fileExtension = projectFile.getExtension(); if (fileExtension != null && fileExtension.equals("irp")) { LOG.warn("File base project not supported"); return null; } Path configFile = Paths.get(FileUtil.toCanonicalPath(projectFile.getPath())); Element componentTag = JDomSerializationUtil.findComponent(JpsLoaderBase.tryLoadRootElement(configFile), "ProjectRootManager"); if (componentTag == null) { LOG.warn("Component tag in config file doesn't exist"); return null; } Element output = componentTag.getChild(OUTPUT_TAG); if (output == null) { LOG.warn("Output tag in config file doesn't exist"); return null; } String url = output.getAttributeValue(URL_ATTRIBUTE); if (url == null) { LOG.warn("URL attribute in output tag doesn't exist"); return null; } return JpsPathUtil.urlToPath(url).replace("$" + PathMacroUtil.PROJECT_DIR_MACRO_NAME + "$", projectBasePath); } private synchronized boolean canRunNewLoading() { if (hasRunningTask.get()) { LOG.warn("Jps cache loading already in progress, can't start the new one"); return false; } if (myBuildOutDir == null) { LOG.warn("Build output dir is not configured for the project"); return false; } if (myWorkspaceConfiguration.MAKE_PROJECT_ON_SAVE) { LOG.warn("Project automatic build should be disabled, it can affect portable caches"); return false; } hasRunningTask.set(true); return true; } private <T> CompletableFuture<LoaderStatus> initLoaders(String commitId, ProgressIndicator indicator, int totalDownloads, Map<String, Map<String, BuildTargetState>> commitSourcesState, Map<String, Map<String, BuildTargetState>> currentSourcesState) { List<JpsOutputLoader<?>> loaders = getLoaders(myProject); // Create indicator with predefined segment size SegmentedProgressIndicatorManager downloadIndicatorManager = new SegmentedProgressIndicatorManager(indicator, totalDownloads, SEGMENT_SIZE); SegmentedProgressIndicatorManager extractIndicatorManager = new SegmentedProgressIndicatorManager(indicator, totalDownloads, SEGMENT_SIZE); JpsLoaderContext loaderContext = JpsLoaderContext.createNewContext(commitId, downloadIndicatorManager, commitSourcesState, currentSourcesState); // Start loaders with own context List<CompletableFuture<LoaderStatus>> completableFutures = ContainerUtil.map(loaders, loader -> CompletableFuture.supplyAsync(() -> loader.extract(loader.load(loaderContext), extractIndicatorManager), INSTANCE)); // Reduce loaders statuses into the one CompletableFuture<LoaderStatus> initialFuture = completableFutures.get(0); if (completableFutures.size() > 1) { for (int i = 1; i < completableFutures.size(); i++) { initialFuture = initialFuture.thenCombine(completableFutures.get(i), JpsOutputLoaderManager::combine); } } return initialFuture; } private static CompletableFuture<Void> applyChanges(LoaderStatus loaderStatus, JpsOutputLoader<?> loader, ProgressIndicator indicator, SegmentedProgressIndicatorManager indicatorManager) { if (loaderStatus == LoaderStatus.FAILED) { indicator.setText(JpsCacheBundle.message("progress.text.rolling.back")); return CompletableFuture.runAsync(() -> loader.rollback(), INSTANCE); } return CompletableFuture.runAsync(() -> loader.apply(indicatorManager), INSTANCE); } private void saveStateAndNotify(LoaderStatus loaderStatus, String commitId, long startTime) { if (loaderStatus == LoaderStatus.FAILED) { onFail(); myProject.getMessageBus().syncPublisher(PortableCachesLoadListener.TOPIC).loadingFinished(false); return; } PropertiesComponent.getInstance().setValue(LATEST_COMMIT_ID, commitId); BuildManager.getInstance().clearState(myProject); long endTime = System.currentTimeMillis() - startTime; ApplicationManager.getApplication().invokeLater(() -> { STANDARD .createNotification(JpsCacheBundle.message("notification.title.compiler.caches.loader"), JpsCacheBundle.message("notification.content.update.compiler.caches.completed.successfully.in.s", endTime / 1000), NotificationType.INFORMATION) .notify(myProject); }); DOWNLOAD_DURATION_EVENT_ID.log(endTime); myProject.getMessageBus().syncPublisher(PortableCachesLoadListener.TOPIC).loadingFinished(true); LOG.info("Loading finished"); } private Void handleExceptions(Void result, Throwable ex, ProgressIndicator indicator) { if (ex != null) { Throwable cause = ex.getCause(); if (cause instanceof ProcessCanceledException) { LOG.info("Jps caches download canceled"); } else { LOG.warn("Couldn't fetch jps compilation caches", ex); onFail(); } getLoaders(myProject).forEach(loader -> loader.rollback()); myProject.getMessageBus().syncPublisher(PortableCachesLoadListener.TOPIC).loadingFinished(false); indicator.setText(JpsCacheBundle.message("progress.text.rolling.back.downloaded.caches")); } return result; } private List<JpsOutputLoader<?>> getLoaders(@NotNull Project project) { if (myJpsOutputLoadersLoaders != null) return myJpsOutputLoadersLoaders; myJpsOutputLoadersLoaders = Arrays.asList(new JpsCacheLoader(myServerClient, project), new JpsCompilationOutputLoader(myServerClient, myBuildOutDir)); return myJpsOutputLoadersLoaders; } private static LoaderStatus combine(LoaderStatus firstStatus, LoaderStatus secondStatus) { if (firstStatus == LoaderStatus.FAILED || secondStatus == LoaderStatus.FAILED) return LoaderStatus.FAILED; return LoaderStatus.COMPLETE; } private void onFail() { ApplicationManager.getApplication().invokeLater(() -> { ATTENTION.createNotification(JpsCacheBundle.message("notification.title.compiler.caches.loader"), JpsCacheBundle.message("notification.content.update.compiler.caches.failed"), NotificationType.WARNING).notify(myProject); }); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.search.aggregations.bucket.composite; import org.apache.lucene.analysis.core.KeywordAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.LongPoint; import org.apache.lucene.document.SortedNumericDocValuesField; import org.apache.lucene.document.SortedSetDocValuesField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.RandomIndexWriter; import org.apache.lucene.search.DocIdSet; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.store.Directory; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.NumericUtils; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.index.fielddata.FieldData; import org.elasticsearch.index.mapper.KeywordFieldMapper; import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.NumberFieldMapper; import org.elasticsearch.search.DocValueFormat; import org.elasticsearch.search.aggregations.AggregatorTestCase; import org.elasticsearch.search.aggregations.LeafBucketCollector; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.elasticsearch.index.mapper.NumberFieldMapper.NumberType.DOUBLE; import static org.elasticsearch.index.mapper.NumberFieldMapper.NumberType.LONG; import static org.hamcrest.Matchers.equalTo; public class CompositeValuesCollectorQueueTests extends AggregatorTestCase { static class ClassAndName { final MappedFieldType fieldType; final Class<? extends Comparable<?>> clazz; ClassAndName(MappedFieldType fieldType, Class<? extends Comparable<?>> clazz) { this.fieldType = fieldType; this.clazz = clazz; } } public void testRandomLong() throws IOException { testRandomCase(new ClassAndName(createNumber("long", LONG) , Long.class)); } public void testRandomDouble() throws IOException { testRandomCase(new ClassAndName(createNumber("double", DOUBLE) , Double.class)); } public void testRandomDoubleAndLong() throws IOException { testRandomCase(new ClassAndName(createNumber("double", DOUBLE), Double.class), new ClassAndName(createNumber("long", LONG), Long.class)); } public void testRandomDoubleAndKeyword() throws IOException { testRandomCase(new ClassAndName(createNumber("double", DOUBLE), Double.class), new ClassAndName(createKeyword("keyword"), BytesRef.class)); } public void testRandomKeyword() throws IOException { testRandomCase(new ClassAndName(createKeyword("keyword"), BytesRef.class)); } public void testRandomLongAndKeyword() throws IOException { testRandomCase(new ClassAndName(createNumber("long", LONG), Long.class), new ClassAndName(createKeyword("keyword"), BytesRef.class)); } public void testRandomLongAndDouble() throws IOException { testRandomCase(new ClassAndName(createNumber("long", LONG), Long.class), new ClassAndName(createNumber("double", DOUBLE) , Double.class)); } public void testRandomKeywordAndLong() throws IOException { testRandomCase(new ClassAndName(createKeyword("keyword"), BytesRef.class), new ClassAndName(createNumber("long", LONG), Long.class)); } public void testRandomKeywordAndDouble() throws IOException { testRandomCase(new ClassAndName(createKeyword("keyword"), BytesRef.class), new ClassAndName(createNumber("double", DOUBLE), Double.class)); } public void testRandom() throws IOException { int numTypes = randomIntBetween(3, 8); ClassAndName[] types = new ClassAndName[numTypes]; for (int i = 0; i < numTypes; i++) { int rand = randomIntBetween(0, 2); switch (rand) { case 0: types[i] = new ClassAndName(createNumber(Integer.toString(i), LONG), Long.class); break; case 1: types[i] = new ClassAndName(createNumber(Integer.toString(i), DOUBLE), Double.class); break; case 2: types[i] = new ClassAndName(createKeyword(Integer.toString(i)), BytesRef.class); break; default: assert(false); } } testRandomCase(true, types); } private void testRandomCase(ClassAndName... types) throws IOException { testRandomCase(true, types); testRandomCase(false, types); } private void testRandomCase(boolean forceMerge, ClassAndName... types) throws IOException { final BigArrays bigArrays = BigArrays.NON_RECYCLING_INSTANCE; int numDocs = randomIntBetween(50, 100); List<Comparable<?>[]> possibleValues = new ArrayList<>(); for (ClassAndName type : types) { int numValues = randomIntBetween(1, numDocs*2); Comparable<?>[] values = new Comparable[numValues]; if (type.clazz == Long.class) { for (int i = 0; i < numValues; i++) { values[i] = randomLong(); } } else if (type.clazz == Double.class) { for (int i = 0; i < numValues; i++) { values[i] = randomDouble(); } } else if (type.clazz == BytesRef.class) { for (int i = 0; i < numValues; i++) { values[i] = new BytesRef(randomAlphaOfLengthBetween(5, 50)); } } else { assert(false); } possibleValues.add(values); } Set<CompositeKey> keys = new HashSet<>(); try (Directory directory = newDirectory()) { try (RandomIndexWriter indexWriter = new RandomIndexWriter(random(), directory, new KeywordAnalyzer())) { for (int i = 0; i < numDocs; i++) { Document document = new Document(); List<List<Comparable<?>>> docValues = new ArrayList<>(); boolean hasAllField = true; for (int j = 0; j < types.length; j++) { int numValues = randomIntBetween(0, 5); if (numValues == 0) { hasAllField = false; } List<Comparable<?>> values = new ArrayList<>(); for (int k = 0; k < numValues; k++) { values.add(possibleValues.get(j)[randomIntBetween(0, possibleValues.get(j).length-1)]); if (types[j].clazz == Long.class) { long value = (Long) values.get(k); document.add(new SortedNumericDocValuesField(types[j].fieldType.name(), value)); document.add(new LongPoint(types[j].fieldType.name(), value)); } else if (types[j].clazz == Double.class) { document.add(new SortedNumericDocValuesField(types[j].fieldType.name(), NumericUtils.doubleToSortableLong((Double) values.get(k)))); } else if (types[j].clazz == BytesRef.class) { BytesRef value = (BytesRef) values.get(k); document.add(new SortedSetDocValuesField(types[j].fieldType.name(), (BytesRef) values.get(k))); document.add(new TextField(types[j].fieldType.name(), value.utf8ToString(), Field.Store.NO)); } else { assert(false); } } docValues.add(values); } if (hasAllField) { List<CompositeKey> comb = createListCombinations(docValues); keys.addAll(comb); } indexWriter.addDocument(document); } if (forceMerge) { indexWriter.forceMerge(1); } } IndexReader reader = DirectoryReader.open(directory); int size = randomIntBetween(1, keys.size()); SingleDimensionValuesSource<?>[] sources = new SingleDimensionValuesSource[types.length]; for (int i = 0; i < types.length; i++) { final MappedFieldType fieldType = types[i].fieldType; if (types[i].clazz == Long.class) { sources[i] = new LongValuesSource(bigArrays, fieldType, context -> context.reader().getSortedNumericDocValues(fieldType.name()), value -> value, DocValueFormat.RAW, size, 1); } else if (types[i].clazz == Double.class) { sources[i] = new DoubleValuesSource(bigArrays, fieldType, context -> FieldData.sortableLongBitsToDoubles(context.reader().getSortedNumericDocValues(fieldType.name())), size, 1); } else if (types[i].clazz == BytesRef.class) { if (forceMerge) { // we don't create global ordinals but we test this mode when the reader has a single segment // since ordinals are global in this case. sources[i] = new GlobalOrdinalValuesSource(bigArrays, fieldType, context -> context.reader().getSortedSetDocValues(fieldType.name()), size, 1); } else { sources[i] = new BinaryValuesSource(fieldType, context -> FieldData.toString(context.reader().getSortedSetDocValues(fieldType.name())), size, 1); } } else { assert(false); } } CompositeKey[] expected = keys.toArray(new CompositeKey[0]); Arrays.sort(expected, (a, b) -> compareKey(a, b)); CompositeValuesCollectorQueue queue = new CompositeValuesCollectorQueue(sources, size); final SortedDocsProducer docsProducer = sources[0].createSortedDocsProducerOrNull(reader, new MatchAllDocsQuery()); for (boolean withProducer : new boolean[] {true, false}) { if (withProducer && docsProducer == null) { continue; } int pos = 0; CompositeKey last = null; while (pos < size) { queue.clear(); if (last != null) { queue.setAfter(last.values()); } for (LeafReaderContext leafReaderContext : reader.leaves()) { final LeafBucketCollector leafCollector = new LeafBucketCollector() { @Override public void collect(int doc, long bucket) throws IOException { queue.addIfCompetitive(); } }; if (withProducer) { assertEquals(DocIdSet.EMPTY, docsProducer.processLeaf(new MatchAllDocsQuery(), queue, leafReaderContext, false)); } else { final LeafBucketCollector queueCollector = queue.getLeafCollector(leafReaderContext, leafCollector); final Bits liveDocs = leafReaderContext.reader().getLiveDocs(); for (int i = 0; i < leafReaderContext.reader().maxDoc(); i++) { if (liveDocs == null || liveDocs.get(i)) { queueCollector.collect(i); } } } } assertEquals(size, Math.min(queue.size(), expected.length - pos)); int ptr = 0; for (int slot : queue.getSortedSlot()) { CompositeKey key = queue.toCompositeKey(slot); assertThat(key, equalTo(expected[ptr++])); last = key; } pos += queue.size(); } } reader.close(); } } private static MappedFieldType createNumber(String name, NumberFieldMapper.NumberType type) { MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType(type); fieldType.setIndexOptions(IndexOptions.DOCS); fieldType.setName(name); fieldType.setHasDocValues(true); fieldType.freeze(); return fieldType; } private static MappedFieldType createKeyword(String name) { MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType(); fieldType.setIndexOptions(IndexOptions.DOCS); fieldType.setName(name); fieldType.setHasDocValues(true); fieldType.freeze(); return fieldType; } private static int compareKey(CompositeKey key1, CompositeKey key2) { assert key1.size() == key2.size(); for (int i = 0; i < key1.size(); i++) { Comparable<Object> cmp1 = (Comparable<Object>) key1.get(i); int cmp = cmp1.compareTo(key2.get(i)); if (cmp != 0) { return cmp; } } return 0; } private static List<CompositeKey> createListCombinations(List<List<Comparable<?>>> values) { List<CompositeKey> keys = new ArrayList<>(); createListCombinations(new Comparable[values.size()], values, 0, values.size(), keys); return keys; } private static void createListCombinations(Comparable<?>[] key, List<List<Comparable<?>>> values, int pos, int maxPos, List<CompositeKey> keys) { if (pos == maxPos) { keys.add(new CompositeKey(key.clone())); } else { for (Comparable<?> val : values.get(pos)) { key[pos] = val; createListCombinations(key, values, pos + 1, maxPos, keys); } } } }
/* * 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.zeppelin.client; import kong.unirest.GetRequest; import kong.unirest.HttpResponse; import kong.unirest.JsonNode; import kong.unirest.Unirest; import kong.unirest.apache.ApacheClient; import kong.unirest.json.JSONArray; import kong.unirest.json.JSONObject; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.ssl.SSLContextBuilder; import org.apache.zeppelin.common.SessionInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import unirest.shaded.org.apache.http.client.HttpClient; import unirest.shaded.org.apache.http.impl.client.HttpClients; import javax.net.ssl.SSLContext; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Low level api for interacting with Zeppelin. Underneath, it use the zeppelin rest api. * You can use this class to operate Zeppelin note/paragraph, * e.g. get/add/delete/update/execute/cancel */ public class ZeppelinClient { private static final Logger LOGGER = LoggerFactory.getLogger(ZeppelinClient.class); private ClientConfig clientConfig; public ZeppelinClient(ClientConfig clientConfig) throws Exception { this.clientConfig = clientConfig; Unirest.config().defaultBaseUrl(clientConfig.getZeppelinRestUrl() + "/api"); if (clientConfig.isUseKnox()) { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) { return true; } }).build(); HttpClient customHttpClient = HttpClients.custom().setSSLContext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); Unirest.config().httpClient(ApacheClient.builder(customHttpClient)); } catch (Exception e) { throw new Exception("Fail to setup httpclient of Unirest", e); } } } public ClientConfig getClientConfig() { return clientConfig; } /** * Throw exception if the status code is not 200. * * @param response * @throws Exception */ private void checkResponse(HttpResponse<JsonNode> response) throws Exception { if (response.getStatus() == 302) { throw new Exception("Please login first"); } if (response.getStatus() != 200) { String message = response.getStatusText(); if (response.getBody() != null && response.getBody().getObject() != null && response.getBody().getObject().has("message")) { message = response.getBody().getObject().getString("message"); } throw new Exception(String.format("Unable to call rest api, status: %s, statusText: %s, message: %s", response.getStatus(), response.getStatusText(), message)); } } /** * Throw exception if the status in the json object is not `OK`. * * @param jsonNode * @throws Exception */ private void checkJsonNodeStatus(JsonNode jsonNode) throws Exception { if (! "OK".equalsIgnoreCase(jsonNode.getObject().getString("status"))) { throw new Exception(StringEscapeUtils.unescapeJava(jsonNode.getObject().getString("message"))); } } /** * Get Zeppelin version. * * @return * @throws Exception */ public String getVersion() throws Exception { HttpResponse<JsonNode> response = Unirest .get("/version") .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); return jsonNode.getObject().getJSONObject("body").getString("version"); } /** * Request a new session id. It doesn't create session (interpreter process) in zeppelin server side, but just * create an unique session id. * * @param interpreter * @return * @throws Exception */ public SessionInfo newSession(String interpreter) throws Exception { HttpResponse<JsonNode> response = Unirest .post("/session") .queryString("interpreter", interpreter) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); return createSessionInfoFromJson(jsonNode.getObject().getJSONObject("body")); } /** * Stop the session(interpreter process) in Zeppelin server. * * @param sessionId * @throws Exception */ public void stopSession(String sessionId) throws Exception { HttpResponse<JsonNode> response = Unirest .delete("/session/{sessionId}") .routeParam("sessionId", sessionId) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); } /** * Get session info for the provided sessionId. * Return null if provided sessionId doesn't exist. * * @param sessionId * @throws Exception */ public SessionInfo getSession(String sessionId) throws Exception { HttpResponse<JsonNode> response = Unirest .get("/session/{sessionId}") .routeParam("sessionId", sessionId) .asJson(); if (response.getStatus() == 404) { String statusText = response.getStatusText(); if (response.getBody().getObject().has("message")) { statusText = response.getBody().getObject().getString("message"); } if (statusText.contains("No such session")) { return null; } } checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); JSONObject bodyObject = jsonNode.getObject().getJSONObject("body"); return createSessionInfoFromJson(bodyObject); } /** * List all the sessions. * * @return * @throws Exception */ public List<SessionInfo> listSessions() throws Exception { return listSessions(null); } /** * List all the sessions for the provided interpreter. * * @param interpreter * @return * @throws Exception */ public List<SessionInfo> listSessions(String interpreter) throws Exception { GetRequest getRequest = Unirest.get("/session"); if (interpreter != null) { getRequest.queryString("interpreter", interpreter); } HttpResponse<JsonNode> response = getRequest.asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); JSONArray sessionJsonArray = jsonNode.getObject().getJSONArray("body"); List<SessionInfo> sessionInfos = new ArrayList<>(); for (int i = 0; i< sessionJsonArray.length();++i) { sessionInfos.add(createSessionInfoFromJson(sessionJsonArray.getJSONObject(i))); } return sessionInfos; } private SessionInfo createSessionInfoFromJson(JSONObject sessionJson) { SessionInfo sessionInfo = new SessionInfo(); if (sessionJson.has("sessionId")) { sessionInfo.setSessionId(sessionJson.getString("sessionId")); } if (sessionJson.has("noteId")) { sessionInfo.setNoteId(sessionJson.getString("noteId")); } if (sessionJson.has("interpreter")) { sessionInfo.setInterpreter(sessionJson.getString("interpreter")); } if (sessionJson.has("state")) { sessionInfo.setState(sessionJson.getString("state")); } if (sessionJson.has("weburl")) { sessionInfo.setWeburl(sessionJson.getString("weburl")); } if (sessionJson.has("startTime")) { sessionInfo.setStartTime(sessionJson.getString("startTime")); } return sessionInfo; } /** * Login zeppelin with userName and password, throw exception if login fails. * * @param userName * @param password * @throws Exception */ public void login(String userName, String password) throws Exception { if (clientConfig.isUseKnox()) { HttpResponse<String> response = Unirest.get(clientConfig.getKnoxSSOUrl() + "?originalUrl=" + clientConfig.getZeppelinRestUrl()) .basicAuth(userName, password) .asString(); if (response.getStatus() != 200) { throw new Exception(String.format("Knox SSO login failed, status: %s, statusText: %s", response.getStatus(), response.getStatusText())); } response = Unirest.get("/security/ticket") .asString(); if (response.getStatus() != 200) { throw new Exception(String.format("Fail to get ticket after Knox SSO, status: %s, statusText: %s", response.getStatus(), response.getStatusText())); } } else { HttpResponse<JsonNode> response = Unirest .post("/login") .field("userName", userName) .field("password", password) .asJson(); if (response.getStatus() != 200) { throw new Exception(String.format("Login failed, status: %s, statusText: %s", response.getStatus(), response.getStatusText())); } } } public String createNote(String notePath) throws Exception { return createNote(notePath, ""); } /** * Create a new empty note with provided notePath and defaultInterpreterGroup * * @param notePath * @param defaultInterpreterGroup * @return * @throws Exception */ public String createNote(String notePath, String defaultInterpreterGroup) throws Exception { JSONObject bodyObject = new JSONObject(); bodyObject.put("name", notePath); bodyObject.put("defaultInterpreterGroup", defaultInterpreterGroup); HttpResponse<JsonNode> response = Unirest .post("/notebook") .body(bodyObject.toString()) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); return jsonNode.getObject().getString("body"); } /** * Delete note with provided noteId. * * @param noteId * @throws Exception */ public void deleteNote(String noteId) throws Exception { HttpResponse<JsonNode> response = Unirest .delete("/notebook/{noteId}") .routeParam("noteId", noteId) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); } /** * Clone a note to a specified notePath. * * @param noteId * @param destPath * @return * @throws Exception */ public String cloneNote(String noteId, String destPath) throws Exception { JSONObject bodyObject = new JSONObject(); bodyObject.put("name", destPath); HttpResponse<JsonNode> response = Unirest .post("/notebook/{noteId}") .routeParam("noteId", noteId) .body(bodyObject.toString()) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); return jsonNode.getObject().getString("body"); } public void renameNote(String noteId, String newNotePath) throws Exception { JSONObject bodyObject = new JSONObject(); bodyObject.put("name", newNotePath); HttpResponse<JsonNode> response = Unirest .put("/notebook/{noteId}/rename") .routeParam("noteId", noteId) .body(bodyObject.toString()) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); } /** * Query {@link NoteResult} with provided noteId. * * @param noteId * @return * @throws Exception */ public NoteResult queryNoteResult(String noteId) throws Exception { HttpResponse<JsonNode> response = Unirest .get("/notebook/{noteId}") .routeParam("noteId", noteId) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); JSONObject noteJsonObject = jsonNode.getObject().getJSONObject("body"); boolean isRunning = false; if (noteJsonObject.has("info")) { JSONObject infoJsonObject = noteJsonObject.getJSONObject("info"); if (infoJsonObject.has("isRunning")) { isRunning = Boolean.parseBoolean(infoJsonObject.getString("isRunning")); } } String notePath = null; if (noteJsonObject.has("path")) { notePath = noteJsonObject.getString("path"); } List<ParagraphResult> paragraphResultList = new ArrayList<>(); if (noteJsonObject.has("paragraphs")) { JSONArray paragraphJsonArray = noteJsonObject.getJSONArray("paragraphs"); for (int i = 0; i< paragraphJsonArray.length(); ++i) { paragraphResultList.add(new ParagraphResult(paragraphJsonArray.getJSONObject(i))); } } return new NoteResult(noteId, notePath, isRunning, paragraphResultList); } /** * Execute note with provided noteId, return until note execution is completed. * Interpreter process will be stopped after note execution. * * @param noteId * @return * @throws Exception */ public NoteResult executeNote(String noteId) throws Exception { return executeNote(noteId, new HashMap<>()); } /** * Execute note with provided noteId and parameters, return until note execution is completed. * Interpreter process will be stopped after note execution. * * @param noteId * @param parameters * @return * @throws Exception */ public NoteResult executeNote(String noteId, Map<String, String> parameters) throws Exception { submitNote(noteId, parameters); return waitUntilNoteFinished(noteId); } /** * Submit note to execute with provided noteId, return at once the submission is completed. * You need to query {@link NoteResult} by yourself afterwards until note execution is completed. * Interpreter process will be stopped after note execution. * * @param noteId * @return * @throws Exception */ public NoteResult submitNote(String noteId) throws Exception { return submitNote(noteId, new HashMap<>()); } /** * Submit note to execute with provided noteId and parameters, return at once the submission is completed. * You need to query {@link NoteResult} by yourself afterwards until note execution is completed. * Interpreter process will be stopped after note execution. * * @param noteId * @param parameters * @return * @throws Exception */ public NoteResult submitNote(String noteId, Map<String, String> parameters) throws Exception { JSONObject bodyObject = new JSONObject(); bodyObject.put("params", parameters); // run note in non-blocking and isolated way. HttpResponse<JsonNode> response = Unirest .post("/notebook/job/{noteId}") .routeParam("noteId", noteId) .queryString("blocking", "false") .queryString("isolated", "true") .body(bodyObject) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); return queryNoteResult(noteId); } /** * Import note with given note json content to the specified notePath. * * @param notePath * @param noteContent * @return * @throws Exception */ public String importNote(String notePath, String noteContent) throws Exception { JSONObject bodyObject = new JSONObject(noteContent); HttpResponse<JsonNode> response = Unirest .post("/notebook/import") .queryString("notePath", notePath) .body(bodyObject) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); return jsonNode.getObject().getString("body"); } /** * Block there until note execution is completed. * * @param noteId * @return * @throws Exception */ public NoteResult waitUntilNoteFinished(String noteId) throws Exception { while (true) { NoteResult noteResult = queryNoteResult(noteId); if (!noteResult.isRunning()) { return noteResult; } Thread.sleep(clientConfig.getQueryInterval()); } } /** * Block there until note execution is completed, and throw exception if note execution is not completed * in <code>timeoutInMills</code>. * * @param noteId * @param timeoutInMills * @return * @throws Exception */ public NoteResult waitUntilNoteFinished(String noteId, long timeoutInMills) throws Exception { long start = System.currentTimeMillis(); while (true && (System.currentTimeMillis() - start) < timeoutInMills) { NoteResult noteResult = queryNoteResult(noteId); if (!noteResult.isRunning()) { return noteResult; } Thread.sleep(clientConfig.getQueryInterval()); } throw new Exception("Note is not finished in " + timeoutInMills / 1000 + " seconds"); } /** * Add paragraph to note with provided title and text. * * @param noteId * @param title * @param text * @return * @throws Exception */ public String addParagraph(String noteId, String title, String text) throws Exception { JSONObject bodyObject = new JSONObject(); bodyObject.put("title", title); bodyObject.put("text", text); HttpResponse<JsonNode> response = Unirest.post("/notebook/{noteId}/paragraph") .routeParam("noteId", noteId) .body(bodyObject.toString()) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); return jsonNode.getObject().getString("body"); } /** * Update paragraph with specified title and text. * * @param noteId * @param paragraphId * @param title * @param text * @throws Exception */ public void updateParagraph(String noteId, String paragraphId, String title, String text) throws Exception { JSONObject bodyObject = new JSONObject(); bodyObject.put("title", title); bodyObject.put("text", text); HttpResponse<JsonNode> response = Unirest.put("/notebook/{noteId}/paragraph/{paragraphId}") .routeParam("noteId", noteId) .routeParam("paragraphId", paragraphId) .body(bodyObject.toString()) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); } /** * Execute paragraph with parameters in specified session. If sessionId is null or empty string, then it depends on * the interpreter binding mode of Note(e.g. isolated per note), otherwise it will run in the specified session. * * @param noteId * @param paragraphId * @param sessionId * @param parameters * @return * @throws Exception */ public ParagraphResult executeParagraph(String noteId, String paragraphId, String sessionId, Map<String, String> parameters) throws Exception { submitParagraph(noteId, paragraphId, sessionId, parameters); return waitUtilParagraphFinish(noteId, paragraphId); } /** * Execute paragraph with parameters. * * @param noteId * @param paragraphId * @param parameters * @return * @throws Exception */ public ParagraphResult executeParagraph(String noteId, String paragraphId, Map<String, String> parameters) throws Exception { return executeParagraph(noteId, paragraphId, "", parameters); } /** * Execute paragraph in specified session. If sessionId is null or empty string, then it depends on * the interpreter binding mode of Note (e.g. isolated per note), otherwise it will run in the specified session. * * @param noteId * @param paragraphId * @param sessionId * @return * @throws Exception */ public ParagraphResult executeParagraph(String noteId, String paragraphId, String sessionId) throws Exception { return executeParagraph(noteId, paragraphId, sessionId, new HashMap<>()); } /** * Execute paragraph. * * @param noteId * @param paragraphId * @return * @throws Exception */ public ParagraphResult executeParagraph(String noteId, String paragraphId) throws Exception { return executeParagraph(noteId, paragraphId, "", new HashMap<>()); } /** * Submit paragraph to execute with provided parameters and sessionId. Return at once the submission is completed. * You need to query {@link ParagraphResult} by yourself afterwards until paragraph execution is completed. * * @param noteId * @param paragraphId * @param sessionId * @param parameters * @return * @throws Exception */ public ParagraphResult submitParagraph(String noteId, String paragraphId, String sessionId, Map<String, String> parameters) throws Exception { JSONObject bodyObject = new JSONObject(); bodyObject.put("params", parameters); HttpResponse<JsonNode> response = Unirest .post("/notebook/job/{noteId}/{paragraphId}") .routeParam("noteId", noteId) .routeParam("paragraphId", paragraphId) .queryString("sessionId", sessionId) .body(bodyObject.toString()) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); return queryParagraphResult(noteId, paragraphId); } /** * Submit paragraph to execute with provided sessionId. Return at once the submission is completed. * You need to query {@link ParagraphResult} by yourself afterwards until paragraph execution is completed. * * @param noteId * @param paragraphId * @param sessionId * @return * @throws Exception */ public ParagraphResult submitParagraph(String noteId, String paragraphId, String sessionId) throws Exception { return submitParagraph(noteId, paragraphId, sessionId, new HashMap<>()); } /** * Submit paragraph to execute with provided parameters. Return at once the submission is completed. * You need to query {@link ParagraphResult} by yourself afterwards until paragraph execution is completed. * * @param noteId * @param paragraphId * @param parameters * @return * @throws Exception */ public ParagraphResult submitParagraph(String noteId, String paragraphId, Map<String, String> parameters) throws Exception { return submitParagraph(noteId, paragraphId, "", parameters); } /** * Submit paragraph to execute. Return at once the submission is completed. * You need to query {@link ParagraphResult} by yourself afterwards until paragraph execution is completed. * * @param noteId * @param paragraphId * @return * @throws Exception */ public ParagraphResult submitParagraph(String noteId, String paragraphId) throws Exception { return submitParagraph(noteId, paragraphId, "", new HashMap<>()); } /** * This used by {@link ZSession} for creating or reusing a paragraph for executing another piece of code. * * @param noteId * @param maxParagraph * @return * @throws Exception */ public String nextSessionParagraph(String noteId, int maxParagraph) throws Exception { HttpResponse<JsonNode> response = Unirest .post("/notebook/{noteId}/paragraph/next") .routeParam("noteId", noteId) .queryString("maxParagraph", maxParagraph) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); return jsonNode.getObject().getString("message"); } /** * Cancel a running paragraph. * * @param noteId * @param paragraphId * @throws Exception */ public void cancelParagraph(String noteId, String paragraphId) throws Exception { HttpResponse<JsonNode> response = Unirest .delete("/notebook/job/{noteId}/{paragraphId}") .routeParam("noteId", noteId) .routeParam("paragraphId", paragraphId) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); } /** * Query {@link ParagraphResult} * * @param noteId * @param paragraphId * @return * @throws Exception */ public ParagraphResult queryParagraphResult(String noteId, String paragraphId) throws Exception { HttpResponse<JsonNode> response = Unirest .get("/notebook/{noteId}/paragraph/{paragraphId}") .routeParam("noteId", noteId) .routeParam("paragraphId", paragraphId) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); JSONObject paragraphJson = jsonNode.getObject().getJSONObject("body"); return new ParagraphResult(paragraphJson); } /** * Query {@link ParagraphResult} until it is finished. * * @param noteId * @param paragraphId * @return * @throws Exception */ public ParagraphResult waitUtilParagraphFinish(String noteId, String paragraphId) throws Exception { while (true) { ParagraphResult paragraphResult = queryParagraphResult(noteId, paragraphId); LOGGER.debug(paragraphResult.toString()); if (paragraphResult.getStatus().isCompleted()) { return paragraphResult; } Thread.sleep(clientConfig.getQueryInterval()); } } /** * Query {@link ParagraphResult} until it is finished or timeout. * * @param noteId * @param paragraphId * @param timeoutInMills * @return * @throws Exception */ public ParagraphResult waitUtilParagraphFinish(String noteId, String paragraphId, long timeoutInMills) throws Exception { long start = System.currentTimeMillis(); while (true && (System.currentTimeMillis() - start) < timeoutInMills) { ParagraphResult paragraphResult = queryParagraphResult(noteId, paragraphId); if (paragraphResult.getStatus().isCompleted()) { return paragraphResult; } Thread.sleep(clientConfig.getQueryInterval()); } throw new Exception("Paragraph is not finished in " + timeoutInMills / 1000 + " seconds"); } /** * Query {@link ParagraphResult} until it is running. * * @param noteId * @param paragraphId * @return * @throws Exception */ public ParagraphResult waitUtilParagraphRunning(String noteId, String paragraphId) throws Exception { while (true) { ParagraphResult paragraphResult = queryParagraphResult(noteId, paragraphId); if (paragraphResult.getStatus().isRunning()) { return paragraphResult; } Thread.sleep(clientConfig.getQueryInterval()); } } /** * This is equal to the restart operation in note page. * * @param noteId * @param interpreter */ public void stopInterpreter(String noteId, String interpreter) throws Exception { JSONObject bodyObject = new JSONObject(); bodyObject.put("noteId", noteId); HttpResponse<JsonNode> response = Unirest .put("/interpreter/setting/restart/{interpreter}") .routeParam("interpreter", interpreter) .body(bodyObject.toString()) .asJson(); checkResponse(response); JsonNode jsonNode = response.getBody(); checkJsonNodeStatus(jsonNode); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/enums/user_interest_taxonomy_type.proto package com.google.ads.googleads.v10.enums; /** * <pre> * Message describing a UserInterestTaxonomyType. * </pre> * * Protobuf type {@code google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum} */ public final class UserInterestTaxonomyTypeEnum extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum) UserInterestTaxonomyTypeEnumOrBuilder { private static final long serialVersionUID = 0L; // Use UserInterestTaxonomyTypeEnum.newBuilder() to construct. private UserInterestTaxonomyTypeEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UserInterestTaxonomyTypeEnum() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new UserInterestTaxonomyTypeEnum(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private UserInterestTaxonomyTypeEnum( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeProto.internal_static_google_ads_googleads_v10_enums_UserInterestTaxonomyTypeEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeProto.internal_static_google_ads_googleads_v10_enums_UserInterestTaxonomyTypeEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum.class, com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum.Builder.class); } /** * <pre> * Enum containing the possible UserInterestTaxonomyTypes. * </pre> * * Protobuf enum {@code google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum.UserInterestTaxonomyType} */ public enum UserInterestTaxonomyType implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> * Not specified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ UNSPECIFIED(0), /** * <pre> * Used for return value only. Represents value unknown in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ UNKNOWN(1), /** * <pre> * The affinity for this user interest. * </pre> * * <code>AFFINITY = 2;</code> */ AFFINITY(2), /** * <pre> * The market for this user interest. * </pre> * * <code>IN_MARKET = 3;</code> */ IN_MARKET(3), /** * <pre> * Users known to have installed applications in the specified categories. * </pre> * * <code>MOBILE_APP_INSTALL_USER = 4;</code> */ MOBILE_APP_INSTALL_USER(4), /** * <pre> * The geographical location of the interest-based vertical. * </pre> * * <code>VERTICAL_GEO = 5;</code> */ VERTICAL_GEO(5), /** * <pre> * User interest criteria for new smart phone users. * </pre> * * <code>NEW_SMART_PHONE_USER = 6;</code> */ NEW_SMART_PHONE_USER(6), UNRECOGNIZED(-1), ; /** * <pre> * Not specified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ public static final int UNSPECIFIED_VALUE = 0; /** * <pre> * Used for return value only. Represents value unknown in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ public static final int UNKNOWN_VALUE = 1; /** * <pre> * The affinity for this user interest. * </pre> * * <code>AFFINITY = 2;</code> */ public static final int AFFINITY_VALUE = 2; /** * <pre> * The market for this user interest. * </pre> * * <code>IN_MARKET = 3;</code> */ public static final int IN_MARKET_VALUE = 3; /** * <pre> * Users known to have installed applications in the specified categories. * </pre> * * <code>MOBILE_APP_INSTALL_USER = 4;</code> */ public static final int MOBILE_APP_INSTALL_USER_VALUE = 4; /** * <pre> * The geographical location of the interest-based vertical. * </pre> * * <code>VERTICAL_GEO = 5;</code> */ public static final int VERTICAL_GEO_VALUE = 5; /** * <pre> * User interest criteria for new smart phone users. * </pre> * * <code>NEW_SMART_PHONE_USER = 6;</code> */ public static final int NEW_SMART_PHONE_USER_VALUE = 6; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static UserInterestTaxonomyType valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static UserInterestTaxonomyType forNumber(int value) { switch (value) { case 0: return UNSPECIFIED; case 1: return UNKNOWN; case 2: return AFFINITY; case 3: return IN_MARKET; case 4: return MOBILE_APP_INSTALL_USER; case 5: return VERTICAL_GEO; case 6: return NEW_SMART_PHONE_USER; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<UserInterestTaxonomyType> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< UserInterestTaxonomyType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<UserInterestTaxonomyType>() { public UserInterestTaxonomyType findValueByNumber(int number) { return UserInterestTaxonomyType.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum.getDescriptor().getEnumTypes().get(0); } private static final UserInterestTaxonomyType[] VALUES = values(); public static UserInterestTaxonomyType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private UserInterestTaxonomyType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum.UserInterestTaxonomyType) } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum)) { return super.equals(obj); } com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum other = (com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Message describing a UserInterestTaxonomyType. * </pre> * * Protobuf type {@code google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum) com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnumOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeProto.internal_static_google_ads_googleads_v10_enums_UserInterestTaxonomyTypeEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeProto.internal_static_google_ads_googleads_v10_enums_UserInterestTaxonomyTypeEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum.class, com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum.Builder.class); } // Construct using com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeProto.internal_static_google_ads_googleads_v10_enums_UserInterestTaxonomyTypeEnum_descriptor; } @java.lang.Override public com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum getDefaultInstanceForType() { return com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum build() { com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum buildPartial() { com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum result = new com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum) { return mergeFrom((com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum other) { if (other == com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum) private static final com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum(); } public static com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UserInterestTaxonomyTypeEnum> PARSER = new com.google.protobuf.AbstractParser<UserInterestTaxonomyTypeEnum>() { @java.lang.Override public UserInterestTaxonomyTypeEnum parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new UserInterestTaxonomyTypeEnum(input, extensionRegistry); } }; public static com.google.protobuf.Parser<UserInterestTaxonomyTypeEnum> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UserInterestTaxonomyTypeEnum> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v10.enums.UserInterestTaxonomyTypeEnum getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
/* * 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 androidx.appcompat.widget; import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import androidx.annotation.RestrictTo; import androidx.appcompat.R; import androidx.appcompat.view.menu.ShowableListMenu; import androidx.core.view.ActionProvider; import androidx.core.view.accessibility.AccessibilityNodeInfoCompat; /** * This class is a view for choosing an activity for handling a given {@link Intent}. * <p> * The view is composed of two adjacent buttons: * <ul> * <li> * The left button is an immediate action and allows one click activity choosing. * Tapping this button immediately executes the intent without requiring any further * user input. Long press on this button shows a popup for changing the default * activity. * </li> * <li> * The right button is an overflow action and provides an optimized menu * of additional activities. Tapping this button shows a popup anchored to this * view, listing the most frequently used activities. This list is initially * limited to a small number of items in frequency used order. The last item, * "Show all..." serves as an affordance to display all available activities. * </li> * </ul> * </p> * * @hide */ @RestrictTo(LIBRARY_GROUP) public class ActivityChooserView extends ViewGroup implements ActivityChooserModel.ActivityChooserModelClient { private static final String LOG_TAG = "ActivityChooserView"; /** * An adapter for displaying the activities in an {@link android.widget.AdapterView}. */ final ActivityChooserViewAdapter mAdapter; /** * Implementation of various interfaces to avoid publishing them in the APIs. */ private final Callbacks mCallbacks; /** * The content of this view. */ private final View mActivityChooserContent; /** * Stores the background drawable to allow hiding and latter showing. */ private final Drawable mActivityChooserContentBackground; /** * The expand activities action button; */ final FrameLayout mExpandActivityOverflowButton; /** * The image for the expand activities action button; */ private final ImageView mExpandActivityOverflowButtonImage; /** * The default activities action button; */ final FrameLayout mDefaultActivityButton; /** * The image for the default activities action button; */ private final ImageView mDefaultActivityButtonImage; /** * The maximal width of the list popup. */ private final int mListPopupMaxWidth; /** * The ActionProvider hosting this view, if applicable. */ ActionProvider mProvider; /** * Observer for the model data. */ final DataSetObserver mModelDataSetObserver = new DataSetObserver() { @Override public void onChanged() { super.onChanged(); mAdapter.notifyDataSetChanged(); } @Override public void onInvalidated() { super.onInvalidated(); mAdapter.notifyDataSetInvalidated(); } }; private final OnGlobalLayoutListener mOnGlobalLayoutListener = new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (isShowingPopup()) { if (!isShown()) { getListPopupWindow().dismiss(); } else { getListPopupWindow().show(); if (mProvider != null) { mProvider.subUiVisibilityChanged(true); } } } } }; /** * Popup window for showing the activity overflow list. */ private ListPopupWindow mListPopupWindow; /** * Listener for the dismissal of the popup/alert. */ PopupWindow.OnDismissListener mOnDismissListener; /** * Flag whether a default activity currently being selected. */ boolean mIsSelectingDefaultActivity; /** * The count of activities in the popup. */ int mInitialActivityCount = ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_DEFAULT; /** * Flag whether this view is attached to a window. */ private boolean mIsAttachedToWindow; /** * String resource for formatting content description of the default target. */ private int mDefaultActionButtonContentDescription; /** * Create a new instance. * * @param context The application environment. */ public ActivityChooserView(Context context) { this(context, null); } /** * Create a new instance. * * @param context The application environment. * @param attrs A collection of attributes. */ public ActivityChooserView(Context context, AttributeSet attrs) { this(context, attrs, 0); } /** * Create a new instance. * * @param context The application environment. * @param attrs A collection of attributes. * @param defStyle The default style to apply to this view. */ public ActivityChooserView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray attributesArray = context.obtainStyledAttributes(attrs, R.styleable.ActivityChooserView, defStyle, 0); mInitialActivityCount = attributesArray.getInt( R.styleable.ActivityChooserView_initialActivityCount, ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_DEFAULT); Drawable expandActivityOverflowButtonDrawable = attributesArray.getDrawable( R.styleable.ActivityChooserView_expandActivityOverflowButtonDrawable); attributesArray.recycle(); LayoutInflater inflater = LayoutInflater.from(getContext()); inflater.inflate(R.layout.abc_activity_chooser_view, this, true); mCallbacks = new Callbacks(); mActivityChooserContent = findViewById(R.id.activity_chooser_view_content); mActivityChooserContentBackground = mActivityChooserContent.getBackground(); mDefaultActivityButton = findViewById(R.id.default_activity_button); mDefaultActivityButton.setOnClickListener(mCallbacks); mDefaultActivityButton.setOnLongClickListener(mCallbacks); mDefaultActivityButtonImage = (ImageView) mDefaultActivityButton.findViewById(R.id.image); final FrameLayout expandButton = findViewById(R.id.expand_activities_button); expandButton.setOnClickListener(mCallbacks); expandButton.setAccessibilityDelegate(new AccessibilityDelegate() { @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(host, info); AccessibilityNodeInfoCompat.wrap(info).setCanOpenPopup(true); } }); expandButton.setOnTouchListener(new ForwardingListener(expandButton) { @Override public ShowableListMenu getPopup() { return getListPopupWindow(); } @Override protected boolean onForwardingStarted() { showPopup(); return true; } @Override protected boolean onForwardingStopped() { dismissPopup(); return true; } }); mExpandActivityOverflowButton = expandButton; mExpandActivityOverflowButtonImage = (ImageView) expandButton.findViewById(R.id.image); mExpandActivityOverflowButtonImage.setImageDrawable(expandActivityOverflowButtonDrawable); mAdapter = new ActivityChooserViewAdapter(); mAdapter.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { super.onChanged(); updateAppearance(); } }); Resources resources = context.getResources(); mListPopupMaxWidth = Math.max(resources.getDisplayMetrics().widthPixels / 2, resources.getDimensionPixelSize(R.dimen.abc_config_prefDialogWidth)); } /** * {@inheritDoc} */ @Override public void setActivityChooserModel(ActivityChooserModel dataModel) { mAdapter.setDataModel(dataModel); if (isShowingPopup()) { dismissPopup(); showPopup(); } } /** * Sets the background for the button that expands the activity * overflow list. * * <strong>Note:</strong> Clients would like to set this drawable * as a clue about the action the chosen activity will perform. For * example, if a share activity is to be chosen the drawable should * give a clue that sharing is to be performed. * * @param drawable The drawable. */ public void setExpandActivityOverflowButtonDrawable(Drawable drawable) { mExpandActivityOverflowButtonImage.setImageDrawable(drawable); } /** * Sets the content description for the button that expands the activity * overflow list. * * description as a clue about the action performed by the button. * For example, if a share activity is to be chosen the content * description should be something like "Share with". * * @param resourceId The content description resource id. */ public void setExpandActivityOverflowButtonContentDescription(int resourceId) { CharSequence contentDescription = getContext().getString(resourceId); mExpandActivityOverflowButtonImage.setContentDescription(contentDescription); } /** * Set the provider hosting this view, if applicable. * @hide Internal use only */ @RestrictTo(LIBRARY_GROUP) public void setProvider(ActionProvider provider) { mProvider = provider; } /** * Shows the popup window with activities. * * @return True if the popup was shown, false if already showing. */ public boolean showPopup() { if (isShowingPopup() || !mIsAttachedToWindow) { return false; } mIsSelectingDefaultActivity = false; showPopupUnchecked(mInitialActivityCount); return true; } /** * Shows the popup no matter if it was already showing. * * @param maxActivityCount The max number of activities to display. */ void showPopupUnchecked(int maxActivityCount) { if (mAdapter.getDataModel() == null) { throw new IllegalStateException("No data model. Did you call #setDataModel?"); } getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener); final boolean defaultActivityButtonShown = mDefaultActivityButton.getVisibility() == VISIBLE; final int activityCount = mAdapter.getActivityCount(); final int maxActivityCountOffset = defaultActivityButtonShown ? 1 : 0; if (maxActivityCount != ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_UNLIMITED && activityCount > maxActivityCount + maxActivityCountOffset) { mAdapter.setShowFooterView(true); mAdapter.setMaxActivityCount(maxActivityCount - 1); } else { mAdapter.setShowFooterView(false); mAdapter.setMaxActivityCount(maxActivityCount); } ListPopupWindow popupWindow = getListPopupWindow(); if (!popupWindow.isShowing()) { if (mIsSelectingDefaultActivity || !defaultActivityButtonShown) { mAdapter.setShowDefaultActivity(true, defaultActivityButtonShown); } else { mAdapter.setShowDefaultActivity(false, false); } final int contentWidth = Math.min(mAdapter.measureContentWidth(), mListPopupMaxWidth); popupWindow.setContentWidth(contentWidth); popupWindow.show(); if (mProvider != null) { mProvider.subUiVisibilityChanged(true); } popupWindow.getListView().setContentDescription(getContext().getString( R.string.abc_activitychooserview_choose_application)); popupWindow.getListView().setSelector(new ColorDrawable(Color.TRANSPARENT)); } } /** * Dismisses the popup window with activities. * * @return True if dismissed, false if already dismissed. */ public boolean dismissPopup() { if (isShowingPopup()) { getListPopupWindow().dismiss(); ViewTreeObserver viewTreeObserver = getViewTreeObserver(); if (viewTreeObserver.isAlive()) { viewTreeObserver.removeGlobalOnLayoutListener(mOnGlobalLayoutListener); } } return true; } /** * Gets whether the popup window with activities is shown. * * @return True if the popup is shown. */ public boolean isShowingPopup() { return getListPopupWindow().isShowing(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); ActivityChooserModel dataModel = mAdapter.getDataModel(); if (dataModel != null) { dataModel.registerObserver(mModelDataSetObserver); } mIsAttachedToWindow = true; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); ActivityChooserModel dataModel = mAdapter.getDataModel(); if (dataModel != null) { dataModel.unregisterObserver(mModelDataSetObserver); } ViewTreeObserver viewTreeObserver = getViewTreeObserver(); if (viewTreeObserver.isAlive()) { viewTreeObserver.removeGlobalOnLayoutListener(mOnGlobalLayoutListener); } if (isShowingPopup()) { dismissPopup(); } mIsAttachedToWindow = false; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { View child = mActivityChooserContent; // If the default action is not visible we want to be as tall as the // ActionBar so if this widget is used in the latter it will look as // a normal action button. if (mDefaultActivityButton.getVisibility() != VISIBLE) { heightMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec), MeasureSpec.EXACTLY); } measureChild(child, widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(child.getMeasuredWidth(), child.getMeasuredHeight()); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { mActivityChooserContent.layout(0, 0, right - left, bottom - top); if (!isShowingPopup()) { dismissPopup(); } } public ActivityChooserModel getDataModel() { return mAdapter.getDataModel(); } /** * Sets a listener to receive a callback when the popup is dismissed. * * @param listener The listener to be notified. */ public void setOnDismissListener(PopupWindow.OnDismissListener listener) { mOnDismissListener = listener; } /** * Sets the initial count of items shown in the activities popup * i.e. the items before the popup is expanded. This is an upper * bound since it is not guaranteed that such number of intent * handlers exist. * * @param itemCount The initial popup item count. */ public void setInitialActivityCount(int itemCount) { mInitialActivityCount = itemCount; } /** * Sets a content description of the default action button. This * resource should be a string taking one formatting argument and * will be used for formatting the content description of the button * dynamically as the default target changes. For example, a resource * pointing to the string "share with %1$s" will result in a content * description "share with Bluetooth" for the Bluetooth activity. * * @param resourceId The resource id. */ public void setDefaultActionButtonContentDescription(int resourceId) { mDefaultActionButtonContentDescription = resourceId; } /** * Gets the list popup window which is lazily initialized. * * @return The popup. */ ListPopupWindow getListPopupWindow() { if (mListPopupWindow == null) { mListPopupWindow = new ListPopupWindow(getContext()); mListPopupWindow.setAdapter(mAdapter); mListPopupWindow.setAnchorView(ActivityChooserView.this); mListPopupWindow.setModal(true); mListPopupWindow.setOnItemClickListener(mCallbacks); mListPopupWindow.setOnDismissListener(mCallbacks); } return mListPopupWindow; } /** * Updates the buttons state. */ void updateAppearance() { // Expand overflow button. if (mAdapter.getCount() > 0) { mExpandActivityOverflowButton.setEnabled(true); } else { mExpandActivityOverflowButton.setEnabled(false); } // Default activity button. final int activityCount = mAdapter.getActivityCount(); final int historySize = mAdapter.getHistorySize(); if (activityCount == 1 || (activityCount > 1 && historySize > 0)) { mDefaultActivityButton.setVisibility(VISIBLE); ResolveInfo activity = mAdapter.getDefaultActivity(); PackageManager packageManager = getContext().getPackageManager(); mDefaultActivityButtonImage.setImageDrawable(activity.loadIcon(packageManager)); if (mDefaultActionButtonContentDescription != 0) { CharSequence label = activity.loadLabel(packageManager); String contentDescription = getContext().getString( mDefaultActionButtonContentDescription, label); mDefaultActivityButton.setContentDescription(contentDescription); } } else { mDefaultActivityButton.setVisibility(View.GONE); } // Activity chooser content. if (mDefaultActivityButton.getVisibility() == VISIBLE) { mActivityChooserContent.setBackgroundDrawable(mActivityChooserContentBackground); } else { mActivityChooserContent.setBackgroundDrawable(null); } } /** * Interface implementation to avoid publishing them in the APIs. */ private class Callbacks implements AdapterView.OnItemClickListener, View.OnClickListener, View.OnLongClickListener, PopupWindow.OnDismissListener { Callbacks() { } // AdapterView#OnItemClickListener @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ActivityChooserViewAdapter adapter = (ActivityChooserViewAdapter) parent.getAdapter(); final int itemViewType = adapter.getItemViewType(position); switch (itemViewType) { case ActivityChooserViewAdapter.ITEM_VIEW_TYPE_FOOTER: { showPopupUnchecked(ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_UNLIMITED); } break; case ActivityChooserViewAdapter.ITEM_VIEW_TYPE_ACTIVITY: { dismissPopup(); if (mIsSelectingDefaultActivity) { // The item at position zero is the default already. if (position > 0) { mAdapter.getDataModel().setDefaultActivity(position); } } else { // If the default target is not shown in the list, the first // item in the model is default action => adjust index position = mAdapter.getShowDefaultActivity() ? position : position + 1; Intent launchIntent = mAdapter.getDataModel().chooseActivity(position); if (launchIntent != null) { launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); getContext().startActivity(launchIntent); } } } break; default: throw new IllegalArgumentException(); } } // View.OnClickListener @Override public void onClick(View view) { if (view == mDefaultActivityButton) { dismissPopup(); ResolveInfo defaultActivity = mAdapter.getDefaultActivity(); final int index = mAdapter.getDataModel().getActivityIndex(defaultActivity); Intent launchIntent = mAdapter.getDataModel().chooseActivity(index); if (launchIntent != null) { launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); getContext().startActivity(launchIntent); } } else if (view == mExpandActivityOverflowButton) { mIsSelectingDefaultActivity = false; showPopupUnchecked(mInitialActivityCount); } else { throw new IllegalArgumentException(); } } // OnLongClickListener#onLongClick @Override public boolean onLongClick(View view) { if (view == mDefaultActivityButton) { if (mAdapter.getCount() > 0) { mIsSelectingDefaultActivity = true; showPopupUnchecked(mInitialActivityCount); } } else { throw new IllegalArgumentException(); } return true; } // PopUpWindow.OnDismissListener#onDismiss @Override public void onDismiss() { notifyOnDismissListener(); if (mProvider != null) { mProvider.subUiVisibilityChanged(false); } } private void notifyOnDismissListener() { if (mOnDismissListener != null) { mOnDismissListener.onDismiss(); } } } /** * Adapter for backing the list of activities shown in the popup. */ private class ActivityChooserViewAdapter extends BaseAdapter { public static final int MAX_ACTIVITY_COUNT_UNLIMITED = Integer.MAX_VALUE; public static final int MAX_ACTIVITY_COUNT_DEFAULT = 4; private static final int ITEM_VIEW_TYPE_ACTIVITY = 0; private static final int ITEM_VIEW_TYPE_FOOTER = 1; private static final int ITEM_VIEW_TYPE_COUNT = 3; private ActivityChooserModel mDataModel; private int mMaxActivityCount = MAX_ACTIVITY_COUNT_DEFAULT; private boolean mShowDefaultActivity; private boolean mHighlightDefaultActivity; private boolean mShowFooterView; ActivityChooserViewAdapter() { } public void setDataModel(ActivityChooserModel dataModel) { ActivityChooserModel oldDataModel = mAdapter.getDataModel(); if (oldDataModel != null && isShown()) { oldDataModel.unregisterObserver(mModelDataSetObserver); } mDataModel = dataModel; if (dataModel != null && isShown()) { dataModel.registerObserver(mModelDataSetObserver); } notifyDataSetChanged(); } @Override public int getItemViewType(int position) { if (mShowFooterView && position == getCount() - 1) { return ITEM_VIEW_TYPE_FOOTER; } else { return ITEM_VIEW_TYPE_ACTIVITY; } } @Override public int getViewTypeCount() { return ITEM_VIEW_TYPE_COUNT; } @Override public int getCount() { int count = 0; int activityCount = mDataModel.getActivityCount(); if (!mShowDefaultActivity && mDataModel.getDefaultActivity() != null) { activityCount--; } count = Math.min(activityCount, mMaxActivityCount); if (mShowFooterView) { count++; } return count; } @Override public Object getItem(int position) { final int itemViewType = getItemViewType(position); switch (itemViewType) { case ITEM_VIEW_TYPE_FOOTER: return null; case ITEM_VIEW_TYPE_ACTIVITY: if (!mShowDefaultActivity && mDataModel.getDefaultActivity() != null) { position++; } return mDataModel.getActivity(position); default: throw new IllegalArgumentException(); } } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { final int itemViewType = getItemViewType(position); switch (itemViewType) { case ITEM_VIEW_TYPE_FOOTER: if (convertView == null || convertView.getId() != ITEM_VIEW_TYPE_FOOTER) { convertView = LayoutInflater.from(getContext()).inflate( R.layout.abc_activity_chooser_view_list_item, parent, false); convertView.setId(ITEM_VIEW_TYPE_FOOTER); TextView titleView = (TextView) convertView.findViewById(R.id.title); titleView.setText(getContext().getString( R.string.abc_activity_chooser_view_see_all)); } return convertView; case ITEM_VIEW_TYPE_ACTIVITY: if (convertView == null || convertView.getId() != R.id.list_item) { convertView = LayoutInflater.from(getContext()).inflate( R.layout.abc_activity_chooser_view_list_item, parent, false); } PackageManager packageManager = getContext().getPackageManager(); // Set the icon ImageView iconView = (ImageView) convertView.findViewById(R.id.icon); ResolveInfo activity = (ResolveInfo) getItem(position); iconView.setImageDrawable(activity.loadIcon(packageManager)); // Set the title. TextView titleView = (TextView) convertView.findViewById(R.id.title); titleView.setText(activity.loadLabel(packageManager)); // Highlight the default. if (mShowDefaultActivity && position == 0 && mHighlightDefaultActivity) { convertView.setActivated(true); } else { convertView.setActivated(false); } return convertView; default: throw new IllegalArgumentException(); } } public int measureContentWidth() { // The user may have specified some of the target not to be shown but we // want to measure all of them since after expansion they should fit. final int oldMaxActivityCount = mMaxActivityCount; mMaxActivityCount = MAX_ACTIVITY_COUNT_UNLIMITED; int contentWidth = 0; View itemView = null; final int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); final int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); final int count = getCount(); for (int i = 0; i < count; i++) { itemView = getView(i, itemView, null); itemView.measure(widthMeasureSpec, heightMeasureSpec); contentWidth = Math.max(contentWidth, itemView.getMeasuredWidth()); } mMaxActivityCount = oldMaxActivityCount; return contentWidth; } public void setMaxActivityCount(int maxActivityCount) { if (mMaxActivityCount != maxActivityCount) { mMaxActivityCount = maxActivityCount; notifyDataSetChanged(); } } public ResolveInfo getDefaultActivity() { return mDataModel.getDefaultActivity(); } public void setShowFooterView(boolean showFooterView) { if (mShowFooterView != showFooterView) { mShowFooterView = showFooterView; notifyDataSetChanged(); } } public int getActivityCount() { return mDataModel.getActivityCount(); } public int getHistorySize() { return mDataModel.getHistorySize(); } public ActivityChooserModel getDataModel() { return mDataModel; } public void setShowDefaultActivity(boolean showDefaultActivity, boolean highlightDefaultActivity) { if (mShowDefaultActivity != showDefaultActivity || mHighlightDefaultActivity != highlightDefaultActivity) { mShowDefaultActivity = showDefaultActivity; mHighlightDefaultActivity = highlightDefaultActivity; notifyDataSetChanged(); } } public boolean getShowDefaultActivity() { return mShowDefaultActivity; } } /** * Allows us to set the background using TintTypedArray * @hide */ @RestrictTo(LIBRARY_GROUP) public static class InnerLayout extends LinearLayout { private static final int[] TINT_ATTRS = { android.R.attr.background }; public InnerLayout(Context context, AttributeSet attrs) { super(context, attrs); TintTypedArray a = TintTypedArray.obtainStyledAttributes(context, attrs, TINT_ATTRS); setBackgroundDrawable(a.getDrawable(0)); a.recycle(); } } }
/* * Copyright 2004-2006 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 * * 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.compass.core.util.config; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import org.compass.core.config.ConfigurationException; /** * This is the default <code>ConfigurationHelper</code> implementation. */ public class XmlConfigurationHelper extends AbstractConfigurationHelper implements ConfigurationHelper, Serializable { private static final long serialVersionUID = 3546076943545219376L; /** * An empty (length zero) array of configuration objects. */ protected static final ConfigurationHelper[] EMPTY_ARRAY = new ConfigurationHelper[0]; private final String m_name; private final String m_location; private final String m_namespace; private final String m_prefix; private HashMap m_attributes; private ArrayList m_children; private String m_value; private boolean m_readOnly; /** * Shallow copy constructor, suitable for craeting a writable clone of a * read-only configuration. To modify children, use <code>getChild()</code>, * <code>removeChild()</code> and <code>addChild()</code>. */ public XmlConfigurationHelper(ConfigurationHelper config) throws ConfigurationException { this(config.getName(), config.getLocation(), config.getNamespace(), ((config instanceof AbstractConfigurationHelper) ? ((AbstractConfigurationHelper) config).getPrefix() : "")); addAll(config); } /** * Create a new <code>DefaultConfiguration</code> instance. */ public XmlConfigurationHelper(final String name) { this(name, null, "", ""); } /** * Create a new <code>DefaultConfiguration</code> instance. */ public XmlConfigurationHelper(final String name, final String location) { this(name, location, "", ""); } /** * Create a new <code>DefaultConfiguration</code> instance. */ public XmlConfigurationHelper(final String name, final String location, final String ns, final String prefix) { m_name = name; m_location = location; m_namespace = ns; m_prefix = prefix; // only used as a serialization hint. Cannot be null } /** * Returns the name of this configuration element. */ public String getName() { return m_name; } /** * Returns the namespace of this configuration element */ public String getNamespace() throws ConfigurationException { if (null != m_namespace) { return m_namespace; } else { throw new ConfigurationException("No namespace (not even default \"\") is associated with the " + "configuration element \"" + getName() + "\" at " + getLocation()); } } /** * Returns the prefix of the namespace */ protected String getPrefix() throws ConfigurationException { if (null != m_prefix) { return m_prefix; } else { throw new ConfigurationException("No prefix (not even default \"\") is associated with the " + "configuration element \"" + getName() + "\" at " + getLocation()); } } /** * Returns a description of location of element. */ public String getLocation() { return m_location; } /** * Returns the value of the configuration element as a <code>String</code>. */ public String getValue(final String defaultValue) { if (null != m_value) { return m_value; } else { return defaultValue; } } /** * Returns the value of the configuration element as a <code>String</code>. */ public String getValue() throws ConfigurationException { if (null != m_value) { return m_value; } else { throw new ConfigurationException("No value is associated with the " + "configuration element \"" + getName() + "\" at " + getLocation()); } } /** * Return an array of all attribute names. */ public String[] getAttributeNames() { if (null == m_attributes) { return new String[0]; } else { return (String[]) m_attributes.keySet().toArray(new String[0]); } } /** * Return an array of <code>Configuration</code> elements containing all * node children. */ public ConfigurationHelper[] getChildren() { if (null == m_children) { return new ConfigurationHelper[0]; } else { return (ConfigurationHelper[]) m_children.toArray(new ConfigurationHelper[0]); } } /** * Returns the value of the attribute specified by its name as a * <code>String</code>. */ public String getAttribute(final String name) throws ConfigurationException { final String value = (null != m_attributes) ? (String) m_attributes.get(name) : null; if (null != value) { return value; } else { throw new ConfigurationException("No attribute named \"" + name + "\" is " + "associated with the configuration element \"" + getName() + "\" at " + getLocation()); } } /** * Return the first <code>Configuration</code> object child of this * associated with the given name. */ public ConfigurationHelper getChild(final String name, final boolean createNew) { if (null != m_children) { final int size = m_children.size(); for (int i = 0; i < size; i++) { final ConfigurationHelper configuration = (ConfigurationHelper) m_children.get(i); if (name.equals(configuration.getName())) { return configuration; } } } if (createNew) { return new XmlConfigurationHelper(name, "<generated>" + getLocation(), m_namespace, m_prefix); } else { return null; } } /** * Return an array of <code>Configuration</code> objects children of this * associated with the given name. <br> * The returned array may be empty but is never <code>null</code>. */ public ConfigurationHelper[] getChildren(final String name) { if (null == m_children) { return new ConfigurationHelper[0]; } else { final ArrayList children = new ArrayList(); final int size = m_children.size(); for (int i = 0; i < size; i++) { final ConfigurationHelper configuration = (ConfigurationHelper) m_children.get(i); if (name.equals(configuration.getName())) { children.add(configuration); } } return (ConfigurationHelper[]) children.toArray(new ConfigurationHelper[0]); } } /** * Set the value of this <code>Configuration</code> object to the * specified string. */ public void setValue(final String value) { checkWriteable(); m_value = value; } /** * Set the value of this <code>Configuration</code> object to the * specified int. */ public void setValue(final int value) { setValue(String.valueOf(value)); } /** * Set the value of this <code>Configuration</code> object to the * specified long. */ public void setValue(final long value) { setValue(String.valueOf(value)); } /** * Set the value of this <code>Configuration</code> object to the * specified boolean. */ public void setValue(final boolean value) { setValue(String.valueOf(value)); } /** * Set the value of this <code>Configuration</code> object to the * specified float. */ public void setValue(final float value) { setValue(String.valueOf(value)); } /** * Set the value of the specified attribute to the specified string. */ public void setAttribute(final String name, final String value) { checkWriteable(); if (null != value) { if (null == m_attributes) { m_attributes = new HashMap(); } m_attributes.put(name, value); } else { if (null != m_attributes) { m_attributes.remove(name); } } } /** * Set the value of the specified attribute to the specified int. */ public void setAttribute(final String name, final int value) { setAttribute(name, String.valueOf(value)); } /** * Set the value of the specified attribute to the specified long. */ public void setAttribute(final String name, final long value) { setAttribute(name, String.valueOf(value)); } /** * Set the value of the specified attribute to the specified boolean. */ public void setAttribute(final String name, final boolean value) { setAttribute(name, String.valueOf(value)); } /** * Set the value of the specified attribute to the specified float. */ public void setAttribute(final String name, final float value) { setAttribute(name, String.valueOf(value)); } /** * Add a child <code>Configuration</code> to this configuration element. */ public void addChild(final ConfigurationHelper configuration) { checkWriteable(); if (null == m_children) { m_children = new ArrayList(); } m_children.add(configuration); } /** * Add all the attributes, children and value from specified configuration * element to current configuration element. */ public void addAll(final ConfigurationHelper other) { checkWriteable(); setValue(other.getValue(null)); addAllAttributes(other); addAllChildren(other); } /** * Add all attributes from specified configuration element to current * configuration element. */ public void addAllAttributes(final ConfigurationHelper other) { checkWriteable(); final String[] attributes = other.getAttributeNames(); for (int i = 0; i < attributes.length; i++) { final String name = attributes[i]; final String value = other.getAttribute(name, null); setAttribute(name, value); } } /** * Add all child <code>Configuration</code> objects from specified * configuration element to current configuration element. */ public void addAllChildren(final ConfigurationHelper other) { checkWriteable(); final ConfigurationHelper[] children = other.getChildren(); for (int i = 0; i < children.length; i++) { addChild(children[i]); } } /** * Add all child <code>Configuration</code> objects from specified * configuration element to current configuration element. */ public void addAllChildrenBefore(final ConfigurationHelper other) { checkWriteable(); final ConfigurationHelper[] children = other.getChildren(); if (null == m_children) { m_children = new ArrayList(); } for (int i = children.length - 1; i >= 0; i--) { m_children.add(0, children[i]); } } /** * Remove a child <code>Configuration</code> to this configuration * element. */ public void removeChild(final ConfigurationHelper configuration) { checkWriteable(); if (null == m_children) { return; } m_children.remove(configuration); } /** * Return count of children. */ public int getChildCount() { if (null == m_children) { return 0; } return m_children.size(); } /** * Make this configuration read-only. */ public void makeReadOnly() { m_readOnly = true; } /** * heck if this configuration is writeable. */ protected final void checkWriteable() throws IllegalStateException { if (m_readOnly) { throw new IllegalStateException("Configuration is read only and can not be modified"); } } /** * Returns true iff this DefaultConfiguration has been made read-only. */ protected final boolean isReadOnly() { return m_readOnly; } /** * Compare if this configuration is equal to another. */ public boolean equals(Object other) { if (other == null) return false; if (!(other instanceof ConfigurationHelper)) return false; return ConfigurationHelperUtil.equals(this, (ConfigurationHelper) other); } /** * Obtaine the hashcode for this configuration. */ public int hashCode() { int hash = m_prefix.hashCode(); if (m_name != null) hash ^= m_name.hashCode(); hash >>>= 7; if (m_location != null) hash ^= m_location.hashCode(); hash >>>= 7; if (m_namespace != null) hash ^= m_namespace.hashCode(); hash >>>= 7; if (m_attributes != null) hash ^= m_attributes.hashCode(); hash >>>= 7; if (m_children != null) hash ^= m_children.hashCode(); hash >>>= 7; if (m_value != null) hash ^= m_value.hashCode(); hash >>>= 7; hash ^= (m_readOnly) ? 1 : 3; return hash; } }
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.drools.reteoo.nodes; import org.drools.core.base.DroolsQuery; import org.drools.core.base.InternalViewChangedEventListener; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalKnowledgeRuntime; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.common.LeftTupleIterator; import org.drools.core.common.PropagationContextFactory; import org.drools.core.common.QueryElementFactHandle; import org.drools.core.common.WorkingMemoryAction; import org.drools.core.definitions.rule.impl.RuleImpl; import org.drools.core.impl.StatefulKnowledgeSessionImpl; import org.drools.core.marshalling.impl.MarshallerReaderContext; import org.drools.core.marshalling.impl.MarshallerWriteContext; import org.drools.core.marshalling.impl.ProtobufMessages.ActionQueue.Action; import org.drools.core.phreak.PropagationEntry; import org.drools.core.reteoo.LeftTuple; import org.drools.core.reteoo.LeftTupleSink; import org.drools.core.reteoo.LeftTupleSource; import org.drools.core.reteoo.LeftTupleSourceUtils; import org.drools.core.reteoo.ModifyPreviousTuples; import org.drools.core.reteoo.QueryElementNode; import org.drools.core.reteoo.QueryTerminalNode; import org.drools.core.reteoo.ReteooBuilder; import org.drools.core.reteoo.RightTuple; import org.drools.core.reteoo.RightTupleImpl; import org.drools.core.reteoo.RuleRemovalContext; import org.drools.core.reteoo.builder.BuildContext; import org.drools.core.rule.Declaration; import org.drools.core.rule.QueryElement; import org.drools.core.spi.PropagationContext; import org.drools.core.util.Iterator; import org.drools.core.util.index.TupleList; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.List; public class ReteQueryElementNode extends QueryElementNode { public ReteQueryElementNode() { } public ReteQueryElementNode(int id, LeftTupleSource tupleSource, QueryElement queryElement, boolean tupleMemoryEnabled, boolean openQuery, BuildContext context) { super(id, tupleSource, queryElement, tupleMemoryEnabled, openQuery, context); } public void modifyLeftTuple(InternalFactHandle factHandle, ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory workingMemory) { LeftTupleSourceUtils.doModifyLeftTuple(factHandle, modifyPreviousTuples, context, workingMemory, this, getLeftInputOtnId(), getLeftInferredMask()); } public void assertLeftTuple(LeftTuple leftTuple, PropagationContext context, InternalWorkingMemory workingMemory) { // the next call makes sure this node's memory is initialised workingMemory.getNodeMemory(this); InternalFactHandle handle = createFactHandle(context, workingMemory, leftTuple); DroolsQuery queryObject = createDroolsQuery(leftTuple, handle, null, null, null, null, workingMemory); QueryInsertAction action = new QueryInsertAction(context, handle, leftTuple, this); queryObject.setAction(action); // this is necessary as queries can be re-entrant, so we can check this before re-sheduling // another action in the modify section. Make sure it's nulled after the action is done // i.e. scheduling an insert and then an update, before the insert is executed context.addInsertAction(action); } public void modifyLeftTuple(LeftTuple leftTuple, PropagationContext context, InternalWorkingMemory workingMemory) { boolean executeAsOpenQuery = openQuery; if (executeAsOpenQuery) { // There is no point in doing an open query if the caller is a non-open query. Object object = leftTuple.get(0).getObject(); if (object instanceof DroolsQuery && !((DroolsQuery) object).isOpen()) { executeAsOpenQuery = false; } } if (!executeAsOpenQuery) { // Was never open so execute as a retract + assert if (leftTuple.getFirstChild() != null) { this.sink.propagateRetractLeftTuple(leftTuple, context, workingMemory); } assertLeftTuple(leftTuple, context, workingMemory); return; } InternalFactHandle handle = (InternalFactHandle) leftTuple.getContextObject(); DroolsQuery queryObject = (DroolsQuery) handle.getObject(); if (queryObject.getAction() != null) { // we already have an insert scheduled for this query, but have re-entered it // do nothing return; } queryObject.setParameters(getActualArguments( leftTuple, workingMemory )); QueryUpdateAction action = new QueryUpdateAction(context, handle, leftTuple, this); context.addInsertAction(action); } public void retractLeftTuple(LeftTuple leftTuple, PropagationContext context, InternalWorkingMemory workingMemory) { QueryRetractAction action = new QueryRetractAction( context, leftTuple, this ); context.addInsertAction( action ); } public void attach(BuildContext context) { super.attach(context); if (context == null) { return; } for (InternalWorkingMemory workingMemory : context.getWorkingMemories()) { PropagationContextFactory pctxFactory = workingMemory.getKnowledgeBase().getConfiguration().getComponentFactory().getPropagationContextFactory(); final PropagationContext propagationContext = pctxFactory.createPropagationContext(workingMemory.getNextPropagationIdCounter(), PropagationContext.Type.RULE_ADDITION, null, null, null); this.leftInput.updateSink(this, propagationContext, workingMemory); } } protected boolean doRemove(RuleRemovalContext context, ReteooBuilder builder, InternalWorkingMemory[] workingMemories) { if (!isInUse()) { for (InternalWorkingMemory workingMemory : workingMemories) { workingMemory.clearNodeMemory(this); } getLeftTupleSource().removeTupleSink(this); return true; } return false; } public void updateSink(final LeftTupleSink sink, final PropagationContext context, final InternalWorkingMemory workingMemory) { Iterator<LeftTuple> it = LeftTupleIterator.iterator(workingMemory, this); for (LeftTuple leftTuple = it.next(); leftTuple != null; leftTuple = it.next()) { LeftTuple childLeftTuple = leftTuple.getFirstChild(); while (childLeftTuple != null) { RightTuple rightParent = childLeftTuple.getRightParent(); sink.assertLeftTuple(sink.createLeftTuple(leftTuple, rightParent, childLeftTuple, null, sink, true), context, workingMemory); while (childLeftTuple != null && childLeftTuple.getRightParent() == rightParent) { // skip to the next child that has a different right parent childLeftTuple = childLeftTuple.getHandleNext(); } } } } protected UnificationNodeViewChangedEventListener createCollector(LeftTuple leftTuple, int[] varIndexes, boolean tupleMemoryEnabled) { return new ReteUnificationNodeViewChangedEventListener(leftTuple, varIndexes, this, tupleMemoryEnabled ); } public static class ReteUnificationNodeViewChangedEventListener extends UnificationNodeViewChangedEventListener implements InternalViewChangedEventListener { public ReteUnificationNodeViewChangedEventListener(LeftTuple leftTuple, int[] variables, QueryElementNode node, boolean tupleMemoryEnabled) { super(leftTuple, variables, node, tupleMemoryEnabled); } public void rowAdded(final RuleImpl rule, LeftTuple resultLeftTuple, PropagationContext context, InternalWorkingMemory workingMemory) { QueryTerminalNode node = (QueryTerminalNode) resultLeftTuple.getTupleSink(); Declaration[] decls = node.getRequiredDeclarations(); DroolsQuery dquery = (DroolsQuery) this.factHandle.getObject(); Object[] objects = new Object[dquery.getElements().length]; Declaration decl; for ( int variable : this.variables ) { decl = decls[variable]; objects[variable] = decl.getValue( workingMemory, resultLeftTuple.get( decl ).getObject() ); } QueryElementFactHandle resultHandle = createQueryResultHandle(context, workingMemory, objects); RightTuple rightTuple = createResultRightTuple(resultHandle, resultLeftTuple, dquery.isOpen()); this.node.getSinkPropagator().createChildLeftTuplesforQuery(this.leftTuple, rightTuple, true, // this must always be true, otherwise we can't // find the child tuples to iterate for evaluating the dquery results dquery.isOpen()); TupleList rightTuples = dquery.getResultInsertRightTupleList(); if (rightTuples == null) { rightTuples = new TupleList(); dquery.setResultInsertRightTupleList(rightTuples); QueryResultInsertAction evalAction = new QueryResultInsertAction(context, this.factHandle, leftTuple, this.node); context.getQueue2().addFirst(evalAction); } rightTuples.add(rightTuple); } protected RightTuple createResultRightTuple(QueryElementFactHandle resultHandle, LeftTuple resultLeftTuple, boolean open) { RightTuple rightTuple = new RightTupleImpl(resultHandle); if (open) { rightTuple.setBlocked( resultLeftTuple ); resultLeftTuple.setContextObject( rightTuple ); } rightTuple.setPropagationContext(resultLeftTuple.getPropagationContext()); return rightTuple; } public void rowRemoved(final RuleImpl rule, final LeftTuple resultLeftTuple, final PropagationContext context, final InternalWorkingMemory workingMemory) { RightTuple rightTuple = (RightTuple) resultLeftTuple.getContextObject(); rightTuple.setBlocked( null ); resultLeftTuple.setContextObject( null ); DroolsQuery query = (DroolsQuery) this.factHandle.getObject(); TupleList rightTuples = query.getResultRetractRightTupleList(); if (rightTuples == null) { rightTuples = new TupleList(); query.setResultRetractRightTupleList(rightTuples); QueryResultRetractAction retractAction = new QueryResultRetractAction(context, this.factHandle, leftTuple, this.node); context.getQueue2().addFirst(retractAction); } if (rightTuple.getMemory() != null) { throw new RuntimeException(); } rightTuples.add(rightTuple); } public void rowUpdated(final RuleImpl rule, final LeftTuple resultLeftTuple, final PropagationContext context, final InternalWorkingMemory workingMemory) { RightTuple rightTuple = (RightTuple) resultLeftTuple.getContextObject(); if (rightTuple.getMemory() != null) { // Already sheduled as an insert return; } rightTuple.setBlocked( null ); resultLeftTuple.setContextObject( null ); // We need to recopy everything back again, as we don't know what has or hasn't changed QueryTerminalNode node = (QueryTerminalNode) resultLeftTuple.getTupleSink(); Declaration[] decls = node.getRequiredDeclarations(); InternalFactHandle rootHandle = resultLeftTuple.get(0); DroolsQuery dquery = (DroolsQuery) rootHandle.getObject(); Object[] objects = new Object[dquery.getElements().length]; Declaration decl; for ( int variable : this.variables ) { decl = decls[variable]; objects[variable] = decl.getValue( workingMemory, resultLeftTuple.get( decl ).getObject() ); } QueryElementFactHandle handle = (QueryElementFactHandle) rightTuple.getFactHandle(); handle.setRecency(workingMemory.getFactHandleFactory().getAtomicRecency().incrementAndGet()); handle.setObject(objects); if (dquery.isOpen()) { rightTuple.setBlocked(resultLeftTuple); resultLeftTuple.setContextObject( rightTuple ); } // Don't need to recreate child links, as they will already be there form the first "add" TupleList rightTuples = dquery.getResultUpdateRightTupleList(); if (rightTuples == null) { rightTuples = new TupleList(); dquery.setResultUpdateRightTupleList(rightTuples); QueryResultUpdateAction updateAction = new QueryResultUpdateAction(context, this.factHandle, leftTuple, this.node); context.getQueue2().addFirst(updateAction); } rightTuples.add(rightTuple); } public List<? extends Object> getResults() { throw new UnsupportedOperationException(getClass().getCanonicalName() + " does not support the getResults() method."); } public LeftTuple getLeftTuple() { return leftTuple; } } public static class QueryInsertAction extends PropagationEntry.AbstractPropagationEntry implements WorkingMemoryAction { private PropagationContext context; private InternalFactHandle factHandle; private LeftTuple leftTuple; private QueryElementNode node; public QueryInsertAction(PropagationContext context) { this.context = context; } public QueryInsertAction(PropagationContext context, InternalFactHandle factHandle, LeftTuple leftTuple, QueryElementNode node) { this.context = context; this.factHandle = factHandle; this.leftTuple = leftTuple; this.node = node; } public QueryInsertAction(MarshallerReaderContext context) throws IOException { throw new UnsupportedOperationException("Should not be present in network on serialisation"); } public Action serialize(MarshallerWriteContext context) throws IOException { throw new UnsupportedOperationException("Should not be present in network on serialisation"); } public void execute(InternalWorkingMemory workingMemory) { // we null this as it blocks this query being called, to avoid re-entrant issues. i.e. scheduling an insert and then an update, before the insert is executed ((DroolsQuery) this.factHandle.getObject()).setAction(null); workingMemory.getEntryPointNode().assertQuery(factHandle, context, workingMemory); } public String toString() { return "[QueryInsertAction facthandle=" + factHandle + ",\n leftTuple=" + leftTuple + "]\n"; } } public static class QueryUpdateAction extends PropagationEntry.AbstractPropagationEntry implements WorkingMemoryAction { private PropagationContext context; private InternalFactHandle factHandle; private LeftTuple leftTuple; private QueryElementNode node; public QueryUpdateAction(PropagationContext context) { this.context = context; } public QueryUpdateAction(PropagationContext context, InternalFactHandle factHandle, LeftTuple leftTuple, QueryElementNode node) { this.context = context; this.factHandle = factHandle; this.leftTuple = leftTuple; this.node = node; } public QueryUpdateAction(MarshallerReaderContext context) throws IOException { throw new UnsupportedOperationException("Should not be present in network on serialisation"); } public void write(MarshallerWriteContext context) throws IOException { throw new UnsupportedOperationException("Should not be present in network on serialisation"); } public Action serialize(MarshallerWriteContext context) { throw new UnsupportedOperationException("Should not be present in network on serialisation"); } public void execute(InternalWorkingMemory workingMemory) { workingMemory.getEntryPointNode().modifyQuery(factHandle, context, workingMemory); } public void execute(InternalKnowledgeRuntime kruntime) { execute(((StatefulKnowledgeSessionImpl) kruntime).getInternalWorkingMemory()); } public String toString() { return "[QueryInsertModifyAction facthandle=" + factHandle + ",\n leftTuple=" + leftTuple + "]\n"; } public void writeExternal(ObjectOutput out) throws IOException { } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } } public static class QueryRetractAction extends PropagationEntry.AbstractPropagationEntry implements WorkingMemoryAction { private PropagationContext context; private LeftTuple leftTuple; private QueryElementNode node; public QueryRetractAction(PropagationContext context) { this.context = context; } public QueryRetractAction(PropagationContext context, LeftTuple leftTuple, QueryElementNode node) { this.context = context; this.leftTuple = leftTuple; this.node = node; } public QueryRetractAction(MarshallerReaderContext context) throws IOException { throw new UnsupportedOperationException("Should not be present in network on serialisation"); } public Action serialize(MarshallerWriteContext context) { throw new UnsupportedOperationException("Should not be present in network on serialisation"); } public void execute(InternalWorkingMemory workingMemory) { InternalFactHandle factHandle = (InternalFactHandle) leftTuple.getContextObject(); if (node.isOpenQuery()) { // iterate to the query terminal node, as the child leftTuples will get picked up there workingMemory.getEntryPointNode().retractObject(factHandle, context, workingMemory.getObjectTypeConfigurationRegistry().getObjectTypeConf(workingMemory.getEntryPoint(), factHandle.getObject()), workingMemory); //workingMemory.getFactHandleFactory().destroyFactHandle( factHandle ); } else { // get child left tuples, as there is no open query if (leftTuple.getFirstChild() != null) { node.getSinkPropagator().propagateRetractLeftTuple(leftTuple, context, workingMemory); } } } public String toString() { return "[QueryRetractAction leftTuple=" + leftTuple + "]\n"; } } public static class QueryResultInsertAction extends PropagationEntry.AbstractPropagationEntry implements WorkingMemoryAction { private PropagationContext context; private LeftTuple leftTuple; private InternalFactHandle factHandle; private QueryElementNode node; public QueryResultInsertAction(PropagationContext context) { this.context = context; } public QueryResultInsertAction(PropagationContext context, InternalFactHandle factHandle, LeftTuple leftTuple, QueryElementNode node) { this.context = context; this.factHandle = factHandle; this.leftTuple = leftTuple; this.node = node; } public QueryResultInsertAction(MarshallerReaderContext context) throws IOException { throw new UnsupportedOperationException("Should not be present in network on serialisation"); } public Action serialize(MarshallerWriteContext context) { throw new UnsupportedOperationException("Should not be present in network on serialisation"); } public void execute(InternalWorkingMemory workingMemory) { DroolsQuery query = (DroolsQuery) factHandle.getObject(); TupleList rightTuples = query.getResultInsertRightTupleList(); query.setResultInsertRightTupleList(null); // null so further operations happen on a new stack element for (RightTuple rightTuple = (RightTuple) rightTuples.getFirst(); rightTuple != null; ) { RightTuple tmp = (RightTuple) rightTuple.getNext(); rightTuples.remove(rightTuple); for (LeftTuple childLeftTuple = rightTuple.getFirstChild(); childLeftTuple != null; childLeftTuple = (LeftTuple) childLeftTuple.getRightParentNext()) { node.getSinkPropagator().doPropagateAssertLeftTuple(context, workingMemory, childLeftTuple, (LeftTupleSink) childLeftTuple.getTupleSink()); } rightTuple = tmp; } // @FIXME, this should work, but it's closing needed fact handles // actually an evaluation 34 appears on the stack twice.... // if ( !node.isOpenQuery() ) { // workingMemory.getFactHandleFactory().destroyFactHandle( this.factHandle ); // } } public LeftTuple getLeftTuple() { return this.leftTuple; } public String toString() { return "[QueryEvaluationAction leftTuple=" + leftTuple + "]\n"; } } public static class QueryResultRetractAction extends PropagationEntry.AbstractPropagationEntry implements WorkingMemoryAction { private PropagationContext context; private LeftTuple leftTuple; private InternalFactHandle factHandle; private QueryElementNode node; public QueryResultRetractAction(PropagationContext context, InternalFactHandle factHandle, LeftTuple leftTuple, QueryElementNode node) { this.context = context; this.factHandle = factHandle; this.leftTuple = leftTuple; this.node = node; } public QueryResultRetractAction(MarshallerReaderContext context) throws IOException { throw new UnsupportedOperationException("Should not be present in network on serialisation"); } public void write(MarshallerWriteContext context) throws IOException { throw new UnsupportedOperationException("Should not be present in network on serialisation"); } public Action serialize(MarshallerWriteContext context) throws IOException { throw new UnsupportedOperationException("Should not be present in network on serialisation"); } public void execute(InternalWorkingMemory workingMemory) { DroolsQuery query = (DroolsQuery) factHandle.getObject(); TupleList rightTuples = query.getResultRetractRightTupleList(); query.setResultRetractRightTupleList(null); // null so further operations happen on a new stack element for (RightTuple rightTuple = (RightTuple) rightTuples.getFirst(); rightTuple != null; ) { RightTuple tmp = (RightTuple) rightTuple.getNext(); rightTuples.remove(rightTuple); this.node.getSinkPropagator().propagateRetractRightTuple(rightTuple, context, workingMemory); rightTuple = tmp; } } public void execute(InternalKnowledgeRuntime kruntime) { execute(((StatefulKnowledgeSessionImpl) kruntime).getInternalWorkingMemory()); } public LeftTuple getLeftTuple() { return this.leftTuple; } public String toString() { return "[QueryResultRetractAction leftTuple=" + leftTuple + "]\n"; } public void writeExternal(ObjectOutput out) throws IOException { } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } } public static class QueryResultUpdateAction extends PropagationEntry.AbstractPropagationEntry implements WorkingMemoryAction { private PropagationContext context; private LeftTuple leftTuple; InternalFactHandle factHandle; private QueryElementNode node; public QueryResultUpdateAction(PropagationContext context, InternalFactHandle factHandle, LeftTuple leftTuple, QueryElementNode node) { this.context = context; this.factHandle = factHandle; this.leftTuple = leftTuple; this.node = node; } public QueryResultUpdateAction(MarshallerReaderContext context) throws IOException { throw new UnsupportedOperationException("Should not be present in network on serialisation"); } public void write(MarshallerWriteContext context) throws IOException { throw new UnsupportedOperationException("Should not be present in network on serialisation"); } public Action serialize(MarshallerWriteContext context) { throw new UnsupportedOperationException("Should not be present in network on serialisation"); } public void execute(InternalWorkingMemory workingMemory) { DroolsQuery query = (DroolsQuery) factHandle.getObject(); TupleList rightTuples = query.getResultUpdateRightTupleList(); query.setResultUpdateRightTupleList(null); // null so further operations happen on a new stack element for (RightTuple rightTuple = (RightTuple) rightTuples.getFirst(); rightTuple != null; ) { RightTuple tmp = (RightTuple) rightTuple.getNext(); rightTuples.remove(rightTuple); this.node.getSinkPropagator().propagateModifyChildLeftTuple(rightTuple.getFirstChild(), rightTuple.getFirstChild().getLeftParent(), context, workingMemory, true); rightTuple = tmp; } } public void execute(InternalKnowledgeRuntime kruntime) { execute(((StatefulKnowledgeSessionImpl) kruntime).getInternalWorkingMemory()); } public LeftTuple getLeftTuple() { return leftTuple; } public String toString() { return "[QueryResultUpdateAction leftTuple=" + leftTuple + "]\n"; } public void writeExternal(ObjectOutput out) throws IOException { } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } } }
/** * The MIT License (MIT) * * Copyright (c) 2014-2016 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.takes.facets.fork; import java.io.IOException; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import lombok.EqualsAndHashCode; import org.takes.Request; import org.takes.Response; import org.takes.Take; import org.takes.misc.Opt; import org.takes.rq.RqHref; import org.takes.tk.TkFixed; import org.takes.tk.TkText; /** * Fork by regular expression pattern. * * <p>Use this class in combination with {@link TkFork}, * for example: * * <pre> Take take = new TkFork( * new FkRegex("/home", new TkHome()), * new FkRegex("/account", new TkAccount()) * );</pre> * * <p>Each instance of {@link org.takes.facets.fork.FkRegex} is being * asked only once by {@link TkFork} whether the * request is good enough to be processed. If the request is suitable * for this particular fork, it will return the relevant * {@link org.takes.Take}. * * <p>Also, keep in mind that the second argument of the constructor may * be of type {@link TkRegex} and accept an * instance of {@link org.takes.facets.fork.RqRegex}, which makes it very * convenient to reuse regular expression matcher, for example: * * <pre> Take take = new TkFork( * new FkRegex( * "/file(.*)", * new Target&lt;RqRegex&gt;() { * &#64;Override * public Response act(final RqRegex req) { * // Here we immediately getting access to the * // matcher that was used during parsing of * // the incoming request * final String file = req.matcher().group(1); * } * } * ) * );</pre> * * <p>The class is immutable and thread-safe. * * @author Yegor Bugayenko ([email protected]) * @version $Id$ * @since 0.4 * @see TkFork * @see TkRegex */ @EqualsAndHashCode(of = { "pattern", "target" }) public final class FkRegex implements Fork { /** * Pattern. */ private final transient Pattern pattern; /** * Target. */ private final transient TkRegex target; /** * Ctor. * @param ptn Pattern * @param text Text */ public FkRegex(final String ptn, final String text) { this( Pattern.compile(ptn, Pattern.CASE_INSENSITIVE | Pattern.DOTALL), new TkText(text) ); } /** * Ctor. * @param ptn Pattern * @param rsp Response * @since 0.16 */ public FkRegex(final String ptn, final Response rsp) { this(ptn, new TkFixed(rsp)); } /** * Ctor. * @param ptn Pattern * @param rsp Response * @since 0.16 */ public FkRegex(final Pattern ptn, final Response rsp) { this(ptn, new TkFixed(rsp)); } /** * Ctor. * @param ptn Pattern * @param tke Take */ public FkRegex(final String ptn, final Take tke) { this( Pattern.compile(ptn, Pattern.CASE_INSENSITIVE | Pattern.DOTALL), tke ); } /** * Ctor. * @param ptn Pattern * @param tke Take */ public FkRegex(final Pattern ptn, final Take tke) { this( ptn, new TkRegex() { @Override public Response act(final RqRegex req) throws IOException { return tke.act(req); } } ); } /** * Ctor. * @param ptn Pattern * @param tke Take */ public FkRegex(final String ptn, final TkRegex tke) { this( Pattern.compile(ptn, Pattern.CASE_INSENSITIVE | Pattern.DOTALL), tke ); } /** * Ctor. * @param ptn Pattern * @param tke Take */ public FkRegex(final Pattern ptn, final TkRegex tke) { this.pattern = ptn; this.target = tke; } @Override public Opt<Response> route(final Request req) throws IOException { String path = new RqHref.Base(req).href().path(); if (path.length() > 1 && path.charAt(path.length() - 1) == '/') { path = path.substring(0, path.length() - 1); } final Matcher matcher = this.pattern.matcher(path); final Opt<Response> resp; if (matcher.matches()) { resp = new Opt.Single<Response>( this.target.act( new RqMatcher(matcher, req) ) ); } else { resp = new Opt.Empty<Response>(); } return resp; } /** * Request with a matcher inside. * * @author Dali Freire ([email protected]) * @version $Id$ * @since 0.32.5 */ private static final class RqMatcher implements RqRegex { /** * Matcher. */ private final transient Matcher mtr; /** * Original request. */ private final transient Request req; /** * Ctor. * @param matcher Matcher * @param request Request */ RqMatcher(final Matcher matcher, final Request request) { this.mtr = matcher; this.req = request; } @Override public Iterable<String> head() throws IOException { return this.req.head(); } @Override public InputStream body() throws IOException { return this.req.body(); } @Override public Matcher matcher() { return this.mtr; } } }
/* * Copyright (c) 2007-2008, debug-commons team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.rubyforge.debugcommons; import java.io.IOException; import java.io.PrintWriter; import java.net.ConnectException; import java.net.Socket; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; import org.rubyforge.debugcommons.model.ExceptionSuspensionPoint; import org.rubyforge.debugcommons.model.IRubyBreakpoint; import org.rubyforge.debugcommons.model.IRubyExceptionBreakpoint; import org.rubyforge.debugcommons.model.IRubyLineBreakpoint; import org.rubyforge.debugcommons.model.SuspensionPoint; import org.rubyforge.debugcommons.model.RubyThreadInfo; import org.rubyforge.debugcommons.model.RubyDebugTarget; import org.rubyforge.debugcommons.model.RubyFrame; import org.rubyforge.debugcommons.model.RubyFrameInfo; import org.rubyforge.debugcommons.model.RubyThread; import org.rubyforge.debugcommons.model.RubyVariable; import org.rubyforge.debugcommons.model.RubyVariableInfo; public final class RubyDebuggerProxy { private static final Logger LOGGER = Logger.getLogger(RubyDebuggerProxy.class.getName()); public static enum DebuggerType { CLASSIC_DEBUGGER, RUBY_DEBUG } public static final DebuggerType CLASSIC_DEBUGGER = DebuggerType.CLASSIC_DEBUGGER; public static final DebuggerType RUBY_DEBUG = DebuggerType.RUBY_DEBUG; public static final List<RubyDebuggerProxy> PROXIES = new CopyOnWriteArrayList<RubyDebuggerProxy>(); private final List<RubyDebugEventListener> listeners; private final Map<Integer, IRubyLineBreakpoint> breakpointsIDs; private final int timeout; private final DebuggerType debuggerType; private RubyDebugTarget debugTarget; private Socket commandSocket; private boolean finished; private PrintWriter commandWriter; private ICommandFactory commandFactory; private ReadersSupport readersSupport; private boolean supportsCondition; // catchpoint removing is not supported by backend yet, handle it in the // debug-commons-java until the support is added // http://rubyforge.org/tracker/index.php?func=detail&aid=20237&group_id=1900&atid=7436 private Set<String> removedCatchpoints; public RubyDebuggerProxy(final DebuggerType debuggerType) { this(debuggerType, 10); // default reading timeout 10s } public RubyDebuggerProxy(final DebuggerType debuggerType, final int timeout) { this.debuggerType = debuggerType; this.listeners = new CopyOnWriteArrayList<RubyDebugEventListener>(); this.breakpointsIDs = new HashMap<Integer, IRubyLineBreakpoint>(); this.removedCatchpoints = new HashSet<String>(); this.timeout = timeout; this.readersSupport = new ReadersSupport(timeout); } public void setDebugTarget(RubyDebugTarget debugTarget) throws IOException, RubyDebuggerException { this.debugTarget = debugTarget; LOGGER.fine("Proxy target: " + debugTarget); } public RubyDebugTarget getDebugTarget() { return debugTarget; } /** <b>Package-private</b> for unit tests only. */ ReadersSupport getReadersSupport() { return readersSupport; } /** * Set initial breakpoints and start the debugging process stopping (and * firing event to the {@link #addRubyDebugEventListener}) on the first * breakpoint. * * @param initialBreakpoints initial set of breakpoints to be set before * triggering the debugging */ public void attach(final IRubyBreakpoint[] initialBreakpoints) throws RubyDebuggerException { try { switch(debuggerType) { case CLASSIC_DEBUGGER: attachToClassicDebugger(initialBreakpoints); break; case RUBY_DEBUG: attachToRubyDebug(initialBreakpoints); break; default: throw new IllegalStateException("Unhandled debugger type: " + debuggerType); } } catch (RubyDebuggerException e) { PROXIES.remove(this); throw e; } startSuspensionReaderLoop(); } /** * Whether client might send command to the proxy. When the debuggee has * finished (in a standard manner or unexpectedly, e.g. was killed) or the * proxy did not start yet, false is returned. */ public synchronized boolean isReady() { return !finished && commandWriter != null && debugTarget.isAvailable(); } private synchronized void attachToClassicDebugger(final IRubyBreakpoint[] initialBreakpoints) throws RubyDebuggerException { try { commandFactory = new ClassicDebuggerCommandFactory(); readersSupport.startCommandLoop(getCommandSocket().getInputStream()); commandWriter = new PrintWriter(getCommandSocket().getOutputStream(), true); setBreakpoints(initialBreakpoints); sendCommand("cont"); } catch (IOException ex) { throw new RubyDebuggerException(ex); } } private synchronized void attachToRubyDebug(final IRubyBreakpoint[] initialBreakpoints) throws RubyDebuggerException { try { commandFactory = new RubyDebugCommandFactory(); readersSupport.startCommandLoop(getCommandSocket().getInputStream()); commandWriter = new PrintWriter(getCommandSocket().getOutputStream(), true); setBreakpoints(initialBreakpoints); sendCommand("start"); } catch (IOException ex) { throw new RubyDebuggerException(ex); } } public void fireDebugEvent(final RubyDebugEvent e) { for (RubyDebugEventListener listener : listeners) { listener.onDebugEvent(e); } } public void addRubyDebugEventListener(final RubyDebugEventListener listener) { listeners.add(listener); } public void removeRubyDebugEventListener(final RubyDebugEventListener listener) { listeners.remove(listener); } private PrintWriter getCommandWriter() throws RubyDebuggerException { assert commandWriter != null : "Proxy has to be started, before using the writer"; return commandWriter; } protected void setBreakpoints(final IRubyBreakpoint[] breakpoints) throws RubyDebuggerException { for (IRubyBreakpoint breakpoint: breakpoints) { addBreakpoint(breakpoint); } } public synchronized void addBreakpoint(final IRubyBreakpoint breakpoint) { LOGGER.fine("Adding breakpoint: " + breakpoint); if (!isReady()) { LOGGER.fine("Session and/or debuggee is not ready, skipping addition of breakpoint: " + breakpoint); return; } assert breakpoint != null : "breakpoint cannot be null"; if (breakpoint.isEnabled()) { try { if (breakpoint instanceof IRubyLineBreakpoint) { IRubyLineBreakpoint lineBreakpoint = (IRubyLineBreakpoint) breakpoint; String command = commandFactory.createAddBreakpoint( lineBreakpoint.getFilePath(), lineBreakpoint.getLineNumber()); sendCommand(command); Integer id = getReadersSupport().readAddedBreakpointNo(); String condition = lineBreakpoint.getCondition(); if (condition != null && supportsCondition) { command = commandFactory.createSetCondition(id, condition); if (command != null) { sendCommand(command); getReadersSupport().readConditionSet(); // read response } else { LOGGER.info("conditional breakpoints are not supported by backend"); } } breakpointsIDs.put(id, lineBreakpoint); } else if (breakpoint instanceof IRubyExceptionBreakpoint) { IRubyExceptionBreakpoint excBreakpoint = (IRubyExceptionBreakpoint) breakpoint; // just 're-enable' if contained in removedCatchpoints if (!removedCatchpoints.remove(excBreakpoint.getException())) { String command = commandFactory.createCatchOn(excBreakpoint); sendCommand(command); getReadersSupport().readCatchpointSet(); // read response } } else { throw new IllegalArgumentException("Unknown breakpoint type: " + breakpoint); } } catch (final RubyDebuggerException ex) { if (isReady()) { LOGGER.log(Level.WARNING, "Cannot add breakpoint to: " + getDebugTarget(), ex); } } } } public synchronized void removeBreakpoint(final IRubyBreakpoint breakpoint) { removeBreakpoint(breakpoint, false); } /** * Remove the given breakpoint from this debugging session. * * @param breakpoint breakpoint to be removed * @param silent whether info message should be omitted if the breakpoint * has not been set in this session */ public synchronized void removeBreakpoint(final IRubyBreakpoint breakpoint, boolean silent) { LOGGER.fine("Removing breakpoint: " + breakpoint); if (!isReady()) { LOGGER.fine("Session and/or debuggee is not ready, skipping removing of breakpoint: " + breakpoint); return; } if (breakpoint instanceof IRubyLineBreakpoint) { IRubyLineBreakpoint lineBreakpoint = (IRubyLineBreakpoint) breakpoint; Integer id = findBreakpointId(lineBreakpoint); if (id != null) { String command = commandFactory.createRemoveBreakpoint(id); try { sendCommand(command); getReadersSupport().waitForRemovedBreakpoint(id); breakpointsIDs.remove(id); LOGGER.fine("Breakpoint " + breakpoint + " with id " + id + " successfully removed"); } catch (RubyDebuggerException e) { LOGGER.log(Level.SEVERE, "Exception during removing breakpoint.", e); } } else if (!silent) { LOGGER.fine("Breakpoint [" + breakpoint + "] cannot be removed since " + "its ID cannot be found. Might have been already removed."); } } else if (breakpoint instanceof IRubyExceptionBreakpoint) { // catchpoint removing is not supported by backend yet, handle in // the debug-commons-java until the support is added // http://rubyforge.org/tracker/index.php?func=detail&aid=20237&group_id=1900&atid=7436 IRubyExceptionBreakpoint catchpoint = (IRubyExceptionBreakpoint) breakpoint; removedCatchpoints.add(catchpoint.getException()); } else { throw new IllegalArgumentException("Unknown breakpoint type: " + breakpoint); } } /** * Update the given breakpoint. Use when <em>enabled</em> property has * changed. */ public void updateBreakpoint(IRubyBreakpoint breakpoint) throws RubyDebuggerException { removeBreakpoint(breakpoint, true); addBreakpoint(breakpoint); } /** * Find ID under which the given breakpoint is known in the current * debugging session. * * @return found ID; might be <tt>null</tt> if none is found */ private synchronized Integer findBreakpointId(final IRubyLineBreakpoint wantedBP) { for (Iterator<Map.Entry<Integer, IRubyLineBreakpoint>> it = breakpointsIDs.entrySet().iterator(); it.hasNext();) { Map.Entry<Integer, IRubyLineBreakpoint> breakpointID = it.next(); IRubyLineBreakpoint bp = breakpointID.getValue(); int id = breakpointID.getKey(); if (wantedBP.getFilePath().equals(bp.getFilePath()) && wantedBP.getLineNumber() == bp.getLineNumber()) { return id; } } return null; } private void startSuspensionReaderLoop() { new SuspensionReaderLoop().start(); } public Socket getCommandSocket() throws RubyDebuggerException { if (commandSocket == null) { commandSocket = attach(); } return commandSocket; } public void resume(final RubyThread thread) { try { sendCommand(commandFactory.createResume(thread)); } catch (RubyDebuggerException e) { LOGGER.log(Level.SEVERE, "resuming of " + thread.getId() + " failed", e); } } private void sendCommand(final String s) throws RubyDebuggerException { LOGGER.fine("Sending command debugger: " + s); if (!isReady()) { throw new RubyDebuggerException("Trying to send a command [" + s + "] to non-started or finished proxy (debuggee: " + getDebugTarget() + ", output: \n\n" + Util.dumpAndDestroyProcess(debugTarget)); } getCommandWriter().println(s); } public void sendStepOver(RubyFrame frame, boolean forceNewLine) { try { if (forceNewLine) { sendCommand(commandFactory.createForcedStepOver(frame)); } else { sendCommand(commandFactory.createStepOver(frame)); } } catch (RubyDebuggerException e) { LOGGER.log(Level.SEVERE, "Stepping failed", e); } } public void sendStepReturnEnd(RubyFrame frame) { try { sendCommand(commandFactory.createStepReturn(frame)); } catch (RubyDebuggerException e) { LOGGER.log(Level.SEVERE, "Stepping failed", e); } } public void sendStepIntoEnd(RubyFrame frame, boolean forceNewLine) { try { if (forceNewLine) { sendCommand(commandFactory.createForcedStepInto(frame)); } else { sendCommand(commandFactory.createStepInto(frame)); } } catch (RubyDebuggerException e) { LOGGER.log(Level.SEVERE, "Stepping failed", e); } } public RubyThreadInfo[] readThreadInfo() throws RubyDebuggerException { sendCommand(commandFactory.createReadThreads()); return getReadersSupport().readThreads(); } public RubyFrame[] readFrames(RubyThread thread) throws RubyDebuggerException { RubyFrameInfo[] infos; try { sendCommand(commandFactory.createReadFrames(thread)); infos = getReadersSupport().readFrames(); } catch (RubyDebuggerException e) { if (isReady()) { throw e; } LOGGER.fine("Session and/or debuggee is not ready, returning empty thread list."); infos = new RubyFrameInfo[0]; } RubyFrame[] frames = new RubyFrame[infos.length]; for (int i = 0; i < infos.length; i++) { RubyFrameInfo info = infos[i]; frames[i] = new RubyFrame(thread, info); } return frames; } public RubyVariable[] readVariables(RubyFrame frame) throws RubyDebuggerException { sendCommand(commandFactory.createReadLocalVariables(frame)); RubyVariableInfo[] infos = getReadersSupport().readVariables(); RubyVariable[] variables= new RubyVariable[infos.length]; for (int i = 0; i < infos.length; i++) { RubyVariableInfo info = infos[i]; variables[i] = new RubyVariable(info, frame); } return variables; } public RubyVariable[] readInstanceVariables(final RubyVariable variable) throws RubyDebuggerException { sendCommand(commandFactory.createReadInstanceVariable(variable)); RubyVariableInfo[] infos = getReadersSupport().readVariables(); RubyVariable[] variables= new RubyVariable[infos.length]; for (int i = 0; i < infos.length; i++) { RubyVariableInfo info = infos[i]; variables[i] = new RubyVariable(info, variable); } return variables; } public RubyVariable[] readGlobalVariables() throws RubyDebuggerException { sendCommand(commandFactory.createReadGlobalVariables()); RubyVariableInfo[] infos = getReadersSupport().readVariables(); RubyVariable[] variables= new RubyVariable[infos.length]; for (int i = 0; i < infos.length; i++) { RubyVariableInfo info = infos[i]; variables[i] = new RubyVariable(this, info); } return variables; } public RubyVariable inspectExpression(RubyFrame frame, String expression) throws RubyDebuggerException { expression = expression.replaceAll("\n", "\\\\n"); sendCommand(commandFactory.createInspect(frame, expression)); RubyVariableInfo[] infos = getReadersSupport().readVariables(); return infos.length == 0 ? null : new RubyVariable(infos[0], frame); } public void finish(final boolean forced) { synchronized(this) { if (finished) { // possible if client call this explicitly and then second time from RubyLoop LOGGER.fine("Trying to finish the same proxy more than once: " + this); return; } if (getDebugTarget().isRemote()) { // TBD rather detach sendExit(); } PROXIES.remove(RubyDebuggerProxy.this); if (forced) { sendExit(); try { // Needed to let the IO readers to read the last pieces of input and // output streams. Thread.sleep(500); } catch (InterruptedException e) { LOGGER.log(Level.INFO, "Interrupted during IO readers waiting", e); } RubyDebugTarget target = getDebugTarget(); if (!target.isRemote()) { LOGGER.fine("Destroying process: " + target); target.getProcess().destroy(); } } finished = true; } fireDebugEvent(RubyDebugEvent.createTerminateEvent()); } private synchronized void sendExit() { if (commandSocket != null && debugTarget.isAvailable()) { try { sendCommand("exit"); } catch (RubyDebuggerException ex) { LOGGER.fine("'exit' command failed. Remote process? -> " + debugTarget.isRemote()); if (!debugTarget.isRemote()) { LOGGER.fine("'exit' command failed. Process running? -> " + debugTarget.isRunning()); } } } } public synchronized void jump(final int line) { try { sendCommand("jump " + line); } catch (final RubyDebuggerException ex) { if (isReady()) { LOGGER.log(Level.WARNING, "Cannot jump", ex); } } } public synchronized void threadPause(final int id) { try { sendCommand("pause " + id); } catch (final RubyDebuggerException ex) { if (isReady()) { LOGGER.log(Level.WARNING, "Cannot pause", ex); } } } public synchronized void setType(final RubyVariable var, final String new_type) { try { sendCommand("set_type " + var.getName() + " " + new_type); } catch (final RubyDebuggerException ex) { if (isReady()) { LOGGER.log(Level.WARNING, "Cannot set_type", ex); } } } /** * Tries to attach to the <code>target</code>'s process and gives up in * <code>timeout</code> seconds. */ private Socket attach() throws RubyDebuggerException { int port = debugTarget.getPort(); String host = debugTarget.getHost(); Socket socket = null; for (int tryCount = (timeout*2), i = 0; i < tryCount && socket == null; i++) { try { socket = new Socket(host, port); LOGGER.finest("Successfully attached to " + host + ':' + port); } catch (ConnectException e) { synchronized (this) { if (finished) { // terminated by frontend before process started throw new RubyDebuggerException("Process was terminated before debugger connection was established."); } if (i == tryCount - 1) { failWithInfo(e); } } try { if (debugTarget.isAvailable()) { LOGGER.finest("Cannot connect to " + host + ':' + port + ". Trying again...(" + (tryCount - i - 1) + ')'); Thread.sleep(500); } else { failWithInfo(e); } } catch (InterruptedException e1) { LOGGER.log(Level.SEVERE, "Interrupted during attaching.", e1); Thread.currentThread().interrupt(); } } catch (IOException e) { throw new RubyDebuggerException(e); } } return socket; } private void failWithInfo(ConnectException e) throws RubyDebuggerException { String info = debugTarget.isRemote() ? "[Remote Process at " + debugTarget.getHost() + ':' + debugTarget.getPort() + "]" : Util.dumpAndDestroyProcess(debugTarget); throw new RubyDebuggerException("Cannot connect to the debugged process at port " + debugTarget.getPort() + " in " + timeout + "s:\n\n" + info, e); } /** * Tells the proxy whether condition on breakpoint is supported. Older * engines version do not support it. */ void setConditionSupport(final boolean supportsCondition) { this.supportsCondition = supportsCondition; } private class SuspensionReaderLoop extends Thread { SuspensionReaderLoop() { this.setName("RubyDebuggerLoop [" + System.currentTimeMillis() + ']'); } public void suspensionOccurred(final SuspensionPoint hit) { new Thread() { public @Override void run() { debugTarget.suspensionOccurred(hit); } }.start(); } public @Override void run() { LOGGER.finest("Waiting for breakpoints."); while (true) { SuspensionPoint sp = getReadersSupport().readSuspension(); if (sp == SuspensionPoint.END) { break; } LOGGER.finest(sp.toString()); // see removedCatchpoints's JavaDoc if (sp.isException()) { ExceptionSuspensionPoint exceptionSP = (ExceptionSuspensionPoint) sp; if (removedCatchpoints.contains(exceptionSP.getExceptionType())) { RubyThread thread = getDebugTarget().getThreadById(sp.getThreadId()); if (thread != null) { RubyDebuggerProxy.this.resume(thread); continue; } } } if (!RubyDebuggerProxy.this.isReady()) { // flush events after proxy is finished LOGGER.info("Session and/or debuggee is not ready, ignoring backend event - suspension point: " + sp); } else { SuspensionReaderLoop.this.suspensionOccurred(sp); } } boolean unexpectedFail = getReadersSupport().isUnexpectedFail(); if (unexpectedFail) { LOGGER.warning("Unexpected fail. Debuggee: " + getDebugTarget() + ", output: \n\n" + Util.dumpAndDestroyProcess(debugTarget)); } finish(unexpectedFail); LOGGER.finest("Socket reader loop finished."); } } }
/** * Copyright (c) 2014 Google, 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.google.fpl.liquidfunpaint; import com.google.fpl.liquidfunpaint.tool.Tool; import com.google.fpl.liquidfunpaint.tool.Tool.ToolType; import android.annotation.TargetApi; import android.app.Activity; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.graphics.PixelFormat; import android.opengl.GLSurfaceView; import android.os.Build; import android.os.Bundle; import android.util.SparseIntArray; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * MainActivity for Splashpaint * Implements the Android UI layout. */ public class MainActivity extends Activity implements OnTouchListener { static String sVersionName; private Controller mController; private GLSurfaceView mWorldView; private RelativeLayout mRootLayout; // Mapping from ImageView to actual RGB values private SparseIntArray mColorMap; // Mapping from ImageView of color palette to the images for Tools private SparseIntArray mPencilImageMap; private SparseIntArray mRigidImageMap; private SparseIntArray mWaterImageMap; // List of ImageView of color palettes private List<View> mRigidColorPalette; private List<View> mWaterColorPalette; // The image view of the selected tool private ImageView mSelected; // The current open palette private List<View> mOpenPalette = null; private boolean mUsingTool = false; private static final int ANIMATION_DURATION = 300; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Explicitly load all shared libraries for Android 4.1 (Jelly Bean) // Or we could get a crash from dependencies. System.loadLibrary("liquidfun"); System.loadLibrary("liquidfun_jni"); // Set the ToolBar layout setContentView(R.layout.tools_layout); mRootLayout = (RelativeLayout) findViewById(R.id.root); mColorMap = new SparseIntArray(); mPencilImageMap = new SparseIntArray(); mRigidImageMap = new SparseIntArray(); mWaterImageMap = new SparseIntArray(); mRigidColorPalette = new ArrayList<View>(); mWaterColorPalette = new ArrayList<View>(); String pencilPrefix = getString(R.string.pencil_prefix); String rigidPrefix = getString(R.string.rigid_prefix); String waterPrefix = getString(R.string.water_prefix); String rigidColorPrefix = getString(R.string.rigid_color_prefix); String waterColorPrefix = getString(R.string.water_color_prefix); Resources r = getResources(); // Look up all the different colors for (int i = 1; i <= r.getInteger(R.integer.num_colors); ++i) { // Get color palette for rigid/pencil tools // 1) Add color RGB values to mColorMap // 2) Add appropriate images for tool // 3) Add the color palette view to the color palette list int viewId = r.getIdentifier( rigidColorPrefix + i, "id", getPackageName()); mColorMap.append( viewId, getColor(rigidColorPrefix + i, "color")); mPencilImageMap.append( viewId, r.getIdentifier(pencilPrefix + i, "drawable", getPackageName())); mRigidImageMap.append( viewId, r.getIdentifier(rigidPrefix + i, "drawable", getPackageName())); mRigidColorPalette.add(findViewById(viewId)); // Get color palette for water tool // 1) Add color RGB values to mColorMap // 2) Add appropriate images for tool // 3) Add the color palette view to the color palette list viewId = r.getIdentifier( waterColorPrefix + i, "id", getPackageName()); mColorMap.append( viewId, getColor(waterColorPrefix + i, "color")); mWaterImageMap.append( viewId, r.getIdentifier(waterPrefix + i, "drawable", getPackageName())); mWaterColorPalette.add(findViewById(viewId)); } // Add the ending piece to both palettes int paletteEndViewId = r.getIdentifier( rigidColorPrefix + "end", "id", getPackageName()); mRigidColorPalette.add(findViewById(paletteEndViewId)); paletteEndViewId = r.getIdentifier( waterColorPrefix + "end", "id", getPackageName()); mWaterColorPalette.add(findViewById(paletteEndViewId)); // Set the restart button's listener findViewById(R.id.button_restart).setOnTouchListener(this); Renderer renderer = Renderer.getInstance(); Renderer.getInstance().init(this); mController = new Controller(this); // Set up the OpenGL WorldView mWorldView = (GLSurfaceView) findViewById(R.id.world); mWorldView.setEGLContextClientVersion(2); mWorldView.setEGLConfigChooser(8, 8, 8, 8, 16, 0); mWorldView.getHolder().setFormat(PixelFormat.TRANSLUCENT); if (BuildConfig.DEBUG) { mWorldView.setDebugFlags( GLSurfaceView.DEBUG_LOG_GL_CALLS | GLSurfaceView.DEBUG_CHECK_GL_ERROR); } mWorldView.setOnTouchListener(this); // GLSurfaceView#setPreserveEGLContextOnPause() is added in API level 11 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { setPreserveEGLContextOnPause(); } mWorldView.setRenderer(renderer); renderer.startSimulation(); // Set default tool colors Tool.getTool(ToolType.PENCIL).setColor( getColor(getString(R.string.default_pencil_color), "color")); Tool.getTool(ToolType.RIGID).setColor( getColor(getString(R.string.default_rigid_color), "color")); Tool.getTool(ToolType.WATER).setColor( getColor(getString(R.string.default_water_color), "color")); // Initialize the first selected tool mSelected = (ImageView) findViewById(R.id.water); onClickTool(mSelected); // Show the title view for 3 seconds LayoutInflater inflater = getLayoutInflater(); inflater.inflate(R.layout.title, mRootLayout); final View title = findViewById(R.id.title); Animation fadeOut = new AlphaAnimation(1, 0); fadeOut.setDuration(500); fadeOut.setStartOffset(3000); fadeOut.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { title.setVisibility(View.GONE); } }); title.setVisibility(View.VISIBLE); title.startAnimation(fadeOut); if (BuildConfig.DEBUG) { View fps = findViewById(R.id.fps); fps.setVisibility(View.VISIBLE); TextView versionView = (TextView) findViewById(R.id.version); try { sVersionName = "Version " + getPackageManager() .getPackageInfo(getPackageName(), 0).versionName; versionView.setText(sVersionName); } catch (NameNotFoundException e) { // The name returned by getPackageName() must be found. } } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setPreserveEGLContextOnPause() { mWorldView.setPreserveEGLContextOnPause(true); } @Override protected void onResume() { super.onResume(); mController.onResume(); mWorldView.onResume(); Renderer.getInstance().totalFrames = -10000; } @Override protected void onPause() { super.onPause(); mController.onPause(); mWorldView.onPause(); } private void togglePalette(View selectedTool, List<View> palette) { // Save the previously opened palette as closePalette() will clear it. List<View> prevOpenPalette = mOpenPalette; // Always close the palette. closePalette(); // If we are not selecting the same tool with an open color palette, // open it. if (!(selectedTool.getId() == mSelected.getId() && prevOpenPalette != null)) { openPalette(palette); } } private void openPalette(List<View> palette) { if (mOpenPalette == null) { float d = getResources().getDimension(R.dimen.color_width); for (int i = 0; i < palette.size(); i++) { Animation slideIn = new TranslateAnimation(-d * (i + 1), 0, 0, 0); slideIn.setDuration(ANIMATION_DURATION); View view = palette.get(i); view.setVisibility(View.VISIBLE); view.setClickable(true); view.startAnimation(slideIn); } } mOpenPalette = palette; } private void closePalette() { if (mOpenPalette != null) { float d = getResources().getDimension(R.dimen.color_width); for (int i = 0; i < mOpenPalette.size(); i++) { View view = mOpenPalette.get(i); Animation slideOut = new TranslateAnimation(0, -d * (i + 1), 0, 0); slideOut.setDuration(ANIMATION_DURATION); view.startAnimation(slideOut); view.setVisibility(View.GONE); } } mOpenPalette = null; } private void select(View v, ToolType tool) { // Send the new tool over to the Controller mController.setTool(tool); // Keep track of the ImageView of the tool and highlight it mSelected = (ImageView) v; View selecting = findViewById(R.id.selecting); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(selecting.getLayoutParams()); params.addRule(RelativeLayout.ALIGN_TOP, v.getId()); selecting.setLayoutParams(params); selecting.setVisibility(View.VISIBLE); } private int getColor(String name, String defType) { Resources r = getResources(); int id = r.getIdentifier(name, defType, getPackageName()); int color = r.getColor(id); // ARGB to ABGR int red = (color >> 16) & 0xFF; int blue = (color << 16) & 0xFF0000; return (color & 0xFF00FF00) | red | blue; } /** * OnTouch event handler. */ @Override public boolean onTouch(View v, MotionEvent event) { boolean retValue = false; switch (v.getId()) { case R.id.button_restart: retValue = onTouchReset(v, event); break; case R.id.world: retValue = onTouchCanvas(v, event); break; default: break; } return retValue; } /** * OnTouch handler for OpenGL canvas. * Called from OnTouchListener event. */ public boolean onTouchCanvas(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mUsingTool = true; if (mSelected.getId() == R.id.rigid) { Renderer.getInstance().pauseSimulation(); } break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: mUsingTool = false; if (mSelected.getId() == R.id.rigid) { Renderer.getInstance().startSimulation(); } break; default: break; } closePalette(); return mController.onTouch(v, event); } /** * OnTouch handler for reset button. * Called from OnTouchListener event. */ public boolean onTouchReset(View v, MotionEvent event) { if (!mUsingTool) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: closePalette(); select(v, null); break; case MotionEvent.ACTION_UP: Renderer.getInstance().reset(); mController.reset(); // Could refactor out to a deselect() function, but this is // the only place that needs it now. View selecting = findViewById(R.id.selecting); selecting.setVisibility(View.INVISIBLE); break; default: break; } } return true; } /** * OnClick method for debug view. * Called from XML layout. */ public void onClickDebug(View v) { } /** * OnClick method for the color palette. * Called from XML layout. */ public void onClickPalette(View v) { if (mUsingTool) { return; } int color = mColorMap.get(v.getId()); mController.setColor(color); switch (mSelected.getId()) { case R.id.pencil: mSelected.setImageResource( mPencilImageMap.get(v.getId())); break; case R.id.rigid: mSelected.setImageResource( mRigidImageMap.get(v.getId())); break; case R.id.water: mSelected.setImageResource( mWaterImageMap.get(v.getId())); break; } // Close the palette on choosing a color closePalette(); } /** * OnClick method for tools. * Called from XML layout. */ public void onClickTool(View v) { if (mUsingTool) { return; } ToolType tool = null; switch (v.getId()) { case R.id.pencil: tool = ToolType.PENCIL; togglePalette(v, mRigidColorPalette); break; case R.id.rigid: tool = ToolType.RIGID; togglePalette(v, mRigidColorPalette); break; case R.id.water: tool = ToolType.WATER; togglePalette(v, mWaterColorPalette); break; case R.id.eraser: tool = ToolType.ERASER; // Always close palettes for non-drawing tools closePalette(); break; case R.id.hand: tool = ToolType.MOVE; // Always close palettes for non-drawing tools closePalette(); break; default: } // Actually select the view select(v, tool); } }
package com.falkonry.helper.models; /*! * falkonry-java-client * Copyright(c) 2017-2018 Falkonry Inc * MIT Licensed */ import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; import java.util.List; /** * */ @JsonIgnoreProperties(ignoreUnknown=true) public class Datastream { private String id; private String sourceId; private String name; private String tenant; private String createdBy; private Long createTime; private String updatedBy; private Long updateTime; private Stats stats; private Field field; private Datasource dataSource; private List<Input> inputList; private String timePrecision; private String live; /** * * @return */ public String getId() { return id; } /** * * @param id * @return */ public Datastream setId(String id) { this.id = id; return this; } /** * * @return */ public String getSourceId() { return sourceId; } /** * * @param sourceId * @return */ public Datastream setSourceId(String sourceId) { this.sourceId = sourceId; return this; } /** * * @return */ public String getName() { return name; } /** * * @param name * @return */ public Datastream setName(String name) { this.name = name; return this; } /** * * @return */ @JsonProperty("tenant") public String getAccount() { return tenant; } /** * * @param account * @return */ @JsonProperty("tenant") public Datastream setAccount(String account) { this.tenant = account; return this; } /** * * @return */ public String getCreatedBy() { return createdBy; } /** * * @param createdBy * @return */ public Datastream setCreatedBy(String createdBy) { this.createdBy = createdBy; return this; } /** * * @return */ public Long getCreateTime() { return createTime; } /** * * @param createTime * @return */ public Datastream setCreateTime(Long createTime) { this.createTime = createTime; return this; } /** * * @return */ public String getUpdatedBy() { return updatedBy; } /** * * @param updatedBy * @return */ public Datastream setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; return this; } /** * * @return */ public Long getUpdateTime() { return updateTime; } /** * * @param updateTime * @return */ public Datastream setUpdateTime(Long updateTime) { this.updateTime = updateTime; return this; } /** * * @return */ public Stats getStats() { return stats; } /** * * @param stats * @return */ public Datastream setStats(Stats stats){ this.stats = stats; return this; } /** * * @return */ public Field getField() { return field; } /** * * @param field * @return */ public Datastream setField(Field field) { this.field = field; return this; } /** * * @return */ @JsonProperty("dataSource") public Datasource getDatasource() { return dataSource; } /** * * @param dataSource * @return */ @JsonProperty("dataSource") public Datastream setDatasource(Datasource dataSource) { this.dataSource = dataSource; return this; } /** * * @return */ public List<Input> getInputList() { return inputList; } /** * * @param inputList * @return */ public Datastream setInputList(List<Input> inputList) { this.inputList = inputList; return this; } /** * * @return */ public String getTimePrecision() { return timePrecision; } /** * * @param timePrecision * @return */ public Datastream setTimePrecision(String timePrecision) { this.timePrecision = timePrecision; return this; } /** * * @return */ public String getLive() { return live; } /** * * @param live * @return */ public Datastream setLive(String live) { this.live = live; return this; } }
/** * 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.camel.component.gridfs; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.Mongo; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; import com.mongodb.gridfs.GridFS; import org.apache.camel.Consumer; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.impl.DefaultEndpoint; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @UriEndpoint(scheme = "gridfs", title = "MongoDBGridFS", syntax = "gridfs:connectionBean", label = "database,nosql") public class GridFsEndpoint extends DefaultEndpoint { public enum QueryStrategy { TimeStamp, PersistentTimestamp, FileAttribute, TimeStampAndFileAttribute, PersistentTimestampAndFileAttribute }; public static final String GRIDFS_OPERATION = "gridfs.operation"; public static final String GRIDFS_METADATA = "gridfs.metadata"; public static final String GRIDFS_CHUNKSIZE = "gridfs.chunksize"; public static final String GRIDFS_FILE_ID_PRODUCED = "gridfs.fileid"; private static final Logger LOG = LoggerFactory.getLogger(GridFsEndpoint.class); @UriPath @Metadata(required = "true") private String connectionBean; @UriParam @Metadata(required = "true") private String database; @UriParam(defaultValue = GridFS.DEFAULT_BUCKET) private String bucket; @UriParam(enums = "ACKNOWLEDGED,W1,W2,W3,UNACKNOWLEDGED,JOURNALED,MAJORITY,SAFE") private WriteConcern writeConcern; @UriParam private WriteConcern writeConcernRef; @UriParam private ReadPreference readPreference; @UriParam(label = "producer") private String operation; @UriParam(label = "consumer") private String query; @UriParam(label = "consumer", defaultValue = "1000") private long initialDelay = 1000; @UriParam(label = "consumer", defaultValue = "500") private long delay = 500; @UriParam(label = "consumer", defaultValue = "TimeStamp") private QueryStrategy queryStrategy = QueryStrategy.TimeStamp; @UriParam(label = "consumer", defaultValue = "camel-timestamps") private String persistentTSCollection = "camel-timestamps"; @UriParam(label = "consumer", defaultValue = "camel-timestamp") private String persistentTSObject = "camel-timestamp"; @UriParam(label = "consumer", defaultValue = "camel-processed") private String fileAttributeName = "camel-processed"; private Mongo mongoConnection; private DB db; private GridFS gridFs; private DBCollection filesCollection; public GridFsEndpoint(String uri, GridFsComponent component) { super(uri, component); } @Override public Producer createProducer() throws Exception { initializeConnection(); return new GridFsProducer(this); } @Override public Consumer createConsumer(Processor processor) throws Exception { initializeConnection(); return new GridFsConsumer(this, processor); } public boolean isSingleton() { return true; } @SuppressWarnings("deprecation") public void initializeConnection() throws Exception { LOG.info("Initialize GridFS endpoint: {}", this.toString()); if (database == null) { throw new IllegalStateException("Missing required endpoint configuration: database"); } db = mongoConnection.getDB(database); if (db == null) { throw new IllegalStateException("Could not initialize GridFsComponent. Database " + database + " does not exist."); } gridFs = new GridFS(db, bucket == null ? GridFS.DEFAULT_BUCKET : bucket) { { filesCollection = getFilesCollection(); } }; } @Override protected void doStart() throws Exception { if (writeConcern != null && writeConcernRef != null) { String msg = "Cannot set both writeConcern and writeConcernRef at the same time. Respective values: " + writeConcern + ", " + writeConcernRef + ". Aborting initialization."; throw new IllegalArgumentException(msg); } setWriteReadOptionsOnConnection(); super.doStart(); } private void setWriteReadOptionsOnConnection() { // Set the WriteConcern if (writeConcern != null) { mongoConnection.setWriteConcern(writeConcern); } else if (writeConcernRef != null) { mongoConnection.setWriteConcern(writeConcernRef); } // Set the ReadPreference if (readPreference != null) { mongoConnection.setReadPreference(readPreference); } } // ======= Getters and setters =============================================== public String getConnectionBean() { return connectionBean; } /** * Name of {@link com.mongodb.Mongo} to use. */ public void setConnectionBean(String connectionBean) { this.connectionBean = connectionBean; } public Mongo getMongoConnection() { return mongoConnection; } /** * Sets the Mongo instance that represents the backing connection * * @param mongoConnection the connection to the database */ public void setMongoConnection(Mongo mongoConnection) { this.mongoConnection = mongoConnection; } public DB getDB() { return db; } public String getDatabase() { return database; } /** * Sets the name of the MongoDB database to target * * @param database name of the MongoDB database */ public void setDatabase(String database) { this.database = database; } /** * Sets the name of the GridFS bucket within the database. Default is "fs". * * @param database name of the MongoDB database */ public String getBucket() { return bucket; } public void setBucket(String bucket) { this.bucket = bucket; } public String getQuery() { return query; } /** * Additional query parameters (in JSON) that are used to configure the query used for finding * files in the GridFsConsumer * @param query */ public void setQuery(String query) { this.query = query; } public long getDelay() { return delay; } /** * Sets the delay between polls within the Consumer. Default is 500ms * @param delay */ public void setDelay(long delay) { this.delay = delay; } public long getInitialDelay() { return initialDelay; } /** * Sets the initialDelay before the consumer will start polling. Default is 1000ms * @param initialDelay */ public void setInitialDelay(long initialDelay) { this.initialDelay = delay; } /** * Sets the QueryStrategy that is used for polling for new files. Default is Timestamp * @see QueryStrategy * @param s */ public void setQueryStrategy(String s) { queryStrategy = QueryStrategy.valueOf(s); } public QueryStrategy getQueryStrategy() { return queryStrategy; } /** * If the QueryType uses a persistent timestamp, this sets the name of the collection within * the DB to store the timestamp. * @param s */ public void setPersistentTSCollection(String s) { persistentTSCollection = s; } public String getPersistentTSCollection() { return persistentTSCollection; } /** * If the QueryType uses a persistent timestamp, this is the ID of the object in the collection * to store the timestamp. * @param s */ public void setPersistentTSObject(String id) { persistentTSObject = id; } public String getPersistentTSObject() { return persistentTSObject; } /** * If the QueryType uses a FileAttribute, this sets the name of the attribute that is used. Default is "camel-processed". * @param f */ public void setFileAttributeName(String f) { fileAttributeName = f; } public String getFileAttributeName() { return fileAttributeName; } /** * Set the {@link WriteConcern} for write operations on MongoDB using the standard ones. * Resolved from the fields of the WriteConcern class by calling the {@link WriteConcern#valueOf(String)} method. * * @param writeConcern the standard name of the WriteConcern * @see <a href="http://api.mongodb.org/java/current/com/mongodb/WriteConcern.html#valueOf(java.lang.String)">possible options</a> */ public void setWriteConcern(String writeConcern) { this.writeConcern = WriteConcern.valueOf(writeConcern); } public WriteConcern getWriteConcern() { return writeConcern; } /** * Set the {@link WriteConcern} for write operations on MongoDB, passing in the bean ref to a custom WriteConcern which exists in the Registry. * You can also use standard WriteConcerns by passing in their key. See the {@link #setWriteConcern(String) setWriteConcern} method. * * @param writeConcernRef the name of the bean in the registry that represents the WriteConcern to use */ public void setWriteConcernRef(String writeConcernRef) { WriteConcern wc = this.getCamelContext().getRegistry().lookupByNameAndType(writeConcernRef, WriteConcern.class); if (wc == null) { String msg = "Camel MongoDB component could not find the WriteConcern in the Registry. Verify that the " + "provided bean name (" + writeConcernRef + ") is correct. Aborting initialization."; throw new IllegalArgumentException(msg); } this.writeConcernRef = wc; } public WriteConcern getWriteConcernRef() { return writeConcernRef; } /** * Sets a MongoDB {@link ReadPreference} on the Mongo connection. Read preferences set directly on the connection will be * overridden by this setting. * <p/> * The {@link com.mongodb.ReadPreference#valueOf(String)} utility method is used to resolve the passed {@code readPreference} * value. Some examples for the possible values are {@code nearest}, {@code primary} or {@code secondary} etc. * * @param readPreference the name of the read preference to set */ public void setReadPreference(String readPreference) { this.readPreference = ReadPreference.valueOf(readPreference); } public ReadPreference getReadPreference() { return readPreference; } /** * Sets the operation this endpoint will execute against GridRS. */ public void setOperation(String operation) { this.operation = operation; } public String getOperation() { return operation; } public GridFS getGridFs() { return gridFs; } public void setGridFs(GridFS gridFs) { this.gridFs = gridFs; } public DBCollection getFilesCollection() { return filesCollection; } }
/* 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.persistence.entity; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.activiti.engine.ActivitiException; import org.activiti.engine.impl.context.Context; import org.activiti.engine.impl.interceptor.CommandContext; import org.activiti.engine.impl.javax.el.ELContext; import org.flowable.variable.api.delegate.VariableScope; import org.flowable.variable.api.persistence.entity.VariableInstance; import org.flowable.variable.api.types.VariableType; import org.flowable.variable.api.types.VariableTypes; /** * @author Tom Baeyens * @author Joram Barrez * @author Tijs Rademakers * @author Saeid Mirzaei */ public abstract class VariableScopeImpl implements Serializable, VariableScope { private static final long serialVersionUID = 1L; // The cache used when fetching all variables protected Map<String, VariableInstanceEntity> variableInstances = null; // needs to be null, the logic depends on it for checking if vars were already fetched // The cache is used when fetching/setting specific variables protected Map<String, VariableInstanceEntity> usedVariablesCache = new HashMap<>(); protected Map<String, VariableInstance> transientVariabes; protected ELContext cachedElContext; protected String id; protected abstract List<VariableInstanceEntity> loadVariableInstances(); protected abstract VariableScopeImpl getParentVariableScope(); protected abstract void initializeVariableInstanceBackPointer(VariableInstanceEntity variableInstance); protected void ensureVariableInstancesInitialized() { if (variableInstances == null) { variableInstances = new HashMap<>(); CommandContext commandContext = Context.getCommandContext(); if (commandContext == null) { throw new ActivitiException("lazy loading outside command context"); } List<VariableInstanceEntity> variableInstancesList = loadVariableInstances(); for (VariableInstanceEntity variableInstance : variableInstancesList) { variableInstances.put(variableInstance.getName(), variableInstance); } } } @Override public Map<String, Object> getVariables() { return collectVariables(new HashMap<String, Object>()); } @Override public Map<String, VariableInstance> getVariableInstances() { return collectVariableInstances(new HashMap<String, VariableInstance>()); } @Override public Map<String, Object> getVariables(Collection<String> variableNames) { return getVariables(variableNames, true); } @Override public Map<String, VariableInstance> getVariableInstances(Collection<String> variableNames) { return getVariableInstances(variableNames, true); } @Override public Map<String, Object> getVariables(Collection<String> variableNames, boolean fetchAllVariables) { Map<String, Object> requestedVariables = new HashMap<>(); Set<String> variableNamesToFetch = new HashSet<>(variableNames); // Transient variables 'shadow' any existing variables. // The values in the fetch-cache will be more recent, so they can override any existing ones for (String variableName : variableNames) { if (transientVariabes != null && transientVariabes.containsKey(variableName)) { requestedVariables.put(variableName, transientVariabes.get(variableName).getValue()); variableNamesToFetch.remove(variableName); } else if (usedVariablesCache.containsKey(variableName)) { requestedVariables.put(variableName, usedVariablesCache.get(variableName).getValue()); variableNamesToFetch.remove(variableName); } } if (fetchAllVariables) { // getVariables() will go up the execution hierarchy, no need to do it here // also, the cached values will already be applied too Map<String, Object> allVariables = getVariables(); for (String variableName : variableNamesToFetch) { requestedVariables.put(variableName, allVariables.get(variableName)); } return requestedVariables; } else { // Fetch variables on this scope List<VariableInstanceEntity> variables = getSpecificVariables(variableNamesToFetch); for (VariableInstanceEntity variable : variables) { requestedVariables.put(variable.getName(), variable.getValue()); } // Go up if needed VariableScopeImpl parent = getParentVariableScope(); if (parent != null) { requestedVariables.putAll(parent.getVariables(variableNamesToFetch, fetchAllVariables)); } return requestedVariables; } } @Override public Map<String, VariableInstance> getVariableInstances(Collection<String> variableNames, boolean fetchAllVariables) { Map<String, VariableInstance> requestedVariables = new HashMap<>(); Set<String> variableNamesToFetch = new HashSet<>(variableNames); // The values in the fetch-cache will be more recent, so they can override any existing ones for (String variableName : variableNames) { if (transientVariabes != null && transientVariabes.containsKey(variableName)) { requestedVariables.put(variableName, transientVariabes.get(variableName)); variableNamesToFetch.remove(variableName); } else if (usedVariablesCache.containsKey(variableName)) { requestedVariables.put(variableName, usedVariablesCache.get(variableName)); variableNamesToFetch.remove(variableName); } } if (fetchAllVariables) { // getVariables() will go up the execution hierarchy, no need to do it here // also, the cached values will already be applied too Map<String, VariableInstance> allVariables = getVariableInstances(); for (String variableName : variableNamesToFetch) { requestedVariables.put(variableName, allVariables.get(variableName)); } return requestedVariables; } else { // Fetch variables on this scope List<VariableInstanceEntity> variables = getSpecificVariables(variableNamesToFetch); for (VariableInstanceEntity variable : variables) { requestedVariables.put(variable.getName(), variable); } // Go up if needed VariableScopeImpl parent = getParentVariableScope(); if (parent != null) { requestedVariables.putAll(parent.getVariableInstances(variableNamesToFetch, fetchAllVariables)); } return requestedVariables; } } protected Map<String, Object> collectVariables(HashMap<String, Object> variables) { ensureVariableInstancesInitialized(); VariableScopeImpl parentScope = getParentVariableScope(); if (parentScope != null) { variables.putAll(parentScope.collectVariables(variables)); } for (VariableInstanceEntity variableInstance : variableInstances.values()) { variables.put(variableInstance.getName(), variableInstance.getValue()); } for (String variableName : usedVariablesCache.keySet()) { variables.put(variableName, usedVariablesCache.get(variableName).getValue()); } if (transientVariabes != null) { for (String variableName : transientVariabes.keySet()) { variables.put(variableName, transientVariabes.get(variableName).getValue()); } } return variables; } protected Map<String, VariableInstance> collectVariableInstances(HashMap<String, VariableInstance> variables) { ensureVariableInstancesInitialized(); VariableScopeImpl parentScope = getParentVariableScope(); if (parentScope != null) { variables.putAll(parentScope.collectVariableInstances(variables)); } for (VariableInstance variableInstance : variableInstances.values()) { variables.put(variableInstance.getName(), variableInstance); } for (String variableName : usedVariablesCache.keySet()) { variables.put(variableName, usedVariablesCache.get(variableName)); } if (transientVariabes != null) { variables.putAll(transientVariabes); } return variables; } @Override public Object getVariable(String variableName) { return getVariable(variableName, true); } @Override public VariableInstance getVariableInstance(String variableName) { return getVariableInstance(variableName, true); } /** * The same operation as {@link VariableScopeImpl#getVariable(String)}, but with an extra parameter to indicate whether or not all variables need to be fetched. * <p> * Note that the default Activiti way (because of backwards compatibility) is to fetch all the variables when doing a get/set of variables. So this means 'true' is the default value for this * method, and in fact it will simply delegate to {@link #getVariable(String)}. This can also be the most performant, if you're doing a lot of variable gets in the same transaction (eg in service * tasks). * <p> * In case 'false' is used, only the specific variable will be fetched. */ @Override public Object getVariable(String variableName, boolean fetchAllVariables) { Object value = null; VariableInstance variable = getVariableInstance(variableName, fetchAllVariables); if (variable != null) { value = variable.getValue(); } return value; } @Override public VariableInstance getVariableInstance(String variableName, boolean fetchAllVariables) { // Transient variable if (transientVariabes != null && transientVariabes.containsKey(variableName)) { return transientVariabes.get(variableName); } // Check the local single-fetch cache if (usedVariablesCache.containsKey(variableName)) { return usedVariablesCache.get(variableName); } if (fetchAllVariables) { ensureVariableInstancesInitialized(); VariableInstanceEntity variableInstance = variableInstances.get(variableName); if (variableInstance != null) { return variableInstance; } // Go up the hierarchy VariableScope parentScope = getParentVariableScope(); if (parentScope != null) { return parentScope.getVariableInstance(variableName, true); } return null; } else { if (usedVariablesCache.containsKey(variableName)) { return usedVariablesCache.get(variableName); } if (variableInstances != null && variableInstances.containsKey(variableName)) { return variableInstances.get(variableName); } VariableInstanceEntity variable = getSpecificVariable(variableName); if (variable != null) { usedVariablesCache.put(variableName, variable); return variable; } // Go up the hierarchy VariableScope parentScope = getParentVariableScope(); if (parentScope != null) { return parentScope.getVariableInstance(variableName, false); } return null; } } protected abstract VariableInstanceEntity getSpecificVariable(String variableName); @Override public Object getVariableLocal(String variableName) { return getVariableLocal(variableName, true); } @Override public VariableInstance getVariableInstanceLocal(String variableName) { return getVariableInstanceLocal(variableName, true); } @Override public Object getVariableLocal(String variableName, boolean fetchAllVariables) { Object value = null; VariableInstance variable = getVariableInstanceLocal(variableName, fetchAllVariables); if (variable != null) { value = variable.getValue(); } return value; } @Override public VariableInstance getVariableInstanceLocal(String variableName, boolean fetchAllVariables) { if (transientVariabes != null && transientVariabes.containsKey(variableName)) { return transientVariabes.get(variableName); } if (usedVariablesCache.containsKey(variableName)) { return usedVariablesCache.get(variableName); } if (fetchAllVariables) { ensureVariableInstancesInitialized(); VariableInstanceEntity variableInstance = variableInstances.get(variableName); if (variableInstance != null) { return variableInstance; } return null; } else { if (usedVariablesCache.containsKey(variableName)) { VariableInstanceEntity variable = usedVariablesCache.get(variableName); if (variable != null) { return variable; } } if (variableInstances != null && variableInstances.containsKey(variableName)) { VariableInstanceEntity variable = variableInstances.get(variableName); if (variable != null) { return variableInstances.get(variableName); } } VariableInstanceEntity variable = getSpecificVariable(variableName); if (variable != null) { usedVariablesCache.put(variableName, variable); return variable; } return null; } } @Override public boolean hasVariables() { if (transientVariabes != null && !transientVariabes.isEmpty()) { return true; } ensureVariableInstancesInitialized(); if (!variableInstances.isEmpty()) { return true; } VariableScope parentScope = getParentVariableScope(); if (parentScope != null) { return parentScope.hasVariables(); } return false; } @Override public boolean hasVariablesLocal() { if (transientVariabes != null && !transientVariabes.isEmpty()) { return true; } ensureVariableInstancesInitialized(); return !variableInstances.isEmpty(); } @Override public boolean hasVariable(String variableName) { if (hasVariableLocal(variableName)) { return true; } VariableScope parentScope = getParentVariableScope(); if (parentScope != null) { return parentScope.hasVariable(variableName); } return false; } @Override public boolean hasVariableLocal(String variableName) { if (transientVariabes != null && transientVariabes.containsKey(variableName)) { return true; } ensureVariableInstancesInitialized(); return variableInstances.containsKey(variableName); } protected Set<String> collectVariableNames(Set<String> variableNames) { if (transientVariabes != null) { variableNames.addAll(transientVariabes.keySet()); } ensureVariableInstancesInitialized(); VariableScopeImpl parentScope = getParentVariableScope(); if (parentScope != null) { variableNames.addAll(parentScope.collectVariableNames(variableNames)); } for (VariableInstanceEntity variableInstance : variableInstances.values()) { variableNames.add(variableInstance.getName()); } return variableNames; } @Override public Set<String> getVariableNames() { return collectVariableNames(new HashSet<String>()); } @Override public Map<String, Object> getVariablesLocal() { Map<String, Object> variables = new HashMap<>(); ensureVariableInstancesInitialized(); for (VariableInstanceEntity variableInstance : variableInstances.values()) { variables.put(variableInstance.getName(), variableInstance.getValue()); } for (String variableName : usedVariablesCache.keySet()) { variables.put(variableName, usedVariablesCache.get(variableName).getValue()); } if (transientVariabes != null) { for (String variableName : transientVariabes.keySet()) { variables.put(variableName, transientVariabes.get(variableName).getValue()); } } return variables; } @Override public Map<String, VariableInstance> getVariableInstancesLocal() { Map<String, VariableInstance> variables = new HashMap<>(); ensureVariableInstancesInitialized(); for (VariableInstanceEntity variableInstance : variableInstances.values()) { variables.put(variableInstance.getName(), variableInstance); } for (String variableName : usedVariablesCache.keySet()) { variables.put(variableName, usedVariablesCache.get(variableName)); } if (transientVariabes != null) { variables.putAll(transientVariabes); } return variables; } @Override public Map<String, Object> getVariablesLocal(Collection<String> variableNames) { return getVariablesLocal(variableNames, true); } @Override public Map<String, VariableInstance> getVariableInstancesLocal(Collection<String> variableNames) { return getVariableInstancesLocal(variableNames, true); } @Override public Map<String, Object> getVariablesLocal(Collection<String> variableNames, boolean fetchAllVariables) { Map<String, Object> requestedVariables = new HashMap<>(); // The values in the fetch-cache will be more recent, so they can override any existing ones Set<String> variableNamesToFetch = new HashSet<>(variableNames); for (String variableName : variableNames) { if (transientVariabes != null && transientVariabes.containsKey(variableName)) { requestedVariables.put(variableName, transientVariabes.get(variableName).getValue()); variableNamesToFetch.remove(variableName); } else if (usedVariablesCache.containsKey(variableName)) { requestedVariables.put(variableName, usedVariablesCache.get(variableName).getValue()); variableNamesToFetch.remove(variableName); } } if (fetchAllVariables) { Map<String, Object> allVariables = getVariablesLocal(); for (String variableName : variableNamesToFetch) { requestedVariables.put(variableName, allVariables.get(variableName)); } } else { List<VariableInstanceEntity> variables = getSpecificVariables(variableNamesToFetch); for (VariableInstanceEntity variable : variables) { requestedVariables.put(variable.getName(), variable.getValue()); } } return requestedVariables; } @Override public Map<String, VariableInstance> getVariableInstancesLocal(Collection<String> variableNames, boolean fetchAllVariables) { Map<String, VariableInstance> requestedVariables = new HashMap<>(); // The values in the fetch-cache will be more recent, so they can override any existing ones Set<String> variableNamesToFetch = new HashSet<>(variableNames); for (String variableName : variableNames) { if (transientVariabes != null && transientVariabes.containsKey(variableName)) { requestedVariables.put(variableName, transientVariabes.get(variableName)); variableNamesToFetch.remove(variableName); } else if (usedVariablesCache.containsKey(variableName)) { requestedVariables.put(variableName, usedVariablesCache.get(variableName)); variableNamesToFetch.remove(variableName); } } if (fetchAllVariables) { Map<String, VariableInstance> allVariables = getVariableInstancesLocal(); for (String variableName : variableNamesToFetch) { requestedVariables.put(variableName, allVariables.get(variableName)); } } else { List<VariableInstanceEntity> variables = getSpecificVariables(variableNamesToFetch); for (VariableInstanceEntity variable : variables) { requestedVariables.put(variable.getName(), variable); } } return requestedVariables; } protected abstract List<VariableInstanceEntity> getSpecificVariables(Collection<String> variableNames); @Override public Set<String> getVariableNamesLocal() { Set<String> variableNames = new HashSet<>(); if (transientVariabes != null) { variableNames.addAll(transientVariabes.keySet()); } ensureVariableInstancesInitialized(); variableNames.addAll(variableInstances.keySet()); return variableNames; } public Map<String, VariableInstanceEntity> getVariableInstanceEntities() { ensureVariableInstancesInitialized(); return Collections.unmodifiableMap(variableInstances); } public Map<String, VariableInstanceEntity> getUsedVariablesCache() { return usedVariablesCache; } public void createVariablesLocal(Map<String, ? extends Object> variables) { if (variables != null) { for (Map.Entry<String, ? extends Object> entry : variables.entrySet()) { createVariableLocal(entry.getKey(), entry.getValue()); } } } @Override public void setVariables(Map<String, ? extends Object> variables) { if (variables != null) { for (String variableName : variables.keySet()) { setVariable(variableName, variables.get(variableName)); } } } @Override public void setVariablesLocal(Map<String, ? extends Object> variables) { if (variables != null) { for (String variableName : variables.keySet()) { setVariableLocal(variableName, variables.get(variableName)); } } } @Override public void removeVariables() { ensureVariableInstancesInitialized(); Set<String> variableNames = new HashSet<>(variableInstances.keySet()); for (String variableName : variableNames) { removeVariable(variableName); } } @Override public void removeVariablesLocal() { List<String> variableNames = new ArrayList<>(getVariableNamesLocal()); for (String variableName : variableNames) { removeVariableLocal(variableName); } } public void deleteVariablesInstanceForLeavingScope() { ensureVariableInstancesInitialized(); for (VariableInstanceEntity variableInstance : variableInstances.values()) { Context.getCommandContext().getHistoryManager().recordVariableUpdate(variableInstance); variableInstance.delete(); } } @Override public void removeVariables(Collection<String> variableNames) { if (variableNames != null) { for (String variableName : variableNames) { removeVariable(variableName); } } } @Override public void removeVariablesLocal(Collection<String> variableNames) { if (variableNames != null) { for (String variableName : variableNames) { removeVariableLocal(variableName); } } } @Override public void setVariable(String variableName, Object value) { setVariable(variableName, value, getSourceActivityExecution(), true); } /** * The default {@link #setVariable(String, Object)} fetches all variables (for historical and backwards compatible reasons) while setting the variables. * <p> * Setting the fetchAllVariables parameter to true is the default behaviour (ie fetching all variables) Setting the fetchAllVariables parameter to false does not do that. */ @Override public void setVariable(String variableName, Object value, boolean fetchAllVariables) { setVariable(variableName, value, getSourceActivityExecution(), fetchAllVariables); } protected void setVariable(String variableName, Object value, ExecutionEntity sourceActivityExecution, boolean fetchAllVariables) { if (fetchAllVariables) { // If it's in the cache, it's more recent if (usedVariablesCache.containsKey(variableName)) { updateVariableInstance(usedVariablesCache.get(variableName), value, sourceActivityExecution); } // If the variable exists on this scope, replace it if (hasVariableLocal(variableName)) { setVariableLocal(variableName, value, sourceActivityExecution, true); return; } // Otherwise, go up the hierarchy (we're trying to put it as high as possible) VariableScopeImpl parentVariableScope = getParentVariableScope(); if (parentVariableScope != null) { if (sourceActivityExecution == null) { parentVariableScope.setVariable(variableName, value); } else { parentVariableScope.setVariable(variableName, value, sourceActivityExecution, true); } return; } // We're as high as possible and the variable doesn't exist yet, so we're creating it createVariableLocal(variableName, value); } else { // Check local cache first if (usedVariablesCache.containsKey(variableName)) { updateVariableInstance(usedVariablesCache.get(variableName), value, sourceActivityExecution); } else if (variableInstances != null && variableInstances.containsKey(variableName)) { updateVariableInstance(variableInstances.get(variableName), value, sourceActivityExecution); } else { // Not in local cache, check if defined on this scope // Create it if it doesn't exist yet VariableInstanceEntity variable = getSpecificVariable(variableName); if (variable != null) { updateVariableInstance(variable, value, sourceActivityExecution); usedVariablesCache.put(variableName, variable); } else { VariableScopeImpl parent = getParentVariableScope(); if (parent != null) { parent.setVariable(variableName, value, sourceActivityExecution, fetchAllVariables); return; } variable = createVariableInstance(variableName, value, sourceActivityExecution); usedVariablesCache.put(variableName, variable); } } } } @Override public Object setVariableLocal(String variableName, Object value) { return setVariableLocal(variableName, value, getSourceActivityExecution(), true); } /** * The default {@link #setVariableLocal(String, Object)} fetches all variables (for historical and backwards compatible reasons) while setting the variables. * <p> * Setting the fetchAllVariables parameter to true is the default behaviour (ie fetching all variables) Setting the fetchAllVariables parameter to false does not do that. */ @Override public Object setVariableLocal(String variableName, Object value, boolean fetchAllVariables) { return setVariableLocal(variableName, value, getSourceActivityExecution(), fetchAllVariables); } public Object setVariableLocal(String variableName, Object value, ExecutionEntity sourceActivityExecution, boolean fetchAllVariables) { if (fetchAllVariables) { // If it's in the cache, it's more recent if (usedVariablesCache.containsKey(variableName)) { updateVariableInstance(usedVariablesCache.get(variableName), value, sourceActivityExecution); } ensureVariableInstancesInitialized(); VariableInstanceEntity variableInstance = variableInstances.get(variableName); if (variableInstance == null) { variableInstance = usedVariablesCache.get(variableName); } if (variableInstance == null) { createVariableLocal(variableName, value); } else { updateVariableInstance(variableInstance, value, sourceActivityExecution); } return null; } else { if (usedVariablesCache.containsKey(variableName)) { updateVariableInstance(usedVariablesCache.get(variableName), value, sourceActivityExecution); } else if (variableInstances != null && variableInstances.containsKey(variableName)) { updateVariableInstance(variableInstances.get(variableName), value, sourceActivityExecution); } else { VariableInstanceEntity variable = getSpecificVariable(variableName); if (variable != null) { updateVariableInstance(variable, value, sourceActivityExecution); } else { variable = createVariableInstance(variableName, value, sourceActivityExecution); } usedVariablesCache.put(variableName, variable); } return null; } } public void createVariableLocal(String variableName, Object value) { createVariableLocal(variableName, value, getSourceActivityExecution()); } /** * only called when a new variable is created on this variable scope. This method is also responsible for propagating the creation of this variable to the history. */ protected void createVariableLocal(String variableName, Object value, ExecutionEntity sourceActivityExecution) { ensureVariableInstancesInitialized(); if (variableInstances.containsKey(variableName)) { throw new ActivitiException("variable '" + variableName + "' already exists. Use setVariableLocal if you want to overwrite the value"); } createVariableInstance(variableName, value, sourceActivityExecution); } @Override public void removeVariable(String variableName) { removeVariable(variableName, getSourceActivityExecution()); } protected void removeVariable(String variableName, ExecutionEntity sourceActivityExecution) { ensureVariableInstancesInitialized(); if (variableInstances.containsKey(variableName)) { removeVariableLocal(variableName); return; } VariableScopeImpl parentVariableScope = getParentVariableScope(); if (parentVariableScope != null) { if (sourceActivityExecution == null) { parentVariableScope.removeVariable(variableName); } else { parentVariableScope.removeVariable(variableName, sourceActivityExecution); } } } @Override public void removeVariableLocal(String variableName) { removeVariableLocal(variableName, getSourceActivityExecution()); } protected ExecutionEntity getSourceActivityExecution() { return null; } protected void removeVariableLocal(String variableName, ExecutionEntity sourceActivityExecution) { ensureVariableInstancesInitialized(); VariableInstanceEntity variableInstance = variableInstances.remove(variableName); if (variableInstance != null) { deleteVariableInstanceForExplicitUserCall(variableInstance, sourceActivityExecution); } } protected void deleteVariableInstanceForExplicitUserCall(VariableInstanceEntity variableInstance, ExecutionEntity sourceActivityExecution) { variableInstance.delete(); variableInstance.setValue(null); // Record historic variable deletion Context.getCommandContext().getHistoryManager() .recordVariableRemoved(variableInstance); // Record historic detail Context.getCommandContext().getHistoryManager() .recordHistoricDetailVariableCreate(variableInstance, sourceActivityExecution, isActivityIdUsedForDetails()); } protected void updateVariableInstance(VariableInstanceEntity variableInstance, Object value, ExecutionEntity sourceActivityExecution) { // Always check if the type should be altered. It's possible that the previous type is lower in the type // checking chain (e.g. serializable) and will return true on isAbleToStore(), even though another type // higher in the chain is eligible for storage. VariableTypes variableTypes = Context .getProcessEngineConfiguration() .getVariableTypes(); VariableType newType = variableTypes.findVariableType(value); if (newType != null && !newType.equals(variableInstance.getType())) { variableInstance.setValue(null); variableInstance.setType(newType); variableInstance.forceUpdate(); variableInstance.setValue(value); } else { variableInstance.setValue(value); } Context.getCommandContext().getHistoryManager() .recordHistoricDetailVariableCreate(variableInstance, sourceActivityExecution, isActivityIdUsedForDetails()); Context.getCommandContext().getHistoryManager() .recordVariableUpdate(variableInstance); } protected VariableInstanceEntity createVariableInstance(String variableName, Object value, ExecutionEntity sourceActivityExecution) { VariableTypes variableTypes = Context .getProcessEngineConfiguration() .getVariableTypes(); VariableType type = variableTypes.findVariableType(value); VariableInstanceEntity variableInstance = VariableInstanceEntity.createAndInsert(variableName, type, value); initializeVariableInstanceBackPointer(variableInstance); if (variableInstances != null) { variableInstances.put(variableName, variableInstance); } // Record historic variable Context.getCommandContext().getHistoryManager() .recordVariableCreate(variableInstance); // Record historic detail Context.getCommandContext().getHistoryManager() .recordHistoricDetailVariableCreate(variableInstance, sourceActivityExecution, isActivityIdUsedForDetails()); return variableInstance; } /** * Execution variable updates have activity instance ids, but historic task variable updates don't. */ protected boolean isActivityIdUsedForDetails() { return true; } /* * Transient variables */ @Override public void setTransientVariablesLocal(Map<String, Object> transientVariables) { for (String variableName : transientVariables.keySet()) { setTransientVariableLocal(variableName, transientVariables.get(variableName)); } } @Override public void setTransientVariableLocal(String variableName, Object variableValue) { if (transientVariabes == null) { transientVariabes = new HashMap<>(); } transientVariabes.put(variableName, new TransientVariableInstance(variableName, variableValue)); } @Override public void setTransientVariables(Map<String, Object> transientVariables) { for (String variableName : transientVariables.keySet()) { setTransientVariable(variableName, transientVariables.get(variableName)); } } @Override public void setTransientVariable(String variableName, Object variableValue) { VariableScopeImpl parentVariableScope = getParentVariableScope(); if (parentVariableScope != null) { parentVariableScope.setTransientVariable(variableName, variableValue); return; } setTransientVariableLocal(variableName, variableValue); } @Override public Object getTransientVariableLocal(String variableName) { if (transientVariabes != null) { return transientVariabes.get(variableName).getValue(); } return null; } @Override public Map<String, Object> getTransientVariablesLocal() { if (transientVariabes != null) { Map<String, Object> variables = new HashMap<>(); for (String variableName : transientVariabes.keySet()) { variables.put(variableName, transientVariabes.get(variableName).getValue()); } return variables; } else { return Collections.emptyMap(); } } @Override public Object getTransientVariable(String variableName) { if (transientVariabes != null && transientVariabes.containsKey(variableName)) { return transientVariabes.get(variableName).getValue(); } VariableScopeImpl parentScope = getParentVariableScope(); if (parentScope != null) { return parentScope.getTransientVariable(variableName); } return null; } @Override public Map<String, Object> getTransientVariables() { return collectTransientVariables(new HashMap<String, Object>()); } protected Map<String, Object> collectTransientVariables(HashMap<String, Object> variables) { VariableScopeImpl parentScope = getParentVariableScope(); if (parentScope != null) { variables.putAll(parentScope.collectVariables(variables)); } if (transientVariabes != null) { for (String variableName : transientVariabes.keySet()) { variables.put(variableName, transientVariabes.get(variableName).getValue()); } } return variables; } @Override public void removeTransientVariableLocal(String variableName) { if (transientVariabes != null) { transientVariabes.remove(variableName); } } @Override public void removeTransientVariablesLocal() { if (transientVariabes != null) { transientVariabes.clear(); } } @Override public void removeTransientVariable(String variableName) { if (transientVariabes != null && transientVariabes.containsKey(variableName)) { removeTransientVariableLocal(variableName); return; } VariableScopeImpl parentVariableScope = getParentVariableScope(); if (parentVariableScope != null) { parentVariableScope.removeTransientVariable(variableName); } } @Override public void removeTransientVariables() { removeTransientVariablesLocal(); VariableScopeImpl parentVariableScope = getParentVariableScope(); if (parentVariableScope != null) { parentVariableScope.removeTransientVariablesLocal(); } } // getters and setters ////////////////////////////////////////////////////// public ELContext getCachedElContext() { return cachedElContext; } public void setCachedElContext(ELContext cachedElContext) { this.cachedElContext = cachedElContext; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public <T> T getVariable(String variableName, Class<T> variableClass) { return variableClass.cast(getVariable(variableName)); } @Override public <T> T getVariableLocal(String variableName, Class<T> variableClass) { return variableClass.cast(getVariableLocal(variableName)); } }
// 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. /** * DescribeSnapshotsOwnersType.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.5.1 Built on : Oct 19, 2009 (10:59:34 EDT) */ package com.amazon.ec2; /** * DescribeSnapshotsOwnersType bean class */ public class DescribeSnapshotsOwnersType implements org.apache.axis2.databinding.ADBBean{ /* This type was generated from the piece of schema that had name = DescribeSnapshotsOwnersType Namespace URI = http://ec2.amazonaws.com/doc/2010-11-15/ Namespace Prefix = ns1 */ private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://ec2.amazonaws.com/doc/2010-11-15/")){ return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * field for Item * This was an Array! */ protected com.amazon.ec2.DescribeSnapshotsOwnerType[] localItem ; /* This tracker boolean wil be used to detect whether the user called the set method * for this attribute. It will be used to determine whether to include this field * in the serialized XML */ protected boolean localItemTracker = false ; /** * Auto generated getter method * @return com.amazon.ec2.DescribeSnapshotsOwnerType[] */ public com.amazon.ec2.DescribeSnapshotsOwnerType[] getItem(){ return localItem; } /** * validate the array for Item */ protected void validateItem(com.amazon.ec2.DescribeSnapshotsOwnerType[] param){ } /** * Auto generated setter method * @param param Item */ public void setItem(com.amazon.ec2.DescribeSnapshotsOwnerType[] param){ validateItem(param); if (param != null){ //update the setting tracker localItemTracker = true; } else { localItemTracker = false; } this.localItem=param; } /** * Auto generated add method for the array for convenience * @param param com.amazon.ec2.DescribeSnapshotsOwnerType */ public void addItem(com.amazon.ec2.DescribeSnapshotsOwnerType param){ if (localItem == null){ localItem = new com.amazon.ec2.DescribeSnapshotsOwnerType[]{}; } //update the setting tracker localItemTracker = true; java.util.List list = org.apache.axis2.databinding.utils.ConverterUtil.toList(localItem); list.add(param); this.localItem = (com.amazon.ec2.DescribeSnapshotsOwnerType[])list.toArray( new com.amazon.ec2.DescribeSnapshotsOwnerType[list.size()]); } /** * isReaderMTOMAware * @return true if the reader supports MTOM */ public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) { boolean isReaderMTOMAware = false; try{ isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE)); }catch(java.lang.IllegalArgumentException e){ isReaderMTOMAware = false; } return isReaderMTOMAware; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,parentQName){ public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { DescribeSnapshotsOwnersType.this.serialize(parentQName,factory,xmlWriter); } }; return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl( parentQName,factory,dataSource); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,factory,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); if ((namespace != null) && (namespace.trim().length() > 0)) { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, parentQName.getLocalPart()); } else { if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } else { xmlWriter.writeStartElement(parentQName.getLocalPart()); } if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://ec2.amazonaws.com/doc/2010-11-15/"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":DescribeSnapshotsOwnersType", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "DescribeSnapshotsOwnersType", xmlWriter); } } if (localItemTracker){ if (localItem!=null){ for (int i = 0;i < localItem.length;i++){ if (localItem[i] != null){ localItem[i].serialize(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/","item"), factory,xmlWriter); } else { // we don't have to do any thing since minOccures is zero } } } else { throw new org.apache.axis2.databinding.ADBException("item cannot be null!!"); } } xmlWriter.writeEndElement(); } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ java.util.ArrayList elementList = new java.util.ArrayList(); java.util.ArrayList attribList = new java.util.ArrayList(); if (localItemTracker){ if (localItem!=null) { for (int i = 0;i < localItem.length;i++){ if (localItem[i] != null){ elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/", "item")); elementList.add(localItem[i]); } else { // nothing to do } } } else { throw new org.apache.axis2.databinding.ADBException("item cannot be null!!"); } } return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory{ /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static DescribeSnapshotsOwnersType parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ DescribeSnapshotsOwnersType object = new DescribeSnapshotsOwnersType(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){ java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName!=null){ java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1){ nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":")); } nsPrefix = nsPrefix==null?"":nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1); if (!"DescribeSnapshotsOwnersType".equals(type)){ //find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (DescribeSnapshotsOwnersType)com.amazon.ec2.ExtensionMapper.getTypeObject( nsUri,type,reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); reader.next(); java.util.ArrayList list1 = new java.util.ArrayList(); while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/","item").equals(reader.getName())){ // Process the array and step past its final element's end. list1.add(com.amazon.ec2.DescribeSnapshotsOwnerType.Factory.parse(reader)); //loop until we find a start element that is not part of this array boolean loopDone1 = false; while(!loopDone1){ // We should be at the end element, but make sure while (!reader.isEndElement()) reader.next(); // Step out of this element reader.next(); // Step to next element event. while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isEndElement()){ //two continuous end elements means we are exiting the xml structure loopDone1 = true; } else { if (new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/","item").equals(reader.getName())){ list1.add(com.amazon.ec2.DescribeSnapshotsOwnerType.Factory.parse(reader)); }else{ loopDone1 = true; } } } // call the converter utility to convert and set the array object.setItem((com.amazon.ec2.DescribeSnapshotsOwnerType[]) org.apache.axis2.databinding.utils.ConverterUtil.convertToArray( com.amazon.ec2.DescribeSnapshotsOwnerType.class, list1)); } // End of if for expected property start element else { } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement()) // A start element we are not expecting indicates a trailing invalid property throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.plugins; import com.intellij.CommonBundle; import com.intellij.core.CoreBundle; import com.intellij.ide.IdeBundle; import com.intellij.ide.plugins.marketplace.MarketplacePluginDownloadService; import com.intellij.ide.plugins.marketplace.PluginSignatureChecker; import com.intellij.ide.plugins.marketplace.statistics.PluginManagerUsageCollector; import com.intellij.ide.plugins.marketplace.statistics.enums.InstallationSourceEnum; import com.intellij.ide.plugins.org.PluginManagerFilters; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ex.MessagesEx; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.Decompressor; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import static com.intellij.ide.startup.StartupActionScriptManager.*; /** * @author stathik */ public final class PluginInstaller { private static final Logger LOG = Logger.getInstance(PluginInstaller.class); public static final String UNKNOWN_HOST_MARKER = "__unknown_repository__"; static final Object ourLock = new Object(); private static final String PLUGINS_PRESELECTION_PATH = "plugins.preselection.path"; private PluginInstaller() { } /** * @return true if restart is needed */ @ApiStatus.Internal public static boolean prepareToUninstall(@NotNull IdeaPluginDescriptorImpl pluginDescriptor) throws IOException { synchronized (ourLock) { if (PluginManagerCore.isPluginInstalled(pluginDescriptor.getPluginId())) { if (pluginDescriptor.isBundled()) { LOG.error("Plugin is bundled: " + pluginDescriptor.getPluginId()); } else { boolean needRestart = pluginDescriptor.isEnabled() && !DynamicPlugins.allowLoadUnloadWithoutRestart(pluginDescriptor); if (needRestart) { uninstallAfterRestart(pluginDescriptor.getPluginPath()); } PluginStateManager.fireState(pluginDescriptor, false); return needRestart; } } } return false; } private static void uninstallAfterRestart(@NotNull Path pluginPath) throws IOException { addActionCommand(new DeleteCommand(pluginPath)); } public static boolean uninstallDynamicPlugin(@Nullable JComponent parentComponent, @NotNull IdeaPluginDescriptorImpl pluginDescriptor, boolean isUpdate) { boolean uninstalledWithoutRestart = true; if (pluginDescriptor.isEnabled()) { DynamicPlugins.UnloadPluginOptions options = new DynamicPlugins.UnloadPluginOptions().withDisable(false) .withUpdate(isUpdate) .withWaitForClassloaderUnload(true); uninstalledWithoutRestart = parentComponent != null ? DynamicPlugins.INSTANCE.unloadPluginWithProgress(null, parentComponent, pluginDescriptor, options) : DynamicPlugins.INSTANCE.unloadPlugin(pluginDescriptor, options); } Path pluginPath = pluginDescriptor.getPluginPath(); if (uninstalledWithoutRestart) { try { FileUtil.delete(pluginPath); } catch (IOException e) { LOG.info("Failed to delete jar of dynamic plugin", e); uninstalledWithoutRestart = false; } } if (!uninstalledWithoutRestart) { try { uninstallAfterRestart(pluginPath); } catch (IOException e) { LOG.error(e); } } return uninstalledWithoutRestart; } public static void installAfterRestart(@NotNull Path sourceFile, boolean deleteSourceFile, @Nullable Path existingPlugin, @NotNull IdeaPluginDescriptor descriptor) throws IOException { List<ActionCommand> commands = new ArrayList<>(); if (existingPlugin != null) { commands.add(new DeleteCommand(existingPlugin)); } Path pluginsPath = getPluginsPath(); if (sourceFile.getFileName().toString().endsWith(".jar")) { commands.add(new CopyCommand(sourceFile, pluginsPath.resolve(sourceFile.getFileName()))); } else { // drops stale directory commands.add(new DeleteCommand(pluginsPath.resolve(rootEntryName(sourceFile)))); commands.add(new UnzipCommand(sourceFile, pluginsPath)); } if (deleteSourceFile) { commands.add(new DeleteCommand(sourceFile)); } addActionCommands(commands); PluginStateManager.fireState(descriptor, true); } private static @Nullable Path installWithoutRestart(@NotNull Path sourceFile, @NotNull IdeaPluginDescriptorImpl descriptor, @Nullable JComponent parent) { Path result; try { Task.WithResult<Path, IOException> task = new Task.WithResult<>(null, parent, IdeBundle .message("progress.title.installing.plugin", descriptor.getName()), false) { @Override protected Path compute(@NotNull ProgressIndicator indicator) throws IOException { return unpackPlugin(sourceFile, getPluginsPath()); } }; result = ProgressManager.getInstance().run(task); } catch (Throwable throwable) { LOG.warn("Plugin " + descriptor + " failed to install without restart. " + throwable.getMessage(), throwable); result = null; } PluginStateManager.fireState(descriptor, true); return result; } public static @NotNull Path unpackPlugin(@NotNull Path sourceFile, @NotNull Path targetPath) throws IOException { Path target; if (sourceFile.getFileName().toString().endsWith(".jar")) { target = targetPath.resolve(sourceFile.getFileName()); FileUtilRt.copy(sourceFile.toFile(), target.toFile()); } else { target = targetPath.resolve(rootEntryName(sourceFile)); FileUtilRt.delete(target.toFile()); new Decompressor.Zip(sourceFile).extract(targetPath); } return target; } public static String rootEntryName(@NotNull Path zip) throws IOException { try (ZipFile zipFile = new ZipFile(zip.toFile())) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); // we do not necessarily get a separate entry for the subdirectory when the file // in the ZIP archive is placed in a subdirectory, so we need to check if the slash // is found anywhere in the path String name = zipEntry.getName(); int i = name.indexOf('/'); if (i > 0) return name.substring(0, i); } } throw new IOException("Corrupted archive (no file entries): " + zip); } public static void addStateListener(@NotNull PluginStateListener listener) { PluginStateManager.addStateListener(listener); } static boolean installFromDisk(@NotNull File file, @Nullable Project project, @Nullable JComponent parent) { return installFromDisk(new InstalledPluginsTableModel(project), PluginEnabler.HEADLESS, file, parent, PluginInstaller::installPluginFromCallbackData); } static boolean installFromDisk(@NotNull InstalledPluginsTableModel model, @NotNull PluginEnabler pluginEnabler, @NotNull File file, @Nullable JComponent parent, @NotNull Consumer<? super PluginInstallCallbackData> callback) { try { Path path = file.toPath(); IdeaPluginDescriptorImpl pluginDescriptor = PluginDescriptorLoader.loadDescriptorFromArtifact(path, null); if (pluginDescriptor == null) { MessagesEx.showErrorDialog(parent, IdeBundle.message("dialog.message.fail.to.load.plugin.descriptor.from.file", file.getName()), CommonBundle.getErrorTitle()); return false; } if (!PluginManagerMain.checkThirdPartyPluginsAllowed(List.of(pluginDescriptor))) { return false; } if (!PluginManagerFilters.getInstance().allowInstallingPlugin(pluginDescriptor)) { String message = IdeBundle.message("dialog.message.plugin.is.not.allowed", pluginDescriptor.getName()); MessagesEx.showWarningDialog(parent, message, IdeBundle.message("dialog.title.install.plugin")); return false; } InstalledPluginsState ourState = InstalledPluginsState.getInstance(); if (ourState.wasInstalled(pluginDescriptor.getPluginId())) { String message = IdeBundle.message("dialog.message.plugin.was.already.installed", pluginDescriptor.getName()); MessagesEx.showWarningDialog(parent, message, IdeBundle.message("dialog.title.install.plugin")); return false; } PluginLoadingError error = PluginManagerCore.checkBuildNumberCompatibility(pluginDescriptor, PluginManagerCore.getBuildNumber()); if (error != null) { MessagesEx.showErrorDialog(parent, error.getDetailedMessage(), CommonBundle.getErrorTitle()); return false; } if (PluginManagerCore.isBrokenPlugin(pluginDescriptor)) { String message = CoreBundle.message("plugin.loading.error.long.marked.as.broken", pluginDescriptor.getName(), pluginDescriptor.getVersion()); MessagesEx.showErrorDialog(parent, message, CommonBundle.getErrorTitle()); return false; } IdeaPluginDescriptor installedPlugin = PluginManagerCore.getPlugin(pluginDescriptor.getPluginId()); if (installedPlugin != null && ApplicationInfoEx.getInstanceEx().isEssentialPlugin(installedPlugin.getPluginId())) { String message = IdeBundle .message("dialog.message.plugin.core.part", pluginDescriptor.getName(), ApplicationNamesInfo.getInstance().getFullProductName()); MessagesEx.showErrorDialog(parent, message, CommonBundle.getErrorTitle()); return false; } PluginManagerUsageCollector.pluginInstallationStarted(pluginDescriptor, InstallationSourceEnum.FROM_DISK, installedPlugin != null ? installedPlugin.getVersion() : null); if (!PluginSignatureChecker.verifyIfRequired(pluginDescriptor, file, false, true)) { return false; } Task.WithResult<Pair<PluginInstallOperation, ? extends IdeaPluginDescriptor>, RuntimeException> task = new Task.WithResult<>(null, parent, IdeBundle.message("progress.title.checking.plugin.dependencies"), true) { @Override protected @NotNull Pair<PluginInstallOperation, ? extends IdeaPluginDescriptor> compute(@NotNull ProgressIndicator indicator) { PluginInstallOperation operation = new PluginInstallOperation(List.of(), CustomPluginRepositoryService.getInstance() .getCustomRepositoryPlugins(), pluginEnabler, indicator); operation.setAllowInstallWithoutRestart(true); return operation.checkMissingDependencies(pluginDescriptor, null) ? Pair.create(operation, operation.checkDependenciesAndReplacements(pluginDescriptor)) : Pair.empty(); } }; Pair<PluginInstallOperation, ? extends IdeaPluginDescriptor> pair = ProgressManager.getInstance().run(task); PluginInstallOperation operation = pair.getFirst(); if (operation == null) { return false; } Path oldFile = installedPlugin != null && !installedPlugin.isBundled() ? installedPlugin.getPluginPath() : null; boolean isRestartRequired = oldFile != null || !DynamicPlugins.allowLoadUnloadWithoutRestart(pluginDescriptor) || operation.isRestartRequired(); if (isRestartRequired) { installAfterRestart(path, false, oldFile, pluginDescriptor); } ourState.onPluginInstall(pluginDescriptor, installedPlugin != null, isRestartRequired); IdeaPluginDescriptor toDisable = pair.getSecond(); if (toDisable != null) { // TODO[yole] unload and check for restart pluginEnabler.disablePlugins(Set.of(toDisable)); } Set<PluginInstallCallbackData> installedDependencies = operation.getInstalledDependentPlugins(); List<IdeaPluginDescriptor> installedPlugins = new ArrayList<>(); installedPlugins.add(pluginDescriptor); for (PluginInstallCallbackData plugin : installedDependencies) { installedPlugins.add(plugin.getPluginDescriptor()); } Set<String> notInstalled = findNotInstalledPluginDependencies(pluginDescriptor.getDependencies(), model, ContainerUtil.map2Set(installedPlugins, PluginDescriptor::getPluginId)); if (!notInstalled.isEmpty()) { String message = IdeBundle.message("dialog.message.plugin.depends.on.unknown.plugin", pluginDescriptor.getName(), notInstalled.size(), StringUtil.join(notInstalled, ", ")); MessagesEx.showWarningDialog(parent, message, IdeBundle.message("dialog.title.install.plugin")); } PluginManagerMain.suggestToEnableInstalledDependantPlugins(pluginEnabler, installedPlugins); callback.accept(new PluginInstallCallbackData(path, pluginDescriptor, isRestartRequired)); for (PluginInstallCallbackData callbackData : installedDependencies) { if (!callbackData.getPluginDescriptor().getPluginId().equals(pluginDescriptor.getPluginId())) { callback.accept(callbackData); } } if (path.toString().endsWith(".zip") && Registry.is("ide.plugins.keep.archive")) { File tempFile = MarketplacePluginDownloadService.getPluginTempFile(); FileUtil.copy(file, tempFile); MarketplacePluginDownloadService.renameFileToZipRoot(tempFile); } return true; } catch (IOException ex) { MessagesEx.showErrorDialog(parent, ex.getMessage(), CommonBundle.getErrorTitle()); return false; } } public static boolean installAndLoadDynamicPlugin(@NotNull Path file, @NotNull IdeaPluginDescriptorImpl descriptor) { return installAndLoadDynamicPlugin(file, null, descriptor); } /** * @return true if plugin was successfully installed without restart, false if restart is required */ public static boolean installAndLoadDynamicPlugin(@NotNull Path file, @Nullable JComponent parent, @NotNull IdeaPluginDescriptorImpl descriptor) { Path targetFile = installWithoutRestart(file, descriptor, parent); if (targetFile == null) { return false; } IdeaPluginDescriptorImpl targetDescriptor = PluginDescriptorLoader.loadDescriptor(targetFile, DisabledPluginsState.disabledPlugins(), false, PluginXmlPathResolver.DEFAULT_PATH_RESOLVER); if (targetDescriptor == null) { return false; } return DynamicPlugins.INSTANCE.loadPlugin(targetDescriptor); } private static @NotNull Set<String> findNotInstalledPluginDependencies(@NotNull List<? extends IdeaPluginDependency> dependencies, @NotNull InstalledPluginsTableModel model, @NotNull Set<PluginId> installedDependencies) { Set<String> notInstalled = new HashSet<>(); for (IdeaPluginDependency dependency : dependencies) { if (dependency.isOptional()) continue; PluginId pluginId = dependency.getPluginId(); if (installedDependencies.contains(pluginId) || model.isLoaded(pluginId) || PluginManagerCore.isModuleDependency(pluginId)) { continue; } notInstalled.add(pluginId.getIdString()); } return notInstalled; } static void chooseAndInstall(@Nullable Project project, @Nullable JComponent parent, @NotNull BiConsumer<? super File, ? super JComponent> callback) { FileChooserDescriptor descriptor = new FileChooserDescriptor(false, false, true, true, false, false) { { setTitle(IdeBundle.message("chooser.title.plugin.file")); setDescription(IdeBundle.message("chooser.description.jar.and.zip.archives.are.accepted")); } @Override public boolean isFileSelectable(@Nullable VirtualFile file) { if (file == null) { return false; } final String extension = file.getExtension(); return Comparing.strEqual(extension, "jar") || Comparing.strEqual(extension, "zip"); } }; String oldPath = PropertiesComponent.getInstance().getValue(PLUGINS_PRESELECTION_PATH); VirtualFile toSelect = oldPath != null ? VfsUtil.findFileByIoFile(new File(FileUtilRt.toSystemDependentName(oldPath)), false) : null; FileChooser.chooseFile(descriptor, project, parent, toSelect, virtualFile -> { File file = VfsUtilCore.virtualToIoFile(virtualFile); PropertiesComponent.getInstance().setValue(PLUGINS_PRESELECTION_PATH, FileUtilRt.toSystemIndependentName(file.getParent())); callback.accept(file, parent); }); } private static @NotNull Path getPluginsPath() { return Paths.get(PathManager.getPluginsPath()); } private static void installPluginFromCallbackData(@NotNull PluginInstallCallbackData callbackData) { IdeaPluginDescriptorImpl descriptor = callbackData.getPluginDescriptor(); if (!callbackData.getRestartNeeded() && installAndLoadDynamicPlugin(callbackData.getFile(), descriptor)) { return; } PluginManagerConfigurable.shutdownOrRestartAppAfterInstall(PluginManagerConfigurable.getUpdatesDialogTitle(), action -> IdeBundle.message("plugin.installed.ide.restart.required.message", descriptor.getName(), action, ApplicationNamesInfo.getInstance() .getFullProductName())); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.action.bulk; import org.apache.lucene.util.Constants; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.create.TransportCreateIndexAction; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.AutoCreateIndex; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.metadata.MetaDataCreateIndexService; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.AtomicArray; import org.elasticsearch.tasks.Task; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.transport.CapturingTransport; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.function.LongSupplier; import static org.elasticsearch.cluster.service.ClusterServiceUtils.createClusterService; import static org.elasticsearch.test.StreamsUtils.copyToStringFromClasspath; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.Matchers.greaterThanOrEqualTo; public class TransportBulkActionTookTests extends ESTestCase { static private ThreadPool threadPool; private ClusterService clusterService; @BeforeClass public static void beforeClass() { threadPool = new ThreadPool("TransportBulkActionTookTests"); } @AfterClass public static void afterClass() { ThreadPool.terminate(threadPool, 30, TimeUnit.SECONDS); threadPool = null; } @Before public void setUp() throws Exception { super.setUp(); clusterService = createClusterService(threadPool); } @After public void tearDown() throws Exception { super.tearDown(); clusterService.close(); } private TransportBulkAction createAction(boolean controlled, AtomicLong expected) { CapturingTransport capturingTransport = new CapturingTransport(); TransportService transportService = new TransportService(capturingTransport, threadPool, clusterService.state().getClusterName()); transportService.start(); transportService.acceptIncomingRequests(); IndexNameExpressionResolver resolver = new Resolver(Settings.EMPTY); ActionFilters actionFilters = new ActionFilters(new HashSet<>()); TransportCreateIndexAction createIndexAction = new TransportCreateIndexAction( Settings.EMPTY, transportService, clusterService, threadPool, null, actionFilters, resolver); if (controlled) { return new TestTransportBulkAction( Settings.EMPTY, threadPool, transportService, clusterService, null, createIndexAction, actionFilters, resolver, null, expected::get) { @Override public void executeBulk(BulkRequest bulkRequest, ActionListener<BulkResponse> listener) { expected.set(1000000); super.executeBulk(bulkRequest, listener); } @Override void executeBulk( Task task, BulkRequest bulkRequest, long startTimeNanos, ActionListener<BulkResponse> listener, AtomicArray<BulkItemResponse> responses) { expected.set(1000000); super.executeBulk(task, bulkRequest, startTimeNanos, listener, responses); } }; } else { return new TestTransportBulkAction( Settings.EMPTY, threadPool, transportService, clusterService, null, createIndexAction, actionFilters, resolver, null, System::nanoTime) { @Override public void executeBulk(BulkRequest bulkRequest, ActionListener<BulkResponse> listener) { long elapsed = spinForAtLeastOneMillisecond(); expected.set(elapsed); super.executeBulk(bulkRequest, listener); } @Override void executeBulk( Task task, BulkRequest bulkRequest, long startTimeNanos, ActionListener<BulkResponse> listener, AtomicArray<BulkItemResponse> responses) { long elapsed = spinForAtLeastOneMillisecond(); expected.set(elapsed); super.executeBulk(task, bulkRequest, startTimeNanos, listener, responses); } }; } } // test unit conversion with a controlled clock public void testTookWithControlledClock() throws Exception { runTestTook(true); } // test took advances with System#nanoTime public void testTookWithRealClock() throws Exception { runTestTook(false); } private void runTestTook(boolean controlled) throws Exception { String bulkAction = copyToStringFromClasspath("/org/elasticsearch/action/bulk/simple-bulk.json"); // translate Windows line endings (\r\n) to standard ones (\n) if (Constants.WINDOWS) { bulkAction = Strings.replace(bulkAction, "\r\n", "\n"); } BulkRequest bulkRequest = new BulkRequest(); bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, null); AtomicLong expected = new AtomicLong(); TransportBulkAction action = createAction(controlled, expected); action.doExecute(null, bulkRequest, new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse bulkItemResponses) { if (controlled) { assertThat( bulkItemResponses.getTook().getMillis(), equalTo(TimeUnit.MILLISECONDS.convert(expected.get(), TimeUnit.NANOSECONDS))); } else { assertThat( bulkItemResponses.getTook().getMillis(), greaterThanOrEqualTo(TimeUnit.MILLISECONDS.convert(expected.get(), TimeUnit.NANOSECONDS))); } } @Override public void onFailure(Throwable e) { } }); } static class Resolver extends IndexNameExpressionResolver { public Resolver(Settings settings) { super(settings); } @Override public String[] concreteIndexNames(ClusterState state, IndicesRequest request) { return request.indices(); } } static class TestTransportBulkAction extends TransportBulkAction { public TestTransportBulkAction( Settings settings, ThreadPool threadPool, TransportService transportService, ClusterService clusterService, TransportShardBulkAction shardBulkAction, TransportCreateIndexAction createIndexAction, ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver, AutoCreateIndex autoCreateIndex, LongSupplier relativeTimeProvider) { super( settings, threadPool, transportService, clusterService, shardBulkAction, createIndexAction, actionFilters, indexNameExpressionResolver, autoCreateIndex, relativeTimeProvider); } @Override boolean needToCheck() { return randomBoolean(); } @Override boolean shouldAutoCreate(String index, ClusterState state) { return randomBoolean(); } } static class TestTransportCreateIndexAction extends TransportCreateIndexAction { public TestTransportCreateIndexAction( Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool, MetaDataCreateIndexService createIndexService, ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver) { super(settings, transportService, clusterService, threadPool, createIndexService, actionFilters, indexNameExpressionResolver); } @Override protected void doExecute(Task task, CreateIndexRequest request, ActionListener<CreateIndexResponse> listener) { listener.onResponse(newResponse()); } } }
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.jbpm.services.task.audit.service; import static org.jbpm.persistence.util.PersistenceUtil.cleanUp; import static org.jbpm.persistence.util.PersistenceUtil.setupWithPoolingDataSource; import static org.junit.Assert.assertEquals; import static org.kie.api.runtime.EnvironmentName.ENTITY_MANAGER_FACTORY; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Random; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.jbpm.process.audit.ProcessInstanceLog; import org.jbpm.process.audit.strategy.StandaloneJtaStrategy; import org.jbpm.process.instance.impl.util.LoggingPrintStream; import org.jbpm.services.task.HumanTaskServiceFactory; import org.jbpm.services.task.audit.JPATaskLifeCycleEventListener; import org.jbpm.services.task.lifecycle.listeners.BAMTaskEventListener; import org.jbpm.services.task.utils.TaskFluent; import org.junit.After; //import org.jbpm.process.instance.impl.util.LoggingPrintStream; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.kie.api.task.model.Task; import org.kie.internal.task.api.AuditTask; import org.kie.internal.task.api.InternalTaskService; import org.kie.internal.task.query.AuditTaskDeleteBuilder; import org.kie.internal.task.query.AuditTaskQueryBuilder; public class AuditTaskDeleteTest extends TaskJPAAuditService { private static HashMap<String, Object> context; private static EntityManagerFactory emf; private Task [] taskTestData; @BeforeClass public static void configure() { LoggingPrintStream.interceptSysOutSysErr(); } @AfterClass public static void reset() { LoggingPrintStream.resetInterceptSysOutSysErr(); } @Before public void setUp() throws Exception { context = setupWithPoolingDataSource("org.jbpm.services.task", "jdbc/jbpm-ds"); emf = (EntityManagerFactory) context.get(ENTITY_MANAGER_FACTORY); this.persistenceStrategy = new StandaloneJtaStrategy(emf); produceTaskInstances(); } @After public void cleanup() { cleanUp(context); } private static Random random = new Random(); private Calendar randomCal() { Calendar cal = GregorianCalendar.getInstance(); cal.roll(Calendar.DAY_OF_YEAR, -1*random.nextInt(10*365)); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR_OF_DAY, 0); return cal; } private void produceTaskInstances() { InternalTaskService taskService = (InternalTaskService) HumanTaskServiceFactory.newTaskServiceConfigurator() .entityManagerFactory(emf) .listener(new JPATaskLifeCycleEventListener(true)) .listener(new BAMTaskEventListener(true)) .getTaskService(); Calendar cal = randomCal(); String processId = "process"; taskTestData = new Task[10]; List<ProcessInstanceLog> pLogs = new ArrayList<>(); for (int i = 0; i < 10; i++) { cal.add(Calendar.HOUR_OF_DAY, 1); Task task = new TaskFluent().setName("This is my task name") .addPotentialGroup("Knights Templer") .setAdminUser("Administrator") .setProcessId(processId + i) .setProcessInstanceId(i) .setCreatedOn(cal.getTime()) .getTask(); taskService.addTask(task, new HashMap<String, Object>()); taskTestData[i] = task; ProcessInstanceLog plog = buildCompletedProcessInstance(i); pLogs.add(plog); } StandaloneJtaStrategy jtaHelper = new StandaloneJtaStrategy(emf); EntityManager em = jtaHelper.getEntityManager(); Object tx = jtaHelper.joinTransaction(em); pLogs.forEach(pl -> { em.persist(pl); }); jtaHelper.leaveTransaction(em, tx); } @Test public void testDeleteAuditTaskInfoLogByProcessId() { int p = 0; String processId = taskTestData[p++].getTaskData().getProcessId(); String processId2 = taskTestData[p++].getTaskData().getProcessId(); AuditTaskDeleteBuilder updateBuilder = this.auditTaskDelete().processId(processId, processId2); int result = updateBuilder.build().execute(); assertEquals(2, result); } @Test public void testDeleteAuditTaskInfoLogByDate() { int p = 0; Date endDate = taskTestData[p++].getTaskData().getCreatedOn(); AuditTaskDeleteBuilder updateBuilder = this.auditTaskDelete().date(endDate); int result = updateBuilder.build().execute(); assertEquals(1, result); } @Test public void testDeleteAuditTaskInfoLogByProcessIdAndDate() { int p = 0; String processId = taskTestData[p].getTaskData().getProcessId(); Date endDate = taskTestData[p].getTaskData().getCreatedOn(); AuditTaskDeleteBuilder updateBuilder = this.auditTaskDelete().date(endDate).processId(processId); int result = updateBuilder.build().execute(); assertEquals(1, result); } @Test public void testDeleteAuditTaskInfoLogByProcessIdAndNotMatchingDate() { int p = 0; String processId = taskTestData[p++].getTaskData().getProcessId(); Date endDate = taskTestData[p++].getTaskData().getCreatedOn(); AuditTaskDeleteBuilder updateBuilder = this.auditTaskDelete().date(endDate).processId(processId); int result = updateBuilder.build().execute(); assertEquals(0, result); } @Test public void testDeleteAuditTaskInfoLogByDateRangeEnd() { Date endDate = taskTestData[4].getTaskData().getCreatedOn(); AuditTaskDeleteBuilder updateBuilder = this.auditTaskDelete().dateRangeEnd(endDate); int result = updateBuilder.build().execute(); assertEquals(5, result); } @Test public void testDeleteAuditTaskInfoLogByDateRangeStart() { Date endDate = taskTestData[8].getTaskData().getCreatedOn(); AuditTaskDeleteBuilder updateBuilder = this.auditTaskDelete().dateRangeStart(endDate); int result = updateBuilder.build().execute(); assertEquals(2, result); } @Test public void testDeleteAuditTaskInfoLogByDateRange() { Date startDate = taskTestData[4].getTaskData().getCreatedOn(); Date endDate = taskTestData[8].getTaskData().getCreatedOn(); AuditTaskDeleteBuilder updateBuilder = this.auditTaskDelete().dateRangeStart(startDate).dateRangeEnd(endDate); int result = updateBuilder.build().execute(); assertEquals(5, result); } @Test public void testTaskAuditServiceClear() { AuditTaskQueryBuilder queryBuilder = this.auditTaskQuery(); List<AuditTask> tasks = queryBuilder.taskId(taskTestData[4].getId()).build().getResultList(); assertEquals(1, tasks.size()); queryBuilder.clear(); List<AuditTask> data = this.auditTaskQuery().build().getResultList(); assertEquals(10, data.size()); this.clear(); data = this.auditTaskQuery().build().getResultList(); assertEquals(0, data.size()); } @Test public void testDeleteAuditTaskInfoLogByTimestamp() { List<AuditTask> tasks = this.auditTaskQuery().taskId(taskTestData[4].getId()).build().getResultList(); assertEquals(1, tasks.size()); AuditTaskDeleteBuilder updateBuilder = this.auditTaskDelete().date(tasks.get(0).getCreatedOn()); int result = updateBuilder.build().execute(); assertEquals(1, result); } private ProcessInstanceLog buildCompletedProcessInstance(long processInstanceId) { ProcessInstanceLog pil = new ProcessInstanceLog(processInstanceId, "test"); pil.setDuration(0L); pil.setExternalId("none"); pil.setIdentity("none"); pil.setOutcome(""); pil.setParentProcessInstanceId(-1L); pil.setProcessId("test"); pil.setProcessName("test process"); pil.setProcessVersion("1"); pil.setStatus(2); pil.setStart(null); pil.setEnd(null); return pil; } }
package com.jayway.jsonpath.internal; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.InvalidModificationException; import com.jayway.jsonpath.spi.json.JsonProvider; import java.util.Collection; public abstract class PathRef implements Comparable<PathRef> { public static final PathRef NO_OP = new PathRef(null){ @Override public Object getAccessor() { return null; } @Override public void set(Object newVal, Configuration configuration) {} @Override public void delete(Configuration configuration) {} @Override public void add(Object newVal, Configuration configuration) {} @Override public void put(String key, Object newVal, Configuration configuration) {} }; protected Object parent; private PathRef(Object parent) { this.parent = parent; } abstract Object getAccessor(); public abstract void set(Object newVal, Configuration configuration); public abstract void delete(Configuration configuration); public abstract void add(Object newVal, Configuration configuration); public abstract void put(String key, Object newVal, Configuration configuration); @Override public int compareTo(PathRef o) { return this.getAccessor().toString().compareTo(o.getAccessor().toString()) * -1; } public static PathRef create(Object obj, String property){ return new ObjectPropertyPathRef(obj, property); } public static PathRef create(Object obj, Collection<String> properties){ return new ObjectMultiPropertyPathRef(obj, properties); } public static PathRef create(Object array, int index){ return new ArrayIndexPathRef(array, index); } public static PathRef createRoot(Object root){ return new RootPathRef(root); } private static class RootPathRef extends PathRef { private RootPathRef(Object parent) { super(parent); } @Override Object getAccessor() { return "$"; } @Override public void set(Object newVal, Configuration configuration) { throw new InvalidModificationException("Invalid delete operation"); } @Override public void delete(Configuration configuration) { throw new InvalidModificationException("Invalid delete operation"); } @Override public void add(Object newVal, Configuration configuration) { if(configuration.jsonProvider().isArray(parent)){ configuration.jsonProvider().setProperty(parent, null, newVal); } else { throw new InvalidModificationException("Invalid add operation. $ is not an array"); } } @Override public void put(String key, Object newVal, Configuration configuration) { if(configuration.jsonProvider().isMap(parent)){ configuration.jsonProvider().setProperty(parent, key, newVal); } else { throw new InvalidModificationException("Invalid put operation. $ is not a map"); } } } private static class ArrayIndexPathRef extends PathRef { private int index; private ArrayIndexPathRef(Object parent, int index) { super(parent); this.index = index; } public void set(Object newVal, Configuration configuration){ configuration.jsonProvider().setArrayIndex(parent, index, newVal); } public void delete(Configuration configuration){ configuration.jsonProvider().removeProperty(parent, index); } public void add(Object value, Configuration configuration){ Object target = configuration.jsonProvider().getArrayIndex(parent, index); if(target == JsonProvider.UNDEFINED || target == null){ return; } if(configuration.jsonProvider().isArray(target)){ configuration.jsonProvider().setProperty(target, null, value); } else { throw new InvalidModificationException("Can only add to an array"); } } public void put(String key, Object value, Configuration configuration){ Object target = configuration.jsonProvider().getArrayIndex(parent, index); if(target == JsonProvider.UNDEFINED || target == null){ return; } if(configuration.jsonProvider().isMap(target)){ configuration.jsonProvider().setProperty(target, key, value); } else { throw new InvalidModificationException("Can only add properties to a map"); } } @Override public Object getAccessor() { return index; } } private static class ObjectPropertyPathRef extends PathRef { private String property; private ObjectPropertyPathRef(Object parent, String property) { super(parent); this.property = property; } public void set(Object newVal, Configuration configuration){ configuration.jsonProvider().setProperty(parent, property, newVal); } public void delete(Configuration configuration){ configuration.jsonProvider().removeProperty(parent, property); } public void add(Object value, Configuration configuration){ Object target = configuration.jsonProvider().getMapValue(parent, property); if(target == JsonProvider.UNDEFINED || target == null){ return; } if(configuration.jsonProvider().isArray(target)){ configuration.jsonProvider().setProperty(target, null, value); } else { throw new InvalidModificationException("Can only add to an array"); } } public void put(String key, Object value, Configuration configuration){ Object target = configuration.jsonProvider().getMapValue(parent, property); if(target == JsonProvider.UNDEFINED || target == null){ return; } if(configuration.jsonProvider().isMap(target)){ configuration.jsonProvider().setProperty(target, key, value); } else { throw new InvalidModificationException("Can only add properties to a map"); } } @Override public Object getAccessor() { return property; } } private static class ObjectMultiPropertyPathRef extends PathRef { private Collection<String> properties; private ObjectMultiPropertyPathRef(Object parent, Collection<String> properties) { super(parent); this.properties = properties; } public void set(Object newVal, Configuration configuration){ for (String property : properties) { configuration.jsonProvider().setProperty(parent, property, newVal); } } public void delete(Configuration configuration){ for (String property : properties) { configuration.jsonProvider().removeProperty(parent, property); } } @Override public void add(Object newVal, Configuration configuration) { throw new InvalidModificationException("Add can not be performed to multiple properties"); } @Override public void put(String key, Object newVal, Configuration configuration) { throw new InvalidModificationException("Add can not be performed to multiple properties"); } @Override public Object getAccessor() { return Utils.join("&&", properties); } } }
package au.com.scds.chats.datamigration.model; import java.io.Serializable; import javax.persistence.*; import java.util.Date; import java.sql.Timestamp; import java.math.BigInteger; /** * The persistent class for the groups database table. * */ @Entity @Table(name="groups") public class Group implements Serializable { private static final long serialVersionUID = 1L; @Id private String id; @Column(name="administrative_role_id") private BigInteger administrativeRoleId; @Column(name="created_by") private BigInteger createdBy; @Column(name="created_dttm") private Timestamp createdDttm; @Column(name="createdby_user_id") private BigInteger createdbyUserId; private Timestamp createdDTTM; @Temporal(TemporalType.TIMESTAMP) private Date deletedDTTM; private String description; private String group; @Column(name="heir_left") private int heirLeft; @Column(name="heir_level") private int heirLevel; @Column(name="heir_right") private int heirRight; @Column(name="lastmodifiedby_user_id") private BigInteger lastmodifiedbyUserId; @Temporal(TemporalType.TIMESTAMP) private Date lastmodifiedDTTM; @Column(name="parent_role_id") private BigInteger parentRoleId; @Column(name="project_id") private BigInteger projectId; private int region; public Group() { } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public BigInteger getAdministrativeRoleId() { return this.administrativeRoleId; } public void setAdministrativeRoleId(BigInteger administrativeRoleId) { this.administrativeRoleId = administrativeRoleId; } public BigInteger getCreatedBy() { return this.createdBy; } public void setCreatedBy(BigInteger createdBy) { this.createdBy = createdBy; } public Timestamp getCreatedDttm() { return this.createdDttm; } public void setCreatedDttm(Timestamp createdDttm) { this.createdDttm = createdDttm; } public BigInteger getCreatedbyUserId() { return this.createdbyUserId; } public void setCreatedbyUserId(BigInteger createdbyUserId) { this.createdbyUserId = createdbyUserId; } public Timestamp getCreatedDTTM() { return this.createdDTTM; } public void setCreatedDTTM(Timestamp createdDTTM) { this.createdDTTM = createdDTTM; } public Date getDeletedDTTM() { return this.deletedDTTM; } public void setDeletedDTTM(Date deletedDTTM) { this.deletedDTTM = deletedDTTM; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getGroup() { return this.group; } public void setGroup(String group) { this.group = group; } public int getHeirLeft() { return this.heirLeft; } public void setHeirLeft(int heirLeft) { this.heirLeft = heirLeft; } public int getHeirLevel() { return this.heirLevel; } public void setHeirLevel(int heirLevel) { this.heirLevel = heirLevel; } public int getHeirRight() { return this.heirRight; } public void setHeirRight(int heirRight) { this.heirRight = heirRight; } public BigInteger getLastmodifiedbyUserId() { return this.lastmodifiedbyUserId; } public void setLastmodifiedbyUserId(BigInteger lastmodifiedbyUserId) { this.lastmodifiedbyUserId = lastmodifiedbyUserId; } public Date getLastmodifiedDTTM() { return this.lastmodifiedDTTM; } public void setLastmodifiedDTTM(Date lastmodifiedDTTM) { this.lastmodifiedDTTM = lastmodifiedDTTM; } public BigInteger getParentRoleId() { return this.parentRoleId; } public void setParentRoleId(BigInteger parentRoleId) { this.parentRoleId = parentRoleId; } public BigInteger getProjectId() { return this.projectId; } public void setProjectId(BigInteger projectId) { this.projectId = projectId; } public int getRegion() { return this.region; } public void setRegion(int region) { this.region = region; } }
package com.xfggh.blog.entity; import java.util.ArrayList; import java.util.List; public class ImoocContentExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public ImoocContentExample() { oredCriteria = new ArrayList<>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Long> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Long> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
/* * 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 javax.el; import org.junit.Assert; import org.junit.Test; public class TestBeanNameELResolver { private static final String BEAN01_NAME = "bean01"; private static final TesterBean BEAN01 = new TesterBean(BEAN01_NAME); private static final String BEAN02_NAME = "bean02"; private static final TesterBean BEAN02 = new TesterBean(BEAN02_NAME); private static final String BEAN99_NAME = "bean99"; private static final TesterBean BEAN99 = new TesterBean(BEAN99_NAME); /** * Creates the resolver that is used for the test. All the tests use a * resolver with the same configuration. */ private BeanNameELResolver createBeanNameELResolver() { return createBeanNameELResolver(true); } private BeanNameELResolver createBeanNameELResolver(boolean allowCreate) { TesterBeanNameResolver beanNameResolver = new TesterBeanNameResolver(); beanNameResolver.setBeanValue(BEAN01_NAME, BEAN01); beanNameResolver.setBeanValue(BEAN02_NAME, BEAN02); beanNameResolver.setAllowCreate(allowCreate); BeanNameELResolver beanNameELResolver = new BeanNameELResolver(beanNameResolver); return beanNameELResolver; } /** * Tests that a null context results in an NPE as per EL Javadoc. */ @Test(expected=NullPointerException.class) public void testGetValue01() { BeanNameELResolver resolver = createBeanNameELResolver(); resolver.getValue(null, new Object(), new Object()); } /** * Tests that a valid bean is resolved. */ @Test public void testGetValue02() { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.getValue(context, null, BEAN01_NAME); Assert.assertEquals(BEAN01, result); Assert.assertTrue(context.isPropertyResolved()); } /** * Tests that a valid bean is not resolved if base is non-null. */ @Test public void testGetValue03() { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.getValue(context, new Object(), BEAN01_NAME); Assert.assertNull(result); Assert.assertFalse(context.isPropertyResolved()); } /** * Tests that a valid bean is not resolved if property is not a String even * if it can be coerced to a valid bean name. */ @Test public void testGetValue04() { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object property = new Object() { @Override public String toString() { return BEAN01_NAME; } }; Object result = resolver.getValue(context, null, property); Assert.assertNull(result); Assert.assertFalse(context.isPropertyResolved()); } /** * Beans that don't exist shouldn't return anything */ @Test public void testGetValue05() { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.getValue(context, null, BEAN99_NAME); Assert.assertNull(result); Assert.assertFalse(context.isPropertyResolved()); } /** * Exception during resolution should be wrapped and re-thrown. */ @Test public void testGetValue06() { doThrowableTest(TesterBeanNameResolver.EXCEPTION_TRIGGER_NAME, MethodUnderTest.GET_VALUE); } /** * Throwable during resolution should be wrapped and re-thrown. */ @Test public void testGetValue07() { doThrowableTest(TesterBeanNameResolver.THROWABLE_TRIGGER_NAME, MethodUnderTest.GET_VALUE); } /** * Tests that a null context results in an NPE as per EL Javadoc. */ @Test(expected=NullPointerException.class) public void testSetValue01() { BeanNameELResolver resolver = createBeanNameELResolver(); resolver.setValue(null, new Object(), new Object(), new Object()); } /** * Test replace with create enabled. */ @Test public void testSetValue02() { doSetValueCreateReplaceTest(true, BEAN01_NAME); } /** * Test replace with create disabled. */ @Test public void testSetValue03() { doSetValueCreateReplaceTest(false, BEAN01_NAME); } /** * Test create with create enabled. */ @Test public void testSetValue04() { doSetValueCreateReplaceTest(true, BEAN99_NAME); } /** * Test create with create disabled. */ @Test public void testSetValue05() { doSetValueCreateReplaceTest(false, BEAN99_NAME); } /** * Test replacing a read-only bean with create enabled. */ @Test(expected=PropertyNotWritableException.class) public void testSetValue06() { doSetValueCreateReplaceTest(true, TesterBeanNameResolver.READ_ONLY_NAME); } /** * Test replacing a read-only bean with create disable. */ @Test(expected=PropertyNotWritableException.class) public void testSetValue07() { doSetValueCreateReplaceTest(false, TesterBeanNameResolver.READ_ONLY_NAME); } /** * Exception during resolution should be wrapped and re-thrown. */ @Test public void testSetValue08() { doThrowableTest(TesterBeanNameResolver.EXCEPTION_TRIGGER_NAME, MethodUnderTest.SET_VALUE); } /** * Throwable during resolution should be wrapped and re-thrown. */ @Test public void testSetValue09() { doThrowableTest(TesterBeanNameResolver.THROWABLE_TRIGGER_NAME, MethodUnderTest.SET_VALUE); } /** * Tests that a null context results in an NPE as per EL Javadoc. */ @Test(expected=NullPointerException.class) public void testGetType01() { BeanNameELResolver resolver = createBeanNameELResolver(); resolver.getType(null, new Object(), new Object()); } /** * Tests that a valid bean is resolved. */ @Test public void testGetType02() { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Class<?> result = resolver.getType(context, null, BEAN01_NAME); Assert.assertEquals(BEAN01.getClass(), result); Assert.assertTrue(context.isPropertyResolved()); } /** * Tests that a valid bean is not resolved if base is non-null. */ @Test public void testGetType03() { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Class<?> result = resolver.getType(context, new Object(), BEAN01_NAME); Assert.assertNull(result); Assert.assertFalse(context.isPropertyResolved()); } /** * Tests that a valid bean is not resolved if property is not a String even * if it can be coerced to a valid bean name. */ @Test public void testGetType04() { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object property = new Object() { @Override public String toString() { return BEAN01_NAME; } }; Class<?> result = resolver.getType(context, null, property); Assert.assertNull(result); Assert.assertFalse(context.isPropertyResolved()); } /** * Beans that don't exist shouldn't return anything */ @Test public void testGetType05() { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Class<?> result = resolver.getType(context, null, BEAN99_NAME); Assert.assertNull(result); Assert.assertFalse(context.isPropertyResolved()); } /** * Exception during resolution should be wrapped and re-thrown. */ @Test public void testGetType06() { doThrowableTest(TesterBeanNameResolver.EXCEPTION_TRIGGER_NAME, MethodUnderTest.GET_TYPE); } /** * Throwable during resolution should be wrapped and re-thrown. */ @Test public void testGetType07() { doThrowableTest(TesterBeanNameResolver.THROWABLE_TRIGGER_NAME, MethodUnderTest.GET_TYPE); } /** * Tests that a null context results in an NPE as per EL Javadoc. */ @Test(expected=NullPointerException.class) public void testIsReadOnly01() { BeanNameELResolver resolver = createBeanNameELResolver(); resolver.isReadOnly(null, new Object(), new Object()); } /** * Tests that a writable bean is reported as writable. */ @Test public void testIsReadOnly02() { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); boolean result = resolver.isReadOnly(context, null, BEAN01_NAME); Assert.assertFalse(result); Assert.assertTrue(context.isPropertyResolved()); } /** * Tests that a read-only bean is reported as not writable. */ @Test public void testIsReadOnly03() { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); boolean result = resolver.isReadOnly(context, null, TesterBeanNameResolver.READ_ONLY_NAME); Assert.assertTrue(result); Assert.assertTrue(context.isPropertyResolved()); } /** * Tests that a valid bean is not resolved if base is non-null. */ @Test public void testIsReadOnly04() { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.isReadOnly(context, new Object(), BEAN01_NAME); Assert.assertFalse(context.isPropertyResolved()); } /** * Tests that a valid bean is not resolved if property is not a String even * if it can be coerced to a valid bean name. */ @Test public void testIsReadOnly05() { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object property = new Object() { @Override public String toString() { return BEAN01_NAME; } }; resolver.isReadOnly(context, null, property); Assert.assertFalse(context.isPropertyResolved()); } /** * Beans that don't exist should not resolve */ @Test public void testIsReadOnly06() { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.isReadOnly(context, null, BEAN99_NAME); Assert.assertFalse(context.isPropertyResolved()); } /** * Exception during resolution should be wrapped and re-thrown. */ @Test public void testIsReadOnly07() { doThrowableTest(TesterBeanNameResolver.EXCEPTION_TRIGGER_NAME, MethodUnderTest.IS_READ_ONLY); } /** * Throwable during resolution should be wrapped and re-thrown. */ @Test public void testIsReadOnly08() { doThrowableTest(TesterBeanNameResolver.THROWABLE_TRIGGER_NAME, MethodUnderTest.IS_READ_ONLY); } /** * Confirm it returns null for 'valid' input. */ public void testGetFeatureDescriptors01() { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.getFeatureDescriptors(context, null); Assert.assertNull(result); Assert.assertFalse(context.isPropertyResolved()); } /** * Confirm it returns null for invalid input. */ public void testGetFeatureDescriptors02() { BeanNameELResolver resolver = createBeanNameELResolver(); Object result = resolver.getFeatureDescriptors(null, new Object()); Assert.assertNull(result); } /** * Confirm it returns String.class for 'valid' input. */ public void testGetCommonPropertyType01() { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.getCommonPropertyType(context, null); Assert.assertNull(result); Assert.assertFalse(context.isPropertyResolved()); } /** * Confirm it returns String.class for invalid input. */ public void testGetCommonPropertyType02() { BeanNameELResolver resolver = createBeanNameELResolver(); Object result = resolver.getCommonPropertyType(null, new Object()); Assert.assertNull(result); } private void doThrowableTest(String trigger, MethodUnderTest method) { BeanNameELResolver resolver = createBeanNameELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); ELException elException = null; try { switch (method) { case GET_VALUE: { resolver.getValue(context, null, trigger); break; } case SET_VALUE: { resolver.setValue(context, null, trigger, new Object()); break; } case GET_TYPE: { resolver.getType(context, null, trigger); break; } case IS_READ_ONLY: { resolver.isReadOnly(context, null, trigger); break; } default: { // Should never happen Assert.fail("Missing case for method"); } } } catch (ELException e) { elException = e; } Assert.assertFalse(context.isPropertyResolved()); Assert.assertNotNull(elException); Throwable cause = elException.getCause(); Assert.assertNotNull(cause); } /** * Tests adding/replacing beans beans */ private void doSetValueCreateReplaceTest(boolean canCreate, String beanName) { BeanNameELResolver resolver = createBeanNameELResolver(canCreate); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); // Get bean one to be sure it has been replaced when testing replace Object bean = resolver.getValue(context, null, BEAN01_NAME); Assert.assertTrue(context.isPropertyResolved()); Assert.assertEquals(BEAN01, bean); // Reset context context.setPropertyResolved(false); // Replace BEAN01 resolver.setValue(context, null, beanName, BEAN99); if (canCreate || BEAN01_NAME.equals(beanName)) { Assert.assertTrue(context.isPropertyResolved()); // Obtain BEAN01 again context.setPropertyResolved(false); bean = resolver.getValue(context, null, beanName); Assert.assertTrue(context.isPropertyResolved()); Assert.assertEquals(BEAN99, bean); } else { Assert.assertFalse(context.isPropertyResolved()); // Obtain BEAN01 again context.setPropertyResolved(false); bean = resolver.getValue(context, null, BEAN01_NAME); Assert.assertTrue(context.isPropertyResolved()); Assert.assertEquals(BEAN01, bean); } } private static enum MethodUnderTest { GET_VALUE, SET_VALUE, GET_TYPE, IS_READ_ONLY } }
/* The MIT License Copyright (c) 2010-2021 Paul R. Holser, Jr. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.pholser.junit.quickcheck; import com.pholser.junit.quickcheck.runner.JUnitQuickcheck; import org.junit.Test; import org.junit.runner.RunWith; import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import static java.util.Arrays.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import static org.junit.Assume.*; import static org.junit.experimental.results.PrintableResult.*; import static org.junit.experimental.results.ResultMatchers.*; public class MapPropertyParameterTypesTest { @Test public void huhToHuh() { assertThat(testResult(MapOfHuhToHuh.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class MapOfHuhToHuh { @Property(trials = 20) public void shouldHold(Map<?, ?> items) { } } @Test public void huhToUpperBound() { assertThat(testResult(MapOfHuhToUpperBound.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class MapOfHuhToUpperBound { @Property(trials = 20) public void shouldHold( Map<?, ? extends Short> items) { for (Short each : items.values()) { // testing type cast } } } @Test public void huhToLowerBound() { assertThat(testResult(MapOfHuhToLowerBound.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class MapOfHuhToLowerBound { @Property(trials = 20) public void shouldHold( Map<?, ? super Date> items) { } } @Test public void huhToArrayOfSerializable() { assertThat( testResult(MapOfHuhToArrayOfSerializable.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class MapOfHuhToArrayOfSerializable { @Property(trials = 20) public void shouldHold( Map<?, Serializable[]> items) { for (Serializable[] each : items.values()) { for (Serializable s : each) { // ensuring the cast works } } } } @Test public void huhToListOfHuh() { assertThat(testResult(MapOfHuhToListOfHuh.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class MapOfHuhToListOfHuh { @Property(trials = 20) public void shouldHold(Map<?, List<?>> items) { for (List<?> each : items.values()) { // ensuring the cast works } } } @Test public void huhToMapOfIntegerToString() { assertThat( testResult(MapOfHuhToMapOfIntegerToString.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class MapOfHuhToMapOfIntegerToString { @Property(trials = 20) public void shouldHold( Map<?, Map<Integer, String>> items) { for (Map<Integer, String> each : items.values()) { for (Map.Entry<Integer, String> eachEntry : each.entrySet()) { // ensuring the cast works Integer key = eachEntry.getKey(); String value = eachEntry.getValue(); } } } } @Test public void shrinkingMapOfIntegerToMapOfByteToShort() { assertThat( testResult(ShrinkingMapOfIntegerToMapOfByteToShort.class), failureCountIs(1)); assertThat( ShrinkingMapOfIntegerToMapOfByteToShort.failed.size(), greaterThan(3)); } @RunWith(JUnitQuickcheck.class) public static class ShrinkingMapOfIntegerToMapOfByteToShort { static Map<Integer, Map<Byte, Short>> failed; @Property(trials = 20) public void shouldHold( Map<Integer, Map<Byte, Short>> items) { assumeThat(items.size(), greaterThan(3)); // ensuring casts work for (Map.Entry<Integer, Map<Byte, Short>> eachEntry : items.entrySet()) { Integer key = eachEntry.getKey(); Map<Byte, Short> value = eachEntry.getValue(); for (Map.Entry<Byte, Short> eachSubEntry : value.entrySet()) { Byte b = eachSubEntry.getKey(); Short sh = eachSubEntry.getValue(); } } failed = items; fail(); } } @Test public void huhToListOfUpperBound() { assertThat( testResult(MapOfHuhToListOfUpperBound.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class MapOfHuhToListOfUpperBound { @Property(trials = 20) public void shouldHold( Map<?, List<? extends Serializable>> items) { for (List<? extends Serializable> each : items.values()) { for (Serializable s : each) { // testing type cast } } } } @Test public void huhToSetOfLowerBound() { assertThat( testResult(MapOfHuhToSetOfLowerBound.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class MapOfHuhToSetOfLowerBound { @Property(trials = 20) public void shouldHold( Map<?, Set<? super HashMap<?, ?>>> items) { for (Set<? super HashMap<?, ?>> each : items.values()) { for (Object eachItem : each) { } } } } @Test public void upperBoundToHuh() { assertThat(testResult(MapOfUpperBoundToHuh.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class MapOfUpperBoundToHuh { @Property(trials = 20) public void shouldHold( Map<? extends Number, ?> items) { for (Number each : items.keySet()) { // testing type cast } } } @Test public void lowerBoundToHuh() { assertThat(testResult(MapOfLowerBoundToHuh.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class MapOfLowerBoundToHuh { @Property(trials = 20) public void shouldHold( Map<? super int[], ?> items) { } } @Test public void arrayOfDateToHuh() { assertThat(testResult(MapOfArrayOfDateToHuh.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class MapOfArrayOfDateToHuh { @Property(trials = 20) public void shouldHold(Map<Date[], ?> items) { for (Date[] each : items.keySet()) { for (Date d : each) { // ensuring the cast works } } } } @Test public void setOfHuhToHuh() { assertThat(testResult(SetOfHuhToHuh.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class SetOfHuhToHuh { @Property(trials = 20) public void shouldHold(Map<Set<?>, ?> items) { for (Set<?> each : items.keySet()) { // ensuring the cast works } } } @Test public void mapOfIntegerToStringToMapOfShortToDate() { assertThat( testResult(MapOfIntegerToStringToMapOfShortToDate.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class MapOfIntegerToStringToMapOfShortToDate { @Property(trials = 20) public void shouldHold( Map<Map<Integer, String>, Map<Short, Date>> items) { for (Map.Entry<Map<Integer, String>, Map<Short, Date>> entry : items.entrySet()) { Map<Integer, String> byInteger = entry.getKey(); Map<Short, Date> byShort = entry.getValue(); for (Map.Entry<Integer, String> integerEntry : byInteger.entrySet()) { // ensuring the cast works Integer key = integerEntry.getKey(); String value = integerEntry.getValue(); } for (Map.Entry<Short, Date> shortEntry : byShort.entrySet()) { // ensuring the cast works Short key = shortEntry.getKey(); Date value = shortEntry.getValue(); } } } } @Test public void iterableOfUpperBoundToHuh() { assertThat( testResult(IterableOfUpperBoundToHuh.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class IterableOfUpperBoundToHuh { @Property(trials = 20) public void shouldHold( Map<Iterable<? extends Number>, ?> items) { for (Iterable<? extends Number> each : items.keySet()) { for (Number n : each) { // testing type cast } } } } @Test public void collectionOfLowerBoundToHuh() { assertThat( testResult(CollectionOfLowerBoundToHuh.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class CollectionOfLowerBoundToHuh { @Property(trials = 20) public void shouldHold( Map<Collection<? super List<?>>, ?> items) { for (Collection<? super List<?>> each : items.keySet()) { for (Object item : each) { } } } } @Test public void mapMerging() { assertThat(testResult(MapMerging.class), isSuccessful()); } @RunWith(JUnitQuickcheck.class) public static class MapMerging { @Property public void mergeMapSize( Map<Integer, Integer> m1, Map<Integer, Integer> m2) { int intersectionSize = intersectByKeys(m1, m2).size(); int mergeSize = merge(asList(m1, m2)).size(); assertEquals( m1.getClass().getName() + '/' + m2.getClass().getName(), m1.size() + m2.size(), mergeSize + intersectionSize); } private static <K, V> Map<K, V> merge(Collection<Map<K, V>> maps) { Map<K, V> result = new HashMap<>(); maps.forEach(result::putAll); return result; } private static <K1, V1, V2> Map<K1, V1> intersectByKeys( Map<K1, V1> m1, Map<K1, V2> m2) { Map<K1, V1> result = new HashMap<>(); m1.forEach((k1, v1) -> { if (m2.containsKey(k1)) result.put(k1, v1); }); return result; } } }
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.intention.impl.config; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.hint.HintUtil; import com.intellij.ide.BrowserUtil; import com.intellij.ide.plugins.IdeaPluginDescriptorImpl; import com.intellij.ide.plugins.PluginManagerConfigurable; import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.ide.ui.search.SearchUtil; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.HintHint; import com.intellij.ui.HyperlinkLabel; import com.intellij.ui.IdeBorderFactory; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.StartupUiUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.HyperlinkEvent; import java.awt.*; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.List; // used in Rider public class IntentionDescriptionPanel { private static final Logger LOG = Logger.getInstance(IntentionDescriptionPanel.class); private JPanel myPanel; private JPanel myAfterPanel; private JPanel myBeforePanel; private JEditorPane myDescriptionBrowser; private JPanel myPoweredByPanel; private JPanel myDescriptionPanel; private final List<IntentionUsagePanel> myBeforeUsagePanels = new ArrayList<>(); private final List<IntentionUsagePanel> myAfterUsagePanels = new ArrayList<>(); @NonNls private static final String BEFORE_TEMPLATE = "before.java.template"; @NonNls private static final String AFTER_TEMPLATE = "after.java.template"; public IntentionDescriptionPanel() { myBeforePanel.setBorder(IdeBorderFactory.createTitledBorder(CodeInsightBundle.message("border.title.before"), false, JBUI.insetsTop(8)).setShowLine(false)); myAfterPanel.setBorder(IdeBorderFactory.createTitledBorder(CodeInsightBundle.message("border.title.after"), false, JBUI.insetsTop(8)).setShowLine(false)); myPoweredByPanel.setBorder(IdeBorderFactory.createTitledBorder( CodeInsightBundle.message("powered.by"), false, JBUI.insetsTop(8)).setShowLine(false)); myDescriptionBrowser.addHyperlinkListener(e -> { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { BrowserUtil.browse(e.getURL()); } }); } // TODO 134099: see SingleInspectionProfilePanel#readHTML and and PostfixDescriptionPanel#readHtml private boolean readHTML(String text) { try { myDescriptionBrowser.read(new StringReader(text), null); return true; } catch (IOException ignored) { return false; } } // TODO 134099: see SingleInspectionProfilePanel#setHTML and PostfixDescriptionPanel#readHtml private String toHTML(@NlsContexts.HintText String text) { final HintHint hintHint = new HintHint(myDescriptionBrowser, new Point(0, 0)); hintHint.setFont(StartupUiUtil.getLabelFont()); return HintUtil.prepareHintText(text, hintHint); } public void reset(IntentionActionMetaData actionMetaData, String filter) { try { final TextDescriptor url = actionMetaData.getDescription(); final String description = StringUtil.isEmpty(url.getText()) ? toHTML(CodeInsightBundle.message("under.construction.string")) : SearchUtil.markup(toHTML(url.getText()), filter); readHTML(description); setupPoweredByPanel(actionMetaData); showUsages(myBeforePanel, myBeforeUsagePanels, actionMetaData.getExampleUsagesBefore()); showUsages(myAfterPanel, myAfterUsagePanels, actionMetaData.getExampleUsagesAfter()); SwingUtilities.invokeLater(() -> myPanel.revalidate()); } catch (IOException e) { LOG.error(e); } } private void setupPoweredByPanel(final IntentionActionMetaData actionMetaData) { PluginId pluginId = actionMetaData == null ? null : actionMetaData.getPluginId(); myPoweredByPanel.removeAll(); IdeaPluginDescriptorImpl pluginDescriptor = (IdeaPluginDescriptorImpl)PluginManagerCore.getPlugin(pluginId); ApplicationInfoEx appInfo = ApplicationInfoEx.getInstanceEx(); boolean isCustomPlugin = pluginDescriptor != null && pluginDescriptor.isBundled() && !appInfo.isEssentialPlugin(pluginId); if (isCustomPlugin) { HyperlinkLabel label = new HyperlinkLabel(CodeInsightBundle.message("powered.by.plugin", pluginDescriptor.getName())); label.addHyperlinkListener(__ -> PluginManagerConfigurable.showPluginConfigurable(ProjectManager.getInstance().getDefaultProject(), List.of(pluginId))); myPoweredByPanel.add(label, BorderLayout.CENTER); } myPoweredByPanel.setVisible(isCustomPlugin); } public void reset(String intentionCategory) { try { readHTML(toHTML(CodeInsightBundle.message("intention.settings.category.text", intentionCategory))); setupPoweredByPanel(null); TextDescriptor beforeTemplate = new PlainTextDescriptor(CodeInsightBundle.message("templates.intention.settings.category.before"), BEFORE_TEMPLATE); showUsages(myBeforePanel, myBeforeUsagePanels, new TextDescriptor[]{beforeTemplate}); TextDescriptor afterTemplate = new PlainTextDescriptor(CodeInsightBundle.message("templates.intention.settings.category.after"), AFTER_TEMPLATE); showUsages(myAfterPanel, myAfterUsagePanels, new TextDescriptor[]{afterTemplate}); SwingUtilities.invokeLater(() -> myPanel.revalidate()); } catch (IOException e) { LOG.error(e); } } private static void showUsages(final JPanel panel, final List<IntentionUsagePanel> usagePanels, final TextDescriptor @Nullable [] exampleUsages) throws IOException { GridBagConstraints gb = null; boolean reuse = exampleUsages != null && panel.getComponents().length == exampleUsages.length; if (!reuse) { disposeUsagePanels(usagePanels); panel.setLayout(new GridBagLayout()); panel.removeAll(); gb = new GridBagConstraints(); gb.anchor = GridBagConstraints.NORTHWEST; gb.fill = GridBagConstraints.BOTH; gb.gridheight = GridBagConstraints.REMAINDER; gb.gridwidth = 1; gb.gridx = 0; gb.gridy = 0; gb.insets = new Insets(0,0,0,0); gb.ipadx = 5; gb.ipady = 5; gb.weightx = 1; gb.weighty = 1; } if (exampleUsages != null) { for (int i = 0; i < exampleUsages.length; i++) { final TextDescriptor exampleUsage = exampleUsages[i]; final String name = exampleUsage.getFileName(); final FileTypeManagerEx fileTypeManager = FileTypeManagerEx.getInstanceEx(); final String extension = fileTypeManager.getExtension(name); final FileType fileType = fileTypeManager.getFileTypeByExtension(extension); IntentionUsagePanel usagePanel; if (reuse) { usagePanel = (IntentionUsagePanel)panel.getComponent(i); } else { usagePanel = new IntentionUsagePanel(); usagePanels.add(usagePanel); } usagePanel.reset(exampleUsage.getText(), fileType); if (!reuse) { panel.add(usagePanel, gb); gb.gridx++; } } } panel.revalidate(); panel.repaint(); } public JPanel getComponent() { return myPanel; } public void dispose() { disposeUsagePanels(myBeforeUsagePanels); disposeUsagePanels(myAfterUsagePanels); } private static void disposeUsagePanels(List<? extends IntentionUsagePanel> usagePanels) { for (final IntentionUsagePanel usagePanel : usagePanels) { Disposer.dispose(usagePanel); } usagePanels.clear(); } public void init(final int preferredWidth) { //adjust vertical dimension to be equal for all three panels double height = (myDescriptionPanel.getSize().getHeight() + myBeforePanel.getSize().getHeight() + myAfterPanel.getSize().getHeight()) / 3; final Dimension newd = new Dimension(preferredWidth, (int)height); myDescriptionPanel.setSize(newd); myDescriptionPanel.setPreferredSize(newd); myDescriptionPanel.setMaximumSize(newd); myDescriptionPanel.setMinimumSize(newd); myBeforePanel.setSize(newd); myBeforePanel.setPreferredSize(newd); myBeforePanel.setMaximumSize(newd); myBeforePanel.setMinimumSize(newd); myAfterPanel.setSize(newd); myAfterPanel.setPreferredSize(newd); myAfterPanel.setMaximumSize(newd); myAfterPanel.setMinimumSize(newd); } }
package org.multibit.hd.core.services; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ListeningExecutorService; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.bitcoinj.core.Context; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.utils.Threading; import org.bouncycastle.openpgp.PGPException; import org.multibit.hd.brit.seed_phrase.Bip39SeedPhraseGenerator; import org.multibit.hd.brit.seed_phrase.SeedPhraseGenerator; import org.multibit.hd.brit.services.BRITServices; import org.multibit.hd.brit.services.FeeService; import org.multibit.hd.core.concurrent.SafeExecutors; import org.multibit.hd.core.config.BitcoinConfiguration; import org.multibit.hd.core.config.Configuration; import org.multibit.hd.core.config.Configurations; import org.multibit.hd.core.config.Yaml; import org.multibit.hd.core.dto.HistoryEntry; import org.multibit.hd.core.dto.WalletId; import org.multibit.hd.core.dto.WalletPassword; import org.multibit.hd.core.dto.WalletSummary; import org.multibit.hd.core.error_reporting.ExceptionHandler; import org.multibit.hd.core.events.CoreEvents; import org.multibit.hd.core.events.ShutdownEvent; import org.multibit.hd.core.exceptions.CoreException; import org.multibit.hd.core.exceptions.PaymentsLoadException; import org.multibit.hd.core.logging.LoggingFactory; import org.multibit.hd.core.managers.InstallationManager; import org.multibit.hd.core.managers.WalletManager; import org.multibit.hd.core.utils.BitcoinNetwork; import org.multibit.hd.hardware.core.HardwareWalletClient; import org.multibit.hd.hardware.core.HardwareWalletService; import org.multibit.hd.hardware.core.wallets.HardwareWallets; import org.multibit.hd.hardware.trezor.clients.TrezorHardwareWalletClient; import org.multibit.hd.hardware.trezor.wallets.v1.TrezorV1HidHardwareWallet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * <p>Factory to provide the following to application API:</p> * <ul> * <li>Entry point to configured instances of Core services</li> * </ul> * * @since 0.0.1 */ public class CoreServices { private static final Logger log = LoggerFactory.getLogger(CoreServices.class); /** * Keep track of selected application events (e.g. exchange rate changes, environment alerts etc) * Not an optional service */ private static ApplicationEventService applicationEventService; /** * Keep track of environment events (e.g. debugger, file permissions etc) across all wallets * Not an optional service */ private static EnvironmentCheckingService environmentCheckingService; /** * Keep track of shutdown events and ensure the configuration is persisted * Not an optional service */ private static ConfigurationService configurationService; /** * Allow lightweight processing of external data as part of Payment Protocol support * Not an optional service */ private static PaymentProtocolService paymentProtocolService; /** * Keep track of the Bitcoin network for the current wallet * Optional service until wallet is unlocked */ private static Optional<BitcoinNetworkService> bitcoinNetworkService = Optional.absent(); /** * Keep track of the hardware wallet service for the application * Optional service if system does not support hardware wallets (or none attached) */ private static Optional<HardwareWalletService> hardwareWalletService = Optional.absent(); /** * Keeps track of the contact service for the current wallet * Optional service until wallet is unlocked */ private static Optional<PersistentContactService> contactService = Optional.absent(); /** * Keeps track of the wallet service for the current wallet * Optional service until wallet is unlocked */ private static Optional<WalletService> walletService = Optional.absent(); /** * Keeps track of the history service for the current wallet * Optional service until wallet is unlocked */ private static Optional<PersistentHistoryService> historyService = Optional.absent(); /** * Keeps track of the backup service for the current wallet * Optional service until wallet is unlocked */ private static Optional<BackupService> backupService = Optional.absent(); /** * Manages CoreService startup and shutdown operations */ private static volatile ListeningExecutorService coreServices = null; private static Context context; public static Context getContext() { return context; } /** * Utilities have a private constructor */ private CoreServices() { } /** * Start the bare minimum to allow correct operation */ public static void bootstrap() { configurationService = new ConfigurationService(); // Start the configuration service to ensure shutdown events are trapped configurationService.start(); log.debug("Loading configuration..."); Optional<Configuration> configuration; try (InputStream is = new FileInputStream(InstallationManager.getConfigurationFile())) { // Load configuration (providing a default if none exists) configuration = Yaml.readYaml(is, Configuration.class); } catch (IOException e) { configuration = Optional.absent(); } if (configuration.isPresent()) { log.info("Using current configuration"); Configurations.currentConfiguration = configuration.get(); } else { log.warn("Using default configuration"); Configurations.currentConfiguration = Configurations.newDefaultConfiguration(); } // Set up the bitcoinj context context = new Context(NetworkParameters.fromID(NetworkParameters.ID_MAINNET)); log.debug("Context identity: {}", System.identityHashCode(context)); // Ensure any errors can be reported ExceptionHandler.registerExceptionHandler(); } /** * <p>Initialises the core services, and can act as an independent starting point for headless operations</p> * * @param args Any command line arguments */ public static void main(String[] args) { // Order is important here applicationEventService = new ApplicationEventService(); environmentCheckingService = new EnvironmentCheckingService(); if (configurationService == null) { bootstrap(); } // Configure logging now that we have a configuration new LoggingFactory(Configurations.currentConfiguration.getLogging(), "MultiBit HD").configure(); // Start environment checking service environmentCheckingService.start(); // Start application event service applicationEventService.start(); // Create Payment Protocol service (once configuration identifies the network parameters) paymentProtocolService = new PaymentProtocolService(BitcoinNetwork.current().get()); paymentProtocolService.start(); // Configure Bitcoinj Threading.UserThread.WARNING_THRESHOLD = Integer.MAX_VALUE; } /** * <p>Typically called directly after a ShutdownEvent is broadcast.</p> * <p>Depending on the shutdown type this method will trigger a <code>System.exit(0)</code> to ensure graceful termination.</p></p> * * @param shutdownType The */ @SuppressFBWarnings({"DM_GC"}) public static synchronized void shutdownNow(final ShutdownEvent.ShutdownType shutdownType) { switch (shutdownType) { default: case HARD: log.info("Applying hard shutdown."); shutdownWalletSupportServices(shutdownType); shutdownApplicationSupportServices(shutdownType); log.info("Issuing system exit"); System.exit(0); break; case SOFT: log.info("Applying soft shutdown."); shutdownWalletSupportServices(shutdownType); shutdownApplicationSupportServices(shutdownType); // Suggest a garbage collection to free resources under test System.gc(); break; case SWITCH: log.info("Applying wallet switch."); shutdownWalletSupportServices(shutdownType); // Suggest a garbage collection System.gc(); break; } } /** * <p>Shutdown all application support services (non-optional)</p> * <ul> * <li>Contact service</li> * <li>History service</li> * <li>Bitcoin network service</li> * <li>Wallet service</li> * <li>Backup service</li> * </ul> * * @param shutdownType The shutdown type providing context */ private static void shutdownWalletSupportServices(ShutdownEvent.ShutdownType shutdownType) { // Allow graceful shutdown of managed services in the correct order shutdownService(contactService, shutdownType); shutdownService(historyService, shutdownType); // Close the Bitcoin network service (peer group, save wallet etc) shutdownService(bitcoinNetworkService, shutdownType); shutdownService(walletService, shutdownType); shutdownService(backupService, shutdownType); // Clear the references bitcoinNetworkService = Optional.absent(); contactService = Optional.absent(); walletService = Optional.absent(); historyService = Optional.absent(); backupService = Optional.absent(); } /** * <p>Shutdown all application support services (non-optional)</p> * <ul> * <li>Hardware wallet service</li> * </ul> * * @param shutdownType The shutdown type providing context */ private static void shutdownApplicationSupportServices(ShutdownEvent.ShutdownType shutdownType) { // Shutdown non-managed services if (hardwareWalletService.isPresent()) { hardwareWalletService.get().stopAndWait(); // Need a fresh instance for correct restart hardwareWalletService = Optional.absent(); } // Allow graceful shutdown in the correct order if (configurationService != null) { configurationService.shutdownNow(shutdownType); } if (environmentCheckingService != null) { environmentCheckingService.shutdownNow(shutdownType); } if (applicationEventService != null) { applicationEventService.shutdownNow(shutdownType); } if (paymentProtocolService != null) { paymentProtocolService.shutdownNow(shutdownType); } // Be judicious when clearing references since it leads to complex behaviour during shutdown } /** * <p>Shutdown a managed service</p> * * @param service The service * @param shutdownType The shutdown type providing context */ private static void shutdownService(Optional<? extends ManagedService> service, ShutdownEvent.ShutdownType shutdownType) { if (service.isPresent()) { service.get().shutdownNow(shutdownType); } } /** * @param bitcoinConfiguration The Bitcoin configuration providing exchange and currency details * * @return A new exchange service based on the current configuration */ public static ExchangeTickerService createAndStartExchangeService(BitcoinConfiguration bitcoinConfiguration) { // Breaks the "get or create" pattern because it is used to examine all exchanges log.debug("Create and start new exchange ticker service"); final ExchangeTickerService exchangeTickerService = new ExchangeTickerService(bitcoinConfiguration); exchangeTickerService.start(); return exchangeTickerService; } /** * @return Create a new hardware wallet service or return the extant one */ public static synchronized Optional<HardwareWalletService> getOrCreateHardwareWalletService() { log.debug("Get hardware wallet service"); if (!hardwareWalletService.isPresent()) { // Attempt Trezor support if (Configurations.currentConfiguration.isTrezor()) { try { // Use factory to statically bind a specific hardware wallet TrezorV1HidHardwareWallet wallet = HardwareWallets.newUsbInstance( TrezorV1HidHardwareWallet.class, Optional.<Integer>absent(), Optional.<Integer>absent(), Optional.<String>absent() ); // Wrap the hardware wallet in a suitable client to simplify message API HardwareWalletClient client = new TrezorHardwareWalletClient(wallet); // Wrap the client in a service for high level API suitable for downstream applications hardwareWalletService = Optional.of(new HardwareWalletService(client)); } catch (Throwable throwable) { log.warn("Could not create the hardware wallet.", throwable); hardwareWalletService = Optional.absent(); } } else { hardwareWalletService = Optional.absent(); } } return hardwareWalletService; } /** * Simplify FEST testing for hardware wallets * * @param service The hardware wallet service to use */ public static void setHardwareWalletService(HardwareWalletService service) { Preconditions.checkState(InstallationManager.unrestricted, "The hardware wallet service should only be set in the context of testing"); hardwareWalletService = Optional.of(service); } /** * <p>Stop the hardware wallet service</p> */ public static void stopHardwareWalletService() { log.debug("Stop hardware wallet service (expect all subscribers to be purged)"); hardwareWalletService.get().stopAndWait(); // Clear the reference to avoid restart issues hardwareWalletService = Optional.absent(); } /** * @return Create a new backup service or return the extant one */ public static BackupService getOrCreateBackupService() { log.debug("Getting backup service"); if (!backupService.isPresent()) { backupService = Optional.of(new BackupService()); } return backupService.get(); } /** * @return Create a new seed phrase generator */ public static SeedPhraseGenerator newSeedPhraseGenerator() { log.debug("Creating new BIP39 seed phrase generator"); return new Bip39SeedPhraseGenerator(); } /** * @return The application event service singleton */ public static ApplicationEventService getApplicationEventService() { return applicationEventService; } /** * @return The environment checking service singleton */ public static EnvironmentCheckingService getEnvironmentCheckingService() { log.debug("Get environment checking service"); return environmentCheckingService; } /** * @return The configuration service singleton */ public static ConfigurationService getConfigurationService() { log.debug("Get configuration service"); return configurationService; } /** * @return The started payment protocol service */ public static PaymentProtocolService getPaymentProtocolService() { log.debug("Get or create payment protocol service"); return paymentProtocolService; } /** * @return The Bitcoin network service - note that this is NOT started */ public static synchronized BitcoinNetworkService getOrCreateBitcoinNetworkService() { log.trace("Get Bitcoin network service "); // Require session singleton so only a null will create a new instance if (!bitcoinNetworkService.isPresent()) { bitcoinNetworkService = Optional.of(new BitcoinNetworkService(BitcoinNetwork.current().get())); } return bitcoinNetworkService.get(); } /** * <p>Stop the Bitcoin network service and allow garbage collection</p> * * <p>This occurs on the CoreServices task thread</p> */ public static synchronized void stopBitcoinNetworkService() { if (coreServices == null) { coreServices = SafeExecutors.newFixedThreadPool(10, "core-services"); } log.debug("Stop Bitcoin network service"); coreServices.submit( new Runnable() { @Override public void run() { if (bitcoinNetworkService.isPresent()) { bitcoinNetworkService.get().shutdownNow(ShutdownEvent.ShutdownType.HARD); bitcoinNetworkService = Optional.absent(); } } }); } /** * @return The wallet service for the current wallet */ public static Optional<WalletService> getCurrentWalletService() { return walletService; } /** * @param walletId The wallet ID for the wallet * * @return The started wallet service for the given wallet ID */ public static WalletService getOrCreateWalletService(WalletId walletId) { log.trace("Get or create wallet service"); Preconditions.checkNotNull(walletId, "'walletId' must be present"); // Check if the wallet service has been created for this wallet ID if (!walletService.isPresent()) { File applicationDirectory = InstallationManager.getOrCreateApplicationDataDirectory(); walletService = Optional.of(new WalletService(BitcoinNetwork.current().get())); try { if (WalletManager.INSTANCE.getCurrentWalletSummary().isPresent()) { CharSequence password = WalletManager.INSTANCE.getCurrentWalletSummary().get().getWalletPassword().getPassword(); walletService.get().initialise(applicationDirectory, walletId, password); } } catch (PaymentsLoadException ple) { ExceptionHandler.handleThrowable(ple); } walletService.get().start(); } // Return the wallet service return walletService.get(); } /** * @return The contact service for the current wallet */ public static ContactService getCurrentContactService() { log.debug("Get current contact service"); Optional<WalletSummary> currentWalletSummary = WalletManager.INSTANCE.getCurrentWalletSummary(); Preconditions.checkState(currentWalletSummary.isPresent(), "'currentWalletSummary' must be present. No wallet is present."); WalletId walletId = currentWalletSummary.get().getWalletId(); return getOrCreateContactService(walletId); } /** * @return The history service for the current wallet */ public static HistoryService getCurrentHistoryService() { log.debug("Get current history service"); Optional<WalletSummary> currentWalletSummary = WalletManager.INSTANCE.getCurrentWalletSummary(); Preconditions.checkState(currentWalletSummary.isPresent(), "'currentWalletSummary' must be present. No wallet is present."); WalletPassword walletPassword = currentWalletSummary.get().getWalletPassword(); return getOrCreateHistoryService(walletPassword); } /** * @return The history service for a wallet (single soft, multiple hard) */ public static HistoryService getOrCreateHistoryService(WalletPassword walletPassword) { log.debug("Get or create history service"); Preconditions.checkNotNull(walletPassword, "'walletPassword' must be present"); if (!historyService.isPresent()) { historyService = Optional.of(new PersistentHistoryService(walletPassword)); } // Return the existing or new history service return historyService.get(); } /** * @param walletId The wallet ID for the wallet * * @return The contact service for a wallet */ public static ContactService getOrCreateContactService(WalletId walletId) { log.debug("Get or create contact service"); Preconditions.checkNotNull(walletId, "'walletId' must be present"); // Check if the contact service has been created for this wallet ID if (!contactService.isPresent()) { contactService = Optional.of(new PersistentContactService(walletId)); } // Return the existing or new contact service return contactService.get(); } /** * <p>Convenience method to log a new history event for the current wallet</p> * * @param localisedDescription The localised description text */ public static void logHistory(String localisedDescription) { // Get the current history service HistoryService historyService = CoreServices.getCurrentHistoryService(); // Create the history entry and persist it HistoryEntry historyEntry = historyService.newHistoryEntry(localisedDescription); historyService.writeHistory(); // OK to let everyone else know CoreEvents.fireHistoryChangedEvent(historyEntry); } /** * @return A BRIT fee service pointing to the live Matcher machine */ public static FeeService createFeeService() throws CoreException { log.debug("Create fee service"); try { return BRITServices.newFeeService(); } catch (IOException | PGPException e) { log.error("Failed to create the FeeService", e); // Throw as ISE to trigger ExceptionHandler throw new IllegalStateException("Failed to create the FeeService"); } } }
/** * * Copyright 2015 The Darks Grid Project (Liu lihua) * * 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 darks.grid.network; import java.net.InetSocketAddress; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import darks.grid.GridRuntime; import darks.grid.beans.GridAddress; import darks.grid.beans.GridNode; import darks.grid.beans.TimerObject; import darks.grid.beans.meta.JoinMeta; import darks.grid.config.GridConfiguration; import darks.grid.manager.GridManager; import darks.grid.utils.SyncPool; public class GridNetworkManager implements GridManager { private static final Logger log = LoggerFactory.getLogger(GridNetworkManager.class); private static final long LOCK_EXPIRE_TIME = 60000; private static final long ACTIVE_EXPIRE_TIME = 120000; private GridMessageServer messageServer; private GridMessageClient messageClient; private Map<GridAddress, TimerObject<GridSession>> waitActive = new ConcurrentHashMap<GridAddress, TimerObject<GridSession>>(); private Map<String, Map<GridAddress, JoinMeta>> waitJoin = new ConcurrentHashMap<String, Map<GridAddress, JoinMeta>>(); private Object mutex = new Object(); private GridSession serverSession; public GridNetworkManager() { } @Override public synchronized boolean initialize(GridConfiguration config) { messageServer = GridNetworkBuilder.buildMessageServer(config); if (messageServer == null) return false; if (bindLocalNode()) { messageClient = GridNetworkBuilder.buildMessageClient(config); return messageClient != null; } else { return false; } } public synchronized boolean bindLocalNode() { if (messageServer == null) return false; serverSession = GridNetworkBuilder.listenServer(messageServer); if (serverSession != null) { GridRuntime.context().setServerAddress(getBindAddress()); GridRuntime.nodes().addLocalNode(serverSession); return true; } else return false; } @Override public void destroy() { messageClient.destroy(); messageServer.destroy(); } public void sendMessageToAll(Object obj) { List<GridNode> nodes = GridRuntime.nodes().getNodesList(); for (GridNode node : nodes) { if (node.isAlive()) node.sendSyncMessage(obj); } } public void sendMessageToOthers(Object obj) { List<GridNode> nodes = GridRuntime.nodes().getNodesList(); for (GridNode node : nodes) { if (!node.isLocal() && node.isAlive()) node.sendSyncMessage(obj); } } public boolean tryJoinAddress(GridAddress address) { return tryJoinAddress(address, true); } public boolean tryJoinAddress(InetSocketAddress address) { return tryJoinAddress(new GridAddress(address), true); } public boolean tryJoinAddress(GridAddress address, boolean sync) { if (address == null) { log.error("Address is null when trying to join."); return false; } Lock lock = SyncPool.lock(address, LOCK_EXPIRE_TIME); if (!lock.tryLock()) { log.error("Address " + address + " locked when trying to join."); return false; } try { if (GridRuntime.nodes().contains(address)) { log.warn("Address " + address + " has joined when trying to join."); return true; } if (messageClient == null) { log.error("Message client is null when trying to join."); return false; } return messageClient.connect(address, sync) != null; } finally { lock.unlock(); } } public int addWaitJoin(String nodeId, JoinMeta meta) { synchronized (mutex) { Map<GridAddress, JoinMeta> channelMap = waitJoin.get(nodeId); if (channelMap == null) { channelMap = new ConcurrentHashMap<GridAddress, JoinMeta>(); waitJoin.put(nodeId, channelMap); } meta.setJoinTime(System.currentTimeMillis()); channelMap.put(meta.getSession().remoteAddress(), meta); return channelMap.size(); } } public void addWaitActive(GridSession session) { waitActive.put(session.remoteAddress(), new TimerObject<GridSession>(session, ACTIVE_EXPIRE_TIME)); } public void removeWaitActive(GridSession session) { waitActive.remove(session.remoteAddress()); } public synchronized Map<GridAddress, JoinMeta> getWaitJoin(String nodeId) { synchronized (mutex) { Map<GridAddress, JoinMeta> channelMap = waitJoin.get(nodeId); if (channelMap == null) { channelMap = new ConcurrentHashMap<GridAddress, JoinMeta>(); waitJoin.put(nodeId, channelMap); } return channelMap; } } public synchronized GridAddress getBindAddress() { if (messageServer == null || serverSession == null) return null; return serverSession.localAddress(); } public GridSession getServerSession() { return serverSession; } }
/* 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 java.util; import com.google.j2objc.annotations.Weak; import java.io.Serializable; /** * An {@code Map} specialized for use with {@code Enum} types as keys. */ public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V> implements Serializable, Cloneable { private static final long serialVersionUID = 458661240069192865L; private Class<K> keyType; transient Enum[] keys; transient Object[] values; transient boolean[] hasMapping; private transient int mappingsCount; transient int enumSize; private transient EnumMapEntrySet<K, V> entrySet = null; // workaround for package-private access to core class variable private Collection<V> valuesCollection; private static class Entry<KT extends Enum<KT>, VT> extends MapEntry<KT, VT> { private final EnumMap<KT, VT> enumMap; private final int ordinal; Entry(KT theKey, VT theValue, EnumMap<KT, VT> em) { super(theKey, theValue); enumMap = em; ordinal = ((Enum) theKey).ordinal(); } @SuppressWarnings("unchecked") @Override public boolean equals(Object object) { if (!enumMap.hasMapping[ordinal]) { return false; } boolean isEqual = false; if (object instanceof Map.Entry) { Map.Entry<KT, VT> entry = (Map.Entry<KT, VT>) object; Object enumKey = entry.getKey(); if (key.equals(enumKey)) { Object theValue = entry.getValue(); isEqual = enumMap.values[ordinal] == null ? null == theValue : enumMap.values[ordinal].equals(theValue); } } return isEqual; } @Override public int hashCode() { return (enumMap.keys[ordinal] == null ? 0 : enumMap.keys[ordinal] .hashCode()) ^ (enumMap.values[ordinal] == null ? 0 : enumMap.values[ordinal].hashCode()); } @SuppressWarnings("unchecked") @Override public KT getKey() { checkEntryStatus(); return (KT) enumMap.keys[ordinal]; } @SuppressWarnings("unchecked") @Override public VT getValue() { checkEntryStatus(); return (VT) enumMap.values[ordinal]; } @SuppressWarnings("unchecked") @Override public VT setValue(VT value) { checkEntryStatus(); return enumMap.put((KT) enumMap.keys[ordinal], value); } @Override public String toString() { StringBuilder result = new StringBuilder(enumMap.keys[ordinal] .toString()); result.append("="); //$NON-NLS-1$ result.append(enumMap.values[ordinal].toString()); return result.toString(); } private void checkEntryStatus() { if (!enumMap.hasMapping[ordinal]) { throw new IllegalStateException(); } } } private static class EnumMapIterator<E, KT extends Enum<KT>, VT> implements Iterator<E> { int position = 0; int prePosition = -1; final EnumMap<KT, VT> enumMap; final MapEntry.Type<E, KT, VT> type; EnumMapIterator(MapEntry.Type<E, KT, VT> value, EnumMap<KT, VT> em) { enumMap = em; type = value; } public boolean hasNext() { int length = enumMap.enumSize; for (; position < length; position++) { if (enumMap.hasMapping[position]) { break; } } return position != length; } @SuppressWarnings("unchecked") public E next() { if (!hasNext()) { throw new NoSuchElementException(); } prePosition = position++; return (E) type.get(new MapEntry(enumMap.keys[prePosition], enumMap.values[prePosition])); } public void remove() { checkStatus(); if (enumMap.hasMapping[prePosition]) { enumMap.remove(enumMap.keys[prePosition]); } prePosition = -1; } @Override @SuppressWarnings("unchecked") public String toString() { if (-1 == prePosition) { return super.toString(); } return type.get( new MapEntry(enumMap.keys[prePosition], enumMap.values[prePosition])).toString(); } private void checkStatus() { if (-1 == prePosition) { throw new IllegalStateException(); } } } private static class EnumMapKeySet<KT extends Enum<KT>, VT> extends AbstractSet<KT> { @Weak private final EnumMap<KT, VT> enumMap; EnumMapKeySet(EnumMap<KT, VT> em) { enumMap = em; } @Override public void clear() { enumMap.clear(); } @Override public boolean contains(Object object) { return enumMap.containsKey(object); } @Override @SuppressWarnings("unchecked") public Iterator iterator() { return new EnumMapIterator<KT, KT, VT>( new MapEntry.Type<KT, KT, VT>() { public KT get(MapEntry<KT, VT> entry) { return entry.key; } }, enumMap); } @Override @SuppressWarnings("unchecked") public boolean remove(Object object) { if (contains(object)) { enumMap.remove(object); return true; } return false; } @Override public int size() { return enumMap.size(); } } private static class EnumMapValueCollection<KT extends Enum<KT>, VT> extends AbstractCollection<VT> { @Weak private final EnumMap<KT, VT> enumMap; EnumMapValueCollection(EnumMap<KT, VT> em) { enumMap = em; } @Override public void clear() { enumMap.clear(); } @Override public boolean contains(Object object) { return enumMap.containsValue(object); } @SuppressWarnings("unchecked") @Override public Iterator iterator() { return new EnumMapIterator<VT, KT, VT>( new MapEntry.Type<VT, KT, VT>() { public VT get(MapEntry<KT, VT> entry) { return entry.value; } }, enumMap); } @Override public boolean remove(Object object) { if (null == object) { for (int i = 0; i < enumMap.enumSize; i++) { if (enumMap.hasMapping[i] && null == enumMap.values[i]) { enumMap.remove(enumMap.keys[i]); return true; } } } else { for (int i = 0; i < enumMap.enumSize; i++) { if (enumMap.hasMapping[i] && object.equals(enumMap.values[i])) { enumMap.remove(enumMap.keys[i]); return true; } } } return false; } @Override public int size() { return enumMap.size(); } } private static class EnumMapEntryIterator<E, KT extends Enum<KT>, VT> extends EnumMapIterator<E, KT, VT> { EnumMapEntryIterator(MapEntry.Type<E, KT, VT> value, EnumMap<KT, VT> em) { super(value, em); } @SuppressWarnings("unchecked") @Override public E next() { if (!hasNext()) { throw new NoSuchElementException(); } prePosition = position++; return type.get(new Entry<KT, VT>((KT) enumMap.keys[prePosition], (VT) enumMap.values[prePosition], enumMap)); } } private static class EnumMapEntrySet<KT extends Enum<KT>, VT> extends AbstractSet<Map.Entry<KT, VT>> { @Weak private final EnumMap<KT, VT> enumMap; EnumMapEntrySet(EnumMap<KT, VT> em) { enumMap = em; } @Override public void clear() { enumMap.clear(); } @Override public boolean contains(Object object) { boolean isEqual = false; if (object instanceof Map.Entry) { Object enumKey = ((Map.Entry) object).getKey(); Object enumValue = ((Map.Entry) object).getValue(); if (enumMap.containsKey(enumKey)) { VT value = enumMap.get(enumKey); isEqual = (value == null ? null == enumValue : value .equals(enumValue)); } } return isEqual; } @Override public Iterator<Map.Entry<KT, VT>> iterator() { return new EnumMapEntryIterator<Map.Entry<KT, VT>, KT, VT>( new MapEntry.Type<Map.Entry<KT, VT>, KT, VT>() { public Map.Entry<KT, VT> get(MapEntry<KT, VT> entry) { return entry; } }, enumMap); } @Override public boolean remove(Object object) { if (contains(object)) { enumMap.remove(((Map.Entry) object).getKey()); return true; } return false; } @Override public int size() { return enumMap.size(); } } /** * Constructs an empty {@code EnumMap} using the given key type. * * @param keyType * the class object giving the type of the keys used by this {@code EnumMap}. * @throws NullPointerException * if {@code keyType} is {@code null}. */ public EnumMap(Class<K> keyType) { initialization(keyType); } /** * Constructs an {@code EnumMap} using the same key type as the given {@code EnumMap} and * initially containing the same mappings. * * @param map * the {@code EnumMap} from which this {@code EnumMap} is initialized. * @throws NullPointerException * if {@code map} is {@code null}. */ public EnumMap(EnumMap<K, ? extends V> map) { initialization(map); } /** * Constructs an {@code EnumMap} initialized from the given map. If the given map * is an {@code EnumMap} instance, this constructor behaves in the exactly the same * way as {@link EnumMap#EnumMap(EnumMap)}}. Otherwise, the given map * should contain at least one mapping. * * @param map * the map from which this {@code EnumMap} is initialized. * @throws IllegalArgumentException * if {@code map} is not an {@code EnumMap} instance and does not contain * any mappings. * @throws NullPointerException * if {@code map} is {@code null}. */ @SuppressWarnings("unchecked") public EnumMap(Map<K, ? extends V> map) { if (map instanceof EnumMap) { initialization((EnumMap<K, V>) map); } else { if (0 == map.size()) { throw new IllegalArgumentException(); } Iterator<K> iter = map.keySet().iterator(); K enumKey = iter.next(); Class clazz = enumKey.getClass(); if (clazz.isEnum()) { initialization(clazz); } else { initialization(clazz.getSuperclass()); } putAllImpl(map); } } /** * Removes all elements from this {@code EnumMap}, leaving it empty. * * @see #isEmpty() * @see #size() */ @Override public void clear() { Arrays.fill(values, null); Arrays.fill(hasMapping, false); mappingsCount = 0; } /** * Returns a shallow copy of this {@code EnumMap}. * * @return a shallow copy of this {@code EnumMap}. */ @SuppressWarnings("unchecked") @Override public EnumMap<K, V> clone() { try { EnumMap<K, V> enumMap = (EnumMap<K, V>) super.clone(); enumMap.initialization(this); return enumMap; } catch (CloneNotSupportedException e) { return null; } } /** * Returns whether this {@code EnumMap} contains the specified key. * * @param key * the key to search for. * @return {@code true} if this {@code EnumMap} contains the specified key, * {@code false} otherwise. */ @Override public boolean containsKey(Object key) { if (isValidKeyType(key)) { int keyOrdinal = ((Enum) key).ordinal(); return hasMapping[keyOrdinal]; } return false; } /** * Returns whether this {@code EnumMap} contains the specified value. * * @param value * the value to search for. * @return {@code true} if this {@code EnumMap} contains the specified value, * {@code false} otherwise. */ @Override public boolean containsValue(Object value) { if (null == value) { for (int i = 0; i < enumSize; i++) { if (hasMapping[i] && null == values[i]) { return true; } } } else { for (int i = 0; i < enumSize; i++) { if (hasMapping[i] && value.equals(values[i])) { return true; } } } return false; } /** * Returns a {@code Set} containing all of the mappings in this {@code EnumMap}. Each mapping is * an instance of {@link Map.Entry}. As the {@code Set} is backed by this {@code EnumMap}, * changes in one will be reflected in the other. * <p> * The order of the entries in the set will be the order that the enum keys * were declared in. * * @return a {@code Set} of the mappings. */ @Override public Set<Map.Entry<K, V>> entrySet() { if (null == entrySet) { entrySet = new EnumMapEntrySet<K, V>(this); } return entrySet; } /** * Compares the argument to the receiver, and returns {@code true} if the * specified {@code Object} is an {@code EnumMap} and both {@code EnumMap}s contain the same mappings. * * @param object * the {@code Object} to compare with this {@code EnumMap}. * @return boolean {@code true} if {@code object} is the same as this {@code EnumMap}, * {@code false} otherwise. * @see #hashCode() * @see #entrySet() */ @SuppressWarnings("unchecked") @Override public boolean equals(Object object) { if (this == object) { return true; } if (!(object instanceof EnumMap)) { return super.equals(object); } EnumMap<K, V> enumMap = (EnumMap<K, V>) object; if (keyType != enumMap.keyType || size() != enumMap.size()) { return false; } return Arrays.equals(hasMapping, enumMap.hasMapping) && Arrays.equals(values, enumMap.values); } /** * Returns the value of the mapping with the specified key. * * @param key * the key. * @return the value of the mapping with the specified key, or {@code null} * if no mapping for the specified key is found. */ @Override @SuppressWarnings("unchecked") public V get(Object key) { if (!isValidKeyType(key)) { return null; } int keyOrdinal = ((Enum) key).ordinal(); return (V) values[keyOrdinal]; } /** * Returns a set of the keys contained in this {@code EnumMap}. The {@code Set} is backed by * this {@code EnumMap} so changes to one are reflected in the other. The {@code Set} does not * support adding. * <p> * The order of the set will be the order that the enum keys were declared * in. * * @return a {@code Set} of the keys. */ @Override public Set<K> keySet() { if (null == keySet) { keySet = new EnumMapKeySet<K, V>(this); } return keySet; } /** * Maps the specified key to the specified value. * * @param key * the key. * @param value * the value. * @return the value of any previous mapping with the specified key or * {@code null} if there was no mapping. * @throws UnsupportedOperationException * if adding to this map is not supported. * @throws ClassCastException * if the class of the key or value is inappropriate for this * map. * @throws IllegalArgumentException * if the key or value cannot be added to this map. * @throws NullPointerException * if the key or value is {@code null} and this {@code EnumMap} does not * support {@code null} keys or values. */ @Override @SuppressWarnings("unchecked") public V put(K key, V value) { return putImpl(key, value); } /** * Copies every mapping in the specified {@code Map} to this {@code EnumMap}. * * @param map * the {@code Map} to copy mappings from. * @throws UnsupportedOperationException * if adding to this {@code EnumMap} is not supported. * @throws ClassCastException * if the class of a key or value is inappropriate for this * {@code EnumMap}. * @throws IllegalArgumentException * if a key or value cannot be added to this map. * @throws NullPointerException * if a key or value is {@code null} and this {@code EnumMap} does not * support {@code null} keys or values. */ @Override @SuppressWarnings("unchecked") public void putAll(Map<? extends K, ? extends V> map) { putAllImpl(map); } /** * Removes a mapping with the specified key from this {@code EnumMap}. * * @param key * the key of the mapping to remove. * @return the value of the removed mapping or {@code null} if no mapping * for the specified key was found. * @throws UnsupportedOperationException * if removing from this {@code EnumMap} is not supported. */ @Override @SuppressWarnings("unchecked") public V remove(Object key) { if (!isValidKeyType(key)) { return null; } int keyOrdinal = ((Enum) key).ordinal(); if (hasMapping[keyOrdinal]) { hasMapping[keyOrdinal] = false; mappingsCount--; } V oldValue = (V) values[keyOrdinal]; values[keyOrdinal] = null; return oldValue; } /** * Returns the number of elements in this {@code EnumMap}. * * @return the number of elements in this {@code EnumMap}. */ @Override public int size() { return mappingsCount; } /** * Returns a {@code Collection} of the values contained in this {@code EnumMap}. The returned * {@code Collection} complies with the general rule specified in * {@link Map#values()}. The {@code Collection}'s {@code Iterator} will return the values * in the their corresponding keys' natural order (the {@code Enum} constants are * declared in this order). * <p> * The order of the values in the collection will be the order that their * corresponding enum keys were declared in. * * @return a collection of the values contained in this {@code EnumMap}. */ @Override public Collection<V> values() { if (null == valuesCollection) { valuesCollection = new EnumMapValueCollection<K, V>(this); } return valuesCollection; } private boolean isValidKeyType(Object key) { if (null != key && keyType.isInstance(key)) { return true; } return false; } @SuppressWarnings("unchecked") private void initialization(EnumMap enumMap) { keyType = enumMap.keyType; keys = enumMap.keys; enumSize = enumMap.enumSize; values = enumMap.values.clone(); hasMapping = enumMap.hasMapping.clone(); mappingsCount = enumMap.mappingsCount; } private void initialization(Class<K> type) { keyType = type; keys = keyType.getEnumConstants(); enumSize = keys.length; values = new Object[enumSize]; hasMapping = new boolean[enumSize]; } @SuppressWarnings("unchecked") private void putAllImpl(Map map) { Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); putImpl((K) entry.getKey(), (V) entry.getValue()); } } @SuppressWarnings("unchecked") private V putImpl(K key, V value) { if (null == key) { throw new NullPointerException(); } if (!isValidKeyType(key)) { throw new ClassCastException(); } int keyOrdinal = key.ordinal(); if (!hasMapping[keyOrdinal]) { hasMapping[keyOrdinal] = true; mappingsCount++; } V oldValue = (V) values[keyOrdinal]; values[keyOrdinal] = value; return oldValue; } }
package com.hubspot.singularity.mesos; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import javax.inject.Singleton; import org.apache.mesos.Protos; import org.apache.mesos.Protos.Offer; import org.apache.mesos.Protos.SlaveID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.hubspot.mesos.JavaUtils; import com.hubspot.mesos.json.MesosMasterSlaveObject; import com.hubspot.mesos.json.MesosMasterStateObject; import com.hubspot.singularity.MachineState; import com.hubspot.singularity.SingularityMachineAbstraction; import com.hubspot.singularity.SingularityRack; import com.hubspot.singularity.SingularitySlave; import com.hubspot.singularity.SingularityTask; import com.hubspot.singularity.SingularityTaskId; import com.hubspot.singularity.SingularityTaskRequest; import com.hubspot.singularity.SlavePlacement; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.data.AbstractMachineManager; import com.hubspot.singularity.data.RackManager; import com.hubspot.singularity.data.SlaveManager; import com.hubspot.singularity.data.TaskManager; import com.hubspot.singularity.scheduler.SingularitySchedulerStateCache; import com.hubspot.singularity.sentry.SingularityExceptionNotifier; @Singleton class SingularitySlaveAndRackManager { private static final Logger LOG = LoggerFactory.getLogger(SingularitySlaveAndRackManager.class); private final SingularityConfiguration configuration; private final SingularityExceptionNotifier exceptionNotifier; private final RackManager rackManager; private final SlaveManager slaveManager; private final TaskManager taskManager; private final SingularitySlaveAndRackHelper slaveAndRackHelper; @Inject SingularitySlaveAndRackManager(SingularitySlaveAndRackHelper slaveAndRackHelper, SingularityConfiguration configuration, SingularityExceptionNotifier exceptionNotifier, RackManager rackManager, SlaveManager slaveManager, TaskManager taskManager) { this.configuration = configuration; this.exceptionNotifier = exceptionNotifier; this.slaveAndRackHelper = slaveAndRackHelper; this.rackManager = rackManager; this.slaveManager = slaveManager; this.taskManager = taskManager; } public enum SlaveMatchState { OK(true), NOT_RACK_OR_SLAVE_PARTICULAR(true), RACK_SATURATED(false), SLAVE_SATURATED(false), SLAVE_DECOMMISSIONING(false), RACK_DECOMMISSIONING(false), RACK_AFFINITY_NOT_MATCHING(false), SLAVE_FROZEN(false), RACK_FROZEN(false); private final boolean isMatchAllowed; private SlaveMatchState(boolean isMatchAllowed) { this.isMatchAllowed = isMatchAllowed; } public boolean isMatchAllowed() { return isMatchAllowed; } } public SlaveMatchState doesOfferMatch(Protos.Offer offer, SingularityTaskRequest taskRequest, SingularitySchedulerStateCache stateCache) { final String host = offer.getHostname(); final String rackId = slaveAndRackHelper.getRackIdOrDefault(offer); final String slaveId = offer.getSlaveId().getValue(); final MachineState currentSlaveState = stateCache.getSlave(slaveId).get().getCurrentState().getState(); if (currentSlaveState == MachineState.FROZEN) { return SlaveMatchState.SLAVE_FROZEN; } if (currentSlaveState.isDecommissioning()) { return SlaveMatchState.SLAVE_DECOMMISSIONING; } final MachineState currentRackState = stateCache.getRack(rackId).get().getCurrentState().getState(); if (currentRackState == MachineState.FROZEN) { return SlaveMatchState.RACK_FROZEN; } if (currentRackState.isDecommissioning()) { return SlaveMatchState.RACK_DECOMMISSIONING; } if (!taskRequest.getRequest().getRackAffinity().or(Collections.<String> emptyList()).isEmpty()) { if (!taskRequest.getRequest().getRackAffinity().get().contains(rackId)) { LOG.trace("Task {} requires a rack in {} (current rack {})", taskRequest.getPendingTask().getPendingTaskId(), taskRequest.getRequest().getRackAffinity().get(), rackId); return SlaveMatchState.RACK_AFFINITY_NOT_MATCHING; } } final SlavePlacement slavePlacement = taskRequest.getRequest().getSlavePlacement().or(configuration.getDefaultSlavePlacement()); if (!taskRequest.getRequest().isRackSensitive() && slavePlacement == SlavePlacement.GREEDY) { return SlaveMatchState.NOT_RACK_OR_SLAVE_PARTICULAR; } final int numDesiredInstances = taskRequest.getRequest().getInstancesSafe(); double numOnRack = 0; double numOnSlave = 0; double numCleaningOnSlave = 0; double numOtherDeploysOnSlave = 0; final String sanitizedHost = JavaUtils.getReplaceHyphensWithUnderscores(host); final String sanitizedRackId = JavaUtils.getReplaceHyphensWithUnderscores(rackId); Collection<SingularityTaskId> cleaningTasks = stateCache.getCleaningTasks(); for (SingularityTaskId taskId : SingularityTaskId.matchingAndNotIn(stateCache.getActiveTaskIds(), taskRequest.getRequest().getId(), Collections.<SingularityTaskId>emptyList())) { // TODO consider using executorIds if (taskId.getSanitizedHost().equals(sanitizedHost)) { if (taskRequest.getDeploy().getId().equals(taskId.getDeployId())) { if (cleaningTasks.contains(taskId)) { numCleaningOnSlave++; } else { numOnSlave++; } } else { numOtherDeploysOnSlave++; } } if (taskId.getSanitizedRackId().equals(sanitizedRackId) && !cleaningTasks.contains(taskId) && taskRequest.getDeploy().getId().equals(taskId.getDeployId())) { numOnRack++; } } if (taskRequest.getRequest().isRackSensitive()) { final double numPerRack = numDesiredInstances / (double) stateCache.getNumActiveRacks(); final boolean isRackOk = numOnRack < numPerRack; if (!isRackOk) { LOG.trace("Rejecting RackSensitive task {} from slave {} ({}) due to numOnRack {} and cleaningOnSlave {}", taskRequest.getRequest().getId(), slaveId, host, numOnRack, numCleaningOnSlave); return SlaveMatchState.RACK_SATURATED; } } switch (slavePlacement) { case SEPARATE: case SEPARATE_BY_DEPLOY: if (numOnSlave > 0 || numCleaningOnSlave > 0) { LOG.trace("Rejecting SEPARATE task {} from slave {} ({}) due to numOnSlave {} numCleaningOnSlave {}", taskRequest.getRequest().getId(), slaveId, host, numOnSlave, numCleaningOnSlave); return SlaveMatchState.SLAVE_SATURATED; } break; case SEPARATE_BY_REQUEST: if (numOnSlave > 0 || numCleaningOnSlave > 0 || numOtherDeploysOnSlave > 0) { LOG.trace("Rejecting SEPARATE task {} from slave {} ({}) due to numOnSlave {} numCleaningOnSlave {} numOtherDeploysOnSlave {}", taskRequest.getRequest().getId(), slaveId, host, numOnSlave, numCleaningOnSlave, numOtherDeploysOnSlave); return SlaveMatchState.SLAVE_SATURATED; } break; case OPTIMISTIC: final double numPerSlave = numDesiredInstances / (double) stateCache.getNumActiveSlaves(); final boolean isSlaveOk = numOnSlave < numPerSlave; if (!isSlaveOk) { LOG.trace("Rejecting OPTIMISTIC task {} from slave {} ({}) due to numOnSlave {}", taskRequest.getRequest().getId(), slaveId, host, numOnSlave); return SlaveMatchState.SLAVE_SATURATED; } break; case GREEDY: } return SlaveMatchState.OK; } public void slaveLost(SlaveID slaveIdObj) { final String slaveId = slaveIdObj.getValue(); Optional<SingularitySlave> slave = slaveManager.getObject(slaveId); if (slave.isPresent()) { slaveManager.changeState(slave.get(), MachineState.DEAD, Optional.<String> absent()); checkRackAfterSlaveLoss(slave.get()); } else { LOG.warn("Lost a slave {}, but didn't know about it", slaveId); } } private void checkRackAfterSlaveLoss(SingularitySlave lostSlave) { List<SingularitySlave> slaves = slaveManager.getObjectsFiltered(MachineState.ACTIVE); int numInRack = 0; for (SingularitySlave slave : slaves) { if (slave.getRackId().equals(lostSlave.getRackId())) { numInRack++; } } LOG.info("Found {} slaves left in rack {}", numInRack, lostSlave.getRackId()); if (numInRack == 0) { rackManager.changeState(lostSlave.getRackId(), MachineState.DEAD, Optional.<String> absent()); } } public void loadSlavesAndRacksFromMaster(MesosMasterStateObject state) { Map<String, SingularitySlave> activeSlavesById = slaveManager.getObjectsByIdForState(MachineState.ACTIVE); Map<String, SingularityRack> activeRacksById = rackManager.getObjectsByIdForState(MachineState.ACTIVE); Map<String, SingularityRack> remainingActiveRacks = Maps.newHashMap(activeRacksById); int slaves = 0; int racks = 0; for (MesosMasterSlaveObject slaveJsonObject : state.getSlaves()) { String slaveId = slaveJsonObject.getId(); String rackId = slaveAndRackHelper.getRackId(slaveJsonObject.getAttributes()); String host = slaveAndRackHelper.getMaybeTruncatedHost(slaveJsonObject.getHostname()); if (activeSlavesById.containsKey(slaveId)) { activeSlavesById.remove(slaveId); } else { SingularitySlave newSlave = new SingularitySlave(slaveId, host, rackId); if (check(newSlave, slaveManager) == CheckResult.NEW) { slaves++; } } if (activeRacksById.containsKey(rackId)) { remainingActiveRacks.remove(rackId); } else { SingularityRack rack = new SingularityRack(rackId); if (check(rack, rackManager) == CheckResult.NEW) { racks++; } } } for (SingularitySlave leftOverSlave : activeSlavesById.values()) { slaveManager.changeState(leftOverSlave, MachineState.MISSING_ON_STARTUP, Optional.<String> absent()); } for (SingularityRack leftOverRack : remainingActiveRacks.values()) { rackManager.changeState(leftOverRack, MachineState.MISSING_ON_STARTUP, Optional.<String> absent()); } LOG.info("Found {} new racks ({} missing) and {} new slaves ({} missing)", racks, remainingActiveRacks.size(), slaves, activeSlavesById.size()); } private enum CheckResult { NEW, DECOMMISSIONING, ALREADY_ACTIVE; } private <T extends SingularityMachineAbstraction<T>> CheckResult check(T object, AbstractMachineManager<T> manager) { Optional<T> existingObject = manager.getObject(object.getId()); if (!existingObject.isPresent()) { manager.saveObject(object); return CheckResult.NEW; } MachineState currentState = existingObject.get().getCurrentState().getState(); switch (currentState) { case ACTIVE: case FROZEN: return CheckResult.ALREADY_ACTIVE; case DEAD: case MISSING_ON_STARTUP: manager.changeState(object.getId(), MachineState.ACTIVE, Optional.<String> absent()); return CheckResult.NEW; case DECOMMISSIONED: case DECOMMISSIONING: case STARTING_DECOMMISSION: return CheckResult.DECOMMISSIONING; } throw new IllegalStateException(String.format("Invalid state %s for %s", currentState, object.getId())); } public void checkOffer(Offer offer) { final String slaveId = offer.getSlaveId().getValue(); final String rackId = slaveAndRackHelper.getRackIdOrDefault(offer); final String host = slaveAndRackHelper.getMaybeTruncatedHost(offer); final SingularitySlave slave = new SingularitySlave(slaveId, host, rackId); if (check(slave, slaveManager) == CheckResult.NEW) { LOG.info("Offer revealed a new slave {}", slave); } final SingularityRack rack = new SingularityRack(rackId); if (check(rack, rackManager) == CheckResult.NEW) { LOG.info("Offer revealed a new rack {}", rack); } } public void checkStateAfterFinishedTask(SingularityTaskId taskId, String slaveId, SingularitySchedulerStateCache stateCache) { Optional<SingularitySlave> slave = slaveManager.getObject(slaveId); if (!slave.isPresent()) { final String message = String.format("Couldn't find slave with id %s for task %s", slaveId, taskId); LOG.warn(message); exceptionNotifier.notify(message, ImmutableMap.of("slaveId", slaveId, "taskId", taskId.toString())); return; } if (slave.get().getCurrentState().getState() == MachineState.DECOMMISSIONING) { if (!hasTaskLeftOnSlave(taskId, slaveId, stateCache)) { slaveManager.changeState(slave.get(), MachineState.DECOMMISSIONED, slave.get().getCurrentState().getUser()); } } Optional<SingularityRack> rack = rackManager.getObject(slave.get().getRackId()); if (!rack.isPresent()) { final String message = String.format("Couldn't find rack with id %s for task %s", slave.get().getRackId(), taskId); LOG.warn(message); exceptionNotifier.notify(message, ImmutableMap.of("rackId", slave.get().getRackId(), "taskId", taskId.toString())); return; } if (rack.get().getCurrentState().getState() == MachineState.DECOMMISSIONING) { if (!hasTaskLeftOnRack(taskId, stateCache)) { rackManager.changeState(rack.get(), MachineState.DECOMMISSIONED, rack.get().getCurrentState().getUser()); } } } private boolean hasTaskLeftOnRack(SingularityTaskId taskId, SingularitySchedulerStateCache stateCache) { for (SingularityTaskId activeTaskId : stateCache.getActiveTaskIds()) { if (!activeTaskId.equals(taskId) && activeTaskId.getSanitizedRackId().equals(taskId.getSanitizedRackId())) { return true; } } return false; } private boolean hasTaskLeftOnSlave(SingularityTaskId taskId, String slaveId, SingularitySchedulerStateCache stateCache) { for (SingularityTaskId activeTaskId : stateCache.getActiveTaskIds()) { if (!activeTaskId.equals(taskId) && activeTaskId.getSanitizedHost().equals(taskId.getSanitizedHost())) { Optional<SingularityTask> maybeTask = taskManager.getTask(activeTaskId); if (maybeTask.isPresent() && slaveId.equals(maybeTask.get().getOffer().getSlaveId().getValue())) { return true; } } } return false; } }
/* * Copyright 2005 JBoss 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 org.drools.modelcompiler; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.drools.modelcompiler.domain.ChildFactComplex; import org.drools.modelcompiler.domain.ChildFactWithEnum1; import org.drools.modelcompiler.domain.ChildFactWithEnum2; import org.drools.modelcompiler.domain.ChildFactWithEnum3; import org.drools.modelcompiler.domain.ChildFactWithFirings1; import org.drools.modelcompiler.domain.ChildFactWithId1; import org.drools.modelcompiler.domain.ChildFactWithId2; import org.drools.modelcompiler.domain.ChildFactWithId3; import org.drools.modelcompiler.domain.ChildFactWithObject; import org.drools.modelcompiler.domain.EnumFact1; import org.drools.modelcompiler.domain.EnumFact2; import org.drools.modelcompiler.domain.InterfaceAsEnum; import org.drools.modelcompiler.domain.RootFact; import org.junit.Test; import org.kie.api.runtime.KieSession; import static org.junit.Assert.assertEquals; public class ComplexRulesTest extends BaseModelTest { public ComplexRulesTest( RUN_TYPE testRunType ) { super( testRunType ); } @Test public void test1() { String str = "import " + EnumFact1.class.getCanonicalName() + ";\n" + "import " + EnumFact2.class.getCanonicalName() + ";\n" + "import " + RootFact.class.getCanonicalName() + ";\n" + "import " + ChildFactWithId1.class.getCanonicalName() + ";\n" + "import " + ChildFactWithId2.class.getCanonicalName() + ";\n" + "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + ChildFactWithId3.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum1.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum2.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum3.class.getCanonicalName() + ";\n" + "import " + ChildFactComplex.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + "global BusinessFunctions functions;\n" + "global java.util.List list;\n" + "rule \"R1\"\n" + " dialect \"java\"\n" + "when\n" + " $rootFact : RootFact( ) \n" + " $childFact1 : ChildFactWithId1( parentId == $rootFact.id ) \n" + " $childFact2 : ChildFactWithId2( parentId == $childFact1.id ) \n" + " $childFactWithEnum1 : ChildFactWithEnum1( parentId == $childFact2.id, enumValue == EnumFact1.FIRST ) \n" + " $childFactWithObject : ChildFactWithObject( parentId == $childFact2.id ) \n" + " $childFactWithEnum2 : ChildFactWithEnum2( parentId == $childFactWithObject.id, enumValue == EnumFact2.SECOND ) \n" + " $countOf : Long( $result : intValue > 0) from accumulate (\n" + " $rootFact_acc : RootFact( ) \n" + " and $childFact1_acc : ChildFactWithId1( parentId == $rootFact_acc.id ) \n" + " and $childFact3_acc : ChildFactWithId3( parentId == $childFact1_acc.id ) \n" + " and $childFactComplex_acc : ChildFactComplex( parentId == $childFact3_acc.id, \n" + " travelDocReady == true, \n" + " enum1Value not in (EnumFact1.FIRST, EnumFact1.THIRD, EnumFact1.FOURTH), \n" + " $childFactComplex_id : id, \n" + " enum2Value == EnumFact2.FIRST, \n" + " cheeseReady != true ) \n" + " ;count($childFactComplex_id))\n" + " exists ( $childFactWithEnum3_ex : ChildFactWithEnum3( parentId == $childFact1.id, enumValue == EnumFact1.FIRST ) )\n" + " not ( \n" + " $policySet_not : ChildFactWithObject ( " + " id == $childFactWithObject.id , \n" + " eval(true == functions.arrayContainsInstanceWithParameters((Object[])$policySet_not.getObjectValue(), new Object[]{\"getMessageId\", \"42103\"}))\n" + " )\n" + " )\n" + " then\n" + " list.add($result);\n" + "end\n"; testComplexRule(str); } @Test public void testNotWithEval() { String str = "import " + EnumFact1.class.getCanonicalName() + ";\n" + "import " + EnumFact2.class.getCanonicalName() + ";\n" + "import " + RootFact.class.getCanonicalName() + ";\n" + "import " + ChildFactWithId1.class.getCanonicalName() + ";\n" + "import " + ChildFactWithId2.class.getCanonicalName() + ";\n" + "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + ChildFactWithId3.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum1.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum2.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum3.class.getCanonicalName() + ";\n" + "import " + ChildFactComplex.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + "global BusinessFunctions functions;\n" + "global java.util.List list;\n" + "rule \"R1\"\n" + " dialect \"java\"\n" + "when\n" + " $rootFact : RootFact( ) \n" + " $childFact1 : ChildFactWithId1( parentId == $rootFact.id ) \n" + " $childFact2 : ChildFactWithId2( parentId == $childFact1.id ) \n" + " $childFactWithEnum1 : ChildFactWithEnum1( parentId == $childFact2.id, enumValue == EnumFact1.FIRST ) \n" + " $childFactWithObject : ChildFactWithObject( parentId == $childFact2.id ) \n" + " $childFactWithEnum2 : ChildFactWithEnum2( parentId == $childFactWithObject.id, enumValue == EnumFact2.SECOND ) \n" + " $countOf : Long( $result : intValue > 0) from accumulate (\n" + " $rootFact_acc : RootFact( ) \n" + " and $childFact1_acc : ChildFactWithId1( parentId == $rootFact_acc.id ) \n" + " and $childFact3_acc : ChildFactWithId3( parentId == $childFact1_acc.id ) \n" + " and $childFactComplex_acc : ChildFactComplex( parentId == $childFact3_acc.id, \n" + " travelDocReady == true, \n" + " enum1Value not in (EnumFact1.FIRST, EnumFact1.THIRD, EnumFact1.FOURTH), \n" + " $childFactComplex_id : id, \n" + " enum2Value == EnumFact2.FIRST, \n" + " cheeseReady != true ) \n" + " ;count($childFactComplex_id))\n" + " exists ( $childFactWithEnum3_ex : ChildFactWithEnum3( parentId == $childFact1.id, enumValue == EnumFact1.FIRST ) )\n" + " not ( \n" + " $policySet_not : ChildFactWithObject ( " + " id == $childFactWithObject.id , \n" + " eval(true == functions.arrayContainsInstanceWithParameters((Object[])$policySet_not.getObjectValue(), new Object[]{\"getMessageId\", \"42103\"}))\n" + " ) and ChildFactWithId1() and eval(false)\n" + " )\n" + " then\n" + " list.add($result);\n" + "end\n"; testComplexRule(str); } private void testComplexRule(final String rule) { KieSession ksession = getKieSession( rule ); List<Integer> list = new ArrayList<>(); ksession.setGlobal( "list", list ); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new RootFact(1) ); ksession.insert( new ChildFactWithId1(2, 1) ); ksession.insert( new ChildFactWithId2(3, 2) ); ksession.insert( new ChildFactWithEnum1(4, 3, EnumFact1.FIRST) ); ksession.insert( new ChildFactWithObject(5, 3, new Object[0]) ); ksession.insert( new ChildFactWithEnum2(6, 5, EnumFact2.SECOND) ); ksession.insert( new ChildFactWithId3(7, 2) ); ksession.insert( new ChildFactComplex(8, 7, true, false, EnumFact1.SECOND, EnumFact2.FIRST) ); ksession.insert( new ChildFactWithEnum3(9, 2, EnumFact1.FIRST) ); assertEquals(1, ksession.fireAllRules()); assertEquals(1, list.size()); assertEquals(1, (int)list.get(0)); } @Test public void test2() { final String drl = " import org.drools.modelcompiler.domain.*;\n" + " rule \"R1\"\n" + " dialect \"java\"\n" + " when\n" + " $rootFact : RootFact( )\n" + " $childFact1 : ChildFactWithId1( parentId == $rootFact.id )\n" + " $childFact2 : ChildFactWithId2( parentId == $childFact1.id )\n" + " $childFact3 : ChildFactWithEnum1( \n" + " parentId == $childFact2.id, \n" + " enumValue == EnumFact1.FIRST, \n" + " $enumValue : enumValue )\n" + " $childFact4 : ChildFactWithFirings1( \n" + " parentId == $childFact1.id, \n" + " $evaluationName : evaluationName, \n" + " firings not contains \"R1\" )\n" + " then\n" + " $childFact4.setEvaluationName(String.valueOf($enumValue));\n" + " $childFact4.getFirings().add(\"R1\");\n" + " update($childFact4);\n" + " end\n"; KieSession ksession = getKieSession( drl ); int initialId = 1; final RootFact rootFact = new RootFact(initialId); final ChildFactWithId1 childFact1First = new ChildFactWithId1(initialId + 1, rootFact.getId()); final ChildFactWithId2 childFact2First = new ChildFactWithId2(initialId + 3, childFact1First.getId()); final ChildFactWithEnum1 childFact3First = new ChildFactWithEnum1(initialId + 4, childFact2First.getId(), EnumFact1.FIRST); final ChildFactWithFirings1 childFact4First = new ChildFactWithFirings1(initialId + 2, childFact1First.getId()); ksession.insert(rootFact); ksession.insert(childFact1First); ksession.insert(childFact2First); ksession.insert(childFact3First); ksession.insert(childFact4First); assertEquals(1, ksession.fireAllRules()); assertEquals(0, ksession.fireAllRules()); } @Test public void test3() { String str = "import " + RootFact.class.getCanonicalName() + ";\n" + "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + ChildFactComplex.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + "global BusinessFunctions functions;\n" + "global java.util.List list;\n" + "rule \"R1\"\n" + " dialect \"java\"\n" + "when\n" + " $childFactWithObject : ChildFactWithObject( $idAsShort : idAsShort ) \n" + " $countOf : Long( $result : intValue > 0) from accumulate (\n" + " $rootFact_acc : RootFact( ) \n" + " and $childFactComplex_acc : ChildFactComplex( \n" + " $childFactComplex_id : id, \n" + " idAsShort == $idAsShort ) \n" + " ;count($childFactComplex_id))\n" + " then\n" + " list.add($result);\n" + "end\n"; KieSession ksession = getKieSession( str ); List<Integer> list = new ArrayList<>(); ksession.setGlobal( "list", list ); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new RootFact(1) ); ksession.insert( new ChildFactWithObject(5, 3, new Object[0]) ); ksession.insert( new ChildFactComplex(5, 7, true, false, EnumFact1.SECOND, EnumFact2.FIRST) ); assertEquals(1, ksession.fireAllRules()); assertEquals(1, list.size()); assertEquals(1, (int)list.get(0)); } @Test public void test4() { String str = "import " + RootFact.class.getCanonicalName() + ";\n" + "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + ChildFactComplex.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + "global BusinessFunctions functions;\n" + "global java.util.List list;\n" + "rule \"R1\"\n" + " dialect \"java\"\n" + "when\n" + " $childFactWithObject : ChildFactWithObject( $idAsShort : idAsShort ) \n" + " $countOf : Long( $result : intValue > 0) from accumulate (\n" + " $childFactComplex_acc : ChildFactComplex( \n" + " $childFactComplex_id : id, \n" + " idAsShort == $idAsShort ) \n" + " ;count($childFactComplex_id))\n" + " then\n" + " list.add($result);\n" + "end\n"; KieSession ksession = getKieSession( str ); List<Integer> list = new ArrayList<>(); ksession.setGlobal( "list", list ); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 3, new Object[0]) ); ksession.insert( new ChildFactComplex(5, 7, true, false, EnumFact1.SECOND, EnumFact2.FIRST) ); assertEquals(1, ksession.fireAllRules()); assertEquals(1, list.size()); assertEquals(1, (int)list.get(0)); } @Test public void testEnum() { String str = "import " + EnumFact1.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum1.class.getCanonicalName() + ";\n" + "rule R when\n" + "\n" + " $factWithEnum : ChildFactWithEnum1( parentId == 3, enumValue == EnumFact1.FIRST ) \n" + " then\n" + "end\n"; KieSession ksession = getKieSession( str ); ksession.insert( new ChildFactWithEnum1(1, 3, EnumFact1.FIRST) ); assertEquals(1, ksession.fireAllRules()); } @Test public void testNotInEnum() { String str = "import " + EnumFact1.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum1.class.getCanonicalName() + ";\n" + "rule R when\n" + "\n" + " $factWithEnum : ChildFactWithEnum1( enumValue not in (EnumFact1.FIRST, EnumFact1.THIRD, EnumFact1.FOURTH) ) \n" + " then\n" + "end\n"; KieSession ksession = getKieSession( str ); ksession.insert( new ChildFactWithEnum1(1, 3, EnumFact1.SECOND) ); assertEquals(1, ksession.fireAllRules()); } @Test public void testNotInInterfaceAsEnum() { String str = "import " + InterfaceAsEnum.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum1.class.getCanonicalName() + ";\n" + "rule R when\n" + "\n" + " $factWithEnum : ChildFactWithEnum1( enumValueFromInterface not in (InterfaceAsEnum.FIRST, InterfaceAsEnum.THIRD, InterfaceAsEnum.FOURTH) ) \n" + " then\n" + "end\n"; KieSession ksession = getKieSession( str ); ksession.insert( new ChildFactWithEnum1(1, 3, EnumFact1.SECOND) ); assertEquals(1, ksession.fireAllRules()); } @Test public void testConstraintWithFunctionUsingThis() { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + "global BusinessFunctions functions;\n" + "rule R when\n" + " $childFactWithObject : ChildFactWithObject ( id == 5\n" + " , !functions.arrayContainsInstanceWithParameters((Object[])this.getObjectValue(),\n" + " new Object[]{\"getMessageId\", \"42103\"})\n" + " )\n" + " then\n" + "end\n"; KieSession ksession = getKieSession( str ); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertEquals(1, ksession.fireAllRules()); } @Test public void testConstraintWithTernaryOperator() { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + "global BusinessFunctions functions;\n" + "rule R when\n" + " $s : String()\n" + " $childFactWithObject : ChildFactWithObject ( id == 5\n" + " , !functions.arrayContainsInstanceWithParameters((Object[])this.getObjectValue(),\n" + " new Object[]{\"getMessageId\", ($s != null ? $s : \"42103\")})\n" + " )\n" + " then\n" + "end\n"; KieSession ksession = getKieSession( str ); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( "test" ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertEquals(1, ksession.fireAllRules()); } @Test public void testCastInConstraint() { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + "global BusinessFunctions functions;\n" + "rule R when\n" + " ChildFactWithObject ( ((Object[])objectValue).length == 0\n )\n" + " then\n" + "end\n"; KieSession ksession = getKieSession( str ); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertEquals(1, ksession.fireAllRules()); } @Test public void testConstraintWithFunctionAndStringConcatenation() { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + "global BusinessFunctions functions;\n" + "rule R when\n" + "\n" + " $childFactWithObject : ChildFactWithObject ( id == 5\n" + " , !functions.arrayContainsInstanceWithParameters((Object[])objectValue,\n" + " new Object[]{\"getMessageId\", \"\" + id})\n" + " )\n" + " then\n" + "end\n"; KieSession ksession = getKieSession( str ); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertEquals(1, ksession.fireAllRules()); } @Test public void testEvalWithFunction() { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + "global BusinessFunctions functions;\n" + "rule R when\n" + "\n" + " $childFactWithObject : ChildFactWithObject ( id == 5\n" + " , eval(false == functions.arrayContainsInstanceWithParameters((Object[])$childFactWithObject.getObjectValue(),\n" + " new Object[]{\"getMessageId\", \"42103\"}))\n" + " )\n" + " then\n" + "end\n"; KieSession ksession = getKieSession( str ); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertEquals(1, ksession.fireAllRules()); } @Test public void testEqualOnShortField() { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + "\n" + " ChildFactWithObject( idAsShort == 5 )\n" + " then\n" + "end\n"; KieSession ksession = getKieSession( str ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertEquals(1, ksession.fireAllRules()); } @Test public void testGreaterOnShortField() { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + "\n" + " ChildFactWithObject( idAsShort > 0 )\n" + " then\n" + "end\n"; KieSession ksession = getKieSession( str ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertEquals(1, ksession.fireAllRules()); } @Test public void testBooleanField() { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + "\n" + " ChildFactWithObject( idIsEven == false )\n" + " then\n" + "end\n"; KieSession ksession = getKieSession( str ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertEquals(1, ksession.fireAllRules()); } @Test public void testConsequenceThrowingException() { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + "global BusinessFunctions functions;\n" + "rule R when\n" + "\n" + " $c : ChildFactWithObject( idIsEven == false )\n" + " then\n" + " functions.doSomethingRisky($c);" + "end\n"; KieSession ksession = getKieSession( str ); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertEquals(1, ksession.fireAllRules()); } @Test public void testCompareDate() { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + "\n" + " $c: ChildFactWithObject( )\n" + " ChildFactWithObject( date > $c.date )\n" + " then\n" + "end\n"; KieSession ksession = getKieSession( str ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); ksession.insert( new ChildFactWithObject(6, 1, new Object[0]) ); assertEquals(1, ksession.fireAllRules()); } @Test public void testCompareDateWithString() { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + "\n" + " ChildFactWithObject( date < \"10-Jul-1974\" )\n" + " then\n" + "end\n"; KieSession ksession = getKieSession( str ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertEquals(1, ksession.fireAllRules()); } @Test public void test2UpperCaseProp() { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + "\n" + " $c: ChildFactWithObject( )\n" + " ChildFactWithObject( VAr == $c.VAr )\n" + " then\n" + "end\n"; KieSession ksession = getKieSession( str ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertEquals(1, ksession.fireAllRules()); } public static class BusinessFunctions { public boolean arrayContainsInstanceWithParameters(Object[] a1, Object[] a2) { return false; } public void doSomethingRisky(Object arg) throws Exception { } } public static class ListContainer { public List<String> getList() { return Arrays.asList("ciao"); } } @Test public void testNameClashBetweenAttributeAndGlobal() { String str = "import " + ListContainer.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + "rule R when\n" + " $l : ListContainer( list contains \"ciao\" )\n" + "then\n" + " list.add($l);" + "end\n"; KieSession ksession = getKieSession( str ); List list = new ArrayList(); ksession.setGlobal( "list", list ); ksession.insert( new ListContainer() ); ksession.fireAllRules(); assertEquals(1, list.size()); } public static class Primitives { public char[] getCharArray() { return new char[0]; } } @Test public void testPrimitiveArray() { String str = "import " + Primitives.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + "rule R when\n" + " Primitives( $c : charArray )\n" + "then\n" + " list.add($c);" + "end\n"; KieSession ksession = getKieSession( str ); List list = new ArrayList(); ksession.setGlobal( "list", list ); ksession.insert( new Primitives() ); ksession.fireAllRules(); assertEquals(1, list.size()); } @Test public void testUseConstructorInConstraint() { // DROOLS-2990 String str = "rule R when\n" + " $s: Short()" + " $d: Double( this > new Double($s) )\n" + "then\n" + "end\n"; KieSession ksession = getKieSession( str ); ksession.insert( (short) 1 ); ksession.insert( 2.0 ); assertEquals(1, ksession.fireAllRules()); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.messy.tests; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptService.ScriptType; import org.elasticsearch.script.groovy.GroovyPlugin; import org.elasticsearch.search.aggregations.bucket.global.Global; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.metrics.AbstractNumericTestCase; import org.elasticsearch.search.aggregations.metrics.avg.Avg; import org.junit.Test; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.search.aggregations.AggregationBuilders.avg; import static org.elasticsearch.search.aggregations.AggregationBuilders.global; import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; /** * */ public class AvgTests extends AbstractNumericTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Collections.singleton(GroovyPlugin.class); } @Override @Test public void testEmptyAggregation() throws Exception { SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx") .setQuery(matchAllQuery()) .addAggregation(histogram("histo").field("value").interval(1l).minDocCount(0).subAggregation(avg("avg"))) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(2l)); Histogram histo = searchResponse.getAggregations().get("histo"); assertThat(histo, notNullValue()); Histogram.Bucket bucket = histo.getBuckets().get(1); assertThat(bucket, notNullValue()); Avg avg = bucket.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(Double.isNaN(avg.getValue()), is(true)); } @Override @Test public void testUnmapped() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx_unmapped") .setQuery(matchAllQuery()) .addAggregation(avg("avg").field("value")) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(0l)); Avg avg = searchResponse.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(avg.getValue(), equalTo(Double.NaN)); } @Override @Test public void testSingleValuedField() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(avg("avg").field("value")) .execute().actionGet(); assertHitCount(searchResponse, 10); Avg avg = searchResponse.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(avg.getValue(), equalTo((double) (1+2+3+4+5+6+7+8+9+10) / 10)); } @Override @Test public void testSingleValuedField_getProperty() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery()) .addAggregation(global("global").subAggregation(avg("avg").field("value"))).execute().actionGet(); assertHitCount(searchResponse, 10); Global global = searchResponse.getAggregations().get("global"); assertThat(global, notNullValue()); assertThat(global.getName(), equalTo("global")); assertThat(global.getDocCount(), equalTo(10l)); assertThat(global.getAggregations(), notNullValue()); assertThat(global.getAggregations().asMap().size(), equalTo(1)); Avg avg = global.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); double expectedAvgValue = (double) (1+2+3+4+5+6+7+8+9+10) / 10; assertThat(avg.getValue(), equalTo(expectedAvgValue)); assertThat((Avg) global.getProperty("avg"), equalTo(avg)); assertThat((double) global.getProperty("avg.value"), equalTo(expectedAvgValue)); assertThat((double) avg.getProperty("value"), equalTo(expectedAvgValue)); } @Override public void testSingleValuedField_PartiallyUnmapped() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx", "idx_unmapped") .setQuery(matchAllQuery()) .addAggregation(avg("avg").field("value")) .execute().actionGet(); assertHitCount(searchResponse, 10); Avg avg = searchResponse.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(avg.getValue(), equalTo((double) (1+2+3+4+5+6+7+8+9+10) / 10)); } @Override @Test public void testSingleValuedField_WithValueScript() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(avg("avg").field("value").script(new Script("_value + 1"))) .execute().actionGet(); assertHitCount(searchResponse, 10); Avg avg = searchResponse.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(avg.getValue(), equalTo((double) (2+3+4+5+6+7+8+9+10+11) / 10)); } @Override @Test public void testSingleValuedField_WithValueScript_WithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("inc", 1); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(avg("avg").field("value").script(new Script("_value + inc", ScriptType.INLINE, null, params))) .execute().actionGet(); assertHitCount(searchResponse, 10); Avg avg = searchResponse.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(avg.getValue(), equalTo((double) (2+3+4+5+6+7+8+9+10+11) / 10)); } public void testSingleValuedField_WithFormatter() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery()) .addAggregation(avg("avg").format("#").field("value")).execute().actionGet(); assertHitCount(searchResponse, 10); Avg avg = searchResponse.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(avg.getValue(), equalTo((double) (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10) / 10)); assertThat(avg.getValueAsString(), equalTo("6")); } @Override @Test public void testMultiValuedField() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(avg("avg").field("values")) .execute().actionGet(); assertHitCount(searchResponse, 10); Avg avg = searchResponse.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(avg.getValue(), equalTo((double) (2+3+3+4+4+5+5+6+6+7+7+8+8+9+9+10+10+11+11+12) / 20)); } @Override @Test public void testMultiValuedField_WithValueScript() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(avg("avg").field("values").script(new Script("_value + 1"))) .execute().actionGet(); assertHitCount(searchResponse, 10); Avg avg = searchResponse.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(avg.getValue(), equalTo((double) (3+4+4+5+5+6+6+7+7+8+8+9+9+10+10+11+11+12+12+13) / 20)); } @Override @Test public void testMultiValuedField_WithValueScript_WithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("inc", 1); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(avg("avg").field("values").script(new Script("_value + inc", ScriptType.INLINE, null, params))) .execute().actionGet(); assertHitCount(searchResponse, 10); Avg avg = searchResponse.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(avg.getValue(), equalTo((double) (3+4+4+5+5+6+6+7+7+8+8+9+9+10+10+11+11+12+12+13) / 20)); } @Override @Test public void testScript_SingleValued() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(avg("avg").script(new Script("doc['value'].value"))) .execute().actionGet(); assertHitCount(searchResponse, 10); Avg avg = searchResponse.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(avg.getValue(), equalTo((double) (1+2+3+4+5+6+7+8+9+10) / 10)); } @Override @Test public void testScript_SingleValued_WithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("inc", 1); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(avg("avg").script(new Script("doc['value'].value + inc", ScriptType.INLINE, null, params))) .execute().actionGet(); assertHitCount(searchResponse, 10); Avg avg = searchResponse.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(avg.getValue(), equalTo((double) (2+3+4+5+6+7+8+9+10+11) / 10)); } @Override @Test public void testScript_ExplicitSingleValued_WithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("inc", 1); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(avg("avg").script(new Script("doc['value'].value + inc", ScriptType.INLINE, null, params))) .execute().actionGet(); assertHitCount(searchResponse, 10); Avg avg = searchResponse.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(avg.getValue(), equalTo((double) (2+3+4+5+6+7+8+9+10+11) / 10)); } @Override @Test public void testScript_MultiValued() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(avg("avg").script(new Script("[ doc['value'].value, doc['value'].value + 1 ]"))) .execute().actionGet(); assertHitCount(searchResponse, 10); Avg avg = searchResponse.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(avg.getValue(), equalTo((double) (1+2+2+3+3+4+4+5+5+6+6+7+7+8+8+9+9+10+10+11) / 20)); } @Override @Test public void testScript_ExplicitMultiValued() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(avg("avg").script(new Script("[ doc['value'].value, doc['value'].value + 1 ]"))) .execute().actionGet(); assertHitCount(searchResponse, 10); Avg avg = searchResponse.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(avg.getValue(), equalTo((double) (1+2+2+3+3+4+4+5+5+6+6+7+7+8+8+9+9+10+10+11) / 20)); } @Override @Test public void testScript_MultiValued_WithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("inc", 1); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( avg("avg").script(new Script("[ doc['value'].value, doc['value'].value + inc ]", ScriptType.INLINE, null, params))) .execute().actionGet(); assertHitCount(searchResponse, 10); Avg avg = searchResponse.getAggregations().get("avg"); assertThat(avg, notNullValue()); assertThat(avg.getName(), equalTo("avg")); assertThat(avg.getValue(), equalTo((double) (1+2+2+3+3+4+4+5+5+6+6+7+7+8+8+9+9+10+10+11) / 20)); } }
/** * 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.hadoop.yarn.api; import java.io.IOException; import org.apache.hadoop.classification.InterfaceAudience.Public; import org.apache.hadoop.classification.InterfaceStability.Stable; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.io.retry.Idempotent; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetClusterMetricsRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetClusterMetricsResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodeLabelsRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodeLabelsResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodesRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodesResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetLabelsToNodesRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetLabelsToNodesResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetNodesToLabelsRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetNodesToLabelsResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetQueueInfoRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetQueueInfoResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetQueueUserAclsInfoRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetQueueUserAclsInfoResponse; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationResponse; import org.apache.hadoop.yarn.api.protocolrecords.MoveApplicationAcrossQueuesRequest; import org.apache.hadoop.yarn.api.protocolrecords.MoveApplicationAcrossQueuesResponse; import org.apache.hadoop.yarn.api.protocolrecords.ReservationDeleteRequest; import org.apache.hadoop.yarn.api.protocolrecords.ReservationDeleteResponse; import org.apache.hadoop.yarn.api.protocolrecords.ReservationSubmissionRequest; import org.apache.hadoop.yarn.api.protocolrecords.ReservationSubmissionResponse; import org.apache.hadoop.yarn.api.protocolrecords.ReservationUpdateRequest; import org.apache.hadoop.yarn.api.protocolrecords.ReservationUpdateResponse; import org.apache.hadoop.yarn.api.protocolrecords.SubmitApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.SubmitApplicationResponse; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.NodeReport; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.api.records.YarnClusterMetrics; import org.apache.hadoop.yarn.exceptions.ApplicationNotFoundException; import org.apache.hadoop.yarn.exceptions.InvalidResourceRequestException; import org.apache.hadoop.yarn.exceptions.YarnException; /** * <p>The protocol between clients and the <code>ResourceManager</code> * to submit/abort jobs and to get information on applications, cluster metrics, * nodes, queues and ACLs.</p> */ @Public @Stable public interface ApplicationClientProtocol extends ApplicationBaseProtocol { /** * <p>The interface used by clients to obtain a new {@link ApplicationId} for * submitting new applications.</p> * * <p>The <code>ResourceManager</code> responds with a new, monotonically * increasing, {@link ApplicationId} which is used by the client to submit * a new application.</p> * * <p>The <code>ResourceManager</code> also responds with details such * as maximum resource capabilities in the cluster as specified in * {@link GetNewApplicationResponse}.</p> * * @param request request to get a new <code>ApplicationId</code> * @return response containing the new <code>ApplicationId</code> to be used * to submit an application * @throws YarnException * @throws IOException * @see #submitApplication(SubmitApplicationRequest) */ @Public @Stable @Idempotent public GetNewApplicationResponse getNewApplication( GetNewApplicationRequest request) throws YarnException, IOException; /** * <p>The interface used by clients to submit a new application to the * <code>ResourceManager.</code></p> * * <p>The client is required to provide details such as queue, * {@link Resource} required to run the <code>ApplicationMaster</code>, * the equivalent of {@link ContainerLaunchContext} for launching * the <code>ApplicationMaster</code> etc. via the * {@link SubmitApplicationRequest}.</p> * * <p>Currently the <code>ResourceManager</code> sends an immediate (empty) * {@link SubmitApplicationResponse} on accepting the submission and throws * an exception if it rejects the submission. However, this call needs to be * followed by {@link #getApplicationReport(GetApplicationReportRequest)} * to make sure that the application gets properly submitted - obtaining a * {@link SubmitApplicationResponse} from ResourceManager doesn't guarantee * that RM 'remembers' this application beyond failover or restart. If RM * failover or RM restart happens before ResourceManager saves the * application's state successfully, the subsequent * {@link #getApplicationReport(GetApplicationReportRequest)} will throw * a {@link ApplicationNotFoundException}. The Clients need to re-submit * the application with the same {@link ApplicationSubmissionContext} when * it encounters the {@link ApplicationNotFoundException} on the * {@link #getApplicationReport(GetApplicationReportRequest)} call.</p> * * <p>During the submission process, it checks whether the application * already exists. If the application exists, it will simply return * SubmitApplicationResponse</p> * * <p> In secure mode,the <code>ResourceManager</code> verifies access to * queues etc. before accepting the application submission.</p> * * @param request request to submit a new application * @return (empty) response on accepting the submission * @throws YarnException * @throws IOException * @see #getNewApplication(GetNewApplicationRequest) */ @Public @Stable @Idempotent public SubmitApplicationResponse submitApplication( SubmitApplicationRequest request) throws YarnException, IOException; /** * <p>The interface used by clients to request the * <code>ResourceManager</code> to abort submitted application.</p> * * <p>The client, via {@link KillApplicationRequest} provides the * {@link ApplicationId} of the application to be aborted.</p> * * <p> In secure mode,the <code>ResourceManager</code> verifies access to the * application, queue etc. before terminating the application.</p> * * <p>Currently, the <code>ResourceManager</code> returns an empty response * on success and throws an exception on rejecting the request.</p> * * @param request request to abort a submitted application * @return <code>ResourceManager</code> returns an empty response * on success and throws an exception on rejecting the request * @throws YarnException * @throws IOException * @see #getQueueUserAcls(GetQueueUserAclsInfoRequest) */ @Public @Stable @Idempotent public KillApplicationResponse forceKillApplication( KillApplicationRequest request) throws YarnException, IOException; /** * <p>The interface used by clients to get metrics about the cluster from * the <code>ResourceManager</code>.</p> * * <p>The <code>ResourceManager</code> responds with a * {@link GetClusterMetricsResponse} which includes the * {@link YarnClusterMetrics} with details such as number of current * nodes in the cluster.</p> * * @param request request for cluster metrics * @return cluster metrics * @throws YarnException * @throws IOException */ @Public @Stable @Idempotent public GetClusterMetricsResponse getClusterMetrics( GetClusterMetricsRequest request) throws YarnException, IOException; /** * <p>The interface used by clients to get a report of all nodes * in the cluster from the <code>ResourceManager</code>.</p> * * <p>The <code>ResourceManager</code> responds with a * {@link GetClusterNodesResponse} which includes the * {@link NodeReport} for all the nodes in the cluster.</p> * * @param request request for report on all nodes * @return report on all nodes * @throws YarnException * @throws IOException */ @Public @Stable @Idempotent public GetClusterNodesResponse getClusterNodes( GetClusterNodesRequest request) throws YarnException, IOException; /** * <p>The interface used by clients to get information about <em>queues</em> * from the <code>ResourceManager</code>.</p> * * <p>The client, via {@link GetQueueInfoRequest}, can ask for details such * as used/total resources, child queues, running applications etc.</p> * * <p> In secure mode,the <code>ResourceManager</code> verifies access before * providing the information.</p> * * @param request request to get queue information * @return queue information * @throws YarnException * @throws IOException */ @Public @Stable @Idempotent public GetQueueInfoResponse getQueueInfo( GetQueueInfoRequest request) throws YarnException, IOException; /** * <p>The interface used by clients to get information about <em>queue * acls</em> for <em>current user</em> from the <code>ResourceManager</code>. * </p> * * <p>The <code>ResourceManager</code> responds with queue acls for all * existing queues.</p> * * @param request request to get queue acls for <em>current user</em> * @return queue acls for <em>current user</em> * @throws YarnException * @throws IOException */ @Public @Stable @Idempotent public GetQueueUserAclsInfoResponse getQueueUserAcls( GetQueueUserAclsInfoRequest request) throws YarnException, IOException; /** * Move an application to a new queue. * * @param request the application ID and the target queue * @return an empty response * @throws YarnException * @throws IOException */ @Public @Unstable @Idempotent public MoveApplicationAcrossQueuesResponse moveApplicationAcrossQueues( MoveApplicationAcrossQueuesRequest request) throws YarnException, IOException; /** * <p> * The interface used by clients to submit a new reservation to the * {@code ResourceManager}. * </p> * * <p> * The client packages all details of its request in a * {@link ReservationSubmissionRequest} object. This contains information * about the amount of capacity, temporal constraints, and concurrency needs. * Furthermore, the reservation might be composed of multiple stages, with * ordering dependencies among them. * </p> * * <p> * In order to respond, a new admission control component in the * {@code ResourceManager} performs an analysis of the resources that have * been committed over the period of time the user is requesting, verify that * the user requests can be fulfilled, and that it respect a sharing policy * (e.g., {@code CapacityOverTimePolicy}). Once it has positively determined * that the ReservationSubmissionRequest is satisfiable the * {@code ResourceManager} answers with a * {@link ReservationSubmissionResponse} that include a non-null * {@link ReservationId}. Upon failure to find a valid allocation the response * is an exception with the reason. * * On application submission the client can use this {@link ReservationId} to * obtain access to the reserved resources. * </p> * * <p> * The system guarantees that during the time-range specified by the user, the * reservationID will be corresponding to a valid reservation. The amount of * capacity dedicated to such queue can vary overtime, depending of the * allocation that has been determined. But it is guaranteed to satisfy all * the constraint expressed by the user in the * {@link ReservationSubmissionRequest}. * </p> * * @param request the request to submit a new Reservation * @return response the {@link ReservationId} on accepting the submission * @throws YarnException if the request is invalid or reservation cannot be * created successfully * @throws IOException * */ @Public @Unstable public ReservationSubmissionResponse submitReservation( ReservationSubmissionRequest request) throws YarnException, IOException; /** * <p> * The interface used by clients to update an existing Reservation. This is * referred to as a re-negotiation process, in which a user that has * previously submitted a Reservation. * </p> * * <p> * The allocation is attempted by virtually substituting all previous * allocations related to this Reservation with new ones, that satisfy the new * {@link ReservationUpdateRequest}. Upon success the previous allocation is * substituted by the new one, and on failure (i.e., if the system cannot find * a valid allocation for the updated request), the previous allocation * remains valid. * * The {@link ReservationId} is not changed, and applications currently * running within this reservation will automatically receive the resources * based on the new allocation. * </p> * * @param request to update an existing Reservation (the ReservationRequest * should refer to an existing valid {@link ReservationId}) * @return response empty on successfully updating the existing reservation * @throws YarnException if the request is invalid or reservation cannot be * updated successfully * @throws IOException * */ @Public @Unstable public ReservationUpdateResponse updateReservation( ReservationUpdateRequest request) throws YarnException, IOException; /** * <p> * The interface used by clients to remove an existing Reservation. * * Upon deletion of a reservation applications running with this reservation, * are automatically downgraded to normal jobs running without any dedicated * reservation. * </p> * * @param request to remove an existing Reservation (the ReservationRequest * should refer to an existing valid {@link ReservationId}) * @return response empty on successfully deleting the existing reservation * @throws YarnException if the request is invalid or reservation cannot be * deleted successfully * @throws IOException * */ @Public @Unstable public ReservationDeleteResponse deleteReservation( ReservationDeleteRequest request) throws YarnException, IOException; /** * <p> * The interface used by client to get node to labels mappings in existing cluster * </p> * * @param request * @return node to labels mappings * @throws YarnException * @throws IOException */ @Public @Unstable public GetNodesToLabelsResponse getNodeToLabels( GetNodesToLabelsRequest request) throws YarnException, IOException; /** * <p> * The interface used by client to get labels to nodes mappings * in existing cluster * </p> * * @param request * @return labels to nodes mappings * @throws YarnException * @throws IOException */ @Public @Unstable public GetLabelsToNodesResponse getLabelsToNodes( GetLabelsToNodesRequest request) throws YarnException, IOException; /** * <p> * The interface used by client to get node labels in the cluster * </p> * * @param request to get node labels collection of this cluster * @return node labels collection of this cluster * @throws YarnException * @throws IOException */ @Public @Unstable public GetClusterNodeLabelsResponse getClusterNodeLabels( GetClusterNodeLabelsRequest request) throws YarnException, IOException; }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.alexaforbusiness.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/alexaforbusiness-2017-11-09/ListTags" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListTagsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The ARN of the specified resource for which to list tags. * </p> */ private String arn; /** * <p> * An optional token returned from a prior request. Use this token for pagination of results from this action. If * this parameter is specified, the response includes only results beyond the token, up to the value specified by * <code>MaxResults</code>. * </p> */ private String nextToken; /** * <p> * The maximum number of results to include in the response. If more results exist than the specified * <code>MaxResults</code> value, a token is included in the response so that the remaining results can be * retrieved. * </p> */ private Integer maxResults; /** * <p> * The ARN of the specified resource for which to list tags. * </p> * * @param arn * The ARN of the specified resource for which to list tags. */ public void setArn(String arn) { this.arn = arn; } /** * <p> * The ARN of the specified resource for which to list tags. * </p> * * @return The ARN of the specified resource for which to list tags. */ public String getArn() { return this.arn; } /** * <p> * The ARN of the specified resource for which to list tags. * </p> * * @param arn * The ARN of the specified resource for which to list tags. * @return Returns a reference to this object so that method calls can be chained together. */ public ListTagsRequest withArn(String arn) { setArn(arn); return this; } /** * <p> * An optional token returned from a prior request. Use this token for pagination of results from this action. If * this parameter is specified, the response includes only results beyond the token, up to the value specified by * <code>MaxResults</code>. * </p> * * @param nextToken * An optional token returned from a prior request. Use this token for pagination of results from this * action. If this parameter is specified, the response includes only results beyond the token, up to the * value specified by <code>MaxResults</code>. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * An optional token returned from a prior request. Use this token for pagination of results from this action. If * this parameter is specified, the response includes only results beyond the token, up to the value specified by * <code>MaxResults</code>. * </p> * * @return An optional token returned from a prior request. Use this token for pagination of results from this * action. If this parameter is specified, the response includes only results beyond the token, up to the * value specified by <code>MaxResults</code>. */ public String getNextToken() { return this.nextToken; } /** * <p> * An optional token returned from a prior request. Use this token for pagination of results from this action. If * this parameter is specified, the response includes only results beyond the token, up to the value specified by * <code>MaxResults</code>. * </p> * * @param nextToken * An optional token returned from a prior request. Use this token for pagination of results from this * action. If this parameter is specified, the response includes only results beyond the token, up to the * value specified by <code>MaxResults</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public ListTagsRequest withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * <p> * The maximum number of results to include in the response. If more results exist than the specified * <code>MaxResults</code> value, a token is included in the response so that the remaining results can be * retrieved. * </p> * * @param maxResults * The maximum number of results to include in the response. If more results exist than the specified * <code>MaxResults</code> value, a token is included in the response so that the remaining results can be * retrieved. */ public void setMaxResults(Integer maxResults) { this.maxResults = maxResults; } /** * <p> * The maximum number of results to include in the response. If more results exist than the specified * <code>MaxResults</code> value, a token is included in the response so that the remaining results can be * retrieved. * </p> * * @return The maximum number of results to include in the response. If more results exist than the specified * <code>MaxResults</code> value, a token is included in the response so that the remaining results can be * retrieved. */ public Integer getMaxResults() { return this.maxResults; } /** * <p> * The maximum number of results to include in the response. If more results exist than the specified * <code>MaxResults</code> value, a token is included in the response so that the remaining results can be * retrieved. * </p> * * @param maxResults * The maximum number of results to include in the response. If more results exist than the specified * <code>MaxResults</code> value, a token is included in the response so that the remaining results can be * retrieved. * @return Returns a reference to this object so that method calls can be chained together. */ public ListTagsRequest withMaxResults(Integer maxResults) { setMaxResults(maxResults); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getArn() != null) sb.append("Arn: ").append(getArn()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()).append(","); if (getMaxResults() != null) sb.append("MaxResults: ").append(getMaxResults()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListTagsRequest == false) return false; ListTagsRequest other = (ListTagsRequest) obj; if (other.getArn() == null ^ this.getArn() == null) return false; if (other.getArn() != null && other.getArn().equals(this.getArn()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; if (other.getMaxResults() == null ^ this.getMaxResults() == null) return false; if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode()); return hashCode; } @Override public ListTagsRequest clone() { return (ListTagsRequest) super.clone(); } }
/* * Copyright (C) 2011 Everit Kft. (http://www.everit.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.everit.blobstore.jdbc.test; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.UncheckedIOException; import java.sql.Connection; import java.sql.SQLException; import java.util.HashMap; import javax.sql.XADataSource; import javax.transaction.xa.XAException; import org.apache.commons.dbcp2.managed.BasicManagedDataSource; import org.apache.geronimo.transaction.manager.GeronimoTransactionManager; import org.everit.blobstore.Blobstore; import org.everit.blobstore.cache.CachedBlobstore; import org.everit.blobstore.jdbc.JdbcBlobstore; import org.everit.blobstore.jdbc.JdbcBlobstoreConfiguration; import org.everit.blobstore.mem.MemBlobstore; import org.everit.blobstore.testbase.AbstractBlobstoreTest; import org.everit.blobstore.testbase.BlobstoreStressAndConsistencyTester; import org.everit.transaction.map.managed.ManagedMap; import org.everit.transaction.map.readcommited.ReadCommitedTransactionalMap; import org.everit.transaction.propagator.TransactionPropagator; import org.everit.transaction.propagator.jta.JTATransactionPropagator; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; import org.junit.runners.MethodSorters; import liquibase.Contexts; import liquibase.Liquibase; import liquibase.database.DatabaseConnection; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.LiquibaseException; import liquibase.resource.ClassLoaderResourceAccessor; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public abstract class AbstractJdbcBlobstoreTest extends AbstractBlobstoreTest { private static String nullOrNonEmptyString(final String text) { if (text == null) { return null; } if ("".equals(text.trim())) { return null; } return text; } protected JdbcBlobstore blobstore; protected BasicManagedDataSource managedDataSource; private boolean skipped = false; protected GeronimoTransactionManager transactionManager; protected TransactionPropagator transactionPropagator; @Override @After public void after() { if (this.skipped) { return; } super.after(); if (this.managedDataSource != null) { try { this.managedDataSource.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } @Before public void before() { DatabaseAccessParametersDTO databaseAccessParameters = resolveDatabaseAccessParameters(); this.skipped = databaseAccessParameters == null; Assume.assumeFalse("Tests are not enabled for database " + getDatabaseTestAttributes().dbName, this.skipped); try { this.transactionManager = new GeronimoTransactionManager(6000); } catch (XAException e) { throw new RuntimeException(e); } XADataSource xaDataSource = createXADataSource(databaseAccessParameters); this.managedDataSource = createManagedDataSource(this.transactionManager, xaDataSource); try (Connection connection = this.managedDataSource.getConnection()) { DatabaseConnection databaseConnection = new JdbcConnection(connection); Liquibase liquibase = new Liquibase( "META-INF/liquibase/org.everit.blobstore.jdbc.changelog.xml", new ClassLoaderResourceAccessor(), databaseConnection); String sqlOutputFolder = System.getProperty("blobstore.sql.outputFolder"); if (sqlOutputFolder != null) { File folder = new File(sqlOutputFolder); folder.mkdirs(); File outputFile = new File(folder, "blobstore-" + getDatabaseTestAttributes().dbName + ".sql"); try (FileWriter fw = new FileWriter(outputFile, true)) { liquibase.update((Contexts) null, fw); } catch (IOException e) { throw new UncheckedIOException(e); } } liquibase.update((Contexts) null); } catch (LiquibaseException | SQLException e) { try { this.managedDataSource.close(); } catch (SQLException e1) { e.addSuppressed(e1); } throw new RuntimeException(e); } this.blobstore = new JdbcBlobstore(this.managedDataSource); this.transactionPropagator = new JTATransactionPropagator(this.transactionManager); } protected JdbcBlobstoreConfiguration createJdbcBlobstoreConfiguration() { return null; } protected BasicManagedDataSource createManagedDataSource( final GeronimoTransactionManager transactionManager, final XADataSource xaDataSource) { BasicManagedDataSource lManagedDataSource = new BasicManagedDataSource(); lManagedDataSource.setTransactionManager(transactionManager); lManagedDataSource.setXaDataSourceInstance(xaDataSource); return lManagedDataSource; } protected abstract XADataSource createXADataSource(DatabaseAccessParametersDTO parameters); @Override protected Blobstore getBlobStore() { return this.blobstore; } protected abstract DatabaseTestAttributesDTO getDatabaseTestAttributes(); @Override protected TransactionPropagator getTransactionPropagator() { return this.transactionPropagator; } protected DatabaseAccessParametersDTO resolveDatabaseAccessParameters() { DatabaseTestAttributesDTO databaseTestAttributes = getDatabaseTestAttributes(); String sysPropPrefix = databaseTestAttributes.dbName + "."; boolean enabled = databaseTestAttributes.enabledByDefault; String enabledSysProp = System.getProperty(sysPropPrefix + "enabled"); if (enabledSysProp != null) { enabled = Boolean.parseBoolean(enabledSysProp); } if (!enabled) { return null; } DatabaseAccessParametersDTO defaultAccessParameters = databaseTestAttributes.defaultAccessParameters; DatabaseAccessParametersDTO result = new DatabaseAccessParametersDTO(); result.host = nullOrNonEmptyString( System.getProperty(sysPropPrefix + "host", defaultAccessParameters.host)); String portString = nullOrNonEmptyString(System.getProperty(sysPropPrefix + "port")); if (portString == null) { result.port = defaultAccessParameters.port; } else { result.port = Integer.parseInt(portString); } result.database = nullOrNonEmptyString( System.getProperty(sysPropPrefix + "database", defaultAccessParameters.database)); result.password = nullOrNonEmptyString( System.getProperty(sysPropPrefix + "password", defaultAccessParameters.password)); result.user = nullOrNonEmptyString( System.getProperty(sysPropPrefix + "user", defaultAccessParameters.user)); result.connectionAttributes = nullOrNonEmptyString(System.getProperty(sysPropPrefix + "connectionAttributes", defaultAccessParameters.connectionAttributes)); return result; } @Test @Ignore("Will be refactored later to be able to run stress tests easily with different" + " configurations") public void testConsistency() { System.out .println( "---------- Consistency Test (" + this.getClass().getSimpleName() + ") --------------"); MemBlobstore memBlobstore = new MemBlobstore(this.transactionManager); BlobstoreStressAndConsistencyTester.BlobstoreStressTestConfiguration testConfiguration = new BlobstoreStressAndConsistencyTester.BlobstoreStressTestConfiguration(); BlobstoreStressAndConsistencyTester.runStressTest(testConfiguration, this.transactionPropagator, memBlobstore, getBlobStore()); } @Test @Ignore("Will be refactored later to be able to run stress tests easily with different" + " configurations") public void testPerformance() { System.out .println( "---------- Performance Test (" + this.getClass().getSimpleName() + ") --------------"); BlobstoreStressAndConsistencyTester.BlobstoreStressTestConfiguration testConfiguration = new BlobstoreStressAndConsistencyTester.BlobstoreStressTestConfiguration(); testConfiguration.initialBlobNum = 100; testConfiguration.createActionChancePart = 5; testConfiguration.updateActionChancePart = 5; testConfiguration.deleteActionChancePart = 5; testConfiguration.readActionChancePart = 85; testConfiguration.iterationNumPerThread = 500; BlobstoreStressAndConsistencyTester.runStressTest(testConfiguration, this.transactionPropagator, getBlobStore()); } @Test public void testPerformanceWithCache() { System.out.println( "---------- Performance with Cache Test (" + this.getClass().getSimpleName() + ") --------------"); BlobstoreStressAndConsistencyTester.BlobstoreStressTestConfiguration testConfiguration = new BlobstoreStressAndConsistencyTester.BlobstoreStressTestConfiguration(); testConfiguration.initialBlobNum = 100; testConfiguration.createActionChancePart = 5; testConfiguration.updateActionChancePart = 5; testConfiguration.deleteActionChancePart = 5; testConfiguration.readActionChancePart = 85; testConfiguration.iterationNumPerThread = 500; CachedBlobstore cachedBlobstore = new CachedBlobstore(getBlobStore(), new ManagedMap<>(new ReadCommitedTransactionalMap<>(new HashMap<>()), this.transactionManager), 1024, this.transactionManager); BlobstoreStressAndConsistencyTester.runStressTest(testConfiguration, this.transactionPropagator, cachedBlobstore); } }
/* * Copyright (c) 2002-2008 LWJGL Project * 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 'LWJGL' 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 org.lwjgl.opengl; import org.lwjgl.util.generator.*; import org.lwjgl.util.generator.Alternate; import org.lwjgl.util.generator.opengl.*; import java.nio.*; public interface GL30 { // ---------------------------------------------------------- // ----------------------[ OpenGL 3.0 ]---------------------- // ---------------------------------------------------------- int GL_MAJOR_VERSION = 0x821B; int GL_MINOR_VERSION = 0x821C; int GL_NUM_EXTENSIONS = 0x821D; int GL_CONTEXT_FLAGS = 0x821E; int GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT = 0x0001; int GL_DEPTH_BUFFER = 0x8223; int GL_STENCIL_BUFFER = 0x8224; int GL_COMPRESSED_RED = 0x8225; int GL_COMPRESSED_RG = 0x8226; int GL_COMPARE_REF_TO_TEXTURE = ARB_shadow.GL_COMPARE_R_TO_TEXTURE_ARB; int GL_CLIP_DISTANCE0 = GL11.GL_CLIP_PLANE0; int GL_CLIP_DISTANCE1 = GL11.GL_CLIP_PLANE1; int GL_CLIP_DISTANCE2 = GL11.GL_CLIP_PLANE2; int GL_CLIP_DISTANCE3 = GL11.GL_CLIP_PLANE3; int GL_CLIP_DISTANCE4 = GL11.GL_CLIP_PLANE4; int GL_CLIP_DISTANCE5 = GL11.GL_CLIP_PLANE5; int GL_CLIP_DISTANCE6 = 0x3006; int GL_CLIP_DISTANCE7 = 0x3007; int GL_MAX_CLIP_DISTANCES = GL11.GL_MAX_CLIP_PLANES; int GL_MAX_VARYING_COMPONENTS = GL20.GL_MAX_VARYING_FLOATS; int GL_BUFFER_ACCESS_FLAGS = 0x911F; int GL_BUFFER_MAP_LENGTH = 0x9120; int GL_BUFFER_MAP_OFFSET = 0x9121; String glGetStringi(@GLenum int name, @GLuint int index); @StripPostfix("value") void glClearBufferfv(@GLenum int buffer, int drawbuffer, @Const @Check("4") FloatBuffer value); @StripPostfix("value") void glClearBufferiv(@GLenum int buffer, int drawbuffer, @Const @Check("4") IntBuffer value); @StripPostfix("value") void glClearBufferuiv(@GLenum int buffer, int drawbuffer, @Const @Check("4") IntBuffer value); void glClearBufferfi(@GLenum int buffer, int drawbuffer, float depth, int stencil); // --------------------------------------------------------------- // ----------------------[ EXT_gpu_shader4 ]---------------------- // --------------------------------------------------------------- /** * Accepted by the &lt;pname&gt; parameters of GetVertexAttribdv, * GetVertexAttribfv, GetVertexAttribiv, GetVertexAttribIiv, and * GetVertexAttribIuiv: */ int GL_VERTEX_ATTRIB_ARRAY_INTEGER = 0x88FD; /** Returned by the &lt;type&gt; parameter of GetActiveUniform: */ int GL_SAMPLER_BUFFER = 0x8DC2; int GL_SAMPLER_CUBE_SHADOW = 0x8DC5; int GL_UNSIGNED_INT_VEC2 = 0x8DC6; int GL_UNSIGNED_INT_VEC3 = 0x8DC7; int GL_UNSIGNED_INT_VEC4 = 0x8DC8; int GL_INT_SAMPLER_1D = 0x8DC9; int GL_INT_SAMPLER_2D = 0x8DCA; int GL_INT_SAMPLER_3D = 0x8DCB; int GL_INT_SAMPLER_CUBE = 0x8DCC; int GL_INT_SAMPLER_2D_RECT = 0x8DCD; int GL_INT_SAMPLER_1D_ARRAY = 0x8DCE; int GL_INT_SAMPLER_2D_ARRAY = 0x8DCF; int GL_INT_SAMPLER_BUFFER = 0x8DD0; int GL_UNSIGNED_INT_SAMPLER_1D = 0x8DD1; int GL_UNSIGNED_INT_SAMPLER_2D = 0x8DD2; int GL_UNSIGNED_INT_SAMPLER_3D = 0x8DD3; int GL_UNSIGNED_INT_SAMPLER_CUBE = 0x8DD4; int GL_UNSIGNED_INT_SAMPLER_2D_RECT = 0x8DD5; int GL_UNSIGNED_INT_SAMPLER_1D_ARRAY = 0x8DD6; int GL_UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8DD7; int GL_UNSIGNED_INT_SAMPLER_BUFFER = 0x8DD8; /** * Accepted by the &lt;pname&gt; parameter of GetBooleanv, GetIntegerv, GetFloatv, * and GetDoublev: */ int GL_MIN_PROGRAM_TEXEL_OFFSET = 0x8904; int GL_MAX_PROGRAM_TEXEL_OFFSET = 0x8905; @NoErrorCheck void glVertexAttribI1i(@GLuint int index, int x); @NoErrorCheck void glVertexAttribI2i(@GLuint int index, int x, int y); @NoErrorCheck void glVertexAttribI3i(@GLuint int index, int x, int y, int z); @NoErrorCheck void glVertexAttribI4i(@GLuint int index, int x, int y, int z, int w); @NoErrorCheck void glVertexAttribI1ui(@GLuint int index, @GLuint int x); @NoErrorCheck void glVertexAttribI2ui(@GLuint int index, @GLuint int x, @GLuint int y); @NoErrorCheck void glVertexAttribI3ui(@GLuint int index, @GLuint int x, @GLuint int y, @GLuint int z); @NoErrorCheck void glVertexAttribI4ui(@GLuint int index, @GLuint int x, @GLuint int y, @GLuint int z, @GLuint int w); @NoErrorCheck @StripPostfix("v") void glVertexAttribI1iv(@GLuint int index, @Check("1") @Const IntBuffer v); @NoErrorCheck @StripPostfix("v") void glVertexAttribI2iv(@GLuint int index, @Check("2") @Const IntBuffer v); @NoErrorCheck @StripPostfix("v") void glVertexAttribI3iv(@GLuint int index, @Check("3") @Const IntBuffer v); @NoErrorCheck @StripPostfix("v") void glVertexAttribI4iv(@GLuint int index, @Check("4") @Const IntBuffer v); @NoErrorCheck @StripPostfix("v") void glVertexAttribI1uiv(@GLuint int index, @Check("1") @Const @GLuint IntBuffer v); @NoErrorCheck @StripPostfix("v") void glVertexAttribI2uiv(@GLuint int index, @Check("2") @Const @GLuint IntBuffer v); @NoErrorCheck @StripPostfix("v") void glVertexAttribI3uiv(@GLuint int index, @Check("3") @Const @GLuint IntBuffer v); @NoErrorCheck @StripPostfix("v") void glVertexAttribI4uiv(@GLuint int index, @Check("4") @Const @GLuint IntBuffer v); @NoErrorCheck @StripPostfix("v") void glVertexAttribI4bv(@GLuint int index, @Check("4") @Const ByteBuffer v); @NoErrorCheck @StripPostfix("v") void glVertexAttribI4sv(@GLuint int index, @Check("4") @Const ShortBuffer v); @NoErrorCheck @StripPostfix("v") void glVertexAttribI4ubv(@GLuint int index, @Check("4") @Const @GLubyte ByteBuffer v); @NoErrorCheck @StripPostfix("v") void glVertexAttribI4usv(@GLuint int index, @Check("4") @Const @GLushort ShortBuffer v); void glVertexAttribIPointer(@GLuint int index, int size, @GLenum int type, @GLsizei int stride, @CachedReference(index = "index", name = "glVertexAttribPointer_buffer") @BufferObject(BufferKind.ArrayVBO) @Check @Const @GLbyte @GLubyte @GLshort @GLushort @GLint @GLuint Buffer buffer); @StripPostfix("params") void glGetVertexAttribIiv(@GLuint int index, @GLenum int pname, @OutParameter @Check("4") IntBuffer params); @StripPostfix("params") void glGetVertexAttribIuiv(@GLuint int index, @GLenum int pname, @OutParameter @Check("4") @GLuint IntBuffer params); void glUniform1ui(int location, @GLuint int v0); void glUniform2ui(int location, @GLuint int v0, @GLuint int v1); void glUniform3ui(int location, @GLuint int v0, @GLuint int v1, @GLuint int v2); void glUniform4ui(int location, @GLuint int v0, @GLuint int v1, @GLuint int v2, @GLuint int v3); @StripPostfix("value") void glUniform1uiv(int location, @AutoSize("value") @GLsizei int count, @Const @GLuint IntBuffer value); @StripPostfix("value") void glUniform2uiv(int location, @AutoSize(value = "value", expression = " >> 1") @GLsizei int count, @Const @GLuint IntBuffer value); @StripPostfix("value") void glUniform3uiv(int location, @AutoSize(value = "value", expression = " / 3") @GLsizei int count, @Const @GLuint IntBuffer value); @StripPostfix("value") void glUniform4uiv(int location, @AutoSize(value = "value", expression = " >> 2") @GLsizei int count, @Const @GLuint IntBuffer value); @StripPostfix("params") void glGetUniformuiv(@GLuint int program, int location, @OutParameter @Check @GLuint IntBuffer params); void glBindFragDataLocation(@GLuint int program, @GLuint int colorNumber, @NullTerminated @Const @GLchar ByteBuffer name); @Alternate("glBindFragDataLocation") void glBindFragDataLocation(@GLuint int program, @GLuint int colorNumber, @NullTerminated CharSequence name); int glGetFragDataLocation(@GLuint int program, @NullTerminated @Const @GLchar ByteBuffer name); @Alternate("glGetFragDataLocation") int glGetFragDataLocation(@GLuint int program, @NullTerminated CharSequence name); // --------------------------------------------------------------------- // ----------------------[ NV_conditional_render ]---------------------- // --------------------------------------------------------------------- /** Accepted by the &lt;mode&gt; parameter of BeginConditionalRender: */ int GL_QUERY_WAIT = 0x8E13; int GL_QUERY_NO_WAIT = 0x8E14; int GL_QUERY_BY_REGION_WAIT = 0x8E15; int GL_QUERY_BY_REGION_NO_WAIT = 0x8E16; void glBeginConditionalRender(@GLuint int id, @GLenum int mode); void glEndConditionalRender(); // -------------------------------------------------------------------- // ----------------------[ ARB_map_buffer_range ]---------------------- // -------------------------------------------------------------------- /** Accepted by the &lt;access&gt; parameter of MapBufferRange: */ int GL_MAP_READ_BIT = 0x0001; int GL_MAP_WRITE_BIT = 0x0002; int GL_MAP_INVALIDATE_RANGE_BIT = 0x0004; int GL_MAP_INVALIDATE_BUFFER_BIT = 0x0008; int GL_MAP_FLUSH_EXPLICIT_BIT = 0x0010; int GL_MAP_UNSYNCHRONIZED_BIT = 0x0020; /** * glMapBufferRange maps a GL buffer object range to a ByteBuffer. The old_buffer argument can be null, * in which case a new ByteBuffer will be created, pointing to the returned memory. If old_buffer is non-null, * it will be returned if it points to the same mapped memory and has the same capacity as the buffer object, * otherwise a new ByteBuffer is created. That way, an application will normally use glMapBufferRange like this: * <p/> * ByteBuffer mapped_buffer; mapped_buffer = glMapBufferRange(..., ..., ..., ..., null); ... // Another map on the same buffer mapped_buffer = glMapBufferRange(..., ..., ..., ..., mapped_buffer); * <p/> * Only ByteBuffers returned from this method are to be passed as the old_buffer argument. User-created ByteBuffers cannot be reused. * * @param old_buffer A ByteBuffer. If this argument points to the same address and has the same capacity as the new mapping, it will be returned and no new buffer will be created. * * @return A ByteBuffer representing the mapped buffer memory. */ @CachedResult(isRange = true) @GLvoid @AutoSize("length") ByteBuffer glMapBufferRange(@GLenum int target, @GLintptr long offset, @GLsizeiptr long length, @GLbitfield int access); void glFlushMappedBufferRange(@GLenum int target, @GLintptr long offset, @GLsizeiptr long length); // ---------------------------------------------------------------------- // ----------------------[ ARB_color_buffer_float ]---------------------- // ---------------------------------------------------------------------- /** * Accepted by the &lt;target&gt; parameter of ClampColor and the &lt;pname&gt; * parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev. */ int GL_CLAMP_VERTEX_COLOR = 0x891A; int GL_CLAMP_FRAGMENT_COLOR = 0x891B; int GL_CLAMP_READ_COLOR = 0x891C; /** Accepted by the &lt;clamp&gt; parameter of ClampColor. */ int GL_FIXED_ONLY = 0x891D; void glClampColor(@GLenum int target, @GLenum int clamp); // ---------------------------------------------------------------------- // ----------------------[ ARB_depth_buffer_float ]---------------------- // ---------------------------------------------------------------------- /** * Accepted by the &lt;internalformat&gt; parameter of TexImage1D, TexImage2D, * TexImage3D, CopyTexImage1D, CopyTexImage2D, and RenderbufferStorageEXT, * and returned in the &lt;data&gt; parameter of GetTexLevelParameter and * GetRenderbufferParameterivEXT: */ int GL_DEPTH_COMPONENT32F = 0x8CAC; int GL_DEPTH32F_STENCIL8 = 0x8CAD; /** * Accepted by the &lt;type&gt; parameter of DrawPixels, ReadPixels, TexImage1D, * TexImage2D, TexImage3D, TexSubImage1D, TexSubImage2D, TexSubImage3D, and * GetTexImage: */ int GL_FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8DAD; // ----------------------------------------------------------------- // ----------------------[ ARB_texture_float ]---------------------- // ----------------------------------------------------------------- /** Accepted by the &lt;value&gt; parameter of GetTexLevelParameter: */ int GL_TEXTURE_RED_TYPE = 0x8C10; int GL_TEXTURE_GREEN_TYPE = 0x8C11; int GL_TEXTURE_BLUE_TYPE = 0x8C12; int GL_TEXTURE_ALPHA_TYPE = 0x8C13; int GL_TEXTURE_LUMINANCE_TYPE = 0x8C14; int GL_TEXTURE_INTENSITY_TYPE = 0x8C15; int GL_TEXTURE_DEPTH_TYPE = 0x8C16; /** Returned by the &lt;params&gt; parameter of GetTexLevelParameter: */ int GL_UNSIGNED_NORMALIZED = 0x8C17; /** * Accepted by the &lt;internalFormat&gt; parameter of TexImage1D, * TexImage2D, and TexImage3D: */ int GL_RGBA32F = 0x8814; int GL_RGB32F = 0x8815; int GL_ALPHA32F = 0x8816; int GL_RGBA16F = 0x881A; int GL_RGB16F = 0x881B; int GL_ALPHA16F = 0x881C; // ---------------------------------------------------------------- // ----------------------[ EXT_packed_float ]---------------------- // ---------------------------------------------------------------- /** * Accepted by the &lt;internalformat&gt; parameter of TexImage1D, * TexImage2D, TexImage3D, CopyTexImage1D, CopyTexImage2D, and * RenderbufferStorage: */ int GL_R11F_G11F_B10F = 0x8C3A; /** * Accepted by the &lt;type&gt; parameter of DrawPixels, ReadPixels, * TexImage1D, TexImage2D, GetTexImage, TexImage3D, TexSubImage1D, * TexSubImage2D, TexSubImage3D, GetHistogram, GetMinmax, * ConvolutionFilter1D, ConvolutionFilter2D, ConvolutionFilter3D, * GetConvolutionFilter, SeparableFilter2D, GetSeparableFilter, * ColorTable, ColorSubTable, and GetColorTable: */ int GL_UNSIGNED_INT_10F_11F_11F_REV = 0x8C3B; // --------------------------------------------------------------------------- // ----------------------[ EXT_texture_shared_exponent ]---------------------- // --------------------------------------------------------------------------- /** * Accepted by the &lt;internalformat&gt; parameter of TexImage1D, * TexImage2D, TexImage3D, CopyTexImage1D, CopyTexImage2D, and * RenderbufferStorage: */ int GL_RGB9_E5 = 0x8C3D; /** * Accepted by the &lt;type&gt; parameter of DrawPixels, ReadPixels, * TexImage1D, TexImage2D, GetTexImage, TexImage3D, TexSubImage1D, * TexSubImage2D, TexSubImage3D, GetHistogram, GetMinmax, * ConvolutionFilter1D, ConvolutionFilter2D, ConvolutionFilter3D, * GetConvolutionFilter, SeparableFilter2D, GetSeparableFilter, * ColorTable, ColorSubTable, and GetColorTable: */ int GL_UNSIGNED_INT_5_9_9_9_REV = 0x8C3E; /** * Accepted by the &lt;pname&gt; parameter of GetTexLevelParameterfv and * GetTexLevelParameteriv: */ int GL_TEXTURE_SHARED_SIZE = 0x8C3F; // ---------------------------------------------------------------------- // ----------------------[ ARB_framebuffer_object ]---------------------- // ---------------------------------------------------------------------- /** * Accepted by the &lt;target&gt; parameter of BindFramebuffer, * CheckFramebufferStatus, FramebufferTexture{1D|2D|3D}, * FramebufferRenderbuffer, and * GetFramebufferAttachmentParameteriv: */ int GL_FRAMEBUFFER = 0x8D40; int GL_READ_FRAMEBUFFER = 0x8CA8; int GL_DRAW_FRAMEBUFFER = 0x8CA9; /** * Accepted by the &lt;target&gt; parameter of BindRenderbuffer, * RenderbufferStorage, and GetRenderbufferParameteriv, and * returned by GetFramebufferAttachmentParameteriv: */ int GL_RENDERBUFFER = 0x8D41; /** * Accepted by the &lt;internalformat&gt; parameter of * RenderbufferStorage: */ int GL_STENCIL_INDEX1 = 0x8D46; int GL_STENCIL_INDEX4 = 0x8D47; int GL_STENCIL_INDEX8 = 0x8D48; int GL_STENCIL_INDEX16 = 0x8D49; /** Accepted by the &lt;pname&gt; parameter of GetRenderbufferParameteriv: */ int GL_RENDERBUFFER_WIDTH = 0x8D42; int GL_RENDERBUFFER_HEIGHT = 0x8D43; int GL_RENDERBUFFER_INTERNAL_FORMAT = 0x8D44; int GL_RENDERBUFFER_RED_SIZE = 0x8D50; int GL_RENDERBUFFER_GREEN_SIZE = 0x8D51; int GL_RENDERBUFFER_BLUE_SIZE = 0x8D52; int GL_RENDERBUFFER_ALPHA_SIZE = 0x8D53; int GL_RENDERBUFFER_DEPTH_SIZE = 0x8D54; int GL_RENDERBUFFER_STENCIL_SIZE = 0x8D55; /** * Accepted by the &lt;pname&gt; parameter of * GetFramebufferAttachmentParameteriv: */ int GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0; int GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1; int GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2; int GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3; int GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING = 0x8210; int GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE = 0x8211; int GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE = 0x8212; int GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE = 0x8213; int GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE = 0x8214; int GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE = 0x8215; int GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE = 0x8216; int GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE = 0x8217; /** Returned in &lt;params&gt; by GetFramebufferAttachmentParameteriv: */ int GL_FRAMEBUFFER_DEFAULT = 0x8218; int GL_INDEX = 0x8222; /** * Accepted by the &lt;attachment&gt; parameter of * FramebufferTexture{1D|2D|3D}, FramebufferRenderbuffer, and * GetFramebufferAttachmentParameteriv */ int GL_COLOR_ATTACHMENT0 = 0x8CE0; int GL_COLOR_ATTACHMENT1 = 0x8CE1; int GL_COLOR_ATTACHMENT2 = 0x8CE2; int GL_COLOR_ATTACHMENT3 = 0x8CE3; int GL_COLOR_ATTACHMENT4 = 0x8CE4; int GL_COLOR_ATTACHMENT5 = 0x8CE5; int GL_COLOR_ATTACHMENT6 = 0x8CE6; int GL_COLOR_ATTACHMENT7 = 0x8CE7; int GL_COLOR_ATTACHMENT8 = 0x8CE8; int GL_COLOR_ATTACHMENT9 = 0x8CE9; int GL_COLOR_ATTACHMENT10 = 0x8CEA; int GL_COLOR_ATTACHMENT11 = 0x8CEB; int GL_COLOR_ATTACHMENT12 = 0x8CEC; int GL_COLOR_ATTACHMENT13 = 0x8CED; int GL_COLOR_ATTACHMENT14 = 0x8CEE; int GL_COLOR_ATTACHMENT15 = 0x8CEF; int GL_DEPTH_ATTACHMENT = 0x8D00; int GL_STENCIL_ATTACHMENT = 0x8D20; int GL_DEPTH_STENCIL_ATTACHMENT = 0x821A; /** Returned by CheckFramebufferStatus(): */ int GL_FRAMEBUFFER_COMPLETE = 0x8CD5; int GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6; int GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7; int GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER = 0x8CDB; int GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER = 0x8CDC; int GL_FRAMEBUFFER_UNSUPPORTED = 0x8CDD; int GL_FRAMEBUFFER_UNDEFINED = 0x8219; /** * Accepted by the &lt;pname&gt; parameters of GetIntegerv, GetFloatv, * and GetDoublev: */ int GL_FRAMEBUFFER_BINDING = 0x8CA6; // alias DRAW_FRAMEBUFFER_BINDING int GL_RENDERBUFFER_BINDING = 0x8CA7; int GL_MAX_COLOR_ATTACHMENTS = 0x8CDF; int GL_MAX_RENDERBUFFER_SIZE = 0x84E8; /** Returned by GetError(): */ int GL_INVALID_FRAMEBUFFER_OPERATION = 0x0506; boolean glIsRenderbuffer(@GLuint int renderbuffer); void glBindRenderbuffer(@GLenum int target, @GLuint int renderbuffer); void glDeleteRenderbuffers(@AutoSize("renderbuffers") int n, @Const @GLuint IntBuffer renderbuffers); @Alternate("glDeleteRenderbuffers") void glDeleteRenderbuffers(@Constant("1") int n, @Constant(value = "APIUtil.getInt(caps, renderbuffer)", keepParam = true) int renderbuffer); void glGenRenderbuffers(@AutoSize("renderbuffers") int n, @OutParameter @GLuint IntBuffer renderbuffers); @Alternate("glGenRenderbuffers") @GLreturn("renderbuffers") void glGenRenderbuffers2(@Constant("1") int n, @OutParameter @GLuint IntBuffer renderbuffers); void glRenderbufferStorage(@GLenum int target, @GLenum int internalformat, @GLsizei int width, @GLsizei int height); @StripPostfix("params") void glGetRenderbufferParameteriv(@GLenum int target, @GLenum int pname, @OutParameter @Check("4") IntBuffer params); /** @deprecated Will be removed in 3.0. Use {@link #glGetRenderbufferParameteri} instead. */ @Alternate("glGetRenderbufferParameteriv") @GLreturn("params") @StripPostfix("params") @Reuse(value = "GL30", method = "glGetRenderbufferParameteri") @Deprecated void glGetRenderbufferParameteriv2(@GLenum int target, @GLenum int pname, @OutParameter IntBuffer params); @Alternate("glGetRenderbufferParameteriv") @GLreturn("params") @StripPostfix(value = "params", hasPostfix = false) void glGetRenderbufferParameteriv3(@GLenum int target, @GLenum int pname, @OutParameter IntBuffer params); boolean glIsFramebuffer(@GLuint int framebuffer); void glBindFramebuffer(@GLenum int target, @GLuint int framebuffer); void glDeleteFramebuffers(@AutoSize("framebuffers") int n, @Const @GLuint IntBuffer framebuffers); @Alternate("glDeleteFramebuffers") void glDeleteFramebuffers(@Constant("1") int n, @Constant(value = "APIUtil.getInt(caps, framebuffer)", keepParam = true) int framebuffer); void glGenFramebuffers(@AutoSize("framebuffers") int n, @OutParameter @GLuint IntBuffer framebuffers); @Alternate("glGenFramebuffers") @GLreturn("framebuffers") void glGenFramebuffers2(@Constant("1") int n, @OutParameter @GLuint IntBuffer framebuffers); @GLenum int glCheckFramebufferStatus(@GLenum int target); void glFramebufferTexture1D(@GLenum int target, @GLenum int attachment, @GLenum int textarget, @GLuint int texture, int level); void glFramebufferTexture2D(@GLenum int target, @GLenum int attachment, @GLenum int textarget, @GLuint int texture, int level); void glFramebufferTexture3D(@GLenum int target, @GLenum int attachment, @GLenum int textarget, @GLuint int texture, int level, int zoffset); void glFramebufferRenderbuffer(@GLenum int target, @GLenum int attachment, @GLenum int renderbuffertarget, @GLuint int renderbuffer); @StripPostfix("params") void glGetFramebufferAttachmentParameteriv(@GLenum int target, @GLenum int attachment, @GLenum int pname, @OutParameter @Check("4") IntBuffer params); /** @deprecated Will be removed in 3.0. Use {@link #glGetFramebufferAttachmentParameteri} instead. */ @Alternate("glGetFramebufferAttachmentParameteriv") @GLreturn("params") @StripPostfix("params") @Reuse(value = "GL30", method = "glGetFramebufferAttachmentParameteri") @Deprecated void glGetFramebufferAttachmentParameteriv2(@GLenum int target, @GLenum int attachment, @GLenum int pname, @OutParameter IntBuffer params); @Alternate("glGetFramebufferAttachmentParameteriv") @GLreturn("params") @StripPostfix(value = "params", hasPostfix = false) void glGetFramebufferAttachmentParameteriv3(@GLenum int target, @GLenum int attachment, @GLenum int pname, @OutParameter IntBuffer params); void glGenerateMipmap(@GLenum int target); // -------------------------------------------------------------------------------------------- // ----------------------[ ARB_half_float_vertex & ARB_half_float_pixel ]---------------------- // -------------------------------------------------------------------------------------------- /** * Accepted by the &lt;type&gt; parameter of DrawPixels, ReadPixels, * TexImage1D, TexImage2D, TexImage3D, GetTexImage, TexSubImage1D, * TexSubImage2D, TexSubImage3D, GetHistogram, GetMinmax, * ConvolutionFilter1D, ConvolutionFilter2D, GetConvolutionFilter, * SeparableFilter2D, GetSeparableFilter, ColorTable, ColorSubTable, * and GetColorTable: * <p/> * Accepted by the &lt;type&gt; argument of VertexPointer, NormalPointer, * ColorPointer, SecondaryColorPointer, FogCoordPointer, TexCoordPointer, * and VertexAttribPointer: */ int GL_HALF_FLOAT = 0x140B; // --------------------------------------------------------------------------- // ----------------------[ EXT_framebuffer_multisample ]---------------------- // --------------------------------------------------------------------------- /** Accepted by the &lt;pname&gt; parameter of GetRenderbufferParameteriv. */ int GL_RENDERBUFFER_SAMPLES = 0x8CAB; /** Returned by CheckFramebufferStatus. */ int GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE = 0x8D56; /** * Accepted by the &lt;pname&gt; parameter of GetBooleanv, GetIntegerv, * GetFloatv, and GetDoublev. */ int GL_MAX_SAMPLES = 0x8D57; /** * Establishes the data storage, format, dimensions, and number of * samples of a renderbuffer object's image. */ void glRenderbufferStorageMultisample( @GLenum int target, @GLsizei int samples, @GLenum int internalformat, @GLsizei int width, @GLsizei int height); // -------------------------------------------------------------------- // ----------------------[ EXT_framebuffer_blit ]---------------------- // -------------------------------------------------------------------- /** Accepted by the &lt;pname&gt; parameters of GetIntegerv, GetFloatv, and GetDoublev. */ int GL_DRAW_FRAMEBUFFER_BINDING = 0x8CA6; // alias FRAMEBUFFER_BINDING int GL_READ_FRAMEBUFFER_BINDING = 0x8CAA; /** * Transfers a rectangle of pixel values from one * region of the read framebuffer to another in the draw framebuffer. * &lt;mask&gt; is the bitwise OR of a number of values indicating which * buffers are to be copied. The values are COLOR_BUFFER_BIT, * DEPTH_BUFFER_BIT, and STENCIL_BUFFER_BIT. * The pixels corresponding to these buffers are * copied from the source rectangle, bound by the locations (srcX0, * srcY0) and (srcX1, srcY1) inclusive, to the destination rectangle, * bound by the locations (dstX0, dstY0) and (dstX1, dstY1) * inclusive. * If the source and destination rectangle dimensions do not match, * the source image is stretched to fit the destination * rectangle. &lt;filter&gt; must be LINEAR or NEAREST and specifies the * method of interpolation to be applied if the image is * stretched. */ void glBlitFramebuffer( @GLint int srcX0, @GLint int srcY0, @GLint int srcX1, @GLint int srcY1, @GLint int dstX0, @GLint int dstY0, @GLint int dstX1, @GLint int dstY1, @GLbitfield int mask, @GLenum int filter); // ------------------------------------------------------------------- // ----------------------[ EXT_texture_integer ]---------------------- // ------------------------------------------------------------------- /** * Accepted by the &lt;pname&gt; parameters of GetBooleanv, GetIntegerv, * GetFloatv, and GetDoublev: */ int GL_RGBA_INTEGER_MODE = 0x8D9E; /** * Accepted by the &lt;internalFormat&gt; parameter of TexImage1D, * TexImage2D, and TexImage3D: */ int GL_RGBA32UI = 0x8D70; int GL_RGB32UI = 0x8D71; int GL_ALPHA32UI = 0x8D72; int GL_RGBA16UI = 0x8D76; int GL_RGB16UI = 0x8D77; int GL_ALPHA16UI = 0x8D78; int GL_RGBA8UI = 0x8D7C; int GL_RGB8UI = 0x8D7D; int GL_ALPHA8UI = 0x8D7E; int GL_RGBA32I = 0x8D82; int GL_RGB32I = 0x8D83; int GL_ALPHA32I = 0x8D84; int GL_RGBA16I = 0x8D88; int GL_RGB16I = 0x8D89; int GL_ALPHA16I = 0x8D8A; int GL_RGBA8I = 0x8D8E; int GL_RGB8I = 0x8D8F; int GL_ALPHA8I = 0x8D90; /** * Accepted by the &lt;format&gt; parameter of TexImage1D, TexImage2D, * TexImage3D, TexSubImage1D, TexSubImage2D, TexSubImage3D, * DrawPixels and ReadPixels: */ int GL_RED_INTEGER = 0x8D94; int GL_GREEN_INTEGER = 0x8D95; int GL_BLUE_INTEGER = 0x8D96; int GL_ALPHA_INTEGER = 0x8D97; int GL_RGB_INTEGER = 0x8D98; int GL_RGBA_INTEGER = 0x8D99; int GL_BGR_INTEGER = 0x8D9A; int GL_BGRA_INTEGER = 0x8D9B; @StripPostfix("params") void glTexParameterIiv(@GLenum int target, @GLenum int pname, @Check("4") IntBuffer params); @Alternate("glTexParameterIiv") @StripPostfix(value = "param", hasPostfix = false) void glTexParameterIiv(@GLenum int target, @GLenum int pname, @Constant(value = "APIUtil.getInt(caps, param)", keepParam = true) int param); @StripPostfix("params") void glTexParameterIuiv(@GLenum int target, @GLenum int pname, @Check("4") @GLuint IntBuffer params); @Alternate("glTexParameterIuiv") @StripPostfix(value = "param", hasPostfix = false) void glTexParameterIuiv(@GLenum int target, @GLenum int pname, @Constant(value = "APIUtil.getInt(caps, param)", keepParam = true) int param); @StripPostfix("params") void glGetTexParameterIiv(@GLenum int target, @GLenum int pname, @OutParameter @Check("4") IntBuffer params); @Alternate("glGetTexParameterIiv") @GLreturn("params") @StripPostfix(value = "params", hasPostfix = false) void glGetTexParameterIiv2(@GLenum int target, @GLenum int pname, @OutParameter IntBuffer params); @StripPostfix("params") void glGetTexParameterIuiv(@GLenum int target, @GLenum int pname, @OutParameter @Check("4") @GLuint IntBuffer params); @Alternate("glGetTexParameterIuiv") @GLreturn("params") @StripPostfix(value = "params", hasPostfix = false) void glGetTexParameterIuiv2(@GLenum int target, @GLenum int pname, @OutParameter @GLuint IntBuffer params); // ----------------------------------------------------------------- // ----------------------[ EXT_texture_array ]---------------------- // ----------------------------------------------------------------- /** * Accepted by the &lt;target&gt; parameter of TexParameteri, TexParameteriv, * TexParameterf, TexParameterfv, and BindTexture: */ int GL_TEXTURE_1D_ARRAY = 0x8C18; int GL_TEXTURE_2D_ARRAY = 0x8C1A; /** * Accepted by the &lt;target&gt; parameter of TexImage3D, TexSubImage3D, * CopyTexSubImage3D, CompressedTexImage3D, and CompressedTexSubImage3D: */ int GL_PROXY_TEXTURE_2D_ARRAY = 0x8C1B; /** * Accepted by the &lt;target&gt; parameter of TexImage2D, TexSubImage2D, * CopyTexImage2D, CopyTexSubImage2D, CompressedTexImage2D, and * CompressedTexSubImage2D: */ int GL_PROXY_TEXTURE_1D_ARRAY = 0x8C19; /** * Accepted by the &lt;pname&gt; parameter of GetBooleanv, GetDoublev, GetIntegerv * and GetFloatv: */ int GL_TEXTURE_BINDING_1D_ARRAY = 0x8C1C; int GL_TEXTURE_BINDING_2D_ARRAY = 0x8C1D; int GL_MAX_ARRAY_TEXTURE_LAYERS = 0x88FF; /** * Accepted by the &lt;param&gt; parameter of TexParameterf, TexParameteri, * TexParameterfv, and TexParameteriv when the &lt;pname&gt; parameter is * TEXTURE_COMPARE_MODE_ARB: */ int GL_COMPARE_REF_DEPTH_TO_TEXTURE = 0x884E; /** * Accepted by the &lt;pname&gt; parameter of * GetFramebufferAttachmentParameteriv: */ int GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER = 0x8CD4; /** Returned by the &lt;type&gt; parameter of GetActiveUniform: */ int GL_SAMPLER_1D_ARRAY = 0x8DC0; int GL_SAMPLER_2D_ARRAY = 0x8DC1; int GL_SAMPLER_1D_ARRAY_SHADOW = 0x8DC3; int GL_SAMPLER_2D_ARRAY_SHADOW = 0x8DC4; void glFramebufferTextureLayer(@GLenum int target, @GLenum int attachment, @GLuint int texture, int level, int layer); // ------------------------------------------------------------------------ // ----------------------[ EXT_packed_depth_stencil ]---------------------- // ------------------------------------------------------------------------ /** * Accepted by the &lt;format&gt; parameter of DrawPixels, ReadPixels, * TexImage1D, TexImage2D, TexImage3D, TexSubImage1D, TexSubImage2D, * TexSubImage3D, and GetTexImage, by the &lt;type&gt; parameter of * CopyPixels, by the &lt;internalformat&gt; parameter of TexImage1D, * TexImage2D, TexImage3D, CopyTexImage1D, CopyTexImage2D, and * RenderbufferStorage, and returned in the &lt;data&gt; parameter of * GetTexLevelParameter and GetRenderbufferParameteriv. */ int GL_DEPTH_STENCIL = 0x84F9; /** * Accepted by the &lt;type&gt; parameter of DrawPixels, ReadPixels, * TexImage1D, TexImage2D, TexImage3D, TexSubImage1D, TexSubImage2D, * TexSubImage3D, and GetTexImage. */ int GL_UNSIGNED_INT_24_8 = 0x84FA; /** * Accepted by the &lt;internalformat&gt; parameter of TexImage1D, * TexImage2D, TexImage3D, CopyTexImage1D, CopyTexImage2D, and * RenderbufferStorage, and returned in the &lt;data&gt; parameter of * GetTexLevelParameter and GetRenderbufferParameteriv. */ int GL_DEPTH24_STENCIL8 = 0x88F0; /** Accepted by the &lt;value&gt; parameter of GetTexLevelParameter. */ int GL_TEXTURE_STENCIL_SIZE = 0x88F1; // ----------------------------------------------------------------- // ----------------------[ EXT_draw_buffers2 ]---------------------- // ----------------------------------------------------------------- void glColorMaski(@GLuint int buf, boolean r, boolean g, boolean b, boolean a); @StripPostfix(value = "data") void glGetBooleani_v(@GLenum int value, @GLuint int index, @OutParameter @Check("4") @GLboolean ByteBuffer data); @Alternate("glGetBooleani_v") @GLreturn("data") @StripPostfix(value = "data") void glGetBooleani_v2(@GLenum int value, @GLuint int index, @OutParameter @GLboolean ByteBuffer data); @StripPostfix("data") void glGetIntegeri_v(@GLenum int value, @GLuint int index, @OutParameter @Check("4") IntBuffer data); @Alternate("glGetIntegeri_v") @GLreturn("data") @StripPostfix("data") void glGetIntegeri_v2(@GLenum int value, @GLuint int index, @OutParameter IntBuffer data); void glEnablei(@GLenum int target, @GLuint int index); void glDisablei(@GLenum int target, @GLuint int index); boolean glIsEnabledi(@GLenum int target, @GLuint int index); // ---------------------------------------------------------------------------- // ----------------------[ ARB_texture_compression_rgtc ]---------------------- // ---------------------------------------------------------------------------- /** * Accepted by the &lt;internalformat&gt; parameter of TexImage2D, * CopyTexImage2D, and CompressedTexImage2D and the &lt;format&gt; parameter * of CompressedTexSubImage2D: */ int GL_COMPRESSED_RED_RGTC1 = 0x8DBB, GL_COMPRESSED_SIGNED_RED_RGTC1 = 0x8DBC, GL_COMPRESSED_RG_RGTC2 = 0x8DBD, GL_COMPRESSED_SIGNED_RG_RGTC2 = 0x8DBE; // -------------------------------------------------------------- // ----------------------[ ARB_texture_rg ]---------------------- // -------------------------------------------------------------- /** * Accepted by the &lt;internalFormat&gt; parameter of TexImage1D, TexImage2D, * TexImage3D, CopyTexImage1D, and CopyTexImage2D: */ int GL_R8 = 0x8229; int GL_R16 = 0x822A; int GL_RG8 = 0x822B; int GL_RG16 = 0x822C; int GL_R16F = 0x822D; int GL_R32F = 0x822E; int GL_RG16F = 0x822F; int GL_RG32F = 0x8230; int GL_R8I = 0x8231; int GL_R8UI = 0x8232; int GL_R16I = 0x8233; int GL_R16UI = 0x8234; int GL_R32I = 0x8235; int GL_R32UI = 0x8236; int GL_RG8I = 0x8237; int GL_RG8UI = 0x8238; int GL_RG16I = 0x8239; int GL_RG16UI = 0x823A; int GL_RG32I = 0x823B; int GL_RG32UI = 0x823C; /** * Accepted by the &lt;format&gt; parameter of TexImage3D, TexImage2D, * TexImage3D, TexSubImage1D, TexSubImage2D, TexSubImage3D, * DrawPixels and ReadPixels: */ int GL_RG = 0x8227; int GL_RG_INTEGER = 0x8228; // ---------------------------------------------------------------------- // ----------------------[ EXT_transform_feedback ]---------------------- // ---------------------------------------------------------------------- /** * Accepted by the &lt;target&gt; parameters of BindBuffer, BufferData, * BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData, * GetBufferPointerv, BindBufferRange, BindBufferOffset and * BindBufferBase: */ int GL_TRANSFORM_FEEDBACK_BUFFER = 0x8C8E; /** * Accepted by the &lt;param&gt; parameter of GetIntegerIndexedv and * GetBooleanIndexedv: */ int GL_TRANSFORM_FEEDBACK_BUFFER_START = 0x8C84; int GL_TRANSFORM_FEEDBACK_BUFFER_SIZE = 0x8C85; /** * Accepted by the &lt;param&gt; parameter of GetIntegerIndexedv and * GetBooleanIndexedv, and by the &lt;pname&gt; parameter of GetBooleanv, * GetDoublev, GetIntegerv, and GetFloatv: */ int GL_TRANSFORM_FEEDBACK_BUFFER_BINDING = 0x8C8F; /** Accepted by the &lt;bufferMode&gt; parameter of TransformFeedbackVaryings: */ int GL_INTERLEAVED_ATTRIBS = 0x8C8C; int GL_SEPARATE_ATTRIBS = 0x8C8D; /** * Accepted by the &lt;target&gt; parameter of BeginQuery, EndQuery, and * GetQueryiv: */ int GL_PRIMITIVES_GENERATED = 0x8C87; int GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = 0x8C88; /** * Accepted by the &lt;cap&gt; parameter of Enable, Disable, and IsEnabled, and by * the &lt;pname&gt; parameter of GetBooleanv, GetIntegerv, GetFloatv, and * GetDoublev: */ int GL_RASTERIZER_DISCARD = 0x8C89; /** * Accepted by the &lt;pname&gt; parameter of GetBooleanv, GetDoublev, GetIntegerv, * and GetFloatv: */ int GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS = 0x8C8A; int GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS = 0x8C8B; int GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS = 0x8C80; /** Accepted by the &lt;pname&gt; parameter of GetProgramiv: */ int GL_TRANSFORM_FEEDBACK_VARYINGS = 0x8C83; int GL_TRANSFORM_FEEDBACK_BUFFER_MODE = 0x8C7F; int GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH = 0x8C76; void glBindBufferRange(@GLenum int target, @GLuint int index, @GLuint int buffer, @GLintptr long offset, @GLsizeiptr long size); void glBindBufferBase(@GLenum int target, @GLuint int index, @GLuint int buffer); void glBeginTransformFeedback(@GLenum int primitiveMode); void glEndTransformFeedback(); void glTransformFeedbackVaryings(@GLuint int program, @GLsizei int count, @Const @NullTerminated("count") @GLchar @PointerArray("count") ByteBuffer varyings, @GLenum int bufferMode); @Alternate("glTransformFeedbackVaryings") void glTransformFeedbackVaryings(@GLuint int program, @Constant("varyings.length") @GLsizei int count, @Const @NullTerminated @PointerArray("count") CharSequence[] varyings, @GLenum int bufferMode); void glGetTransformFeedbackVarying(@GLuint int program, @GLuint int index, @AutoSize("name") @GLsizei int bufSize, @OutParameter @GLsizei @Check(value = "1", canBeNull = true) IntBuffer length, @OutParameter @GLsizei @Check("1") IntBuffer size, @OutParameter @GLenum @Check("1") IntBuffer type, @OutParameter @GLchar ByteBuffer name); @Alternate("glGetTransformFeedbackVarying") @GLreturn(value = "name", maxLength = "bufSize") void glGetTransformFeedbackVarying2(@GLuint int program, @GLuint int index, @GLsizei int bufSize, @OutParameter @GLsizei @Constant("MemoryUtil.getAddress0(name_length)") IntBuffer length, @OutParameter @GLsizei @Check("1") IntBuffer size, @OutParameter @GLenum @Check("1") IntBuffer type, @OutParameter @GLchar ByteBuffer name); // ----------------------------------------------------------------------- // ----------------------[ ARB_vertex_array_object ]---------------------- // ----------------------------------------------------------------------- /** * Accepted by the &lt;pname&gt; parameter of GetBooleanv, GetIntegerv, * GetFloatv, and GetDoublev: */ int GL_VERTEX_ARRAY_BINDING = 0x85B5; @Code(" StateTracker.bindVAO(caps, array);") void glBindVertexArray(@GLuint int array); @Code(" StateTracker.deleteVAO(caps, arrays);") void glDeleteVertexArrays(@AutoSize("arrays") @GLsizei int n, @Const @GLuint IntBuffer arrays); @Alternate("glDeleteVertexArrays") @Code(" StateTracker.deleteVAO(caps, array);") void glDeleteVertexArrays(@Constant("1") @GLsizei int n, @Constant(value = "APIUtil.getInt(caps, array)", keepParam = true) int array); void glGenVertexArrays(@AutoSize("arrays") @GLsizei int n, @OutParameter @GLuint IntBuffer arrays); @Alternate("glGenVertexArrays") @GLreturn("arrays") void glGenVertexArrays2(@Constant("1") @GLsizei int n, @OutParameter @GLuint IntBuffer arrays); boolean glIsVertexArray(@GLuint int array); // -------------------------------------------------------------------- // ----------------------[ ARB_framebuffer_sRGB ]---------------------- // -------------------------------------------------------------------- /** * Accepted by the &lt;cap&gt; parameter of Enable, Disable, and IsEnabled, * and by the &lt;pname&gt; parameter of GetBooleanv, GetIntegerv, GetFloatv, * and GetDoublev: */ int GL_FRAMEBUFFER_SRGB = 0x8DB9; /** * Accepted by the &lt;pname&gt; parameter of GetBooleanv, GetIntegerv, * GetFloatv, and GetDoublev: */ int GL_FRAMEBUFFER_SRGB_CAPABLE = 0x8DBA; }
/* * Copyright (c) 2008-2015 Citrix Systems, 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.citrix.netscaler.nitro.resource.config.network; import com.citrix.netscaler.nitro.resource.base.*; import com.citrix.netscaler.nitro.service.nitro_service; import com.citrix.netscaler.nitro.service.options; import com.citrix.netscaler.nitro.util.*; import com.citrix.netscaler.nitro.exception.nitro_exception; class bridgetable_response extends base_response { public bridgetable[] bridgetable; } /** * Configuration for bridge table entry resource. */ public class bridgetable extends base_resource { private Long bridgeage; private Long vlan; private String ifnum; //------- Read only Parameter ---------; private String mac; private Long channel; private Long __count; /** * <pre> * Time-out value for the bridge table entries, in seconds. The new value applies only to the entries that are dynamically learned after the new value is set. Previously existing bridge table entries expire after the previously configured time-out value.<br> Default value: 300<br> Minimum value = 60<br> Maximum value = 300 * </pre> */ public void set_bridgeage(long bridgeage) throws Exception { this.bridgeage = new Long(bridgeage); } /** * <pre> * Time-out value for the bridge table entries, in seconds. The new value applies only to the entries that are dynamically learned after the new value is set. Previously existing bridge table entries expire after the previously configured time-out value.<br> Default value: 300<br> Minimum value = 60<br> Maximum value = 300 * </pre> */ public void set_bridgeage(Long bridgeage) throws Exception{ this.bridgeage = bridgeage; } /** * <pre> * Time-out value for the bridge table entries, in seconds. The new value applies only to the entries that are dynamically learned after the new value is set. Previously existing bridge table entries expire after the previously configured time-out value.<br> Default value: 300<br> Minimum value = 60<br> Maximum value = 300 * </pre> */ public Long get_bridgeage() throws Exception { return this.bridgeage; } /** * <pre> * VLAN whose entries are to be removed. * </pre> */ public void set_vlan(long vlan) throws Exception { this.vlan = new Long(vlan); } /** * <pre> * VLAN whose entries are to be removed. * </pre> */ public void set_vlan(Long vlan) throws Exception{ this.vlan = vlan; } /** * <pre> * VLAN whose entries are to be removed. * </pre> */ public Long get_vlan() throws Exception { return this.vlan; } /** * <pre> * INTERFACE whose entries are to be removed. * </pre> */ public void set_ifnum(String ifnum) throws Exception{ this.ifnum = ifnum; } /** * <pre> * INTERFACE whose entries are to be removed. * </pre> */ public String get_ifnum() throws Exception { return this.ifnum; } /** * <pre> * The MAC address of the target. * </pre> */ public String get_mac() throws Exception { return this.mac; } /** * <pre> * The Tunnel through which bridge entry is learned. * </pre> */ public Long get_channel() throws Exception { return this.channel; } /** * <pre> * converts nitro response into object and returns the object array in case of get request. * </pre> */ protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception{ bridgetable_response result = (bridgetable_response) service.get_payload_formatter().string_to_resource(bridgetable_response.class, response); if(result.errorcode != 0) { if (result.errorcode == 444) { service.clear_session(); } if(result.severity != null) { if (result.severity.equals("ERROR")) throw new nitro_exception(result.message,result.errorcode); } else { throw new nitro_exception(result.message,result.errorcode); } } return result.bridgetable; } /** * <pre> * Returns the value of object identifier argument * </pre> */ protected String get_object_name() { return null; } /** * Use this API to update bridgetable. */ public static base_response update(nitro_service client, bridgetable resource) throws Exception { bridgetable updateresource = new bridgetable(); updateresource.bridgeage = resource.bridgeage; return updateresource.update_resource(client); } /** * Use this API to update bridgetable resources. */ public static base_responses update(nitro_service client, bridgetable resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { bridgetable updateresources[] = new bridgetable[resources.length]; for (int i=0;i<resources.length;i++){ updateresources[i] = new bridgetable(); updateresources[i].bridgeage = resources[i].bridgeage; } result = update_bulk_request(client, updateresources); } return result; } /** * Use this API to unset the properties of bridgetable resource. * Properties that need to be unset are specified in args array. */ public static base_response unset(nitro_service client, bridgetable resource, String[] args) throws Exception{ bridgetable unsetresource = new bridgetable(); return unsetresource.unset_resource(client,args); } /** * Use this API to unset the properties of bridgetable resources. * Properties that need to be unset are specified in args array. */ public static base_responses unset(nitro_service client, bridgetable resources[], String[] args) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { bridgetable unsetresources[] = new bridgetable[resources.length]; for (int i=0;i<resources.length;i++){ unsetresources[i] = new bridgetable(); } result = unset_bulk_request(client, unsetresources,args); } return result; } /** * Use this API to clear bridgetable. */ public static base_response clear(nitro_service client, bridgetable resource) throws Exception { bridgetable clearresource = new bridgetable(); clearresource.vlan = resource.vlan; clearresource.ifnum = resource.ifnum; return clearresource.perform_operation(client,"clear"); } /** * Use this API to clear bridgetable resources. */ public static base_responses clear(nitro_service client, bridgetable resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { bridgetable clearresources[] = new bridgetable[resources.length]; for (int i=0;i<resources.length;i++){ clearresources[i] = new bridgetable(); clearresources[i].vlan = resources[i].vlan; clearresources[i].ifnum = resources[i].ifnum; } result = perform_operation_bulk_request(client, clearresources,"clear"); } return result; } /** * Use this API to fetch all the bridgetable resources that are configured on netscaler. */ public static bridgetable[] get(nitro_service service) throws Exception{ bridgetable obj = new bridgetable(); bridgetable[] response = (bridgetable[])obj.get_resources(service); return response; } /** * Use this API to fetch all the bridgetable resources that are configured on netscaler. */ public static bridgetable[] get(nitro_service service, options option) throws Exception{ bridgetable obj = new bridgetable(); bridgetable[] response = (bridgetable[])obj.get_resources(service,option); return response; } /** * Use this API to fetch filtered set of bridgetable resources. * filter string should be in JSON format.eg: "port:80,servicetype:HTTP". */ public static bridgetable[] get_filtered(nitro_service service, String filter) throws Exception{ bridgetable obj = new bridgetable(); options option = new options(); option.set_filter(filter); bridgetable[] response = (bridgetable[]) obj.getfiltered(service, option); return response; } /** * Use this API to fetch filtered set of bridgetable resources. * set the filter parameter values in filtervalue object. */ public static bridgetable[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{ bridgetable obj = new bridgetable(); options option = new options(); option.set_filter(filter); bridgetable[] response = (bridgetable[]) obj.getfiltered(service, option); return response; } /** * Use this API to count the bridgetable resources configured on NetScaler. */ public static long count(nitro_service service) throws Exception{ bridgetable obj = new bridgetable(); options option = new options(); option.set_count(true); bridgetable[] response = (bridgetable[])obj.get_resources(service, option); if (response != null) { return response[0].__count; } return 0; } /** * Use this API to count filtered the set of bridgetable resources. * filter string should be in JSON format.eg: "port:80,servicetype:HTTP". */ public static long count_filtered(nitro_service service, String filter) throws Exception{ bridgetable obj = new bridgetable(); options option = new options(); option.set_count(true); option.set_filter(filter); bridgetable[] response = (bridgetable[]) obj.getfiltered(service, option); if (response != null) { return response[0].__count; } return 0; } /** * Use this API to count the filtered set of bridgetable resources. * set the filter parameter values in filtervalue object. */ public static long count_filtered(nitro_service service, filtervalue[] filter) throws Exception{ bridgetable obj = new bridgetable(); options option = new options(); option.set_count(true); option.set_filter(filter); bridgetable[] response = (bridgetable[]) obj.getfiltered(service, option); if (response != null) { return response[0].__count; } return 0; } }
/** * Copyright (c) 2009/09-2012/08, Regents of the University of Colorado * 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. * * 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. */ /** * Copyright 2012/09-2013/04, 2013/11-Present, University of Massachusetts Amherst * Copyright 2013/05-2013/10, IPSoft 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.clearnlp.classification.feature; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.clearnlp.util.UTXml; import com.clearnlp.util.pair.IntIntPair; /** * @since 1.0.0 * @author Jinho D. Choi ({@code [email protected]}) */ abstract public class AbstractFtrXml implements Serializable { private static final long serialVersionUID = 1558293248573950051L; static protected final String XML_TEMPLATE = "feature_template"; static protected final String XML_CUTOFF = "cutoff"; static protected final String XML_LABEL = "label"; static protected final String XML_TYPE = "type"; static protected final String XML_FEATURE = "feature"; static protected final String XML_LEXICA = "lexica"; /** The type of feature. */ static protected final String XML_FEATURE_T = "t"; /** The number of tokens used for each feature. */ static protected final String XML_FEATURE_N = "n"; /** The field to extract features from (e.g., form, pos). */ static protected final String XML_FEATURE_F = "f"; /** If {@code false}, this feature is not visible. */ static protected final String XML_FEATURE_VISIBLE = "visible"; /** If {@code false}, this feature is not visible. */ static protected final String XML_FEATURE_NOTE = "note"; /** Field delimiter ({@code ":"}). */ static protected final String DELIM_F = ":"; /** Relation delimiter ({@code "_"}). */ static protected final String DELIM_R = "_"; protected FtrTemplate[] f_templates; protected boolean b_skipInvisible; protected int[] cutoff_label; protected int[] cutoff_feature; private String s_prettyPrint; /** * @param in the input stream of the XML file. * Skips invisible features. * @param in the input stream of the XML file. */ public AbstractFtrXml(InputStream in) { init(in, true); } /** * @param in the input stream of the XML file. * @param in the input stream of the XML file. * @param skipInvisible if {@code true}, skips invisible features. */ public AbstractFtrXml(InputStream in, boolean skipInvisible) { init(in, skipInvisible); } /** * Called by constructors. * Initializes cutoffs and feature templates. */ protected void init(InputStream in, boolean skipInvisible) { DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); b_skipInvisible = skipInvisible; try { DocumentBuilder builder = dFactory.newDocumentBuilder(); Document doc = builder.parse(in); initCutoffs(doc); initFeatures(doc); initMore(doc); s_prettyPrint = UTXml.getPrettyPrint(doc); } catch (Exception e) {e.printStackTrace();System.exit(1);} } /** Called by {@link AbstractFtrXml#init(InputStream, boolean)}. */ protected void initCutoffs(Document doc) throws Exception { NodeList eList = doc.getElementsByTagName(XML_CUTOFF); int i, size = eList.getLength(); Element eCutoff; cutoff_label = new int[size]; cutoff_feature = new int[size]; for (i=0; i<size; i++) { eCutoff = (Element)eList.item(i); cutoff_label [i] = eCutoff.hasAttribute(XML_LABEL ) ? Integer.parseInt(eCutoff.getAttribute(XML_LABEL )) : 0; cutoff_feature[i] = eCutoff.hasAttribute(XML_FEATURE) ? Integer.parseInt(eCutoff.getAttribute(XML_FEATURE)) : 0; } initCutoffMore(eList); } abstract protected void initMore(Document doc) throws Exception; /** Called by {@link AbstractFtrXml#init(InputStream, boolean)}. */ protected void initFeatures(Document doc) throws Exception { NodeList eList = doc.getElementsByTagName(XML_FEATURE); int i, j, n = eList.getLength(); FtrTemplate template; Element eFeature; List<FtrTemplate> list = new ArrayList<FtrTemplate>(); for (i=0,j=0; i<n; i++) { eFeature = (Element)eList.item(i); template = getFtrTemplate(eFeature); if (template != null) { list.add(template); if (!template.isBooleanFeature()) template.type += j++; } } f_templates = new FtrTemplate[list.size()]; list.toArray(f_templates); } /** Called by {@link AbstractFtrXml#initFeatures(Document)}. */ protected FtrTemplate getFtrTemplate(Element eFeature) { String tmp = eFeature.getAttribute(XML_FEATURE_VISIBLE).trim(); boolean visible = tmp.isEmpty() ? true : Boolean.parseBoolean(tmp); if (b_skipInvisible && !visible) return null; String type = eFeature.getAttribute(XML_FEATURE_T).trim(); int n = Integer.parseInt(eFeature.getAttribute(XML_FEATURE_N)), i; String note = eFeature.getAttribute(XML_FEATURE_NOTE).trim(); FtrTemplate ftr = new FtrTemplate(type, n, visible, note); for (i=0; i<n; i++) ftr.setFtrToken(i, getFtrToken(eFeature.getAttribute(XML_FEATURE_F + i))); return ftr; } /** * Called by {@link AbstractFtrXml#getFtrTemplate(Element)}. * @param ftr (e.g., "l.f", "l+1.m", "l-1.p", "l0_hd.d") */ protected FtrToken getFtrToken(String ftr) { String[] aField = ftr .split(DELIM_F); // {"l-1_hd", "p"} String[] aRelation = aField[0].split(DELIM_R); // {"l-1", "hd"} char source = aRelation[0].charAt(0); if (!validSource(source)) xmlError(ftr); int offset = 0; if (aRelation[0].length() >= 2) { if (aRelation[0].charAt(1) == '+') offset = Integer.parseInt(aRelation[0].substring(2)); else offset = Integer.parseInt(aRelation[0].substring(1)); } String relation = null; if (aRelation.length > 1) { relation = aRelation[1]; if (!validRelation(relation)) xmlError(ftr); } String field = aField[1]; if (!validField(field)) xmlError(ftr); return new FtrToken(source, offset, relation, field); } /** Prints system error and exits. */ protected void xmlError(String error) { System.err.println("Invalid feature: "+error); System.exit(1); } public IntIntPair getSourceWindow(char source) { int min = 0, max = 0; for (FtrTemplate template : f_templates) { for (FtrToken token : template.tokens) { if (token.source == source) { if (token.offset < min) min = token.offset; else if (token.offset > max) max = token.offset; } } } return new IntIntPair(min, max); } /** * Returns the array of feature templates. * @return the array of feature templates. */ public FtrTemplate[] getFtrTemplates() { return f_templates; } /** * Returns the index'th label cutoff. * If the label cutoff is not specified, returns 0. * @param index the index of the label cutoff to be returned. * @return the index'th label cutoff. */ public int getLabelCutoff(int index) { return (index < cutoff_label.length) ? cutoff_label[index] : 0; } /** * Returns the index'th feature cutoff. * If the feature cutoff is not specified, returns 0. * @param index the index of the feature cutoff to be returned. * @return the index'th feature cutoff. */ public int getFeatureCutoff(int index) { return (index < cutoff_feature.length) ? cutoff_feature[index] : 0; } public String toString() { return s_prettyPrint; } /** * Initializes sub-class specific cutoffs. * @param eList the list of cutoff elements. */ abstract protected void initCutoffMore(NodeList eList); /** * Returns {@code true} if the specific source is valid. * @param source the source to be compared. * @return {@code true} if the specific source is valid. */ abstract protected boolean validSource(char source); /** * Returns {@code true} if the specific relation is valid. * @param relation the relation to be compared. * @return {@code true} if the specific relation is valid. */ abstract protected boolean validRelation(String relation); /** * Returns {@code true} if the specific field is valid. * @param filed the field to be compared. * @return {@code true} if the specific field is valid. */ abstract protected boolean validField(String filed); }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.hadoop.serialization; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.elasticsearch.hadoop.EsHadoopIllegalArgumentException; import org.elasticsearch.hadoop.cfg.Settings; import org.elasticsearch.hadoop.rest.EsHadoopParsingException; import org.elasticsearch.hadoop.serialization.Parser.NumberType; import org.elasticsearch.hadoop.serialization.Parser.Token; import org.elasticsearch.hadoop.serialization.builder.ValueParsingCallback; import org.elasticsearch.hadoop.serialization.builder.ValueReader; import org.elasticsearch.hadoop.serialization.dto.mapping.Field; import org.elasticsearch.hadoop.serialization.dto.mapping.MappingUtils; import org.elasticsearch.hadoop.serialization.field.FieldFilter; import org.elasticsearch.hadoop.serialization.field.FieldFilter.NumberedInclude; import org.elasticsearch.hadoop.serialization.json.JacksonJsonParser; import org.elasticsearch.hadoop.util.Assert; import org.elasticsearch.hadoop.util.BytesArray; import org.elasticsearch.hadoop.util.FastByteArrayInputStream; import org.elasticsearch.hadoop.util.IOUtils; import org.elasticsearch.hadoop.util.StringUtils; /** * Class handling the conversion of data from ES to target objects. It performs tree navigation tied to a potential ES mapping (if available). * Expected to read a _search response. */ public class ScrollReader { private static class JsonFragment { static final JsonFragment EMPTY = new JsonFragment(-1, -1) { @Override public String toString() { return "Empty"; } }; final int charStart, charStop; JsonFragment(int charStart, int charStop) { this.charStart = charStart; this.charStop = charStop; } boolean isValid() { return charStart >= 0 && charStop >= 0; } @Override public String toString() { return "[" + charStart + "," + charStop + "]"; } } // a collection of Json Fragments private static class JsonResult { private JsonFragment doc = JsonFragment.EMPTY; // typically only 2 fragments are needed = metadata prefix + private final List<JsonFragment> fragments = new ArrayList<JsonFragment>(2); void addMetadata(JsonFragment fragment) { if (fragment != null && fragment.isValid()) { this.fragments.add(fragment); } } void addDoc(JsonFragment fragment) { if (fragment != null && fragment.isValid()) { this.doc = fragment; } } boolean hasDoc() { return doc.isValid(); } int[] asCharPos() { int positions = fragments.size() << 1; if (doc.isValid()) { positions += 2; } int[] pos = new int[positions]; int index = 0; if (doc.isValid()) { pos[index++] = doc.charStart; pos[index++] = doc.charStop; } for (JsonFragment fragment : fragments) { pos[index++] = fragment.charStart; pos[index++] = fragment.charStop; } return pos; } @Override public String toString() { return "doc=" + doc + "metadata=" + fragments; } } public static class Scroll { static final Scroll EMPTY = new Scroll("", -1l, Collections.<Object[]> emptyList()); private final String scrollId; private final long total; private final List<Object[]> hits; private Scroll(String scrollId, long total, List<Object[]> hits) { this.scrollId = scrollId; this.hits = hits; this.total = total; } public String getScrollId() { return scrollId; } public long getTotalHits() { return total; } public List<Object[]> getHits() { return hits; } } public static class ScrollReaderConfig { public ValueReader reader; public boolean readMetadata; public String metadataName; public boolean returnRawJson; public boolean ignoreUnmappedFields; public List<String> includeFields; public List<String> excludeFields; public Field rootField; public ScrollReaderConfig(ValueReader reader, Field rootField, boolean readMetadata, String metadataName, boolean returnRawJson, boolean ignoreUnmappedFields, List<String> includeFields, List<String> excludeFields) { super(); this.reader = reader; this.readMetadata = readMetadata; this.metadataName = metadataName; this.returnRawJson = returnRawJson; this.ignoreUnmappedFields = ignoreUnmappedFields; this.includeFields = includeFields; this.excludeFields = excludeFields; this.rootField = rootField; } public ScrollReaderConfig(ValueReader reader, Field rootField, boolean readMetadata, String metadataName, boolean returnRawJson, boolean ignoreUnmappedFields) { this(reader, rootField, readMetadata, metadataName, returnRawJson, ignoreUnmappedFields, Collections.<String> emptyList(), Collections.<String> emptyList()); } public ScrollReaderConfig(ValueReader reader) { this(reader, null, false, "_metadata", false, false, Collections.<String> emptyList(), Collections.<String> emptyList()); } public ScrollReaderConfig(ValueReader reader, Field field, Settings cfg) { this(reader, field, cfg.getReadMetadata(), cfg.getReadMetadataField(), cfg.getOutputAsJson(), cfg.getReadMappingMissingFieldsIgnore(), StringUtils.tokenize(cfg.getReadFieldInclude()), StringUtils.tokenize(cfg.getReadFieldExclude())); } } private static final Log log = LogFactory.getLog(ScrollReader.class); private Parser parser; private final ValueReader reader; private final ValueParsingCallback parsingCallback; private final Map<String, FieldType> esMapping; private final boolean trace = log.isTraceEnabled(); private final boolean readMetadata; private final String metadataField; private final boolean returnRawJson; private final boolean ignoreUnmappedFields; private boolean insideGeo = false; private final List<NumberedInclude> includeFields; private final List<String> excludeFields; private static final String[] SCROLL_ID = new String[] { "_scroll_id" }; private static final String[] HITS = new String[] { "hits" }; private static final String ID_FIELD = "_id"; private static final String[] ID = new String[] { ID_FIELD }; private static final String[] FIELDS = new String[] { "fields" }; private static final String[] SOURCE = new String[] { "_source" }; private static final String[] TOTAL = new String[] { "hits", "total" }; public ScrollReader(ScrollReaderConfig scrollConfig) { this.reader = scrollConfig.reader; this.parsingCallback = (reader instanceof ValueParsingCallback ? (ValueParsingCallback) reader : null); this.readMetadata = scrollConfig.readMetadata; this.metadataField = scrollConfig.metadataName; this.returnRawJson = scrollConfig.returnRawJson; this.ignoreUnmappedFields = scrollConfig.ignoreUnmappedFields; this.includeFields = FieldFilter.toNumberedFilter(scrollConfig.includeFields); this.excludeFields = scrollConfig.excludeFields; Field mapping = scrollConfig.rootField; // optimize filtering if (ignoreUnmappedFields) { mapping = MappingUtils.filter(mapping, scrollConfig.includeFields, scrollConfig.excludeFields); } this.esMapping = Field.toLookupMap(mapping); } public Scroll read(InputStream content) throws IOException { Assert.notNull(content); BytesArray copy = null; if (log.isTraceEnabled() || returnRawJson) { //copy content copy = IOUtils.asBytes(content); content = new FastByteArrayInputStream(copy); log.trace("About to parse scroll content " + copy); } this.parser = new JacksonJsonParser(content); try { return read(copy); } finally { parser.close(); } } private Scroll read(BytesArray input) { // get scroll_id Token token = ParsingUtils.seek(parser, SCROLL_ID); Assert.isTrue(token == Token.VALUE_STRING, "invalid response"); String scrollId = parser.text(); long totalHits = hitsTotal(); // check hits/total if (totalHits == 0) { return Scroll.EMPTY; } // move to hits/hits token = ParsingUtils.seek(parser, HITS); // move through the list and for each hit, extract the _id and _source Assert.isTrue(token == Token.START_ARRAY, "invalid response"); List<Object[]> results = new ArrayList<Object[]>(); for (token = parser.nextToken(); token != Token.END_ARRAY; token = parser.nextToken()) { results.add(readHit()); } // convert the char positions into actual content if (returnRawJson) { // get all the longs int[] pos = new int[results.size() * 6]; int offset = 0; List<int[]> fragmentsPos = new ArrayList<int[]>(results.size()); for (Object[] result : results) { int[] asCharPos = ((JsonResult) result[1]).asCharPos(); // remember the positions to easily replace the fragment later on fragmentsPos.add(asCharPos); // copy them into the lookup array System.arraycopy(asCharPos, 0, pos, offset, asCharPos.length); offset += asCharPos.length; } // convert them into byte positions //int[] bytesPosition = BytesUtils.charToBytePosition(input, pos); int[] bytesPosition = pos; int bytesPositionIndex = 0; BytesArray doc = new BytesArray(128); // replace the fragments with the actual json // trimming is currently disabled since it appears mainly within fields and not outside of it // in other words in needs to be treated when the fragments are constructed for (int fragmentIndex = 0; fragmentIndex < fragmentsPos.size(); fragmentIndex++ ) { Object[] result = results.get(fragmentIndex); JsonResult jsonPointers = (JsonResult) result[1]; // current fragment of doc + metadata (prefix + suffix) // used to iterate through the byte array pointers int[] fragmentPos = fragmentsPos.get(fragmentIndex); int currentFragmentIndex = 0; int rangeStart, rangeStop; doc.add('{'); // first add the doc if (jsonPointers.hasDoc()) { rangeStart = bytesPosition[bytesPositionIndex]; rangeStop = bytesPosition[bytesPositionIndex + 1]; if (rangeStop - rangeStart < 0) { throw new IllegalArgumentException(String.format("Invalid position given=%s %s",rangeStart, rangeStop)); } // trim //rangeStart = BytesUtils.trimLeft(input.bytes(), rangeStart, rangeStop); //rangeStop = BytesUtils.trimRight(input.bytes(), rangeStart, rangeStop); doc.add(input.bytes(), rangeStart, rangeStop - rangeStart); // consumed doc pointers currentFragmentIndex += 2; bytesPositionIndex += 2; } // followed by the metadata under designed field if (readMetadata) { if (jsonPointers.hasDoc()) { doc.add(','); } doc.add('"'); doc.add(StringUtils.jsonEncoding(metadataField)); doc.add('"'); doc.add(':'); doc.add('{'); // consume metadata for (; currentFragmentIndex < fragmentPos.length; currentFragmentIndex += 2) { rangeStart = bytesPosition[bytesPositionIndex]; rangeStop = bytesPosition[bytesPositionIndex + 1]; // trim //rangeStart = BytesUtils.trimLeft(input.bytes(), rangeStart, rangeStop); //rangeStop = BytesUtils.trimRight(input.bytes(), rangeStart, rangeStop); if (rangeStop - rangeStart < 0) { throw new IllegalArgumentException(String.format("Invalid position given=%s %s",rangeStart, rangeStop)); } doc.add(input.bytes(), rangeStart, rangeStop - rangeStart); bytesPositionIndex += 2; } doc.add('}'); } doc.add('}'); // replace JsonResult with assembled document result[1] = reader.wrapString(doc.toString()); doc.reset(); } } return new Scroll(scrollId, totalHits, results); } private Object[] readHit() { Token t = parser.currentToken(); Assert.isTrue(t == Token.START_OBJECT, "expected object, found " + t); return (returnRawJson ? readHitAsJson() : readHitAsMap()); } private Object[] readHitAsMap() { Object[] result = new Object[2]; Object metadata = null; Object id = null; Token t = parser.currentToken(); if (parsingCallback != null) { parsingCallback.beginDoc(); } // read everything until SOURCE or FIELDS is encountered if (readMetadata) { if (parsingCallback != null) { parsingCallback.beginLeadMetadata(); } metadata = reader.createMap(); result[1] = metadata; String absoluteName; // move parser t = parser.nextToken(); while ((t = parser.currentToken()) != null) { String name = parser.currentName(); absoluteName = StringUtils.stripFieldNameSourcePrefix(parser.absoluteName()); Object value = null; if (t == Token.FIELD_NAME) { if (!("fields".equals(name) || "_source".equals(name))) { reader.beginField(absoluteName); value = read(absoluteName, parser.nextToken(), null); if (ID_FIELD.equals(name)) { id = value; } reader.addToMap(metadata, reader.wrapString(name), value); reader.endField(absoluteName); } else { t = parser.nextToken(); break; } } else { // if = no _source or field found, else select START_OBJECT t = null; break; } } if (parsingCallback != null) { parsingCallback.endLeadMetadata(); } Assert.notNull(id, "no id found"); result[0] = id; } // no metadata is needed, fast fwd else { Assert.notNull(ParsingUtils.seek(parser, ID), "no id found"); result[0] = reader.wrapString(parser.text()); t = ParsingUtils.seek(parser, SOURCE, FIELDS); } // no fields found Object data = Collections.emptyMap(); if (t != null) { if (parsingCallback != null) { parsingCallback.beginSource(); } data = read(StringUtils.EMPTY, t, null); if (parsingCallback != null) { parsingCallback.endSource(); } if (readMetadata) { reader.addToMap(data, reader.wrapString(metadataField), metadata); } } else { if (readMetadata) { data = reader.createMap(); reader.addToMap(data, reader.wrapString(metadataField), metadata); } } result[1] = data; if (readMetadata) { if (parsingCallback != null) { parsingCallback.beginTrailMetadata(); } } // in case of additional fields (matched_query), add them to the metadata while (parser.currentToken() == Token.FIELD_NAME) { String name = parser.currentName(); String absoluteName = StringUtils.stripFieldNameSourcePrefix(parser.absoluteName()); if (readMetadata) { // skip sort (useless and is an array which triggers the row mapping which does not apply) if (!"sort".equals(name)) { reader.addToMap(data, reader.wrapString(name), read(absoluteName, parser.nextToken(), null)); } else { parser.nextToken(); parser.skipChildren(); parser.nextToken(); } } else { parser.nextToken(); parser.skipChildren(); parser.nextToken(); } } if (readMetadata) { if (parsingCallback != null) { parsingCallback.endTrailMetadata(); } } if (parsingCallback != null) { parsingCallback.endDoc(); } if (trace) { log.trace(String.format("Read hit result [%s]", result)); } return result; } private boolean shouldSkip(String absoluteName) { // when parsing geo structures, ignore filtering as depending on the // type, JSON can have an object structure // especially for geo shapes if (insideGeo) { return false; } // if ignoring unmapped fields, the filters are already applied if (ignoreUnmappedFields) { return !esMapping.containsKey(absoluteName); } else { return !FieldFilter.filter(absoluteName, includeFields, excludeFields).matched; } } private Object[] readHitAsJson() { // return results as raw json Object[] result = new Object[2]; Object id = null; Token t = parser.currentToken(); JsonResult snippet = new JsonResult(); // read everything until SOURCE or FIELDS is encountered if (readMetadata) { result[1] = snippet; String name; String absoluteName; t = parser.nextToken(); // move parser int metadataStartChar = parser.tokenCharOffset(); int metadataStopChar = -1; int endCharOfLastElement = -1; while ((t = parser.currentToken()) != null) { name = parser.currentName(); absoluteName = StringUtils.stripFieldNameSourcePrefix(parser.absoluteName()); if (t == Token.FIELD_NAME) { if (ID_FIELD.equals(name)) { reader.beginField(absoluteName); t = parser.nextToken(); id = reader.wrapString(parser.text()); endCharOfLastElement = parser.tokenCharOffset(); reader.endField(absoluteName); t = parser.nextToken(); } else if ("fields".equals(name) || "_source".equals(name)) { metadataStopChar = endCharOfLastElement; // break meta-parsing t = parser.nextToken(); break; } else { parser.skipChildren(); parser.nextToken(); t = parser.nextToken(); endCharOfLastElement = parser.tokenCharOffset(); } } else { // no _source or field found metadataStopChar = endCharOfLastElement; //parser.nextToken(); // indicate no data found t = null; break; } } Assert.notNull(id, "no id found"); result[0] = id; if (metadataStartChar >= 0 && metadataStopChar >= 0) { snippet.addMetadata(new JsonFragment(metadataStartChar, metadataStopChar)); } } // no metadata is needed, fast fwd else { Assert.notNull(ParsingUtils.seek(parser, ID), "no id found"); String absoluteName = StringUtils.stripFieldNameSourcePrefix(parser.absoluteName()); reader.beginField(absoluteName); result[0] = reader.wrapString(parser.text()); reader.endField(absoluteName); t = ParsingUtils.seek(parser, SOURCE, FIELDS); } // no fields found if (t != null) { // move past _source or fields field name to get the accurate token location t = parser.nextToken(); switch (t) { case FIELD_NAME: int charStart = parser.tokenCharOffset(); // can't use skipChildren as we are within the object ParsingUtils.skipCurrentBlock(parser); // make sure to include the ending char int charStop = parser.tokenCharOffset(); // move pass end of object t = parser.nextToken(); snippet.addDoc(new JsonFragment(charStart, charStop)); break; case END_OBJECT: // move pass end of object t = parser.nextToken(); snippet.addDoc(JsonFragment.EMPTY); break; default: throw new EsHadoopIllegalArgumentException("unexpected token in _source: " + t); } } // should include , plus whatever whitespace there is int metadataSuffixStartCharPos = parser.tokenCharOffset(); int metadataSuffixStopCharPos = -1; // in case of additional fields (matched_query), add them to the metadata while ((t = parser.currentToken()) == Token.FIELD_NAME) { t = parser.nextToken(); ParsingUtils.skipCurrentBlock(parser); t = parser.nextToken(); if (readMetadata) { metadataSuffixStopCharPos = parser.tokenCharOffset(); } } if (readMetadata) { if (metadataSuffixStartCharPos >= 0 && metadataSuffixStopCharPos >= 0) { snippet.addMetadata(new JsonFragment(metadataSuffixStartCharPos, metadataSuffixStopCharPos)); } } result[1] = snippet; if (trace) { log.trace(String.format("Read hit result [%s]", result)); } return result; } private long hitsTotal() { ParsingUtils.seek(parser, TOTAL); long hits = parser.longValue(); return hits; } protected Object read(String fieldName, Token t, String fieldMapping) { if (t == Token.START_ARRAY) { return list(fieldName, fieldMapping); } // handle nested nodes first else if (t == Token.START_OBJECT) { return map(fieldMapping); } FieldType esType = mapping(fieldMapping); if (t.isValue()) { String rawValue = parser.text(); try { return parseValue(esType); } catch (Exception ex) { throw new EsHadoopParsingException(String.format(Locale.ROOT, "Cannot parse value [%s] for field [%s]", rawValue, fieldName), ex); } } return null; } private Object parseValue(FieldType esType) { Object obj; // special case of handing null (as text() will return "null") if (parser.currentToken() == Token.VALUE_NULL) { obj = null; } else { obj = reader.readValue(parser, parser.text(), esType); } parser.nextToken(); return obj; } protected Object list(String fieldName, String fieldMapping) { Token t = parser.currentToken(); if (t == null) { t = parser.nextToken(); } if (t == Token.START_ARRAY) { t = parser.nextToken(); } Object array = reader.createArray(mapping(fieldMapping)); // create only one element since with fields, we always get arrays which create unneeded allocations List<Object> content = new ArrayList<Object>(1); for (; parser.currentToken() != Token.END_ARRAY;) { content.add(read(fieldName, parser.currentToken(), fieldMapping)); } // eliminate END_ARRAY parser.nextToken(); array = reader.addToArray(array, content); return array; } protected Object map(String fieldMapping) { Token t = parser.currentToken(); if (t == null) { t = parser.nextToken(); } if (t == Token.START_OBJECT) { t = parser.nextToken(); } boolean toggleGeo = false; if (fieldMapping != null) { // parse everything underneath without mapping if (FieldType.isGeo(mapping(fieldMapping))) { toggleGeo = true; insideGeo = true; if (parsingCallback != null) { parsingCallback.beginGeoField(); } } } Object map = reader.createMap(); for (; parser.currentToken() != Token.END_OBJECT;) { String currentName = parser.currentName(); String nodeMapping = fieldMapping; if (nodeMapping != null) { nodeMapping = fieldMapping + "." + currentName; } else { nodeMapping = currentName; } String absoluteName = StringUtils.stripFieldNameSourcePrefix(parser.absoluteName()); if (!absoluteName.equals(nodeMapping)) { throw new EsHadoopParsingException("Different node mapping " + absoluteName + "|" + nodeMapping); } if (shouldSkip(absoluteName)) { Token nt = parser.nextToken(); if (nt.isValue()) { // consume and move on parser.nextToken(); } else { ParsingUtils.skipCurrentBlock(parser); parser.nextToken(); } } else { reader.beginField(absoluteName); // Must point to field name Object fieldName = reader.readValue(parser, currentName, FieldType.STRING); // And then the value... reader.addToMap(map, fieldName, read(absoluteName, parser.nextToken(), nodeMapping)); reader.endField(absoluteName); } } // geo field finished, returning if (toggleGeo) { insideGeo = false; if (parsingCallback != null) { parsingCallback.endGeoField(); } } // eliminate END_OBJECT parser.nextToken(); return map; } private FieldType mapping(String fieldMapping) { FieldType esType = esMapping.get(fieldMapping); if (esType != null) { return esType; } // fall back to JSON Token currentToken = parser.currentToken(); if (!currentToken.isValue()) { // nested type return FieldType.OBJECT; } switch (currentToken) { case VALUE_NULL: esType = FieldType.NULL; break; case VALUE_BOOLEAN: esType = FieldType.BOOLEAN; break; case VALUE_STRING: esType = FieldType.STRING; break; case VALUE_NUMBER: NumberType numberType = parser.numberType(); switch (numberType) { case INT: esType = FieldType.INTEGER; break; case LONG: esType = FieldType.LONG; break; case FLOAT: esType = FieldType.FLOAT; break; case DOUBLE: esType = FieldType.DOUBLE; break; case BIG_DECIMAL: throw new UnsupportedOperationException(); case BIG_INTEGER: throw new UnsupportedOperationException(); default: break; } break; default: break; } return esType; } }
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.sensitivities; import java.util.Map; import org.joda.beans.Bean; import org.joda.beans.BeanBuilder; import org.joda.beans.BeanDefinition; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaProperty; import org.joda.beans.Property; import org.joda.beans.PropertyDefinition; import org.joda.beans.impl.direct.DirectBean; import org.joda.beans.impl.direct.DirectBeanBuilder; import org.joda.beans.impl.direct.DirectMetaBean; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import org.threeten.bp.LocalDate; import com.opengamma.id.ExternalId; import com.opengamma.util.money.Currency; /** * */ @BeanDefinition public class SecurityEntryData extends DirectBean { /** Name for the external security scheme */ public static final String SECURITY_SCHEME = "EXTERNAL_SENSITIVITIES_SECURITY"; @PropertyDefinition private ExternalId _id; @PropertyDefinition private Currency _currency; @PropertyDefinition private LocalDate _maturityDate; @PropertyDefinition private ExternalId _factorSetId; /** Name of the external security type */ public static final String EXTERNAL_SENSITIVITIES_SECURITY_TYPE = "EXTERNAL_SENSITIVITIES_SECURITY"; public SecurityEntryData() { } public SecurityEntryData(ExternalId id, Currency currency, LocalDate maturityDate, ExternalId factorSetId) { setId(id); setCurrency(currency); setMaturityDate(maturityDate); setFactorSetId(factorSetId); } //------------------------- AUTOGENERATED START ------------------------- ///CLOVER:OFF /** * The meta-bean for {@code SecurityEntryData}. * @return the meta-bean, not null */ public static SecurityEntryData.Meta meta() { return SecurityEntryData.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(SecurityEntryData.Meta.INSTANCE); } @Override public SecurityEntryData.Meta metaBean() { return SecurityEntryData.Meta.INSTANCE; } //----------------------------------------------------------------------- /** * Gets the id. * @return the value of the property */ public ExternalId getId() { return _id; } /** * Sets the id. * @param id the new value of the property */ public void setId(ExternalId id) { this._id = id; } /** * Gets the the {@code id} property. * @return the property, not null */ public final Property<ExternalId> id() { return metaBean().id().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the currency. * @return the value of the property */ public Currency getCurrency() { return _currency; } /** * Sets the currency. * @param currency the new value of the property */ public void setCurrency(Currency currency) { this._currency = currency; } /** * Gets the the {@code currency} property. * @return the property, not null */ public final Property<Currency> currency() { return metaBean().currency().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the maturityDate. * @return the value of the property */ public LocalDate getMaturityDate() { return _maturityDate; } /** * Sets the maturityDate. * @param maturityDate the new value of the property */ public void setMaturityDate(LocalDate maturityDate) { this._maturityDate = maturityDate; } /** * Gets the the {@code maturityDate} property. * @return the property, not null */ public final Property<LocalDate> maturityDate() { return metaBean().maturityDate().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the factorSetId. * @return the value of the property */ public ExternalId getFactorSetId() { return _factorSetId; } /** * Sets the factorSetId. * @param factorSetId the new value of the property */ public void setFactorSetId(ExternalId factorSetId) { this._factorSetId = factorSetId; } /** * Gets the the {@code factorSetId} property. * @return the property, not null */ public final Property<ExternalId> factorSetId() { return metaBean().factorSetId().createProperty(this); } //----------------------------------------------------------------------- @Override public SecurityEntryData clone() { return JodaBeanUtils.cloneAlways(this); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { SecurityEntryData other = (SecurityEntryData) obj; return JodaBeanUtils.equal(getId(), other.getId()) && JodaBeanUtils.equal(getCurrency(), other.getCurrency()) && JodaBeanUtils.equal(getMaturityDate(), other.getMaturityDate()) && JodaBeanUtils.equal(getFactorSetId(), other.getFactorSetId()); } return false; } @Override public int hashCode() { int hash = getClass().hashCode(); hash = hash * 31 + JodaBeanUtils.hashCode(getId()); hash = hash * 31 + JodaBeanUtils.hashCode(getCurrency()); hash = hash * 31 + JodaBeanUtils.hashCode(getMaturityDate()); hash = hash * 31 + JodaBeanUtils.hashCode(getFactorSetId()); return hash; } @Override public String toString() { StringBuilder buf = new StringBuilder(160); buf.append("SecurityEntryData{"); int len = buf.length(); toString(buf); if (buf.length() > len) { buf.setLength(buf.length() - 2); } buf.append('}'); return buf.toString(); } protected void toString(StringBuilder buf) { buf.append("id").append('=').append(JodaBeanUtils.toString(getId())).append(',').append(' '); buf.append("currency").append('=').append(JodaBeanUtils.toString(getCurrency())).append(',').append(' '); buf.append("maturityDate").append('=').append(JodaBeanUtils.toString(getMaturityDate())).append(',').append(' '); buf.append("factorSetId").append('=').append(JodaBeanUtils.toString(getFactorSetId())).append(',').append(' '); } //----------------------------------------------------------------------- /** * The meta-bean for {@code SecurityEntryData}. */ public static class Meta extends DirectMetaBean { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code id} property. */ private final MetaProperty<ExternalId> _id = DirectMetaProperty.ofReadWrite( this, "id", SecurityEntryData.class, ExternalId.class); /** * The meta-property for the {@code currency} property. */ private final MetaProperty<Currency> _currency = DirectMetaProperty.ofReadWrite( this, "currency", SecurityEntryData.class, Currency.class); /** * The meta-property for the {@code maturityDate} property. */ private final MetaProperty<LocalDate> _maturityDate = DirectMetaProperty.ofReadWrite( this, "maturityDate", SecurityEntryData.class, LocalDate.class); /** * The meta-property for the {@code factorSetId} property. */ private final MetaProperty<ExternalId> _factorSetId = DirectMetaProperty.ofReadWrite( this, "factorSetId", SecurityEntryData.class, ExternalId.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap( this, null, "id", "currency", "maturityDate", "factorSetId"); /** * Restricted constructor. */ protected Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case 3355: // id return _id; case 575402001: // currency return _currency; case -414641441: // maturityDate return _maturityDate; case 42976526: // factorSetId return _factorSetId; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder<? extends SecurityEntryData> builder() { return new DirectBeanBuilder<SecurityEntryData>(new SecurityEntryData()); } @Override public Class<? extends SecurityEntryData> beanType() { return SecurityEntryData.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return _metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code id} property. * @return the meta-property, not null */ public final MetaProperty<ExternalId> id() { return _id; } /** * The meta-property for the {@code currency} property. * @return the meta-property, not null */ public final MetaProperty<Currency> currency() { return _currency; } /** * The meta-property for the {@code maturityDate} property. * @return the meta-property, not null */ public final MetaProperty<LocalDate> maturityDate() { return _maturityDate; } /** * The meta-property for the {@code factorSetId} property. * @return the meta-property, not null */ public final MetaProperty<ExternalId> factorSetId() { return _factorSetId; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case 3355: // id return ((SecurityEntryData) bean).getId(); case 575402001: // currency return ((SecurityEntryData) bean).getCurrency(); case -414641441: // maturityDate return ((SecurityEntryData) bean).getMaturityDate(); case 42976526: // factorSetId return ((SecurityEntryData) bean).getFactorSetId(); } return super.propertyGet(bean, propertyName, quiet); } @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { switch (propertyName.hashCode()) { case 3355: // id ((SecurityEntryData) bean).setId((ExternalId) newValue); return; case 575402001: // currency ((SecurityEntryData) bean).setCurrency((Currency) newValue); return; case -414641441: // maturityDate ((SecurityEntryData) bean).setMaturityDate((LocalDate) newValue); return; case 42976526: // factorSetId ((SecurityEntryData) bean).setFactorSetId((ExternalId) newValue); return; } super.propertySet(bean, propertyName, newValue, quiet); } } ///CLOVER:ON //-------------------------- AUTOGENERATED END -------------------------- }
/* * Copyright 2016 Dimitry Ivanov ([email protected]) * * 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 scriptjava.parser; import scriptjava.buildins.Bool; import java.lang.reflect.Modifier; import java.util.Set; public class StatementParserManual extends StatementParserBase { public StatementParserManual(Class<?>[] buildIns) { super(buildIns); } @Override public Statement parse(String line) { return new LineParser(buildIns, line).parse(); } private static class LineParser { private final Set<String> buildIns; private final String line; private final int length; int index = -1; char c; LineParser(Set<String> buildIns, String line) { this.buildIns = buildIns; this.line = line; this.length = line.length(); } Statement parse() { next(); // the `static {` & `{` if (isInitializationBlock()) { return new StatementMember(line); } // let's check modifiers final int modifiers = modifiers(); // ok, if modifiers are already interface|abstract|(visibility)|static|synchronized|native|transient|volatile // then it's a member if (isMemberModifiers(modifiers)) { return new StatementMember(line); } // ok, as we have passed modifiers at this point check what is it next: class, method (without modifiers) if (isClassDeclaration()) { return new StatementMember(line); } // loops & if/else if (isCodeBlock()) { return new StatementExecution(line, false); } // check if it's void call // check if it's out build-in method call final Statement methodOrVariable = methodOrVariable(); if (methodOrVariable != null) { return methodOrVariable; } // just in case return new StatementExecution(line, true); } private boolean isMemberModifiers(int modifiers) { return Modifier.isPublic(modifiers) || Modifier.isPrivate(modifiers) || Modifier.isProtected(modifiers) || Modifier.isStatic(modifiers) || Modifier.isInterface(modifiers) || Modifier.isAbstract(modifiers) || Modifier.isSynchronized(modifiers) || Modifier.isNative(modifiers) || Modifier.isTransient(modifiers) || Modifier.isVolatile(modifiers); } // static void log(String message, Object... args) { // System.out.printf(message, args); // System.out.println(); // } boolean next() { return next(1); } boolean next(int step) { final boolean result; index += step; if (!canRead()) { c = '\0'; result = false; } else { c = line.charAt(index); result = true; } return result; } private boolean isInitializationBlock() { if (!clearSpaces()) { return false; } final int started = index; boolean result = false; switch (c) { case '{': result = true; break; case 's': result = read("tatic {") || read("tatic{"); if (!result) { reset(started); } break; } return result; } private int modifiers() { // in case we didn't match any of the modifiers, we must set the `i` to initial value int started = index; int mod = 0; boolean reading = true; while (reading) { if (isWhiteSpace()) { if (!next()) { reading = false; } else { continue; } } if (reading) { switch (c) { case 'p': if (!next()) { reading = false; break; } // read public private protected if ('u' == c) { // public if (read("blic ")) { mod += Modifier.PUBLIC; } else { // we didn't match the public reading = false; } } else if ('r' == c) { if (!next()) { reading = false; break; } // private | protected if ('i' == c) { // private if (read("vate ")) { mod += Modifier.PRIVATE; } else { reading = false; } } else if ('o' == c) { // protected if (read("tected ")) { mod += Modifier.PROTECTED; } else { reading = false; } } else { reading = false; } } break; case 's': if (!next()) { reading = false; break; } // read static, synchronized // 's' -> strictfp is not supported if ('t' == c) { // static if (read("atic ")) { mod += Modifier.STATIC; } else { reading = false; } } else if ('y' == c) { // synchronized if (read("nchronized ")) { mod += Modifier.SYNCHRONIZED; } else { reading = false; } } else { reading = false; } break; case 'f': // read final if (read("inal ")) { mod += Modifier.FINAL; } else { reading = false; } break; case 'a': // read abstract if (read("bstract ")) { mod += Modifier.ABSTRACT; } else { reading = false; } break; case 't': // read transient if (read("ransient")) { mod += Modifier.TRANSIENT; } else { reading = false; } break; case 'v': // read volatile if (read("olatile ")) { mod += Modifier.VOLATILE; } else { reading = false; } break; case 'n': // read native if (read("ative ")) { mod += Modifier.NATIVE; } else { reading = false; } break; case 'i': // read interface if (read("nterface ")) { mod += Modifier.INTERFACE; } else { reading = false; } break; default: reading = false; } } } // we didn't match anything -> revert to the started position if (mod == 0) { reset(started); } return mod; } private boolean isClassDeclaration() { // class Name // <Type> name () { final int started = index; boolean result = false; if (!clearSpaces()) { return false; } if ('c' == c) { // check if it's `class ` // else if could be return type for a method if (read("lass ")) { result = true; } } if (!result) { reset(started); } return result; } private Statement methodOrVariable() { // Method declaration: <Type> <Space> <Name> <*Space> <(> <*> <)> // Method call: <*Type && `.`><Name><*Space><(><*><)> // Variable declaration: <Type> <Space> <Name> <*Space> <`=`> <*> // Variable reassignment: <Name> <*Space> <`=`> <*> // SomeClass.<String>myMethod(null); // new Thread(/**/).start(); // new Date() { public void toString() { return "date"; } }; -> `new` should not be type // SomeClass.SomeInnerClass nameOfTheMethod(); // chain1().chain2().chain3(); // chain1().field = null; // (true == true) -> is not a method call // also... `String s`; -> must be valid variable declaration... // ok, it looks like we must start from the end of the line if (!clearSpaces()) { return null; } final int started = index; char ch; boolean isMethod = false; boolean isVariable = false; // method: wee need to find the most `()` to the left int i; for (i = index; i < length; i++) { ch = line.charAt(i); if ('(' == ch) { isMethod = true; break; } else if('!' == ch) { break; } else if ('=' == ch) { // but we need to be sure that it's not `==` i += 1; if (line.charAt(i) == '=') { // it's not a variable it's a boolean expression break; } else { isVariable = true; break; } } } i -= 1; final Statement statement; if (isMethod) { Statement method = null; // let's check if there is a caller info previously to `(.*)` // and parse it -> if it contains return type -> method declaration // else method call // if it's method declaration -> the name cannot contain anything except valid java identifier (no generics, no dots) String name = null; char methodChar; final StringBuilder builder = new StringBuilder(); outer: for (int m = i; m >= index; m--) { // the space can be: before `(` -> optional // the space can be: before <Name> methodChar = line.charAt(m); if (!Character.isWhitespace(methodChar)) { // here we start, depending on the state: // parsing name // parsing type (we can skip parsing the full type, as long as there is a least one char -> it's it) if (Bool.bool(name)) { // we already have name -> it's type info // also need to insert a check if type equals `new` -> simple method call, not method declaration builder.setLength(0); char innerChar; for (int m2 = m; m2 >= index; m2--) { innerChar = line.charAt(m2); if (Character.isWhitespace(innerChar)) { // if we have out builder here -> stop // else skip if (builder.length() == 0) { continue; } } // to ignore all possible operations: `+`, etc if (Character.isLetterOrDigit(innerChar)) { builder.insert(0, innerChar); } else { // but we must ignore all the `(),` // check for `=` sign? if ('=' == innerChar) { // check fo bool expressions... m2 -= 1; if ('=' == line.charAt(m2) || '!' == line.charAt(m2)) { // boolean } else { // variable? method = new StatementExecution(line, false); } } name = null; builder.setLength(0); break outer; } } // if it's just simple `new Date()` for example -> just execute it if ("new".equals(builder.toString())) { method = new StatementExecution(line, false); } else { method = new StatementMember(line); } break; } else if ('.' == methodChar) { // CHECK here if it's a dot `.` -> method call name = builder.toString(); builder.setLength(0); break; } else { // if name is still not present // in case of wrapped calls `bool(file())` if (Character.isLetterOrDigit(methodChar)) { builder.insert(0, methodChar); } else { name = null; builder.setLength(0); } } } else { // todo, else let's check if we have something previously // if we have -> we need to parse it also if (!Bool.bool(name) && builder.length() != 0) { name = builder.toString(); builder.setLength(0); } } } if (method != null) { statement = method; } else { // method call? // if name != null || builder.length > 0 if (!Bool.bool(name)) { name = builder.toString(); } if (Bool.bool(name)) { // check if it's our build-in method final boolean isPrint = !"print".equals(name) && !"printf".equals(name) && buildIns.contains(name); statement = new StatementExecution(line, isPrint); } else { statement = null; } } } else if (isVariable) { // two possible states -> new variable (local to execution state) & reassignment // if it's simply <Name><`=`> -> reassignment, else declaration // Variable declaration: <Type> <Space> <Name> <*Space> <`=`> <*> // Variable reassignment: <Name> <*Space> <`=`> <*> statement = new StatementExecution(line, false, true); } else { statement = null; } if (statement == null) { reset(started); } return statement; } // loops & if/else private boolean isCodeBlock() { // if // for // while // do if (!clearSpaces()) { return false; } final int started = index; boolean result = false; switch (c) { case 'i': // if result = read("f ") || read("f("); break; case 'f': // for result = read("or ") || read("or("); break; case 'w': // while: result = read("hile ") || read("hile("); break; case 'd': // do result = read("o ") || read("o{"); break; } if (!result) { reset(started); } return result; } private boolean isWhiteSpace() { return Character.isWhitespace(c); } private boolean canRead() { return index < length; } private boolean canRead(int plus) { return (index + plus) < length; } private boolean clearSpaces() { while (isWhiteSpace()) { if (!next()) { return false; } } return true; } private void reset(int position) { index = position; c = line.charAt(index); } private boolean read(String what) { final int readLength = what.length(); // ok, here we must check that we are in bounds if (!canRead(readLength)) { return false; } boolean matched = true; for (int i = 0; i < readLength; i++) { if (next() && c == what.charAt(i)) { continue; } else { matched = false; } } if (matched) { next(); } return matched; } } }
/** * Copyright (c) 2009 * Philipp Giese, Sven Wagner-Boysen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package de.hpi.bpmn2_0.model.activity; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import de.hpi.bpmn2_0.model.FlowNode; import de.hpi.bpmn2_0.model.activity.loop.LoopCharacteristics; import de.hpi.bpmn2_0.model.activity.loop.MultiInstanceLoopCharacteristics; import de.hpi.bpmn2_0.model.activity.loop.StandardLoopCharacteristics; import de.hpi.bpmn2_0.model.activity.resource.ActivityResource; import de.hpi.bpmn2_0.model.activity.resource.HumanPerformer; import de.hpi.bpmn2_0.model.activity.resource.Performer; import de.hpi.bpmn2_0.model.activity.resource.PotentialOwner; import de.hpi.bpmn2_0.model.connector.DataInputAssociation; import de.hpi.bpmn2_0.model.connector.DataOutputAssociation; import de.hpi.bpmn2_0.model.data_object.DataInput; import de.hpi.bpmn2_0.model.data_object.DataOutput; import de.hpi.bpmn2_0.model.data_object.InputOutputSpecification; import de.hpi.bpmn2_0.model.data_object.InputSet; import de.hpi.bpmn2_0.model.data_object.OutputSet; import de.hpi.bpmn2_0.model.event.BoundaryEvent; import de.hpi.bpmn2_0.model.misc.IoOption; import de.hpi.bpmn2_0.model.misc.Property; import de.hpi.diagram.OryxUUID; /** * <p>Java class for tActivity complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="tActivity"> * &lt;complexContent> * &lt;extension base="{http://www.omg.org/bpmn20}tFlowNode"> * &lt;sequence> * &lt;element ref="{http://www.omg.org/bpmn20}ioSpecification" minOccurs="0"/> * &lt;element ref="{http://www.omg.org/bpmn20}property" maxOccurs="unbounded" minOccurs="0"/> * &lt;element ref="{http://www.omg.org/bpmn20}dataInputAssociation" maxOccurs="unbounded" minOccurs="0"/> * &lt;element ref="{http://www.omg.org/bpmn20}dataOutputAssociation" maxOccurs="unbounded" minOccurs="0"/> * &lt;element ref="{http://www.omg.org/bpmn20}activityResource" maxOccurs="unbounded" minOccurs="0"/> * &lt;element ref="{http://www.omg.org/bpmn20}loopCharacteristics" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="isForCompensation" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" /> * &lt;attribute name="startQuantity" type="{http://www.w3.org/2001/XMLSchema}integer" default="1" /> * &lt;attribute name="completionQuantity" type="{http://www.w3.org/2001/XMLSchema}integer" default="1" /> * &lt;attribute name="default" type="{http://www.w3.org/2001/XMLSchema}IDREF" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "tActivity", propOrder = { "ioSpecification", "property", "boundaryEventRefs", "dataInputAssociation", "dataOutputAssociation", "activityResource", "loopCharacteristics" }) @XmlSeeAlso({ SubProcess.class, Transaction.class, Task.class, CallActivity.class }) public abstract class Activity extends FlowNode { protected InputOutputSpecification ioSpecification; protected List<Property> property; @XmlElement(name = "dataInputAssociation", type = DataInputAssociation.class) protected List<DataInputAssociation> dataInputAssociation; @XmlElement(name = "dataOutputAssociation", type = DataOutputAssociation.class) protected List<DataOutputAssociation> dataOutputAssociation; @XmlElementRefs({ @XmlElementRef(type = ActivityResource.class), @XmlElementRef(type = Performer.class), @XmlElementRef(type = HumanPerformer.class), @XmlElementRef(type = PotentialOwner.class) }) protected List<ActivityResource> activityResource; @XmlElementRefs({ @XmlElementRef(type = StandardLoopCharacteristics.class), @XmlElementRef(type = MultiInstanceLoopCharacteristics.class) }) protected LoopCharacteristics loopCharacteristics; @XmlIDREF @XmlElement(name = "boundaryEventRef", type = BoundaryEvent.class) protected List<BoundaryEvent> boundaryEventRefs; @XmlAttribute protected Boolean isForCompensation; @XmlAttribute protected BigInteger startQuantity; @XmlAttribute protected BigInteger completionQuantity; @XmlAttribute(name = "default") @XmlIDREF @XmlSchemaType(name = "IDREF") protected Object _default; @XmlTransient private List<HashMap<String, IoOption>> inputSetInfo; @XmlTransient private List<HashMap<String, IoOption>> outputSetInfo; /** * Default constructor */ public Activity() { } /** * Copy constructor * * @param act * The {@link Activity} to copy */ public Activity(Activity act) { super(act); if(act.getProperty().size() > 0) this.getProperty().addAll(act.getProperty()); if(act.getDataInputAssociation().size() > 0) this.getDataInputAssociation().addAll(act.getDataInputAssociation()); if(act.getDataOutputAssociation().size() > 0) this.getDataOutputAssociation().addAll(act.getDataOutputAssociation()); if(act.getActivityResource().size() > 0) this.getActivityResource().addAll(act.getActivityResource()); if(act.getBoundaryEventRefs().size() > 0) this.getBoundaryEventRefs().addAll(act.getBoundaryEventRefs()); if(act.getInputSetInfo().size() > 0) this.getInputSetInfo().addAll(act.getInputSetInfo()); if(act.getOutputSetInfo().size() > 0) this.getOutputSetInfo().addAll(act.getOutputSetInfo()); this.setIoSpecification(act.getIoSpecification()); this.setLoopCharacteristics(act.getLoopCharacteristics()); this.setIsForCompensation(act.isForCompensation); this.setStartQuantity(act.getStartQuantity()); this.setCompletionQuantity(act.getCompletionQuantity()); this.setDefault(act.getDefault()); } /* Transformation logic methods */ /** * Determines and sets the {@link InputOutputSpecification} of an activity. * * Per default there exists exactly one {@link InputSet} and one {@link OutputSet}. * All input and output data objects are associated by theses sets. Both * sets are linked towards each other to define a default IORule. */ public void determineIoSpecification() { /* Process data inputs */ InputSet inputSet = new InputSet(); inputSet.setName("DefaultInputSet"); inputSet.setId(OryxUUID.generate()); for(DataInputAssociation dia : this.getDataInputAssociation()) { if(dia.getSourceRef() instanceof DataInput) { DataInput input = (DataInput) dia.getSourceRef(); for(HashMap<String, IoOption> inputSetDesc : this.getInputSetInfo()) { IoOption opt = inputSetDesc.get(input.getName()); if(opt != null) { /* Append to appropriate list of data inputs */ inputSet.getDataInputRefs().add(input); if(opt.isOptional()) inputSet.getOptionalInputRefs().add(input); if(opt.isWhileExecuting()) inputSet.getWhileExecutingInputRefs().add(input); } } } } /* Process data outputs */ OutputSet outputSet = new OutputSet(); outputSet.setName("DefaultOutputSet"); outputSet.setId(OryxUUID.generate()); for(DataOutputAssociation dia : this.getDataOutputAssociation()) { if(dia.getTargetRef() instanceof DataOutput) { DataOutput output = (DataOutput) dia.getTargetRef(); for(HashMap<String, IoOption> outputSetDesc : this.getOutputSetInfo()) { IoOption opt = outputSetDesc.get(output.getName()); if(opt != null) { /* Append to appropriate list of data inputs */ outputSet.getDataOutputRefs().add(output); if(opt.isOptional()) outputSet.getOptionalOutputRefs().add(output); if(opt.isWhileExecuting()) outputSet.getWhileExecutingOutputRefs().add(output); } } } } /* Link both sets against each other to specifies a default IORule and * dependency between them. */ inputSet.getOutputSetRefs().add(outputSet); outputSet.getInputSetRefs().add(inputSet); /* Add input set to specification */ if(inputSet.getDataInputRefs().size() > 0 && outputSet.getDataOutputRefs().size() > 0) { InputOutputSpecification ioSpec = new InputOutputSpecification(); ioSpec.setId(OryxUUID.generate()); ioSpec.getInputSet().add(inputSet); ioSpec.getOutputSet().add(outputSet); ioSpec.getDataInput(); ioSpec.getDataOutput(); this.setIoSpecification(ioSpec); } } /* Getter & Setter */ /** * @return The list of boundary event references */ public List<BoundaryEvent> getBoundaryEventRefs() { if(this.boundaryEventRefs == null) { this.boundaryEventRefs = new ArrayList<BoundaryEvent>(); } return this.boundaryEventRefs; } /** * Gets the value of the ioSpecification property. * * @return * possible object is * {@link InputOutputSpecification } * */ public InputOutputSpecification getIoSpecification() { return ioSpecification; } /** * Sets the value of the ioSpecification property. * * @param value * allowed object is * {@link InputOutputSpecification } * */ public void setIoSpecification(InputOutputSpecification value) { this.ioSpecification = value; } /** * Gets the value of the property property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the property property. * * <p> * For example, to add a new item, do as follows: * <pre> * getProperty().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Property } * * */ public List<Property> getProperty() { if (property == null) { property = new ArrayList<Property>(); } return this.property; } /** * Gets the value of the dataInputAssociation property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the dataInputAssociation property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDataInputAssociation().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DataInputAssociation } * * */ public List<DataInputAssociation> getDataInputAssociation() { if (dataInputAssociation == null) { dataInputAssociation = new ArrayList<DataInputAssociation>(); } return this.dataInputAssociation; } /** * Gets the value of the dataOutputAssociation property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the dataOutputAssociation property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDataOutputAssociation().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DataOutputAssociation } * * */ public List<DataOutputAssociation> getDataOutputAssociation() { if (dataOutputAssociation == null) { dataOutputAssociation = new ArrayList<DataOutputAssociation>(); } return this.dataOutputAssociation; } /** * Gets the value of the activityResource property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the activityResource property. * * <p> * For example, to add a new item, do as follows: * <pre> * getActivityResource().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@code <}{@link HumanPerformer }{@code >} * {@code <}{@link Performer }{@code >} * {@code <}{@link PotentialOwner }{@code >} * {@code <}{@link ActivityResource }{@code >} * * */ public List<ActivityResource> getActivityResource() { if (activityResource == null) { activityResource = new ArrayList<ActivityResource>(); } return this.activityResource; } /** * Gets the value of the loopCharacteristics property. * * @return * possible object is * {@ link MultiInstanceLoopCharacteristics } * {@link LoopCharacteristics } * {@link StandardLoopCharacteristics } * */ public LoopCharacteristics getLoopCharacteristics() { return loopCharacteristics; } /** * Sets the value of the loopCharacteristics property. * * @param value * allowed object is * {@ link MultiInstanceLoopCharacteristics } * {@link LoopCharacteristics } * {@link StandardLoopCharacteristics } * */ public void setLoopCharacteristics(LoopCharacteristics value) { this.loopCharacteristics = value; } /** * Gets the value of the isForCompensation property. * * @return * possible object is * {@link Boolean } * */ public boolean isIsForCompensation() { if (isForCompensation == null) { return false; } else { return isForCompensation; } } /** * Sets the value of the isForCompensation property. * * @param value * allowed object is * {@link Boolean } * */ public void setIsForCompensation(Boolean value) { this.isForCompensation = value; } /** * Gets the value of the startQuantity property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getStartQuantity() { if (startQuantity == null) { return new BigInteger("1"); } else { return startQuantity; } } /** * Sets the value of the startQuantity property. * * @param value * allowed object is * {@link BigInteger } * */ public void setStartQuantity(BigInteger value) { this.startQuantity = value; } /** * Gets the value of the completionQuantity property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCompletionQuantity() { if (completionQuantity == null) { return new BigInteger("1"); } else { return completionQuantity; } } /** * Sets the value of the completionQuantity property. * * @param value * allowed object is * {@link BigInteger } * */ public void setCompletionQuantity(BigInteger value) { this.completionQuantity = value; } /** * Gets the value of the default property. * * @return * possible object is * {@link Object } * */ public Object getDefault() { return _default; } /** * Sets the value of the default property. * * @param value * allowed object is * {@link Object } * */ public void setDefault(Object value) { this._default = value; } /** * @return the inputSetInfo */ public List<HashMap<String, IoOption>> getInputSetInfo() { if(this.inputSetInfo == null) this.inputSetInfo = new ArrayList<HashMap<String,IoOption>>(); return inputSetInfo; } /** * @return the outputSetInfo */ public List<HashMap<String, IoOption>> getOutputSetInfo() { if(this.outputSetInfo == null) this.outputSetInfo = new ArrayList<HashMap<String,IoOption>>(); return outputSetInfo; } }
/* * 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.druid.query.groupby; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import com.google.common.primitives.Longs; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import org.apache.druid.java.util.common.DateTimes; import org.apache.druid.java.util.common.IAE; import org.apache.druid.java.util.common.ISE; import org.apache.druid.java.util.common.granularity.Granularities; import org.apache.druid.java.util.common.granularity.Granularity; import org.apache.druid.java.util.common.guava.Comparators; import org.apache.druid.java.util.common.guava.Sequence; import org.apache.druid.java.util.common.guava.Sequences; import org.apache.druid.query.BaseQuery; import org.apache.druid.query.DataSource; import org.apache.druid.query.Queries; import org.apache.druid.query.Query; import org.apache.druid.query.QueryDataSource; import org.apache.druid.query.TableDataSource; import org.apache.druid.query.aggregation.AggregatorFactory; import org.apache.druid.query.aggregation.PostAggregator; import org.apache.druid.query.dimension.DefaultDimensionSpec; import org.apache.druid.query.dimension.DimensionSpec; import org.apache.druid.query.filter.DimFilter; import org.apache.druid.query.groupby.having.HavingSpec; import org.apache.druid.query.groupby.orderby.DefaultLimitSpec; import org.apache.druid.query.groupby.orderby.LimitSpec; import org.apache.druid.query.groupby.orderby.NoopLimitSpec; import org.apache.druid.query.groupby.orderby.OrderByColumnSpec; import org.apache.druid.query.ordering.StringComparator; import org.apache.druid.query.ordering.StringComparators; import org.apache.druid.query.spec.LegacySegmentSpec; import org.apache.druid.query.spec.QuerySegmentSpec; import org.apache.druid.segment.DimensionHandlerUtils; import org.apache.druid.segment.VirtualColumn; import org.apache.druid.segment.VirtualColumns; import org.apache.druid.segment.column.ColumnHolder; import org.apache.druid.segment.column.RowSignature; import org.apache.druid.segment.column.ValueType; import org.joda.time.DateTime; import org.joda.time.Interval; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; /** * */ public class GroupByQuery extends BaseQuery<ResultRow> { public static final String CTX_KEY_SORT_BY_DIMS_FIRST = "sortByDimsFirst"; private static final String CTX_KEY_FUDGE_TIMESTAMP = "fudgeTimestamp"; private static final Comparator<ResultRow> NON_GRANULAR_TIME_COMP = (ResultRow lhs, ResultRow rhs) -> Longs.compare(lhs.getLong(0), rhs.getLong(0)); public static Builder builder() { return new Builder(); } private final VirtualColumns virtualColumns; private final LimitSpec limitSpec; @Nullable private final HavingSpec havingSpec; @Nullable private final DimFilter dimFilter; private final List<DimensionSpec> dimensions; private final List<AggregatorFactory> aggregatorSpecs; private final List<PostAggregator> postAggregatorSpecs; @Nullable private final List<List<String>> subtotalsSpec; private final boolean applyLimitPushDown; private final Function<Sequence<ResultRow>, Sequence<ResultRow>> postProcessingFn; private final RowSignature resultRowSignature; /** * This is set when we know that all rows will have the same timestamp, and allows us to not actually store * and track it throughout the query execution process. */ @Nullable private final DateTime universalTimestamp; @JsonCreator public GroupByQuery( @JsonProperty("dataSource") DataSource dataSource, @JsonProperty("intervals") QuerySegmentSpec querySegmentSpec, @JsonProperty("virtualColumns") VirtualColumns virtualColumns, @JsonProperty("filter") @Nullable DimFilter dimFilter, @JsonProperty("granularity") Granularity granularity, @JsonProperty("dimensions") List<DimensionSpec> dimensions, @JsonProperty("aggregations") List<AggregatorFactory> aggregatorSpecs, @JsonProperty("postAggregations") List<PostAggregator> postAggregatorSpecs, @JsonProperty("having") @Nullable HavingSpec havingSpec, @JsonProperty("limitSpec") LimitSpec limitSpec, @JsonProperty("subtotalsSpec") @Nullable List<List<String>> subtotalsSpec, @JsonProperty("context") Map<String, Object> context ) { this( dataSource, querySegmentSpec, virtualColumns, dimFilter, granularity, dimensions, aggregatorSpecs, postAggregatorSpecs, havingSpec, limitSpec, subtotalsSpec, null, context ); } private Function<Sequence<ResultRow>, Sequence<ResultRow>> makePostProcessingFn() { Function<Sequence<ResultRow>, Sequence<ResultRow>> postProcessingFn = limitSpec.build(this); if (havingSpec != null) { postProcessingFn = Functions.compose( postProcessingFn, (Sequence<ResultRow> input) -> { havingSpec.setQuery(this); return Sequences.filter(input, havingSpec::eval); } ); } return postProcessingFn; } /** * A private constructor that avoids recomputing postProcessingFn. */ private GroupByQuery( final DataSource dataSource, final QuerySegmentSpec querySegmentSpec, final VirtualColumns virtualColumns, final @Nullable DimFilter dimFilter, final Granularity granularity, final @Nullable List<DimensionSpec> dimensions, final @Nullable List<AggregatorFactory> aggregatorSpecs, final @Nullable List<PostAggregator> postAggregatorSpecs, final @Nullable HavingSpec havingSpec, final LimitSpec limitSpec, final @Nullable List<List<String>> subtotalsSpec, final @Nullable Function<Sequence<ResultRow>, Sequence<ResultRow>> postProcessingFn, final Map<String, Object> context ) { super(dataSource, querySegmentSpec, false, context, granularity); this.virtualColumns = VirtualColumns.nullToEmpty(virtualColumns); this.dimFilter = dimFilter; this.dimensions = dimensions == null ? ImmutableList.of() : dimensions; for (DimensionSpec spec : this.dimensions) { Preconditions.checkArgument(spec != null, "dimensions has null DimensionSpec"); } this.aggregatorSpecs = aggregatorSpecs == null ? ImmutableList.of() : aggregatorSpecs; this.postAggregatorSpecs = Queries.prepareAggregations( this.dimensions.stream().map(DimensionSpec::getOutputName).collect(Collectors.toList()), this.aggregatorSpecs, postAggregatorSpecs == null ? ImmutableList.of() : postAggregatorSpecs ); // Verify no duplicate names between dimensions, aggregators, and postAggregators. // They will all end up in the same namespace in the returned Rows and we can't have them clobbering each other. verifyOutputNames(this.dimensions, this.aggregatorSpecs, this.postAggregatorSpecs); this.universalTimestamp = computeUniversalTimestamp(); this.resultRowSignature = computeResultRowSignature(); this.havingSpec = havingSpec; this.limitSpec = LimitSpec.nullToNoopLimitSpec(limitSpec); this.subtotalsSpec = verifySubtotalsSpec(subtotalsSpec, this.dimensions); this.postProcessingFn = postProcessingFn != null ? postProcessingFn : makePostProcessingFn(); // Check if limit push down configuration is valid and check if limit push down will be applied this.applyLimitPushDown = determineApplyLimitPushDown(); } @Nullable private List<List<String>> verifySubtotalsSpec( @Nullable List<List<String>> subtotalsSpec, List<DimensionSpec> dimensions ) { // if subtotalsSpec exists then validate that all are subsets of dimensions spec. if (subtotalsSpec != null) { for (List<String> subtotalSpec : subtotalsSpec) { for (String s : subtotalSpec) { boolean found = false; for (DimensionSpec ds : dimensions) { if (s.equals(ds.getOutputName())) { found = true; break; } } if (!found) { throw new IAE( "Subtotal spec %s is either not a subset of top level dimensions.", subtotalSpec ); } } } } return subtotalsSpec; } @JsonProperty @Override public VirtualColumns getVirtualColumns() { return virtualColumns; } @Nullable @JsonProperty("filter") public DimFilter getDimFilter() { return dimFilter; } @JsonProperty public List<DimensionSpec> getDimensions() { return dimensions; } @JsonProperty("aggregations") public List<AggregatorFactory> getAggregatorSpecs() { return aggregatorSpecs; } @JsonProperty("postAggregations") public List<PostAggregator> getPostAggregatorSpecs() { return postAggregatorSpecs; } @JsonProperty("having") public HavingSpec getHavingSpec() { return havingSpec; } @JsonProperty public LimitSpec getLimitSpec() { return limitSpec; } @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty("subtotalsSpec") @Nullable public List<List<String>> getSubtotalsSpec() { return subtotalsSpec; } /** * Returns a list of field names, of the same size as {@link #getResultRowSizeWithPostAggregators()}, in the * order that they will appear in ResultRows for this query. * * @see ResultRow for documentation about the order that fields will be in */ public RowSignature getResultRowSignature() { return resultRowSignature; } /** * Returns the size of ResultRows for this query when they do not include post-aggregators. */ public int getResultRowSizeWithoutPostAggregators() { return getResultRowPostAggregatorStart(); } /** * Returns the size of ResultRows for this query when they include post-aggregators. */ public int getResultRowSizeWithPostAggregators() { return resultRowSignature.size(); } /** * If this query has a single universal timestamp, return it. Otherwise return null. * * This method will return a nonnull timestamp in the following two cases: * * 1) CTX_KEY_FUDGE_TIMESTAMP is set (in which case this timestamp will be returned). * 2) Granularity is "ALL". * * If this method returns null, then {@link #getResultRowHasTimestamp()} will return true. The reverse is also true: * if this method returns nonnull, then {@link #getResultRowHasTimestamp()} will return false. */ @Nullable public DateTime getUniversalTimestamp() { return universalTimestamp; } /** * Returns true if ResultRows for this query include timestamps, false otherwise. * * @see #getUniversalTimestamp() for details about when timestamps are included in ResultRows */ public boolean getResultRowHasTimestamp() { return universalTimestamp == null; } /** * Returns the position of the first dimension in ResultRows for this query. */ public int getResultRowDimensionStart() { return getResultRowHasTimestamp() ? 1 : 0; } /** * Returns the position of the first aggregator in ResultRows for this query. */ public int getResultRowAggregatorStart() { return getResultRowDimensionStart() + dimensions.size(); } /** * Returns the position of the first post-aggregator in ResultRows for this query. */ public int getResultRowPostAggregatorStart() { return getResultRowAggregatorStart() + aggregatorSpecs.size(); } @Override public boolean hasFilters() { return dimFilter != null; } @Override @Nullable public DimFilter getFilter() { return dimFilter; } @Override public String getType() { return GROUP_BY; } @JsonIgnore public boolean getContextSortByDimsFirst() { return getContextBoolean(CTX_KEY_SORT_BY_DIMS_FIRST, false); } @JsonIgnore public boolean isApplyLimitPushDown() { return applyLimitPushDown; } @JsonIgnore public boolean getApplyLimitPushDownFromContext() { return getContextBoolean(GroupByQueryConfig.CTX_KEY_APPLY_LIMIT_PUSH_DOWN, true); } @Override public Ordering getResultOrdering() { final Ordering<ResultRow> rowOrdering = getRowOrdering(false); return Ordering.from( (lhs, rhs) -> { if (lhs instanceof ResultRow) { return rowOrdering.compare((ResultRow) lhs, (ResultRow) rhs); } else { //noinspection unchecked (Probably bySegment queries; see BySegmentQueryRunner for details) return ((Ordering) Comparators.naturalNullsFirst()).compare(lhs, rhs); } } ); } private boolean validateAndGetForceLimitPushDown() { final boolean forcePushDown = getContextBoolean(GroupByQueryConfig.CTX_KEY_FORCE_LIMIT_PUSH_DOWN, false); if (forcePushDown) { if (!(limitSpec instanceof DefaultLimitSpec)) { throw new IAE("When forcing limit push down, a limit spec must be provided."); } if (!((DefaultLimitSpec) limitSpec).isLimited()) { throw new IAE("When forcing limit push down, the provided limit spec must have a limit."); } if (havingSpec != null) { throw new IAE("Cannot force limit push down when a having spec is present."); } for (OrderByColumnSpec orderBySpec : ((DefaultLimitSpec) limitSpec).getColumns()) { if (OrderByColumnSpec.getPostAggIndexForOrderBy(orderBySpec, postAggregatorSpecs) > -1) { throw new UnsupportedOperationException("Limit push down when sorting by a post aggregator is not supported."); } } } return forcePushDown; } private RowSignature computeResultRowSignature() { final RowSignature.Builder builder = RowSignature.builder(); if (universalTimestamp == null) { builder.addTimeColumn(); } return builder.addDimensions(dimensions) .addAggregators(aggregatorSpecs) .addPostAggregators(postAggregatorSpecs) .build(); } private boolean determineApplyLimitPushDown() { if (subtotalsSpec != null) { return false; } final boolean forceLimitPushDown = validateAndGetForceLimitPushDown(); if (limitSpec instanceof DefaultLimitSpec) { DefaultLimitSpec defaultLimitSpec = (DefaultLimitSpec) limitSpec; // If only applying an orderby without a limit, don't try to push down if (!defaultLimitSpec.isLimited()) { return false; } if (forceLimitPushDown) { return true; } if (!getApplyLimitPushDownFromContext()) { return false; } if (havingSpec != null) { return false; } // If the sorting order only uses columns in the grouping key, we can always push the limit down // to the buffer grouper without affecting result accuracy boolean sortHasNonGroupingFields = DefaultLimitSpec.sortingOrderHasNonGroupingFields( (DefaultLimitSpec) limitSpec, getDimensions() ); return !sortHasNonGroupingFields; } return false; } /** * When limit push down is applied, the partial results would be sorted by the ordering specified by the * limit/order spec (unlike non-push down case where the results always use the default natural ascending order), * so when merging these partial result streams, the merge needs to use the same ordering to get correct results. */ private Ordering<ResultRow> getRowOrderingForPushDown( final boolean granular, final DefaultLimitSpec limitSpec ) { final boolean sortByDimsFirst = getContextSortByDimsFirst(); final IntList orderedFieldNumbers = new IntArrayList(); final Set<Integer> dimsInOrderBy = new HashSet<>(); final List<Boolean> needsReverseList = new ArrayList<>(); final List<ValueType> dimensionTypes = new ArrayList<>(); final List<StringComparator> comparators = new ArrayList<>(); for (OrderByColumnSpec orderSpec : limitSpec.getColumns()) { boolean needsReverse = orderSpec.getDirection() != OrderByColumnSpec.Direction.ASCENDING; int dimIndex = OrderByColumnSpec.getDimIndexForOrderBy(orderSpec, dimensions); if (dimIndex >= 0) { DimensionSpec dim = dimensions.get(dimIndex); orderedFieldNumbers.add(resultRowSignature.indexOf(dim.getOutputName())); dimsInOrderBy.add(dimIndex); needsReverseList.add(needsReverse); final ValueType type = dimensions.get(dimIndex).getOutputType(); dimensionTypes.add(type); comparators.add(orderSpec.getDimensionComparator()); } } for (int i = 0; i < dimensions.size(); i++) { if (!dimsInOrderBy.contains(i)) { orderedFieldNumbers.add(resultRowSignature.indexOf(dimensions.get(i).getOutputName())); needsReverseList.add(false); final ValueType type = dimensions.get(i).getOutputType(); dimensionTypes.add(type); comparators.add(StringComparators.LEXICOGRAPHIC); } } final Comparator<ResultRow> timeComparator = getTimeComparator(granular); if (timeComparator == null) { return Ordering.from( (lhs, rhs) -> compareDimsForLimitPushDown( orderedFieldNumbers, needsReverseList, dimensionTypes, comparators, lhs, rhs ) ); } else if (sortByDimsFirst) { return Ordering.from( (lhs, rhs) -> { final int cmp = compareDimsForLimitPushDown( orderedFieldNumbers, needsReverseList, dimensionTypes, comparators, lhs, rhs ); if (cmp != 0) { return cmp; } return timeComparator.compare(lhs, rhs); } ); } else { return Ordering.from( (lhs, rhs) -> { final int timeCompare = timeComparator.compare(lhs, rhs); if (timeCompare != 0) { return timeCompare; } return compareDimsForLimitPushDown( orderedFieldNumbers, needsReverseList, dimensionTypes, comparators, lhs, rhs ); } ); } } public Ordering<ResultRow> getRowOrdering(final boolean granular) { if (applyLimitPushDown) { if (!DefaultLimitSpec.sortingOrderHasNonGroupingFields((DefaultLimitSpec) limitSpec, dimensions)) { return getRowOrderingForPushDown(granular, (DefaultLimitSpec) limitSpec); } } final boolean sortByDimsFirst = getContextSortByDimsFirst(); final Comparator<ResultRow> timeComparator = getTimeComparator(granular); if (timeComparator == null) { return Ordering.from((lhs, rhs) -> compareDims(dimensions, lhs, rhs)); } else if (sortByDimsFirst) { return Ordering.from( (lhs, rhs) -> { final int cmp = compareDims(dimensions, lhs, rhs); if (cmp != 0) { return cmp; } return timeComparator.compare(lhs, rhs); } ); } else { return Ordering.from( (lhs, rhs) -> { final int timeCompare = timeComparator.compare(lhs, rhs); if (timeCompare != 0) { return timeCompare; } return compareDims(dimensions, lhs, rhs); } ); } } @Nullable private Comparator<ResultRow> getTimeComparator(boolean granular) { if (Granularities.ALL.equals(getGranularity())) { return null; } else { if (!getResultRowHasTimestamp()) { // Sanity check (should never happen). throw new ISE("Cannot do time comparisons!"); } if (granular) { return (lhs, rhs) -> Longs.compare( getGranularity().bucketStart(DateTimes.utc(lhs.getLong(0))).getMillis(), getGranularity().bucketStart(DateTimes.utc(rhs.getLong(0))).getMillis() ); } else { return NON_GRANULAR_TIME_COMP; } } } private int compareDims(List<DimensionSpec> dimensions, ResultRow lhs, ResultRow rhs) { final int dimensionStart = getResultRowDimensionStart(); for (int i = 0; i < dimensions.size(); i++) { DimensionSpec dimension = dimensions.get(i); final int dimCompare = DimensionHandlerUtils.compareObjectsAsType( lhs.get(dimensionStart + i), rhs.get(dimensionStart + i), dimension.getOutputType() ); if (dimCompare != 0) { return dimCompare; } } return 0; } /** * Computes the timestamp that will be returned by {@link #getUniversalTimestamp()}. */ @Nullable private DateTime computeUniversalTimestamp() { final String timestampStringFromContext = getContextValue(CTX_KEY_FUDGE_TIMESTAMP, ""); final Granularity granularity = getGranularity(); if (!timestampStringFromContext.isEmpty()) { return DateTimes.utc(Long.parseLong(timestampStringFromContext)); } else if (Granularities.ALL.equals(granularity)) { final DateTime timeStart = getIntervals().get(0).getStart(); return granularity.getIterable(new Interval(timeStart, timeStart.plus(1))).iterator().next().getStart(); } else { return null; } } private static int compareDimsForLimitPushDown( final IntList fields, final List<Boolean> needsReverseList, final List<ValueType> dimensionTypes, final List<StringComparator> comparators, final ResultRow lhs, final ResultRow rhs ) { for (int i = 0; i < fields.size(); i++) { final int fieldNumber = fields.getInt(i); final StringComparator comparator = comparators.get(i); final ValueType dimensionType = dimensionTypes.get(i); final int dimCompare; final Object lhsObj = lhs.get(fieldNumber); final Object rhsObj = rhs.get(fieldNumber); if (ValueType.isNumeric(dimensionType)) { if (comparator.equals(StringComparators.NUMERIC)) { dimCompare = DimensionHandlerUtils.compareObjectsAsType(lhsObj, rhsObj, dimensionType); } else { dimCompare = comparator.compare(String.valueOf(lhsObj), String.valueOf(rhsObj)); } } else { dimCompare = comparator.compare((String) lhsObj, (String) rhsObj); } if (dimCompare != 0) { return needsReverseList.get(i) ? -dimCompare : dimCompare; } } return 0; } /** * Apply the havingSpec and limitSpec. Because havingSpecs are not thread safe, and because they are applied during * accumulation of the returned sequence, callers must take care to avoid accumulating two different Sequences * returned by this method in two different threads. * * @param results sequence of rows to apply havingSpec and limitSpec to * * @return sequence of rows after applying havingSpec and limitSpec */ public Sequence<ResultRow> postProcess(Sequence<ResultRow> results) { return postProcessingFn.apply(results); } @Override public GroupByQuery withOverriddenContext(Map<String, Object> contextOverride) { return new Builder(this).overrideContext(contextOverride).build(); } @Override public GroupByQuery withQuerySegmentSpec(QuerySegmentSpec spec) { return new Builder(this).setQuerySegmentSpec(spec).build(); } public GroupByQuery withVirtualColumns(final VirtualColumns virtualColumns) { return new Builder(this).setVirtualColumns(virtualColumns).build(); } public GroupByQuery withDimFilter(@Nullable final DimFilter dimFilter) { return new Builder(this).setDimFilter(dimFilter).build(); } @Override public Query<ResultRow> withDataSource(DataSource dataSource) { return new Builder(this).setDataSource(dataSource).build(); } public GroupByQuery withDimensionSpecs(final List<DimensionSpec> dimensionSpecs) { return new Builder(this).setDimensions(dimensionSpecs).build(); } public GroupByQuery withLimitSpec(LimitSpec limitSpec) { return new Builder(this).setLimitSpec(limitSpec).build(); } public GroupByQuery withAggregatorSpecs(final List<AggregatorFactory> aggregatorSpecs) { return new Builder(this).setAggregatorSpecs(aggregatorSpecs).build(); } public GroupByQuery withSubtotalsSpec(@Nullable final List<List<String>> subtotalsSpec) { return new Builder(this).setSubtotalsSpec(subtotalsSpec).build(); } public GroupByQuery withPostAggregatorSpecs(final List<PostAggregator> postAggregatorSpecs) { return new Builder(this).setPostAggregatorSpecs(postAggregatorSpecs).build(); } private static void verifyOutputNames( List<DimensionSpec> dimensions, List<AggregatorFactory> aggregators, List<PostAggregator> postAggregators ) { final Set<String> outputNames = new HashSet<>(); for (DimensionSpec dimension : dimensions) { if (!outputNames.add(dimension.getOutputName())) { throw new IAE("Duplicate output name[%s]", dimension.getOutputName()); } } for (AggregatorFactory aggregator : aggregators) { if (!outputNames.add(aggregator.getName())) { throw new IAE("Duplicate output name[%s]", aggregator.getName()); } } for (PostAggregator postAggregator : postAggregators) { if (!outputNames.add(postAggregator.getName())) { throw new IAE("Duplicate output name[%s]", postAggregator.getName()); } } if (outputNames.contains(ColumnHolder.TIME_COLUMN_NAME)) { throw new IAE( "'%s' cannot be used as an output name for dimensions, aggregators, or post-aggregators.", ColumnHolder.TIME_COLUMN_NAME ); } } public static class Builder { @Nullable private static List<List<String>> copySubtotalSpec(@Nullable List<List<String>> subtotalsSpec) { if (subtotalsSpec == null) { return null; } return subtotalsSpec.stream().map(ArrayList::new).collect(Collectors.toList()); } private DataSource dataSource; private QuerySegmentSpec querySegmentSpec; private VirtualColumns virtualColumns; @Nullable private DimFilter dimFilter; private Granularity granularity; @Nullable private List<DimensionSpec> dimensions; @Nullable private List<AggregatorFactory> aggregatorSpecs; @Nullable private List<PostAggregator> postAggregatorSpecs; @Nullable private HavingSpec havingSpec; @Nullable private Map<String, Object> context; @Nullable private List<List<String>> subtotalsSpec = null; @Nullable private LimitSpec limitSpec = null; @Nullable private Function<Sequence<ResultRow>, Sequence<ResultRow>> postProcessingFn; private List<OrderByColumnSpec> orderByColumnSpecs = new ArrayList<>(); private int limit = Integer.MAX_VALUE; public Builder() { } public Builder(GroupByQuery query) { dataSource = query.getDataSource(); querySegmentSpec = query.getQuerySegmentSpec(); virtualColumns = query.getVirtualColumns(); dimFilter = query.getDimFilter(); granularity = query.getGranularity(); dimensions = query.getDimensions(); aggregatorSpecs = query.getAggregatorSpecs(); postAggregatorSpecs = query.getPostAggregatorSpecs(); havingSpec = query.getHavingSpec(); limitSpec = query.getLimitSpec(); subtotalsSpec = query.subtotalsSpec; postProcessingFn = query.postProcessingFn; context = query.getContext(); } public Builder(Builder builder) { dataSource = builder.dataSource; querySegmentSpec = builder.querySegmentSpec; virtualColumns = builder.virtualColumns; dimFilter = builder.dimFilter; granularity = builder.granularity; dimensions = builder.dimensions; aggregatorSpecs = builder.aggregatorSpecs; postAggregatorSpecs = builder.postAggregatorSpecs; havingSpec = builder.havingSpec; limitSpec = builder.limitSpec; subtotalsSpec = copySubtotalSpec(builder.subtotalsSpec); postProcessingFn = builder.postProcessingFn; limit = builder.limit; orderByColumnSpecs = new ArrayList<>(builder.orderByColumnSpecs); context = builder.context; } public Builder setDataSource(DataSource dataSource) { this.dataSource = dataSource; return this; } public Builder setDataSource(String dataSource) { this.dataSource = new TableDataSource(dataSource); return this; } public Builder setDataSource(Query query) { this.dataSource = new QueryDataSource(query); return this; } public Builder setInterval(QuerySegmentSpec interval) { return setQuerySegmentSpec(interval); } public Builder setInterval(List<Interval> intervals) { return setQuerySegmentSpec(new LegacySegmentSpec(intervals)); } public Builder setInterval(Interval interval) { return setQuerySegmentSpec(new LegacySegmentSpec(interval)); } public Builder setInterval(String interval) { return setQuerySegmentSpec(new LegacySegmentSpec(interval)); } public Builder setVirtualColumns(VirtualColumns virtualColumns) { this.virtualColumns = Preconditions.checkNotNull(virtualColumns, "virtualColumns"); return this; } public Builder setVirtualColumns(VirtualColumn... virtualColumns) { this.virtualColumns = VirtualColumns.create(Arrays.asList(virtualColumns)); return this; } public Builder setLimit(int limit) { ensureExplicitLimitSpecNotSet(); this.limit = limit; this.postProcessingFn = null; return this; } public Builder setSubtotalsSpec(@Nullable List<List<String>> subtotalsSpec) { this.subtotalsSpec = subtotalsSpec; return this; } public Builder addOrderByColumn(String dimension) { return addOrderByColumn(dimension, null); } public Builder addOrderByColumn(String dimension, @Nullable OrderByColumnSpec.Direction direction) { return addOrderByColumn(new OrderByColumnSpec(dimension, direction)); } public Builder addOrderByColumn(OrderByColumnSpec columnSpec) { ensureExplicitLimitSpecNotSet(); this.orderByColumnSpecs.add(columnSpec); this.postProcessingFn = null; return this; } public Builder setLimitSpec(LimitSpec limitSpec) { Preconditions.checkNotNull(limitSpec); ensureFluentLimitsNotSet(); this.limitSpec = limitSpec; this.postProcessingFn = null; return this; } private void ensureExplicitLimitSpecNotSet() { if (limitSpec != null) { throw new ISE("Ambiguous build, limitSpec[%s] already set", limitSpec); } } private void ensureFluentLimitsNotSet() { if (!(limit == Integer.MAX_VALUE && orderByColumnSpecs.isEmpty())) { throw new ISE("Ambiguous build, limit[%s] or columnSpecs[%s] already set.", limit, orderByColumnSpecs); } } public Builder setQuerySegmentSpec(QuerySegmentSpec querySegmentSpec) { this.querySegmentSpec = querySegmentSpec; return this; } public Builder setDimFilter(@Nullable DimFilter dimFilter) { this.dimFilter = dimFilter; return this; } public Builder setGranularity(Granularity granularity) { this.granularity = granularity; return this; } public Builder addDimension(String column) { return addDimension(column, column); } public Builder addDimension(String column, String outputName) { return addDimension(new DefaultDimensionSpec(column, outputName)); } public Builder addDimension(DimensionSpec dimension) { if (dimensions == null) { dimensions = new ArrayList<>(); } dimensions.add(dimension); this.postProcessingFn = null; return this; } public Builder setDimensions(List<DimensionSpec> dimensions) { this.dimensions = Lists.newArrayList(dimensions); this.postProcessingFn = null; return this; } public Builder setDimensions(DimensionSpec... dimensions) { this.dimensions = new ArrayList<>(Arrays.asList(dimensions)); this.postProcessingFn = null; return this; } public Builder addAggregator(AggregatorFactory aggregator) { if (aggregatorSpecs == null) { aggregatorSpecs = new ArrayList<>(); } aggregatorSpecs.add(aggregator); this.postProcessingFn = null; return this; } public Builder setAggregatorSpecs(List<AggregatorFactory> aggregatorSpecs) { this.aggregatorSpecs = Lists.newArrayList(aggregatorSpecs); this.postProcessingFn = null; return this; } public Builder setAggregatorSpecs(AggregatorFactory... aggregatorSpecs) { this.aggregatorSpecs = new ArrayList<>(Arrays.asList(aggregatorSpecs)); this.postProcessingFn = null; return this; } public Builder setPostAggregatorSpecs(List<PostAggregator> postAggregatorSpecs) { this.postAggregatorSpecs = Lists.newArrayList(postAggregatorSpecs); this.postProcessingFn = null; return this; } public Builder setContext(Map<String, Object> context) { this.context = context; return this; } public Builder randomQueryId() { return queryId(UUID.randomUUID().toString()); } public Builder queryId(String queryId) { context = BaseQuery.computeOverriddenContext(context, ImmutableMap.of(BaseQuery.QUERY_ID, queryId)); return this; } public Builder overrideContext(Map<String, Object> contextOverride) { this.context = computeOverriddenContext(context, contextOverride); return this; } public Builder setHavingSpec(@Nullable HavingSpec havingSpec) { this.havingSpec = havingSpec; this.postProcessingFn = null; return this; } public Builder copy() { return new Builder(this); } public GroupByQuery build() { final LimitSpec theLimitSpec; if (limitSpec == null) { if (orderByColumnSpecs.isEmpty() && limit == Integer.MAX_VALUE) { theLimitSpec = NoopLimitSpec.instance(); } else { theLimitSpec = new DefaultLimitSpec(orderByColumnSpecs, limit); } } else { theLimitSpec = limitSpec; } return new GroupByQuery( dataSource, querySegmentSpec, virtualColumns, dimFilter, granularity, dimensions, aggregatorSpecs, postAggregatorSpecs, havingSpec, theLimitSpec, subtotalsSpec, postProcessingFn, context ); } } @Override public String toString() { return "GroupByQuery{" + "dataSource='" + getDataSource() + '\'' + ", querySegmentSpec=" + getQuerySegmentSpec() + ", virtualColumns=" + virtualColumns + ", limitSpec=" + limitSpec + ", dimFilter=" + dimFilter + ", granularity=" + getGranularity() + ", dimensions=" + dimensions + ", aggregatorSpecs=" + aggregatorSpecs + ", postAggregatorSpecs=" + postAggregatorSpecs + (subtotalsSpec != null ? (", subtotalsSpec=" + subtotalsSpec) : "") + ", havingSpec=" + havingSpec + ", context=" + getContext() + '}'; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } final GroupByQuery that = (GroupByQuery) o; return Objects.equals(virtualColumns, that.virtualColumns) && Objects.equals(limitSpec, that.limitSpec) && Objects.equals(havingSpec, that.havingSpec) && Objects.equals(dimFilter, that.dimFilter) && Objects.equals(dimensions, that.dimensions) && Objects.equals(aggregatorSpecs, that.aggregatorSpecs) && Objects.equals(postAggregatorSpecs, that.postAggregatorSpecs) && Objects.equals(subtotalsSpec, that.subtotalsSpec); } @Override public int hashCode() { return Objects.hash( super.hashCode(), virtualColumns, limitSpec, havingSpec, dimFilter, dimensions, aggregatorSpecs, postAggregatorSpecs, subtotalsSpec ); } }
/* * Copyright (c) 2016, 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.carbon.identity.claim.metadata.mgt.ui.client; import org.apache.axis2.AxisFault; import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; import org.apache.axis2.context.ConfigurationContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.claim.metadata.mgt.stub.ClaimMetadataManagementServiceClaimMetadataException; import org.wso2.carbon.identity.claim.metadata.mgt.stub.ClaimMetadataManagementServiceStub; import org.wso2.carbon.identity.claim.metadata.mgt.stub.dto.ClaimDialectDTO; import org.wso2.carbon.identity.claim.metadata.mgt.stub.dto.ExternalClaimDTO; import org.wso2.carbon.identity.claim.metadata.mgt.stub.dto.LocalClaimDTO; import java.rmi.RemoteException; /** * This class invokes the operations of ClaimMetadataManagementService. */ public class ClaimMetadataAdminClient { private static final Log log = LogFactory.getLog(ClaimMetadataAdminClient.class); private ClaimMetadataManagementServiceStub stub; /** * Instantiates ClaimMetadataAdminClient * * @param cookie For session management * @param backendServerURL URL of the back end server where ClaimManagementServiceStub is running. * @param configCtx ConfigurationContext * @throws org.apache.axis2.AxisFault if error occurs when instantiating the stub */ public ClaimMetadataAdminClient(String cookie, String backendServerURL, ConfigurationContext configCtx) throws AxisFault { String serviceURL = backendServerURL + "ClaimMetadataManagementService"; stub = new ClaimMetadataManagementServiceStub(configCtx, serviceURL); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); } public ClaimDialectDTO[] getClaimDialects() throws RemoteException, ClaimMetadataManagementServiceClaimMetadataException { try { return stub.getClaimDialects(); } catch (RemoteException e) { log.error(e.getMessage(), e); throw e; } catch (ClaimMetadataManagementServiceClaimMetadataException e) { log.error(e.getMessage(), e); throw e; } } public void addClaimDialect(ClaimDialectDTO externalClaimDialect) throws RemoteException, ClaimMetadataManagementServiceClaimMetadataException { try { stub.addClaimDialect(externalClaimDialect); } catch (RemoteException e) { log.error(e.getMessage(), e); throw e; } catch (ClaimMetadataManagementServiceClaimMetadataException e) { log.error(e.getMessage(), e); throw e; } } public void removeClaimDialect(String externalClaimDialect) throws RemoteException, ClaimMetadataManagementServiceClaimMetadataException { try { ClaimDialectDTO claimDialect = new ClaimDialectDTO(); claimDialect.setClaimDialectURI(externalClaimDialect); stub.removeClaimDialect(claimDialect); } catch (RemoteException e) { log.error(e.getMessage(), e); throw e; } catch (ClaimMetadataManagementServiceClaimMetadataException e) { log.error(e.getMessage(), e); throw e; } } public LocalClaimDTO[] getLocalClaims() throws RemoteException, ClaimMetadataManagementServiceClaimMetadataException { try { return stub.getLocalClaims(); } catch (RemoteException e) { log.error(e.getMessage(), e); throw e; } catch (ClaimMetadataManagementServiceClaimMetadataException e) { log.error(e.getMessage(), e); throw e; } } public void addLocalClaim(LocalClaimDTO localCLaim) throws RemoteException, ClaimMetadataManagementServiceClaimMetadataException { try { stub.addLocalClaim(localCLaim); } catch (RemoteException e) { log.error(e.getMessage(), e); throw e; } catch (ClaimMetadataManagementServiceClaimMetadataException e) { log.error(e.getMessage(), e); throw e; } } public void updateLocalClaim(LocalClaimDTO localClaim) throws RemoteException, ClaimMetadataManagementServiceClaimMetadataException { try { stub.updateLocalClaim(localClaim); } catch (RemoteException e) { log.error(e.getMessage(), e); throw e; } catch (ClaimMetadataManagementServiceClaimMetadataException e) { log.error(e.getMessage(), e); throw e; } } public void removeLocalClaim(String localCLaimURI) throws RemoteException, ClaimMetadataManagementServiceClaimMetadataException { try { stub.removeLocalClaim(localCLaimURI); } catch (RemoteException e) { log.error(e.getMessage(), e); throw e; } catch (ClaimMetadataManagementServiceClaimMetadataException e) { log.error(e.getMessage(), e); throw e; } } public ExternalClaimDTO[] getExternalClaims(String externalClaimDialectURI) throws RemoteException, ClaimMetadataManagementServiceClaimMetadataException { try { return stub.getExternalClaims(externalClaimDialectURI); } catch (RemoteException e) { log.error(e.getMessage(), e); throw e; } catch (ClaimMetadataManagementServiceClaimMetadataException e) { log.error(e.getMessage(), e); throw e; } } public void addExternalClaim(ExternalClaimDTO externalClaim) throws RemoteException, ClaimMetadataManagementServiceClaimMetadataException { try { stub.addExternalClaim(externalClaim); } catch (RemoteException e) { log.error(e.getMessage(), e); throw e; } catch (ClaimMetadataManagementServiceClaimMetadataException e) { log.error(e.getMessage(), e); throw e; } } public void updateExternalClaim(ExternalClaimDTO externalClaim) throws RemoteException, ClaimMetadataManagementServiceClaimMetadataException { try { stub.updateExternalClaim(externalClaim); } catch (RemoteException e) { log.error(e.getMessage(), e); throw e; } catch (ClaimMetadataManagementServiceClaimMetadataException e) { log.error(e.getMessage(), e); throw e; } } public void removeExternalClaim(String externalClaimDialectURI, String externalClaimURI) throws RemoteException, ClaimMetadataManagementServiceClaimMetadataException { try { stub.removeExternalClaim(externalClaimDialectURI, externalClaimURI); } catch (RemoteException e) { log.error(e.getMessage(), e); throw e; } catch (ClaimMetadataManagementServiceClaimMetadataException e) { log.error(e.getMessage(), e); throw e; } } }
/* * Copyright 2009-present, Stephen Colebourne * * 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.joda.money.format; import java.math.BigDecimal; import java.text.ParsePosition; import java.util.Locale; import org.joda.money.BigMoney; import org.joda.money.CurrencyUnit; /** * Context used when parsing money. * <p> * This class is mutable and intended for use by a single thread. * A new instance is created for each parse. */ public final class MoneyParseContext { /** * The locale to parse using. */ private Locale locale; /** * The text to parse. */ private CharSequence text; /** * The text index. */ private int textIndex; /** * The text error index. */ private int textErrorIndex = -1; /** * The parsed currency. */ private CurrencyUnit currency; /** * The parsed amount. */ private BigDecimal amount; /** * Constructor. * * @param locale the locale, not null * @param text the text to parse, not null * @param index the current text index */ MoneyParseContext(Locale locale, CharSequence text, int index) { this.locale = locale; this.text = text; this.textIndex = index; } /** * Constructor. * * @param locale the locale, not null * @param text the text to parse, not null * @param index the current text index * @param errorIndex the error index * @param currency the currency * @param amount the parsed amount */ MoneyParseContext(Locale locale, CharSequence text, int index, int errorIndex, CurrencyUnit currency, BigDecimal amount) { this.locale = locale; this.text = text; this.textIndex = index; this.textErrorIndex = errorIndex; this.currency = currency; this.amount = amount; } //----------------------------------------------------------------------- /** * Gets the locale. * * @return the locale, not null */ public Locale getLocale() { return locale; } /** * Sets the locale. * * @param locale the locale, not null */ public void setLocale(Locale locale) { MoneyFormatter.checkNotNull(locale, "Locale must not be null"); this.locale = locale; } /** * Gets the text being parsed. * * @return the text being parsed, never null */ public CharSequence getText() { return text; } /** * Sets the text. * * @param text the text being parsed, not null */ public void setText(CharSequence text) { MoneyFormatter.checkNotNull(text, "Text must not be null"); this.text = text; } /** * Gets the length of the text being parsed. * * @return the length of the text being parsed */ public int getTextLength() { return text.length(); } /** * Gets a substring of the text being parsed. * * @param start the start index * @param end the end index * @return the substring, not null */ public String getTextSubstring(int start, int end) { return text.subSequence(start, end).toString(); } //----------------------------------------------------------------------- /** * Gets the current parse position index. * * @return the current parse position index */ public int getIndex() { return textIndex; } /** * Sets the current parse position index. * * @param index the current parse position index */ public void setIndex(int index) { this.textIndex = index; } //----------------------------------------------------------------------- /** * Gets the error index. * * @return the error index, negative if no error */ public int getErrorIndex() { return textErrorIndex; } /** * Sets the error index. * * @param index the error index */ public void setErrorIndex(int index) { this.textErrorIndex = index; } /** * Sets the error index from the current index. */ public void setError() { this.textErrorIndex = textIndex; } //----------------------------------------------------------------------- /** * Gets the parsed currency. * * @return the parsed currency, null if not parsed yet */ public CurrencyUnit getCurrency() { return currency; } /** * Sets the parsed currency. * * @param currency the parsed currency, may be null */ public void setCurrency(CurrencyUnit currency) { this.currency = currency; } //----------------------------------------------------------------------- /** * Gets the parsed amount. * * @return the parsed amount, null if not parsed yet */ public BigDecimal getAmount() { return amount; } /** * Sets the parsed currency. * * @param amount the parsed amount, may be null */ public void setAmount(BigDecimal amount) { this.amount = amount; } //----------------------------------------------------------------------- /** * Checks if the parse has found an error. * * @return whether a parse error has occurred */ public boolean isError() { return textErrorIndex >= 0; } /** * Checks if the text has been fully parsed such that there is no more text to parse. * * @return true if fully parsed */ public boolean isFullyParsed() { return textIndex == getTextLength(); } /** * Checks if the context contains a currency and amount suitable for creating * a monetary value. * * @return true if able to create a monetary value */ public boolean isComplete() { return currency != null && amount != null; } //----------------------------------------------------------------------- /** * Creates a child context. * * @return the child context, never null */ MoneyParseContext createChild() { return new MoneyParseContext(locale, text, textIndex, textErrorIndex, currency, amount); } /** * Merges the child context back into this instance. * * @param child the child context, not null */ void mergeChild(MoneyParseContext child) { setLocale(child.getLocale()); setText(child.getText()); setIndex(child.getIndex()); setErrorIndex(child.getErrorIndex()); setCurrency(child.getCurrency()); setAmount(child.getAmount()); } //----------------------------------------------------------------------- /** * Converts the indexes to a parse position. * * @return the parse position, never null */ public ParsePosition toParsePosition() { ParsePosition pp = new ParsePosition(textIndex); pp.setErrorIndex(textErrorIndex); return pp; } /** * Converts the context to a {@code BigMoney}. * * @return the monetary value, never null * @throws MoneyFormatException if either the currency or amount is missing */ public BigMoney toBigMoney() { if (currency == null) { throw new MoneyFormatException("Cannot convert to BigMoney as no currency found"); } if (amount == null) { throw new MoneyFormatException("Cannot convert to BigMoney as no amount found"); } return BigMoney.of(currency, amount); } }
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.metahistory; import java.util.*; import net.java.sip.communicator.service.callhistory.*; import net.java.sip.communicator.service.callhistory.event.*; import net.java.sip.communicator.service.contactlist.*; import net.java.sip.communicator.service.filehistory.*; import net.java.sip.communicator.service.history.event.*; import net.java.sip.communicator.service.history.event.ProgressEvent; import net.java.sip.communicator.service.metahistory.*; import net.java.sip.communicator.service.msghistory.*; import net.java.sip.communicator.service.msghistory.event.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; import org.osgi.framework.*; /** * The Meta History Service is wrapper around the other known * history services. Query them all at once, sort the result and return all * merged records in one collection. * * @author Damian Minkov */ public class MetaHistoryServiceImpl implements MetaHistoryService, ServiceListener { /** * The logger for this class. */ private static final Logger logger = Logger.getLogger(MetaHistoryServiceImpl.class); /** * The BundleContext that we got from the OSGI bus. */ private BundleContext bundleContext = null; /** * Caching of the used services */ private Hashtable<String, Object> services = new Hashtable<String, Object>(); private final List<HistorySearchProgressListener> progressListeners = new ArrayList<HistorySearchProgressListener>(); /** * Returns all the records for the descriptor after the given date. * * @param services the services classnames we will query * @param descriptor CallPeer address(String), * MetaContact or ChatRoom. * @param startDate Date the date of the first record to return * @return Collection sorted result that consists of records returned from * the services we wrap * @throws RuntimeException */ public Collection<Object> findByStartDate(String[] services, Object descriptor, Date startDate) throws RuntimeException { MessageProgressWrapper listenWrapper = new MessageProgressWrapper(services.length); TreeSet<Object> result = new TreeSet<Object>(new RecordsComparator()); for (int i = 0; i < services.length; i++) { String name = services[i]; Object serv = getService(name); if(serv instanceof MessageHistoryService) { MessageHistoryService mhs = (MessageHistoryService)serv; listenWrapper.setIx(i); mhs.addSearchProgressListener(listenWrapper); if(descriptor instanceof MetaContact) { result.addAll( mhs.findByStartDate((MetaContact)descriptor, startDate)); } else if(descriptor instanceof ChatRoom) { result.addAll( mhs.findByStartDate((ChatRoom)descriptor, startDate)); } mhs.removeSearchProgressListener(listenWrapper); } else if(serv instanceof FileHistoryService && descriptor instanceof MetaContact) { result.addAll( ((FileHistoryService)serv).findByStartDate( (MetaContact)descriptor, startDate)); } else if(serv instanceof CallHistoryService) { CallHistoryService chs = (CallHistoryService)serv; listenWrapper.setIx(i); chs.addSearchProgressListener(listenWrapper); result.addAll(chs.findByStartDate(startDate)); chs.removeSearchProgressListener(listenWrapper); } } listenWrapper.fireLastProgress(startDate, null, null); return result; } /** * Returns all the records before the given date * * @param services the services classnames we will query * @param descriptor CallPeer address(String), * MetaContact or ChatRoom. * @param endDate Date the date of the last record to return * @return Collection sorted result that conists of records returned from * the services we wrap * @throws RuntimeException */ public Collection<Object> findByEndDate(String[] services, Object descriptor, Date endDate) throws RuntimeException { MessageProgressWrapper listenWrapper = new MessageProgressWrapper(services.length); TreeSet<Object> result = new TreeSet<Object>(new RecordsComparator()); for (int i = 0; i < services.length; i++) { String name = services[i]; Object serv = getService(name); if(serv instanceof MessageHistoryService) { MessageHistoryService mhs = (MessageHistoryService)serv; listenWrapper.setIx(i); mhs.addSearchProgressListener(listenWrapper); if(descriptor instanceof MetaContact) { result.addAll( mhs.findByEndDate((MetaContact)descriptor, endDate)); } else if(descriptor instanceof ChatRoom) { result.addAll( mhs.findByEndDate((ChatRoom)descriptor, endDate)); } mhs.removeSearchProgressListener(listenWrapper); } else if(serv instanceof FileHistoryService && descriptor instanceof MetaContact) { result.addAll( ((FileHistoryService)serv).findByEndDate( (MetaContact)descriptor, endDate)); } else if(serv instanceof CallHistoryService) { CallHistoryService chs = (CallHistoryService)serv; listenWrapper.setIx(i); chs.addSearchProgressListener(listenWrapper); result.addAll( chs.findByEndDate(endDate)); chs.removeSearchProgressListener(listenWrapper); } } listenWrapper.fireLastProgress(null, endDate, null); return result; } /** * Returns all the records between the given dates * * @param services the services classnames we will query * @param descriptor CallPeer address(String), * MetaContact or ChatRoom. * @param startDate Date the date of the first record to return * @param endDate Date the date of the last record to return * @return Collection sorted result that conists of records returned from * the services we wrap * @throws RuntimeException */ public Collection<Object> findByPeriod(String[] services, Object descriptor, Date startDate, Date endDate) throws RuntimeException { MessageProgressWrapper listenWrapper = new MessageProgressWrapper(services.length); LinkedList<Object> result = new LinkedList<Object>(); for (int i = 0; i < services.length; i++) { String name = services[i]; Object serv = getService(name); if(serv instanceof MessageHistoryService) { MessageHistoryService mhs = (MessageHistoryService)serv; listenWrapper.setIx(i); mhs.addSearchProgressListener(listenWrapper); if(descriptor instanceof MetaContact) { result.addAll( mhs.findByPeriod( (MetaContact)descriptor, startDate, endDate)); } else if(descriptor instanceof ChatRoom) { result.addAll( mhs.findByPeriod( (ChatRoom)descriptor, startDate, endDate)); } mhs.removeSearchProgressListener(listenWrapper); } else if(serv instanceof FileHistoryService && descriptor instanceof MetaContact) { result.addAll( ((FileHistoryService)serv).findByPeriod( (MetaContact)descriptor, startDate, endDate)); } else if(serv instanceof CallHistoryService) { CallHistoryService chs = (CallHistoryService)serv; listenWrapper.setIx(i); chs.addSearchProgressListener(listenWrapper); result.addAll( chs.findByPeriod(startDate, endDate)); chs.removeSearchProgressListener(listenWrapper); } } listenWrapper.fireLastProgress(startDate, endDate, null); Collections.sort(result, new RecordsComparator()); return result; } /** * Returns all the records between the given dates and having the given * keywords * * @param services the services classnames we will query * @param descriptor CallPeer address(String), * MetaContact or ChatRoom. * @param startDate Date the date of the first record to return * @param endDate Date the date of the last record to return * @param keywords array of keywords * @return Collection sorted result that conists of records returned from * the services we wrap * @throws RuntimeException */ public Collection<Object> findByPeriod(String[] services, Object descriptor, Date startDate, Date endDate, String[] keywords) throws RuntimeException { return findByPeriod(services, descriptor, startDate, endDate, keywords, false); } /** * Returns all the records between the given dates and having the given * keywords * * @param services the services classnames we will query * @param descriptor CallPeer address(String), * MetaContact or ChatRoom. * @param startDate Date the date of the first record to return * @param endDate Date the date of the last record to return * @param keywords array of keywords * @param caseSensitive is keywords search case sensitive * @return Collection sorted result that conists of records returned from * the services we wrap * @throws RuntimeException */ public Collection<Object> findByPeriod(String[] services, Object descriptor, Date startDate, Date endDate, String[] keywords, boolean caseSensitive) throws RuntimeException { MessageProgressWrapper listenWrapper = new MessageProgressWrapper(services.length); TreeSet<Object> result = new TreeSet<Object>(new RecordsComparator()); for (int i = 0; i < services.length; i++) { String name = services[i]; Object serv = getService(name); if(serv instanceof MessageHistoryService) { MessageHistoryService mhs = (MessageHistoryService)serv; listenWrapper.setIx(i); mhs.addSearchProgressListener(listenWrapper); if(descriptor instanceof MetaContact) { result.addAll( mhs.findByPeriod( (MetaContact)descriptor, startDate, endDate, keywords, caseSensitive)); } else if(descriptor instanceof ChatRoom) { result.addAll( mhs.findByPeriod( (ChatRoom)descriptor, startDate, endDate, keywords, caseSensitive)); } mhs.removeSearchProgressListener(listenWrapper); } else if(serv instanceof FileHistoryService && descriptor instanceof MetaContact) { result.addAll( ((FileHistoryService)serv).findByPeriod( (MetaContact)descriptor, startDate, endDate, keywords, caseSensitive)); } else if(serv instanceof CallHistoryService) { CallHistoryService chs = (CallHistoryService)serv; listenWrapper.setIx(i); chs.addSearchProgressListener(listenWrapper); Collection<CallRecord> cs = chs.findByPeriod(startDate, endDate); Iterator<CallRecord> iter = cs.iterator(); while (iter.hasNext()) { CallRecord callRecord = iter.next(); if(matchCallPeer( callRecord.getPeerRecords(), keywords, caseSensitive)) result.add(callRecord); } chs.removeSearchProgressListener(listenWrapper); } } listenWrapper.fireLastProgress(startDate, endDate, keywords); return result; } /** * Returns all the records having the given keyword * * @param services the services classnames we will query * @param descriptor CallPeer address(String), * MetaContact or ChatRoom. * @param keyword keyword * @return Collection sorted result that conists of records returned from * the services we wrap * @throws RuntimeException */ public Collection<Object> findByKeyword(String[] services, Object descriptor, String keyword) throws RuntimeException { return findByKeyword(services, descriptor, keyword, false); } /** * Returns all the records having the given keyword * * @param services the services classnames we will query * @param descriptor CallPeer address(String), * MetaContact or ChatRoom. * @param keyword keyword * @param caseSensitive is keywords search case sensitive * @return Collection sorted result that conists of records returned from * the services we wrap * @throws RuntimeException */ public Collection<Object> findByKeyword(String[] services, Object descriptor, String keyword, boolean caseSensitive) throws RuntimeException { return findByKeywords( services, descriptor, new String[]{keyword}, caseSensitive); } /** * Returns all the records having the given keywords * * @param services the services classnames we will query * @param descriptor CallPeer address(String), * MetaContact or ChatRoom. * @param keywords keyword * @return Collection sorted result that conists of records returned from * the services we wrap * @throws RuntimeException */ public Collection<Object> findByKeywords(String[] services, Object descriptor, String[] keywords) throws RuntimeException { return findByKeywords(services, descriptor, keywords, false); } /** * Returns all the records having the given keywords * * @param services the services classnames we will query * @param descriptor CallPeer address(String), * MetaContact or ChatRoom. * @param keywords keyword * @param caseSensitive is keywords search case sensitive * @return Collection sorted result that conists of records returned from * the services we wrap * @throws RuntimeException */ public Collection<Object> findByKeywords(String[] services, Object descriptor, String[] keywords, boolean caseSensitive) throws RuntimeException { MessageProgressWrapper listenWrapper = new MessageProgressWrapper(services.length); TreeSet<Object> result = new TreeSet<Object>(new RecordsComparator()); for (int i = 0; i < services.length; i++) { String name = services[i]; Object serv = getService(name); if(serv instanceof MessageHistoryService) { MessageHistoryService mhs = (MessageHistoryService)serv; listenWrapper.setIx(i); mhs.addSearchProgressListener(listenWrapper); if(descriptor instanceof MetaContact) { result.addAll( mhs.findByKeywords( (MetaContact)descriptor, keywords, caseSensitive)); } else if(descriptor instanceof ChatRoom) { result.addAll( mhs.findByKeywords( (ChatRoom)descriptor, keywords, caseSensitive)); } mhs.removeSearchProgressListener(listenWrapper); } else if(serv instanceof FileHistoryService && descriptor instanceof MetaContact) { result.addAll( ((FileHistoryService)serv).findByKeywords( (MetaContact)descriptor, keywords, caseSensitive)); } else if(serv instanceof CallHistoryService) { CallHistoryService chs = (CallHistoryService)serv; listenWrapper.setIx(i); chs.addSearchProgressListener(listenWrapper); // this will get all call records Collection<CallRecord> cs = chs.findByEndDate(new Date()); Iterator<CallRecord> iter = cs.iterator(); while (iter.hasNext()) { CallRecord callRecord = iter.next(); if(matchCallPeer( callRecord.getPeerRecords(), keywords, caseSensitive)) result.add(callRecord); } chs.removeSearchProgressListener(listenWrapper); } } listenWrapper.fireLastProgress(null, null, keywords); return result; } /** * Returns the supplied number of recent records. * * @param services the services classnames we will query * @param descriptor CallPeer address(String), * MetaContact or ChatRoom. * @param count messages count * @return Collection sorted result that conists of records returned from * the services we wrap * @throws RuntimeException */ public Collection<Object> findLast(String[] services, Object descriptor, int count) throws RuntimeException { MessageProgressWrapper listenWrapper = new MessageProgressWrapper(services.length); TreeSet<Object> result = new TreeSet<Object>(new RecordsComparator()); for (int i = 0; i < services.length; i++) { String name = services[i]; Object serv = getService(name); if(serv instanceof MessageHistoryService) { MessageHistoryService mhs = (MessageHistoryService)serv; listenWrapper.setIx(i); mhs.addSearchProgressListener(listenWrapper); if(descriptor instanceof MetaContact) { result.addAll( mhs.findLast( (MetaContact)descriptor, count)); } else if(descriptor instanceof ChatRoom) { result.addAll( mhs.findLast( (ChatRoom)descriptor, count)); } mhs.removeSearchProgressListener(listenWrapper); } else if(serv instanceof FileHistoryService && descriptor instanceof MetaContact) { result.addAll( ((FileHistoryService)serv).findLast( (MetaContact)descriptor, count)); } else if(serv instanceof CallHistoryService) { CallHistoryService chs = (CallHistoryService)serv; listenWrapper.setIx(i); chs.addSearchProgressListener(listenWrapper); result.addAll( chs.findLast(count)); chs.removeSearchProgressListener(listenWrapper); } } listenWrapper.fireLastProgress(null, null, null); LinkedList<Object> resultAsList = new LinkedList<Object>(result); int startIndex = resultAsList.size() - count; if(startIndex < 0) startIndex = 0; return resultAsList.subList(startIndex, resultAsList.size()); } /** * Returns the supplied number of recent records after the given date * * @param services the services classnames we will query * @param descriptor CallPeer address(String), * MetaContact or ChatRoom. * @param date messages after date * @param count messages count * @return Collection sorted result that conists of records returned from * the services we wrap * @throws RuntimeException */ public Collection<Object> findFirstMessagesAfter(String[] services, Object descriptor, Date date, int count) throws RuntimeException { MessageProgressWrapper listenWrapper = new MessageProgressWrapper(services.length); TreeSet<Object> result = new TreeSet<Object>(new RecordsComparator()); for (int i = 0; i < services.length; i++) { String name = services[i]; Object serv = getService(name); if(serv instanceof MessageHistoryService) { MessageHistoryService mhs = (MessageHistoryService)serv; listenWrapper.setIx(i); mhs.addSearchProgressListener(listenWrapper); if(descriptor instanceof MetaContact) { result.addAll( mhs.findFirstMessagesAfter( (MetaContact)descriptor, date, count)); } else if(descriptor instanceof ChatRoom) { result.addAll( mhs.findFirstMessagesAfter( (ChatRoom)descriptor, date, count)); } mhs.removeSearchProgressListener(listenWrapper); } else if(serv instanceof FileHistoryService && descriptor instanceof MetaContact) { result.addAll( ((FileHistoryService)serv).findFirstRecordsAfter( (MetaContact)descriptor, date, count)); } else if(serv instanceof CallHistoryService) { CallHistoryService chs = (CallHistoryService)serv; listenWrapper.setIx(i); chs.addSearchProgressListener(listenWrapper); Collection<CallRecord> col = chs.findByStartDate(date); if(col.size() > count) { // before we make a sublist make sure there are sorted in the // right order List<CallRecord> l = new LinkedList<CallRecord>(col); Collections.sort(l, new RecordsComparator()); result.addAll(l.subList(0, count)); } else result.addAll(col); chs.removeSearchProgressListener(listenWrapper); } } listenWrapper.fireLastProgress(date, null, null); LinkedList<Object> resultAsList = new LinkedList<Object>(result); int toIndex = count; if(toIndex > resultAsList.size()) toIndex = resultAsList.size(); return resultAsList.subList(0, toIndex); } /** * Returns the supplied number of recent records before the given date * * @param services the services classnames we will query * @param descriptor CallPeer address(String), * MetaContact or ChatRoom. * @param date messages before date * @param count messages count * @return Collection sorted result that conists of records returned from * the services we wrap * @throws RuntimeException */ public Collection<Object> findLastMessagesBefore(String[] services, Object descriptor, Date date, int count) throws RuntimeException { MessageProgressWrapper listenWrapper = new MessageProgressWrapper(services.length); TreeSet<Object> result = new TreeSet<Object>(new RecordsComparator()); for (int i = 0; i < services.length; i++) { String name = services[i]; Object serv = getService(name); if(serv instanceof MessageHistoryService) { MessageHistoryService mhs = (MessageHistoryService)serv; listenWrapper.setIx(i); mhs.addSearchProgressListener(listenWrapper); if(descriptor instanceof MetaContact) { result.addAll( mhs.findLastMessagesBefore( (MetaContact)descriptor, date, count)); } else if(descriptor instanceof ChatRoom) { result.addAll( mhs.findLastMessagesBefore( (ChatRoom)descriptor, date, count)); } mhs.removeSearchProgressListener(listenWrapper); } else if(serv instanceof FileHistoryService && descriptor instanceof MetaContact) { result.addAll( ((FileHistoryService)serv).findLastRecordsBefore( (MetaContact)descriptor, date, count)); } else if(serv instanceof CallHistoryService) { CallHistoryService chs = (CallHistoryService)serv; listenWrapper.setIx(i); chs.addSearchProgressListener(listenWrapper); Collection<CallRecord> col = chs.findByEndDate(date); if(col.size() > count) { List<CallRecord> l = new LinkedList<CallRecord>(col); result.addAll(l.subList(l.size() - count, l.size())); } else result.addAll(col); chs.removeSearchProgressListener(listenWrapper); } } listenWrapper.fireLastProgress(date, null, null); LinkedList<Object> resultAsList = new LinkedList<Object>(result); int startIndex = resultAsList.size() - count; if(startIndex < 0) startIndex = 0; return resultAsList.subList(startIndex, resultAsList.size()); } /** * Adding progress listener for monitoring progress of search process * * @param listener HistorySearchProgressListener */ public void addSearchProgressListener(HistorySearchProgressListener listener) { synchronized(progressListeners) { if(!progressListeners.contains(listener)) progressListeners.add(listener); } } /** * Removing progress listener * * @param listener HistorySearchProgressListener */ public void removeSearchProgressListener(HistorySearchProgressListener listener) { synchronized(progressListeners) { progressListeners.remove(listener); } } private Object getService(String name) { Object serv = services.get(name); if(serv == null) { ServiceReference refHistory = bundleContext.getServiceReference(name); serv = bundleContext.getService(refHistory); } return serv; } private boolean matchAnyCallPeer( List<CallPeerRecord> cps, String[] keywords, boolean caseSensitive) { for (CallPeerRecord callPeer : cps) { for (String k : keywords) { if(caseSensitive && callPeer.getPeerAddress().contains(k)) return true; else if(callPeer.getPeerAddress().toLowerCase(). contains(k.toLowerCase())) return true; } } return false; } private boolean matchCallPeer( List<CallPeerRecord> cps, String[] keywords, boolean caseSensitive) { Iterator<CallPeerRecord> iter = cps.iterator(); while (iter.hasNext()) { boolean match = false; CallPeerRecord callPeer = iter.next(); for (int i = 0; i < keywords.length; i++) { String k = keywords[i]; if(caseSensitive) { if(callPeer.getPeerAddress().contains(k)) { match = true; } else { match = false; break; } continue; } else if(callPeer.getPeerAddress().toLowerCase(). contains(k.toLowerCase())) { match = true; } else { match = false; break; } } if(match) return true; } return false; } public void serviceChanged(ServiceEvent serviceEvent) { if(serviceEvent.getType() == ServiceEvent.UNREGISTERING) { Object sService = bundleContext.getService( serviceEvent.getServiceReference()); services.remove(sService.getClass().getName()); } } /** * starts the service. * * @param bc BundleContext */ public void start(BundleContext bc) { if (logger.isDebugEnabled()) logger.debug("Starting the call history implementation."); this.bundleContext = bc; services.clear(); // start listening for newly register or removed services bc.addServiceListener(this); } /** * stops the service. * * @param bc BundleContext */ public void stop(BundleContext bc) { bc.removeServiceListener(this); services.clear(); } /** * Used to compare various records * to be ordered in TreeSet according their timestamp. */ private static class RecordsComparator implements Comparator<Object> { private Date getDate(Object o) { Date date = new Date(0); if(o instanceof MessageDeliveredEvent) date = ((MessageDeliveredEvent)o).getTimestamp(); else if(o instanceof MessageReceivedEvent) date = ((MessageReceivedEvent)o).getTimestamp(); else if(o instanceof ChatRoomMessageDeliveredEvent) date = ((ChatRoomMessageDeliveredEvent)o).getTimestamp(); else if(o instanceof ChatRoomMessageReceivedEvent) date = ((ChatRoomMessageReceivedEvent)o).getTimestamp(); else if(o instanceof CallRecord) date = ((CallRecord)o).getStartTime(); else if(o instanceof FileRecord) date = ((FileRecord)o).getDate(); return date; } public int compare(Object o1, Object o2) { Date date1 = getDate(o1); Date date2 = getDate(o2); return date1.compareTo(date2); } } private class MessageProgressWrapper implements MessageHistorySearchProgressListener, CallHistorySearchProgressListener { private final int count; private int ix; public MessageProgressWrapper(int count) { this.count = count; } public void setIx(int ix) { this.ix = ix; } private void fireProgress(int origProgress, int maxVal, Date startDate, Date endDate, String[] keywords) { ProgressEvent ev = new ProgressEvent( MetaHistoryServiceImpl.this, startDate, endDate, keywords); double part1 = origProgress/ ((double)maxVal*count); double convProgress = part1*HistorySearchProgressListener.PROGRESS_MAXIMUM_VALUE + ix*HistorySearchProgressListener.PROGRESS_MAXIMUM_VALUE/count; ev.setProgress((int)convProgress); fireEvent(ev); } private void fireEvent(ProgressEvent ev) { Iterable<HistorySearchProgressListener> listeners; synchronized(progressListeners) { listeners = new ArrayList<HistorySearchProgressListener>( progressListeners); } for (HistorySearchProgressListener listener : listeners) listener.progressChanged(ev); } public void fireLastProgress( Date startDate, Date endDate, String[] keywords) { ProgressEvent ev = new ProgressEvent( MetaHistoryServiceImpl.this, startDate, endDate, keywords); ev.setProgress(HistorySearchProgressListener.PROGRESS_MAXIMUM_VALUE); fireEvent(ev); } public void progressChanged( net.java.sip.communicator.service.msghistory.event.ProgressEvent evt) { fireProgress( evt.getProgress(), MessageHistorySearchProgressListener.PROGRESS_MAXIMUM_VALUE, evt.getStartDate(), evt.getEndDate(), evt.getKeywords()); } public void progressChanged(net.java.sip.communicator.service.callhistory.event.ProgressEvent evt) { fireProgress( evt.getProgress(), CallHistorySearchProgressListener.PROGRESS_MAXIMUM_VALUE, evt.getStartDate(), evt.getEndDate(), null); } } }
// Copyright 2021 Google LLC // // 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. /** * Placement.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.admanager.axis.v202105; /** * A {@code Placement} groups related {@code AdUnit} objects. */ public class Placement extends com.google.api.ads.admanager.axis.v202105.SiteTargetingInfo implements java.io.Serializable { /* Uniquely identifies the {@code Placement}. This attribute is * read-only and * is assigned by Google when a placement is created. */ private java.lang.Long id; /* The name of the {@code Placement}. This value is required and * has a maximum * length of 255 characters. */ private java.lang.String name; /* A description of the {@code Placement}. This value is optional * and its * maximum length is 65,535 characters. */ private java.lang.String description; /* A string used to uniquely identify the {@code Placement} for * purposes of * serving the ad. This attribute is read-only and * is assigned by Google when * a placement is created. */ private java.lang.String placementCode; /* The status of the {@code Placement}. This attribute is read-only. */ private com.google.api.ads.admanager.axis.v202105.InventoryStatus status; /* The collection of {@code AdUnit} object IDs that constitute * the {@code * Placement}. */ private java.lang.String[] targetedAdUnitIds; /* The date and time this placement was last modified. */ private com.google.api.ads.admanager.axis.v202105.DateTime lastModifiedDateTime; public Placement() { } public Placement( java.lang.Long id, java.lang.String name, java.lang.String description, java.lang.String placementCode, com.google.api.ads.admanager.axis.v202105.InventoryStatus status, java.lang.String[] targetedAdUnitIds, com.google.api.ads.admanager.axis.v202105.DateTime lastModifiedDateTime) { this.id = id; this.name = name; this.description = description; this.placementCode = placementCode; this.status = status; this.targetedAdUnitIds = targetedAdUnitIds; this.lastModifiedDateTime = lastModifiedDateTime; } @Override public String toString() { return com.google.common.base.MoreObjects.toStringHelper(this.getClass()) .omitNullValues() .add("description", getDescription()) .add("id", getId()) .add("lastModifiedDateTime", getLastModifiedDateTime()) .add("name", getName()) .add("placementCode", getPlacementCode()) .add("status", getStatus()) .add("targetedAdUnitIds", getTargetedAdUnitIds()) .toString(); } /** * Gets the id value for this Placement. * * @return id * Uniquely identifies the {@code Placement}. This attribute is * read-only and * is assigned by Google when a placement is created. */ public java.lang.Long getId() { return id; } /** * Sets the id value for this Placement. * * @param id * Uniquely identifies the {@code Placement}. This attribute is * read-only and * is assigned by Google when a placement is created. */ public void setId(java.lang.Long id) { this.id = id; } /** * Gets the name value for this Placement. * * @return name * The name of the {@code Placement}. This value is required and * has a maximum * length of 255 characters. */ public java.lang.String getName() { return name; } /** * Sets the name value for this Placement. * * @param name * The name of the {@code Placement}. This value is required and * has a maximum * length of 255 characters. */ public void setName(java.lang.String name) { this.name = name; } /** * Gets the description value for this Placement. * * @return description * A description of the {@code Placement}. This value is optional * and its * maximum length is 65,535 characters. */ public java.lang.String getDescription() { return description; } /** * Sets the description value for this Placement. * * @param description * A description of the {@code Placement}. This value is optional * and its * maximum length is 65,535 characters. */ public void setDescription(java.lang.String description) { this.description = description; } /** * Gets the placementCode value for this Placement. * * @return placementCode * A string used to uniquely identify the {@code Placement} for * purposes of * serving the ad. This attribute is read-only and * is assigned by Google when * a placement is created. */ public java.lang.String getPlacementCode() { return placementCode; } /** * Sets the placementCode value for this Placement. * * @param placementCode * A string used to uniquely identify the {@code Placement} for * purposes of * serving the ad. This attribute is read-only and * is assigned by Google when * a placement is created. */ public void setPlacementCode(java.lang.String placementCode) { this.placementCode = placementCode; } /** * Gets the status value for this Placement. * * @return status * The status of the {@code Placement}. This attribute is read-only. */ public com.google.api.ads.admanager.axis.v202105.InventoryStatus getStatus() { return status; } /** * Sets the status value for this Placement. * * @param status * The status of the {@code Placement}. This attribute is read-only. */ public void setStatus(com.google.api.ads.admanager.axis.v202105.InventoryStatus status) { this.status = status; } /** * Gets the targetedAdUnitIds value for this Placement. * * @return targetedAdUnitIds * The collection of {@code AdUnit} object IDs that constitute * the {@code * Placement}. */ public java.lang.String[] getTargetedAdUnitIds() { return targetedAdUnitIds; } /** * Sets the targetedAdUnitIds value for this Placement. * * @param targetedAdUnitIds * The collection of {@code AdUnit} object IDs that constitute * the {@code * Placement}. */ public void setTargetedAdUnitIds(java.lang.String[] targetedAdUnitIds) { this.targetedAdUnitIds = targetedAdUnitIds; } public java.lang.String getTargetedAdUnitIds(int i) { return this.targetedAdUnitIds[i]; } public void setTargetedAdUnitIds(int i, java.lang.String _value) { this.targetedAdUnitIds[i] = _value; } /** * Gets the lastModifiedDateTime value for this Placement. * * @return lastModifiedDateTime * The date and time this placement was last modified. */ public com.google.api.ads.admanager.axis.v202105.DateTime getLastModifiedDateTime() { return lastModifiedDateTime; } /** * Sets the lastModifiedDateTime value for this Placement. * * @param lastModifiedDateTime * The date and time this placement was last modified. */ public void setLastModifiedDateTime(com.google.api.ads.admanager.axis.v202105.DateTime lastModifiedDateTime) { this.lastModifiedDateTime = lastModifiedDateTime; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof Placement)) return false; Placement other = (Placement) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.id==null && other.getId()==null) || (this.id!=null && this.id.equals(other.getId()))) && ((this.name==null && other.getName()==null) || (this.name!=null && this.name.equals(other.getName()))) && ((this.description==null && other.getDescription()==null) || (this.description!=null && this.description.equals(other.getDescription()))) && ((this.placementCode==null && other.getPlacementCode()==null) || (this.placementCode!=null && this.placementCode.equals(other.getPlacementCode()))) && ((this.status==null && other.getStatus()==null) || (this.status!=null && this.status.equals(other.getStatus()))) && ((this.targetedAdUnitIds==null && other.getTargetedAdUnitIds()==null) || (this.targetedAdUnitIds!=null && java.util.Arrays.equals(this.targetedAdUnitIds, other.getTargetedAdUnitIds()))) && ((this.lastModifiedDateTime==null && other.getLastModifiedDateTime()==null) || (this.lastModifiedDateTime!=null && this.lastModifiedDateTime.equals(other.getLastModifiedDateTime()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getId() != null) { _hashCode += getId().hashCode(); } if (getName() != null) { _hashCode += getName().hashCode(); } if (getDescription() != null) { _hashCode += getDescription().hashCode(); } if (getPlacementCode() != null) { _hashCode += getPlacementCode().hashCode(); } if (getStatus() != null) { _hashCode += getStatus().hashCode(); } if (getTargetedAdUnitIds() != null) { for (int i=0; i<java.lang.reflect.Array.getLength(getTargetedAdUnitIds()); i++) { java.lang.Object obj = java.lang.reflect.Array.get(getTargetedAdUnitIds(), i); if (obj != null && !obj.getClass().isArray()) { _hashCode += obj.hashCode(); } } } if (getLastModifiedDateTime() != null) { _hashCode += getLastModifiedDateTime().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(Placement.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202105", "Placement")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("id"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202105", "id")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("name"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202105", "name")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("description"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202105", "description")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("placementCode"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202105", "placementCode")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("status"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202105", "status")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202105", "InventoryStatus")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("targetedAdUnitIds"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202105", "targetedAdUnitIds")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); elemField.setMaxOccursUnbounded(true); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("lastModifiedDateTime"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202105", "lastModifiedDateTime")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202105", "DateTime")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
/* * 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.server.impl; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.ToLongFunction; import io.netty.buffer.ByteBuf; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.ActiveMQPropertyConversionException; import org.apache.activemq.artemis.api.core.Message; import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.filter.Filter; import org.apache.activemq.artemis.core.message.impl.CoreMessage; import org.apache.activemq.artemis.core.persistence.CoreMessageObjectPools; import org.apache.activemq.artemis.core.paging.PagingStore; import org.apache.activemq.artemis.core.paging.cursor.PageSubscription; import org.apache.activemq.artemis.core.persistence.OperationContext; import org.apache.activemq.artemis.core.persistence.Persister; import org.apache.activemq.artemis.core.postoffice.Binding; import org.apache.activemq.artemis.core.server.Consumer; import org.apache.activemq.artemis.core.server.MessageReference; import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.core.server.RoutingContext; import org.apache.activemq.artemis.core.server.ServerConsumer; import org.apache.activemq.artemis.core.transaction.Transaction; import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.ReferenceCounter; import org.apache.activemq.artemis.utils.UUID; import org.apache.activemq.artemis.utils.collections.LinkedListIterator; import org.apache.activemq.artemis.utils.critical.CriticalComponentImpl; import org.apache.activemq.artemis.utils.critical.EmptyCriticalAnalyzer; import org.jboss.logging.Logger; import org.junit.Assert; import org.junit.Test; public class ScheduledDeliveryHandlerTest extends Assert { private static final Logger log = Logger.getLogger(ScheduledDeliveryHandlerTest.class); @Test public void testScheduleRandom() throws Exception { ScheduledDeliveryHandlerImpl handler = new ScheduledDeliveryHandlerImpl(null, new FakeQueueForScheduleUnitTest(0)); long nextMessage = 0; long NUMBER_OF_SEQUENCES = 100000; for (int i = 0; i < NUMBER_OF_SEQUENCES; i++) { int numberOfMessages = RandomUtil.randomInt() % 10; if (numberOfMessages == 0) numberOfMessages = 1; long nextScheduledTime = RandomUtil.randomPositiveLong(); for (int j = 0; j < numberOfMessages; j++) { boolean tail = RandomUtil.randomBoolean(); addMessage(handler, nextMessage++, nextScheduledTime, tail); } } debugList(true, handler, nextMessage); } @Test public void testScheduleSameTimeHeadAndTail() throws Exception { ScheduledDeliveryHandlerImpl handler = new ScheduledDeliveryHandlerImpl(null, new FakeQueueForScheduleUnitTest(0)); long time = System.currentTimeMillis() + 10000; for (int i = 10001; i < 20000; i++) { addMessage(handler, i, time, true); } addMessage(handler, 10000, time, false); time = System.currentTimeMillis() + 5000; for (int i = 1; i < 10000; i++) { addMessage(handler, i, time, true); } addMessage(handler, 0, time, false); debugList(true, handler, 20000); validateSequence(handler); } @Test public void testScheduleFixedSample() throws Exception { ScheduledDeliveryHandlerImpl handler = new ScheduledDeliveryHandlerImpl(null, new FakeQueueForScheduleUnitTest(0)); addMessage(handler, 0, 48L, true); addMessage(handler, 1, 75L, true); addMessage(handler, 2, 56L, true); addMessage(handler, 3, 7L, false); addMessage(handler, 4, 69L, true); debugList(true, handler, 5); } @Test public void testScheduleWithAddHeads() throws Exception { ScheduledDeliveryHandlerImpl handler = new ScheduledDeliveryHandlerImpl(null, new FakeQueueForScheduleUnitTest(0)); addMessage(handler, 0, 1, true); addMessage(handler, 1, 2, true); addMessage(handler, 2, 3, true); addMessage(handler, 3, 3, true); addMessage(handler, 4, 4, true); addMessage(handler, 10, 5, false); addMessage(handler, 9, 5, false); addMessage(handler, 8, 5, false); addMessage(handler, 7, 5, false); addMessage(handler, 6, 5, false); addMessage(handler, 5, 5, false); validateSequence(handler); } @Test public void testScheduleFixedSampleTailAndHead() throws Exception { ScheduledDeliveryHandlerImpl handler = new ScheduledDeliveryHandlerImpl(null, new FakeQueueForScheduleUnitTest(0)); // mix a sequence of tails / heads, but at the end this was supposed to be all sequential addMessage(handler, 1, 48L, true); addMessage(handler, 2, 48L, true); addMessage(handler, 3, 48L, true); addMessage(handler, 4, 48L, true); addMessage(handler, 5, 48L, true); addMessage(handler, 0, 48L, false); addMessage(handler, 13, 59L, true); addMessage(handler, 14, 59L, true); addMessage(handler, 15, 59L, true); addMessage(handler, 16, 59L, true); addMessage(handler, 17, 59L, true); addMessage(handler, 12, 59L, false); addMessage(handler, 7, 49L, true); addMessage(handler, 8, 49L, true); addMessage(handler, 9, 49L, true); addMessage(handler, 10, 49L, true); addMessage(handler, 11, 49L, true); addMessage(handler, 6, 49L, false); validateSequence(handler); } @Test public void testScheduleNow() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(50, ActiveMQThreadFactory.defaultThreadFactory()); ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1, ActiveMQThreadFactory.defaultThreadFactory()); try { for (int i = 0; i < 100; i++) { // it's better to run the test a few times instead of run millions of messages here internalSchedule(executor, scheduler); } } finally { scheduler.shutdownNow(); executor.shutdownNow(); } } private void internalSchedule(ExecutorService executor, ScheduledThreadPoolExecutor scheduler) throws Exception { final int NUMBER_OF_MESSAGES = 200; int NUMBER_OF_THREADS = 20; final FakeQueueForScheduleUnitTest fakeQueue = new FakeQueueForScheduleUnitTest(NUMBER_OF_MESSAGES * NUMBER_OF_THREADS); final ScheduledDeliveryHandlerImpl handler = new ScheduledDeliveryHandlerImpl(scheduler, fakeQueue); final long now = System.currentTimeMillis(); final CountDownLatch latchDone = new CountDownLatch(NUMBER_OF_THREADS); final AtomicInteger error = new AtomicInteger(0); class ProducerThread implements Runnable { @Override public void run() { try { for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { checkAndSchedule(handler, i, now, false, fakeQueue); } } catch (Exception e) { e.printStackTrace(); error.incrementAndGet(); } finally { latchDone.countDown(); } } } for (int i = 0; i < NUMBER_OF_THREADS; i++) { executor.execute(new ProducerThread()); } assertTrue(latchDone.await(1, TimeUnit.MINUTES)); assertEquals(0, error.get()); if (!fakeQueue.waitCompletion(2, TimeUnit.SECONDS)) { fail("Couldn't complete queue.add, expected " + NUMBER_OF_MESSAGES + ", still missing " + fakeQueue.expectedElements.toString()); } } private void validateSequence(ScheduledDeliveryHandlerImpl handler) throws Exception { long lastSequence = -1; for (MessageReference ref : handler.getScheduledReferences()) { assertEquals(lastSequence + 1, ref.getMessage().getMessageID()); lastSequence = ref.getMessage().getMessageID(); } } private void addMessage(ScheduledDeliveryHandlerImpl handler, long nextMessageID, long nextScheduledTime, boolean tail) { MessageReferenceImpl refImpl = new MessageReferenceImpl(new FakeMessage(nextMessageID), null); refImpl.setScheduledDeliveryTime(nextScheduledTime); handler.addInPlace(nextScheduledTime, refImpl, tail); } private void checkAndSchedule(ScheduledDeliveryHandlerImpl handler, long nextMessageID, long nextScheduledTime, boolean tail, Queue queue) { MessageReferenceImpl refImpl = new MessageReferenceImpl(new FakeMessage(nextMessageID), queue); refImpl.setScheduledDeliveryTime(nextScheduledTime); handler.checkAndSchedule(refImpl, tail); } private void debugList(boolean fail, ScheduledDeliveryHandlerImpl handler, long numberOfExpectedMessages) throws Exception { List<MessageReference> refs = handler.getScheduledReferences(); HashSet<Long> messages = new HashSet<>(); long lastTime = -1; for (MessageReference ref : refs) { assertFalse(messages.contains(ref.getMessage().getMessageID())); messages.add(ref.getMessage().getMessageID()); if (fail) { assertTrue(ref.getScheduledDeliveryTime() >= lastTime); } else { if (ref.getScheduledDeliveryTime() < lastTime) { log.debug("^^^fail at " + ref.getScheduledDeliveryTime()); } } lastTime = ref.getScheduledDeliveryTime(); } for (long i = 0; i < numberOfExpectedMessages; i++) { assertTrue(messages.contains(Long.valueOf(i))); } } class FakeMessage implements Message { @Override public SimpleString getReplyTo() { return null; } @Override public Message setReplyTo(SimpleString address) { return null; } @Override public Object removeAnnotation(SimpleString key) { return null; } @Override public Object getAnnotation(SimpleString key) { return null; } @Override public void persist(ActiveMQBuffer targetRecord) { } @Override public int getDurableCount() { return 0; } @Override public Long getScheduledDeliveryTime() { return null; } @Override public void reloadPersistence(ActiveMQBuffer record, CoreMessageObjectPools pools) { } @Override public Persister<Message> getPersister() { return null; } @Override public int getPersistSize() { return 0; } final long id; @Override public CoreMessage toCore() { return toCore(null); } @Override public CoreMessage toCore(CoreMessageObjectPools coreMessageObjectPools) { return null; } FakeMessage(final long id) { this.id = id; } @Override public FakeMessage setMessageID(long id) { return this; } @Override public long getMessageID() { return id; } @Override public int durableUp() { return 0; } @Override public int durableDown() { return 0; } @Override public Message copy(long newID) { return null; } @Override public Message copy() { return null; } @Override public int getMemoryEstimate() { return 0; } @Override public int getRefCount() { return 0; } @Override public byte[] getDuplicateIDBytes() { return new byte[0]; } @Override public Object getDuplicateProperty() { return null; } @Override public void messageChanged() { } @Override public UUID getUserID() { return null; } @Override public String getAddress() { return null; } @Override public SimpleString getAddressSimpleString() { return null; } @Override public Message setBuffer(ByteBuf buffer) { return null; } @Override public ByteBuf getBuffer() { return null; } @Override public Message setAddress(String address) { return null; } @Override public Message setAddress(SimpleString address) { return null; } @Override public boolean isDurable() { return false; } @Override public FakeMessage setDurable(boolean durable) { return this; } @Override public long getExpiration() { return 0; } @Override public boolean isExpired() { return false; } @Override public FakeMessage setExpiration(long expiration) { return this; } @Override public long getTimestamp() { return 0; } @Override public FakeMessage setTimestamp(long timestamp) { return this; } @Override public byte getPriority() { return 0; } @Override public FakeMessage setPriority(byte priority) { return this; } @Override public int getEncodeSize() { return 0; } @Override public boolean isLargeMessage() { return false; } @Override public Message putBooleanProperty(SimpleString key, boolean value) { return null; } @Override public Message putBooleanProperty(String key, boolean value) { return null; } @Override public Message putByteProperty(SimpleString key, byte value) { return null; } @Override public Message putByteProperty(String key, byte value) { return null; } @Override public Message putBytesProperty(SimpleString key, byte[] value) { return null; } @Override public Message putBytesProperty(String key, byte[] value) { return null; } @Override public Message putShortProperty(SimpleString key, short value) { return null; } @Override public Message putShortProperty(String key, short value) { return null; } @Override public Message putCharProperty(SimpleString key, char value) { return null; } @Override public Message putCharProperty(String key, char value) { return null; } @Override public Message putIntProperty(SimpleString key, int value) { return null; } @Override public Message putIntProperty(String key, int value) { return null; } @Override public Message putLongProperty(SimpleString key, long value) { return null; } @Override public Message putLongProperty(String key, long value) { return null; } @Override public Message putFloatProperty(SimpleString key, float value) { return null; } @Override public Message putFloatProperty(String key, float value) { return null; } @Override public Message putDoubleProperty(SimpleString key, double value) { return null; } @Override public Message putDoubleProperty(String key, double value) { return null; } @Override public Message putStringProperty(SimpleString key, SimpleString value) { return null; } @Override public Message putStringProperty(SimpleString key, String value) { return null; } @Override public Message putStringProperty(String key, String value) { return null; } @Override public Message putObjectProperty(SimpleString key, Object value) throws ActiveMQPropertyConversionException { return null; } @Override public Message putObjectProperty(String key, Object value) throws ActiveMQPropertyConversionException { return null; } @Override public Object removeProperty(SimpleString key) { return null; } @Override public Object removeProperty(String key) { return null; } @Override public boolean containsProperty(SimpleString key) { return false; } @Override public boolean containsProperty(String key) { return false; } @Override public Boolean getBooleanProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override public Boolean getBooleanProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override public Byte getByteProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override public Byte getByteProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override public Double getDoubleProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override public Double getDoubleProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override public Integer getIntProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override public Integer getIntProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override public Long getLongProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override public Long getLongProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override public Object getObjectProperty(SimpleString key) { return null; } @Override public Object getObjectProperty(String key) { return null; } @Override public Short getShortProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override public Short getShortProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override public Float getFloatProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override public Float getFloatProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override public String getStringProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override public String getStringProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override public SimpleString getSimpleStringProperty(SimpleString key) throws ActiveMQPropertyConversionException { return null; } @Override public SimpleString getSimpleStringProperty(String key) throws ActiveMQPropertyConversionException { return null; } @Override public byte[] getBytesProperty(SimpleString key) throws ActiveMQPropertyConversionException { return new byte[0]; } @Override public byte[] getBytesProperty(String key) throws ActiveMQPropertyConversionException { return new byte[0]; } @Override public Set<SimpleString> getPropertyNames() { return null; } @Override public Map<String, Object> toMap() { return null; } @Override public Map<String, Object> toPropertyMap() { return null; } @Override public Message setUserID(Object userID) { return null; } @Override public void receiveBuffer(ByteBuf buffer) { } @Override public int getUsage() { return 0; } @Override public int usageUp() { return 0; } @Override public int usageDown() { return 0; } @Override public int refUp() { return 0; } @Override public int refDown() { return 0; } @Override public void sendBuffer(ByteBuf buffer, int count) { } @Override public long getPersistentSize() throws ActiveMQException { return 0; } @Override public Object getOwner() { return null; } @Override public void setOwner(Object object) { } } public class FakeQueueForScheduleUnitTest extends CriticalComponentImpl implements Queue { @Override public void setPurgeOnNoConsumers(boolean value) { } @Override public boolean isEnabled() { return false; } @Override public void setEnabled(boolean value) { } @Override public PagingStore getPagingStore() { return null; } @Override public int durableUp(Message message) { return 1; } @Override public int durableDown(Message message) { return 1; } @Override public void refUp(MessageReference messageReference) { } @Override public MessageReference removeWithSuppliedID(long id, ToLongFunction<MessageReference> idSupplier) { return null; } @Override public void refDown(MessageReference messageReference) { } @Override public void removeAddress() throws Exception { } @Override public long getAcknowledgeAttempts() { return 0; } @Override public boolean allowsReferenceCallback() { return false; } @Override public int getConsumersBeforeDispatch() { return 0; } @Override public void setConsumersBeforeDispatch(int consumersBeforeDispatch) { } @Override public long getDelayBeforeDispatch() { return 0; } @Override public void setDelayBeforeDispatch(long delayBeforeDispatch) { } @Override public long getDispatchStartTime() { return 0; } @Override public boolean isDispatching() { return false; } @Override public void setDispatching(boolean dispatching) { } @Override public void setMaxConsumer(int maxConsumers) { } @Override public int getGroupBuckets() { return 0; } @Override public void setGroupBuckets(int groupBuckets) { } @Override public boolean isGroupRebalance() { return false; } @Override public void setGroupRebalance(boolean groupRebalance) { } @Override public boolean isGroupRebalancePauseDispatch() { return false; } @Override public void setGroupRebalancePauseDispatch(boolean groupRebalancePauseDisptach) { } @Override public SimpleString getGroupFirstKey() { return null; } @Override public void setGroupFirstKey(SimpleString groupFirstKey) { } @Override public boolean isConfigurationManaged() { return false; } @Override public void setConfigurationManaged(boolean configurationManaged) { } @Override public void recheckRefCount(OperationContext context) { } @Override public void unproposed(SimpleString groupID) { } public FakeQueueForScheduleUnitTest(final int expectedElements) { super(EmptyCriticalAnalyzer.getInstance(), 1); this.expectedElements = new CountDownLatch(expectedElements); } @Override public boolean isPersistedPause() { return false; } public boolean waitCompletion(long timeout, TimeUnit timeUnit) throws Exception { return expectedElements.await(timeout, timeUnit); } final CountDownLatch expectedElements; LinkedList<MessageReference> messages = new LinkedList<>(); @Override public SimpleString getName() { return null; } @Override public Long getID() { return Long.valueOf(0L); } @Override public void pause(boolean persist) { } @Override public void reloadPause(long recordID) { } @Override public Filter getFilter() { return null; } @Override public void setFilter(Filter filter) { } @Override public PageSubscription getPageSubscription() { return null; } @Override public RoutingType getRoutingType() { return null; } @Override public void setRoutingType(RoutingType routingType) { } @Override public boolean isDurable() { return false; } @Override public boolean isDurableMessage() { return false; } @Override public boolean isAutoDelete() { // no-op return false; } @Override public long getAutoDeleteDelay() { // no-op return -1; } @Override public long getAutoDeleteMessageCount() { // no-op return -1; } @Override public boolean isTemporary() { return false; } @Override public boolean isAutoCreated() { return false; } @Override public boolean isPurgeOnNoConsumers() { return false; } @Override public int getMaxConsumers() { return -1; } @Override public void addConsumer(Consumer consumer) throws Exception { } @Override public void addLingerSession(String sessionId) { } @Override public void removeLingerSession(String sessionId) { } @Override public void removeConsumer(Consumer consumer) { } @Override public int retryMessages(Filter filter) throws Exception { return 0; } @Override public int getConsumerCount() { return 0; } @Override public long getConsumerRemovedTimestamp() { return 0; } @Override public void setRingSize(long ringSize) { } @Override public long getRingSize() { return 0; } @Override public void setConsumersRefCount(ReferenceCounter referenceCounter) { } @Override public ReferenceCounter getConsumersRefCount() { return null; } @Override public void addSorted(List<MessageReference> refs, boolean scheduling) { addHead(refs, scheduling); } @Override public void reload(MessageReference ref) { } @Override public void addTail(MessageReference ref) { } @Override public void addTail(MessageReference ref, boolean direct) { } @Override public void addHead(MessageReference ref, boolean scheduling) { } @Override public void addSorted(MessageReference ref, boolean scheduling) { } @Override public void addHead(List<MessageReference> refs, boolean scheduling) { for (MessageReference ref : refs) { addFirst(ref); } } private void addFirst(MessageReference ref) { expectedElements.countDown(); this.messages.addFirst(ref); } @Override public void acknowledge(MessageReference ref) throws Exception { } @Override public void acknowledge(MessageReference ref, ServerConsumer consumer) throws Exception { } @Override public void acknowledge(MessageReference ref, AckReason reason, ServerConsumer consumer) throws Exception { } @Override public void acknowledge(Transaction tx, MessageReference ref) throws Exception { } @Override public void acknowledge(Transaction tx, MessageReference ref, AckReason reason, ServerConsumer consumer) throws Exception { } @Override public void reacknowledge(Transaction tx, MessageReference ref) throws Exception { } @Override public void cancel(Transaction tx, MessageReference ref) { } @Override public void cancel(Transaction tx, MessageReference ref, boolean ignoreRedeliveryCheck) { } @Override public void cancel(MessageReference reference, long timeBase) throws Exception { } @Override public void deliverAsync() { } @Override public void forceDelivery() { } @Override public void deleteQueue() throws Exception { } @Override public void deleteQueue(boolean removeConsumers) throws Exception { } @Override public void destroyPaging() throws Exception { } @Override public long getMessageCount() { return 0; } @Override public long getPersistentSize() { return 0; } @Override public long getDurableMessageCount() { return 0; } @Override public long getDurablePersistentSize() { return 0; } @Override public int getDeliveringCount() { return 0; } @Override public long getDeliveringSize() { return 0; } @Override public int getDurableDeliveringCount() { return 0; } @Override public long getDurableDeliveringSize() { return 0; } @Override public int getDurableScheduledCount() { return 0; } @Override public long getDurableScheduledSize() { return 0; } @Override public void referenceHandled(MessageReference ref) { } @Override public int getScheduledCount() { return 0; } @Override public long getScheduledSize() { return 0; } @Override public List<MessageReference> getScheduledMessages() { return null; } @Override public Map<String, List<MessageReference>> getDeliveringMessages() { return null; } @Override public long getMessagesAdded() { return 0; } @Override public long getMessagesAcknowledged() { return 0; } @Override public long getMessagesExpired() { return 0; } @Override public long getMessagesKilled() { return 0; } @Override public long getMessagesReplaced() { return 0; } @Override public MessageReference removeReferenceWithID(long id) throws Exception { return null; } @Override public MessageReference getReference(long id) { return null; } @Override public int deleteAllReferences() throws Exception { return 0; } @Override public int deleteAllReferences(int flushLimit) throws Exception { return 0; } @Override public boolean deleteReference(long messageID) throws Exception { return false; } @Override public int deleteMatchingReferences(Filter filter) throws Exception { return 0; } @Override public int deleteMatchingReferences(int flushLImit, Filter filter, AckReason reason) throws Exception { return 0; } @Override public boolean expireReference(long messageID) throws Exception { return false; } @Override public int expireReferences(Filter filter) throws Exception { return 0; } @Override public void expireReferences() throws Exception { } @Override public void expire(MessageReference ref) throws Exception { } @Override public void expire(MessageReference ref, ServerConsumer consumer) throws Exception { } @Override public boolean sendToDeadLetterAddress(Transaction tx, MessageReference ref) throws Exception { return false; } @Override public boolean sendMessageToDeadLetterAddress(long messageID) throws Exception { return false; } @Override public int sendMessagesToDeadLetterAddress(Filter filter) throws Exception { return 0; } @Override public boolean changeReferencePriority(long messageID, byte newPriority) throws Exception { return false; } @Override public int changeReferencesPriority(Filter filter, byte newPriority) throws Exception { return 0; } @Override public boolean moveReference(long messageID, SimpleString toAddress, Binding binding, boolean rejectDuplicates) throws Exception { return false; } @Override public int moveReferences(Filter filter, SimpleString toAddress, Binding binding) throws Exception { return 0; } @Override public int moveReferences(int flushLimit, Filter filter, SimpleString toAddress, boolean rejectDuplicates, Binding binding) throws Exception { return 0; } @Override public int moveReferences(int flushLimit, Filter filter, SimpleString toAddress, boolean rejectDuplicates, int messageCount, Binding binding) throws Exception { return 0; } @Override public void addRedistributor(long delay) { } @Override public void cancelRedistributor() throws Exception { } @Override public boolean hasMatchingConsumer(Message message) { return false; } @Override public Collection<Consumer> getConsumers() { return null; } @Override public Map<SimpleString, Consumer> getGroups() { return null; } @Override public void resetGroup(SimpleString groupID) { } @Override public void resetAllGroups() { } @Override public int getGroupCount() { return 0; } @Override public Pair<Boolean, Boolean> checkRedelivery(MessageReference ref, long timeBase, boolean ignoreRedeliveryDelay) throws Exception { return new Pair<>(false, false); } @Override public LinkedListIterator<MessageReference> iterator() { return null; } @Override public LinkedListIterator<MessageReference> browserIterator() { return null; } @Override public SimpleString getExpiryAddress() { return null; } @Override public void pause() { } @Override public void resume() { } @Override public boolean isPaused() { return false; } @Override public Executor getExecutor() { return null; } @Override public void resetAllIterators() { } @Override public boolean flushExecutor() { return false; } @Override public void close() throws Exception { } @Override public boolean isDirectDeliver() { return false; } @Override public SimpleString getAddress() { return null; } @Override public boolean isInternalQueue() { return false; } @Override public void setInternalQueue(boolean internalQueue) { } @Override public void resetMessagesAdded() { } @Override public void resetMessagesAcknowledged() { } @Override public void resetMessagesExpired() { } @Override public void resetMessagesKilled() { } @Override public void incrementMesssagesAdded() { } @Override public void deliverScheduledMessages() { } @Override public void route(Message message, RoutingContext context) throws Exception { } @Override public void routeWithAck(Message message, RoutingContext context) { } @Override public void postAcknowledge(MessageReference ref, AckReason reason) { } @Override public float getRate() { return 0.0f; } @Override public SimpleString getUser() { return null; } @Override public void setUser(SimpleString user) { } @Override public boolean isLastValue() { return false; } @Override public SimpleString getLastValueKey() { return null; } @Override public boolean isNonDestructive() { return false; } @Override public void setNonDestructive(boolean nonDestructive) { } @Override public boolean isExclusive() { return false; } @Override public void setExclusive(boolean exclusive) { } } }
package mvm.rya.indexing.accumulo.entity; /* * 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. */ import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import mvm.rya.accumulo.documentIndex.TextColumn; import mvm.rya.api.domain.RyaType; import mvm.rya.api.domain.RyaURI; import mvm.rya.api.resolver.RdfToRyaConversions; import mvm.rya.api.resolver.RyaContext; import mvm.rya.api.resolver.RyaTypeResolverException; import mvm.rya.joinselect.AccumuloSelectivityEvalDAO; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.hadoop.io.Text; import org.openrdf.model.Value; import org.openrdf.query.BindingSet; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.Var; import com.beust.jcommander.internal.Maps; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.primitives.Bytes; public class StarQuery { private List<StatementPattern> nodes; private TextColumn[] nodeColumnCond; private String commonVarName; private Var commonVar; private Var context; private String contextURI =""; private Map<String,Integer> varPos = Maps.newHashMap(); private boolean isCommonVarURI = false; public StarQuery(List<StatementPattern> nodes) { this.nodes = nodes; if(nodes.size() == 0) { throw new IllegalArgumentException("Nodes cannot be empty!"); } nodeColumnCond = new TextColumn[nodes.size()]; Var tempContext = nodes.get(0).getContextVar(); if(tempContext != null) { context = tempContext.clone(); } else { context = new Var(); } try { this.init(); } catch (RyaTypeResolverException e) { e.printStackTrace(); } } public StarQuery(Set<StatementPattern> nodes) { this(Lists.newArrayList(nodes)); } public int size() { return nodes.size(); } public StarQuery(StarQuery other) { this(other.nodes); } public List<StatementPattern> getNodes() { return nodes; } public TextColumn[] getColumnCond() { return nodeColumnCond; } public boolean isCommonVarURI() { return isCommonVarURI; } public String getCommonVarName() { return commonVarName; } public Var getCommonVar() { return commonVar; } public boolean commonVarHasValue() { return commonVar.getValue() != null; } public boolean commonVarConstant() { return commonVar.isConstant(); } public String getCommonVarValue() { if(commonVarHasValue()) { return commonVar.getValue().stringValue(); } else { return null; } } public Set<String> getUnCommonVars() { return varPos.keySet(); } public Map<String,Integer> getVarPos() { return varPos; } public boolean hasContext() { return context.getValue() != null; } public String getContextURI() { return contextURI; } public Set<String> getBindingNames() { Set<String> bindingNames = Sets.newHashSet(); for(StatementPattern sp: nodes) { if(bindingNames.size() == 0) { bindingNames = sp.getBindingNames(); } else { bindingNames = Sets.union(bindingNames, sp.getBindingNames()); } } return bindingNames; } public Set<String> getAssuredBindingNames() { Set<String> bindingNames = Sets.newHashSet(); for(StatementPattern sp: nodes) { if(bindingNames.size() == 0) { bindingNames = sp.getAssuredBindingNames(); } else { bindingNames = Sets.union(bindingNames, sp.getAssuredBindingNames()); } } return bindingNames; } public CardinalityStatementPattern getMinCardSp(AccumuloSelectivityEvalDAO ase) { StatementPattern minSp = null; double cardinality = Double.MAX_VALUE; double tempCard = -1; for (StatementPattern sp : nodes) { try { tempCard = ase.getCardinality(ase.getConf(), sp); if (tempCard < cardinality) { cardinality = tempCard; minSp = sp; } } catch (TableNotFoundException e) { e.printStackTrace(); } } return new CardinalityStatementPattern(minSp, cardinality) ; } public class CardinalityStatementPattern { private StatementPattern sp; private double cardinality; public CardinalityStatementPattern(StatementPattern sp, double cardinality) { this.sp = sp; this.cardinality = cardinality; } public StatementPattern getSp() { return sp; } public double getCardinality() { return cardinality; } } public double getCardinality( AccumuloSelectivityEvalDAO ase) { double cardinality = Double.MAX_VALUE; double tempCard = -1; ase.setDenormalized(true); try { for (int i = 0; i < nodes.size(); i++) { for (int j = i + 1; j < nodes.size(); j++) { tempCard = ase.getJoinSelect(ase.getConf(), nodes.get(i), nodes.get(j)); if (tempCard < cardinality) { cardinality = tempCard; } } } } catch (Exception e) { e.printStackTrace(); } ase.setDenormalized(false); return cardinality/(nodes.size() + 1); } public static Set<String> getCommonVars(StarQuery query, BindingSet bs) { Set<String> starQueryVarNames = Sets.newHashSet(); if(bs == null || bs.size() == 0) { return Sets.newHashSet(); } Set<String> bindingNames = bs.getBindingNames(); starQueryVarNames.addAll(query.getUnCommonVars()); if(!query.commonVarConstant()) { starQueryVarNames.add(query.getCommonVarName()); } return Sets.intersection(bindingNames, starQueryVarNames); } public static StarQuery getConstrainedStarQuery(StarQuery query, BindingSet bs) { if(bs.size() == 0) { return query; } Set<String> bindingNames = bs.getBindingNames(); Set<String> unCommonVarNames = query.getUnCommonVars(); Set<String> intersectVar = Sets.intersection(bindingNames, unCommonVarNames); if (!query.commonVarConstant()) { Value v = bs.getValue(query.getCommonVarName()); if (v != null) { query.commonVar.setValue(v); } } for(String s: intersectVar) { try { query.nodeColumnCond[query.varPos.get(s)] = query.setValue(query.nodeColumnCond[query.varPos.get(s)], bs.getValue(s)); } catch (RyaTypeResolverException e) { e.printStackTrace(); } } return query; } private TextColumn setValue(TextColumn tc, Value v) throws RyaTypeResolverException { String cq = tc.getColumnQualifier().toString(); String[] cqArray = cq.split("\u0000"); if (cqArray[0].equals("subject")) { // RyaURI subjURI = (RyaURI) RdfToRyaConversions.convertValue(v); tc.setColumnQualifier(new Text("subject" + "\u0000" + v.stringValue())); tc.setIsPrefix(false); } else if (cqArray[0].equals("object")) { RyaType objType = RdfToRyaConversions.convertValue(v); byte[][] b1 = RyaContext.getInstance().serializeType(objType); byte[] b2 = Bytes.concat("object".getBytes(), "\u0000".getBytes(), b1[0], b1[1]); tc.setColumnQualifier(new Text(b2)); tc.setIsPrefix(false); } else { throw new IllegalStateException("Invalid direction!"); } return tc; } //assumes nodes forms valid star query with only one common variable //assumes nodes and commonVar has been set private TextColumn nodeToTextColumn(StatementPattern node, int i) throws RyaTypeResolverException { RyaContext rc = RyaContext.getInstance(); Var subjVar = node.getSubjectVar(); Var predVar = node.getPredicateVar(); Var objVar = node.getObjectVar(); RyaURI predURI = (RyaURI) RdfToRyaConversions.convertValue(node.getPredicateVar().getValue()); //assumes StatementPattern contains at least on variable if (subjVar.isConstant()) { if (commonVarConstant()) { varPos.put(objVar.getName(), i); return new TextColumn(new Text(predURI.getData()), new Text("object")); } else { return new TextColumn(new Text(predURI.getData()), new Text("subject" + "\u0000" + subjVar.getValue().stringValue())); } } else if (objVar.isConstant()) { if (commonVarConstant()) { varPos.put(subjVar.getName(), i); return new TextColumn(new Text(predURI.getData()), new Text("subject")); } else { isCommonVarURI = true; RyaType objType = RdfToRyaConversions.convertValue(objVar.getValue()); byte[][] b1 = rc.serializeType(objType); byte[] b2 = Bytes.concat("object".getBytes(), "\u0000".getBytes(), b1[0], b1[1]); return new TextColumn(new Text(predURI.getData()), new Text(b2)); } } else { if (subjVar.getName().equals(commonVarName)) { isCommonVarURI = true; varPos.put(objVar.getName(), i); TextColumn tc = new TextColumn(new Text(predURI.getData()), new Text("object")); tc.setIsPrefix(true); return tc; } else { varPos.put(subjVar.getName(), i); TextColumn tc = new TextColumn(new Text(predURI.getData()), new Text("subject")); tc.setIsPrefix(true); return tc; } } } //called in constructor after nodes set //assumes nodes and nodeColumnCond are same size private void init() throws RyaTypeResolverException { commonVar = this.getCommonVar(nodes); if(!commonVar.isConstant()) { commonVarName = commonVar.getName(); } else { commonVarName = commonVar.getName().substring(7); } if(hasContext()) { RyaURI ctxtURI = (RyaURI) RdfToRyaConversions.convertValue(context.getValue()); contextURI = ctxtURI.getData(); } for(int i = 0; i < nodes.size(); i++){ nodeColumnCond[i] = nodeToTextColumn(nodes.get(i), i); } } // called after nodes set // assumes nodes forms valid query with single, common variable private Var getCommonVar(List<StatementPattern> nodes) { Set<Var> vars = null; List<Var> tempVar; Set<Var> tempSet; int i = 0; for (StatementPattern sp : nodes) { if (vars == null) { vars = Sets.newHashSet(); vars.add(sp.getSubjectVar()); vars.add(sp.getObjectVar()); } else { tempSet = Sets.newHashSet(); tempSet.add(sp.getSubjectVar()); tempSet.add(sp.getObjectVar()); vars = Sets.intersection(vars, tempSet); } } if (vars.size() == 1) { return vars.iterator().next(); } else if (vars.size() > 1) { Var first = null; i = 0; for (Var v : vars) { i++; if (i == 1) { first = v; } else { if (v.isConstant()) { return v; } } } return first; } else { throw new IllegalStateException("No common Var!"); } } //assumes bindings is not of size 0 private static boolean isBindingsetValid(Set<String> bindings) { int varCount = 0; if (bindings.size() == 1) { return true; } else { for (String s : bindings) { if (!s.startsWith("-const-")) { varCount++; } if (varCount > 1) { return false; } } return true; } } public static boolean isValidStarQuery(Collection<StatementPattern> nodes) { Set<String> bindings = null; boolean contextSet = false; Var context = null; if(nodes.size() < 2) { return false; } for(StatementPattern sp: nodes) { Var tempContext = sp.getContextVar(); Var predVar = sp.getPredicateVar(); //does not support variable context if(tempContext != null && !tempContext.isConstant()) { return false; } if(!contextSet) { context = tempContext; contextSet = true; } else { if(context == null && tempContext != null) { return false; } else if (context != null && !context.equals(tempContext)) { return false; } } if(!predVar.isConstant()) { return false; } if(bindings == null ) { bindings = sp.getBindingNames(); if(bindings.size() == 0) { return false; } } else { bindings = Sets.intersection(bindings, sp.getBindingNames()); if(bindings.size() == 0) { return false; } } } return isBindingsetValid(bindings); } // private static Set<String> getSpVariables(StatementPattern sp) { // // Set<String> variables = Sets.newHashSet(); // List<Var> varList = sp.getVarList(); // // for(Var v: varList) { // if(!v.isConstant()) { // variables.add(v.getName()); // } // } // // return variables; // // } // @Override public String toString() { String s = "Term conditions: " + "\n"; for (TextColumn element : this.nodeColumnCond) { s = s + element.toString() + "\n"; } s = s + "Common Var: " + this.commonVar.toString() + "\n"; s = s + "Context: " + this.contextURI; return s; } }
package gov.usgs.cida.gcmrcservices.nude.transform; import com.google.common.base.Objects; import gov.usgs.cida.nude.column.Column; import gov.usgs.cida.nude.filter.transform.MathFunction; import gov.usgs.cida.nude.filter.transform.WindowedMathTransform; import gov.usgs.cida.nude.resultset.inmemory.TableRow; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.joda.time.DateTime; import org.joda.time.Period; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author dmsibley */ public class DygraphsMinMeanMaxTransform extends WindowedMathTransform { private static final Logger log = LoggerFactory.getLogger(DygraphsMinMeanMaxTransform.class); public DygraphsMinMeanMaxTransform(Column time, Column val, Period duration) { super(time, val, null, duration); } @Override public String transform(TableRow row) { String result = null; String val = row.getValue(col); String time = row.getValue(timeCol); BigDecimal bigVal = null; if (null != val) { try { bigVal = new BigDecimal(val); } catch (NumberFormatException e) { log.trace("NumberFormatException for " + val); } } boolean fullDuration = sync(new DateTime(Long.parseLong(time)), bigVal, times, vals, duration); started = started || fullDuration; if (!started) { started = checkLogicallyFull(times, duration); } if (started) { result = aggRun(vals); } return result; } public static String aggRun(Iterable<BigDecimal> items) { StringBuilder result = new StringBuilder(); AggregateResult aggRes = runAggregate(items); if (null != aggRes) { // result.append(aggRes.mean.toPlainString()) // .append(";") // .append(aggRes.stdDev.toPlainString()); result.append(aggRes.min.toPlainString()) .append(";") .append(aggRes.mean.toPlainString()) .append(";") .append(aggRes.max.toPlainString()); } return StringUtils.trimToNull(result.toString()); } protected static AggregateResult runAggregate(Iterable<BigDecimal> items) { AggregateResult result = null; if (null != items) { BigDecimal sum = null; int cnt = 0; BigDecimal mean = null; BigDecimal min = null; BigDecimal max = null; for (BigDecimal i : items) { if (null == sum) { sum = BigDecimal.ZERO; } sum = sum.add(i); cnt++; min = min(min, i); max = max(max, i); } BigDecimal count = new BigDecimal(cnt); if (null != sum && count.compareTo(BigDecimal.ZERO) != 0) { mean = sum.divide(count, new MathContext(sum.precision(), RoundingMode.HALF_EVEN)); BigDecimal stdDev = stdDev(sumDeviation(items, mean), count); result = new AggregateResult(count, sum, mean, min, max, stdDev); } } return result; } protected static class AggregateResult { public final BigDecimal count; public final BigDecimal sum; public final BigDecimal mean; public final BigDecimal min; public final BigDecimal max; public final BigDecimal stdDev; public AggregateResult(BigDecimal count, BigDecimal sum, BigDecimal mean, BigDecimal min, BigDecimal max, BigDecimal stdDev) { this.count = count; this.sum = sum; this.mean = mean; this.min = min; this.max = max; this.stdDev = stdDev; } @Override public int hashCode() { return new HashCodeBuilder() .append(this.count) .append(this.mean) .append(this.sum) .append(this.min) .append(this.max) .append(this.stdDev) .toHashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj instanceof AggregateResult) { AggregateResult rhs = (AggregateResult) obj; return new EqualsBuilder() .append(this.count, rhs.count) .append(this.sum, rhs.sum) .append(this.mean, rhs.mean) .append(this.min, rhs.min) .append(this.max, rhs.max) .append(this.stdDev, rhs.stdDev) .isEquals(); } return false; } @Override public String toString() { return Objects.toStringHelper(AggregateResult.class) .add("count", this.count) .add("sum", this.sum) .add("mean", this.mean) .add("min", this.min) .add("max", this.max) .add("stdDev", this.stdDev) .toString(); } } public static BigDecimal min(BigDecimal a, BigDecimal b) { BigDecimal result = a; if (null == result || (null != b && b.compareTo(result) < 0)) { result = b; } return result; } public static BigDecimal max(BigDecimal a, BigDecimal b) { BigDecimal result = a; if (null == result || (null != b && b.compareTo(result) > 0)) { result = b; } return result; } public static BigDecimal sumDeviation(Iterable<BigDecimal> items, BigDecimal mean) { BigDecimal sumDeviation = null; for (BigDecimal i : items) { if (null == sumDeviation) { sumDeviation = BigDecimal.ZERO; } sumDeviation = sumDeviation.add((i.subtract(mean)).pow(2, new MathContext(mean.precision(), RoundingMode.HALF_EVEN))); } return sumDeviation; } public static BigDecimal stdDev(BigDecimal sumDeviation, BigDecimal count) { BigDecimal result = null; if (null != sumDeviation && count.compareTo(BigDecimal.ZERO) != 0) { BigDecimal preSR = sumDeviation.divide(count, new MathContext(sumDeviation.precision(), RoundingMode.HALF_EVEN)); double postSR = Math.sqrt(preSR.doubleValue()); result = new BigDecimal(Double.toString(postSR), new MathContext(sumDeviation.precision(), RoundingMode.HALF_EVEN)); } return result; } }
/* * Copyright 2015 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.kie.remote.services.jaxb; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import org.drools.core.common.DefaultFactHandle; import org.jbpm.process.audit.NodeInstanceLog; import org.jbpm.process.audit.ProcessInstanceLog; import org.jbpm.process.audit.VariableInstanceLog; import org.jbpm.process.audit.event.AuditEvent; import org.jbpm.services.task.commands.GetContentMapForUserCommand; import org.jbpm.services.task.commands.GetTaskContentCommand; import org.jbpm.services.task.impl.model.xml.JaxbContent; import org.jbpm.services.task.impl.model.xml.JaxbTask; import org.kie.api.command.Command; import org.kie.api.runtime.process.ProcessInstance; import org.kie.api.runtime.process.WorkItem; import org.kie.api.task.model.Comment; import org.kie.api.task.model.TaskSummary; import org.kie.services.client.serialization.jaxb.impl.JaxbCommandResponse; import org.kie.services.client.serialization.jaxb.impl.JaxbLongListResponse; import org.kie.services.client.serialization.jaxb.impl.JaxbOtherResponse; import org.kie.services.client.serialization.jaxb.impl.JaxbPrimitiveResponse; import org.kie.services.client.serialization.jaxb.impl.JaxbRequestStatus; import org.kie.services.client.serialization.jaxb.impl.JaxbStringListResponse; import org.kie.services.client.serialization.jaxb.impl.JaxbVariablesResponse; import org.kie.services.client.serialization.jaxb.impl.audit.JaxbHistoryLogList; import org.kie.services.client.serialization.jaxb.impl.audit.JaxbNodeInstanceLog; import org.kie.services.client.serialization.jaxb.impl.audit.JaxbProcessInstanceLog; import org.kie.services.client.serialization.jaxb.impl.audit.JaxbVariableInstanceLog; import org.kie.services.client.serialization.jaxb.impl.process.JaxbProcessInstanceListResponse; import org.kie.services.client.serialization.jaxb.impl.process.JaxbProcessInstanceResponse; import org.kie.services.client.serialization.jaxb.impl.process.JaxbWorkItemResponse; import org.kie.services.client.serialization.jaxb.impl.task.JaxbTaskContentResponse; import org.kie.services.client.serialization.jaxb.rest.JaxbExceptionResponse; @XmlRootElement(name = "command-response") @XmlAccessorType(XmlAccessType.FIELD) @SuppressWarnings("rawtypes") public class JaxbCommandsResponse { @XmlElement(name = "deployment-id") @XmlSchemaType(name = "string") private String deploymentId; @XmlElement(name = "process-instance-id") @XmlSchemaType(name = "long") private Long processInstanceId; @XmlElement(name = "ver") @XmlSchemaType(name = "string") private String version; @XmlElements({ @XmlElement(name = "exception", type = JaxbExceptionResponse.class), @XmlElement(name = "long-list", type = JaxbLongListResponse.class), @XmlElement(name = "string-list", type = JaxbStringListResponse.class), @XmlElement(name = "primitive", type = JaxbPrimitiveResponse.class), @XmlElement(name = "process-instance", type = JaxbProcessInstanceResponse.class), @XmlElement(name = "process-instance-list", type = JaxbProcessInstanceListResponse.class), @XmlElement(name = "task-response", type = JaxbTaskResponse.class), @XmlElement(name = "content-response", type = JaxbContentResponse.class ), @XmlElement(name = "task-content-response", type = JaxbTaskContentResponse.class ), @XmlElement(name = "task-comment-response", type = JaxbTaskCommentResponse.class ), @XmlElement(name = "task-comment-list-response", type = JaxbTaskCommentListResponse.class ), @XmlElement(name = "task-summary-list", type = JaxbTaskSummaryListResponse.class), @XmlElement(name = "work-item", type = JaxbWorkItemResponse.class), @XmlElement(name = "variables", type = JaxbVariablesResponse.class), @XmlElement(name = "other", type = JaxbOtherResponse.class), @XmlElement(name = "history-log-list", type = JaxbHistoryLogList.class), @XmlElement(name = "proc-inst-log", type = JaxbProcessInstanceLog.class), @XmlElement(name = "node-inst-log", type = JaxbNodeInstanceLog.class), @XmlElement(name = "var-inst-log", type = JaxbVariableInstanceLog.class) }) private List<JaxbCommandResponse<?>> responses; public JaxbCommandsResponse() { // Default constructor } public JaxbCommandsResponse(JaxbCommandsRequest request) { super(); this.deploymentId = request.getDeploymentId(); this.processInstanceId = request.getProcessInstanceId(); } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public Long getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(Long processInstanceId) { this.processInstanceId = processInstanceId; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } private void lazyInitResponseList() { if( this.responses == null ) { this.responses = new ArrayList<JaxbCommandResponse<?>>(); } } public List<JaxbCommandResponse<?>> getResponses() { lazyInitResponseList(); return responses; } public void setResponses(List<JaxbCommandResponse<?>> responses) { this.responses = responses; } public void addException(Exception exception, int i, Command<?> cmd, JaxbRequestStatus status) { lazyInitResponseList(); this.responses.add(new JaxbExceptionResponse(exception, i, cmd, status)); } @SuppressWarnings("unchecked") public void addResult(Object result, int i, Command<?> cmd) { lazyInitResponseList(); boolean unknownResultType = false; String className = result.getClass().getName(); // DBG System.out.println( ">> Adding " + className + " result"); if (result instanceof ProcessInstance) { this.responses.add(new JaxbProcessInstanceResponse((ProcessInstance) result, i, cmd)); } else if (result instanceof JaxbTask) { this.responses.add(new JaxbTaskResponse((JaxbTask) result, i, cmd)); } else if (result instanceof JaxbContent) { if (((JaxbContent) result).getId() == -1) { this.responses.add(new JaxbTaskContentResponse(((JaxbContent) result).getContentMap(), i, cmd)); } else { this.responses.add(new JaxbContentResponse((JaxbContent) result, i, cmd)); } } else if (List.class.isInstance(result)) { // Neccessary to determine return type of empty lists Class listType = getListType(cmd); if( listType == null ) { unknownResultType = true; } else if( listType.equals(TaskSummary.class) ) { this.responses.add(new JaxbTaskSummaryListResponse((List<TaskSummary>) result, i, cmd)); } else if( listType.equals(Long.class) ) { this.responses.add(new JaxbLongListResponse((List<Long>)result, i, cmd)); } else if( listType.equals(String.class) ) { this.responses.add(new JaxbStringListResponse((List<String>)result, i, cmd)); } else if( listType.equals(ProcessInstance.class) ) { this.responses.add(new JaxbProcessInstanceListResponse((List<ProcessInstance>) result, i, cmd)); } else if( listType.equals(ProcessInstanceLog.class) || listType.equals(NodeInstanceLog.class) || listType.equals(VariableInstanceLog.class) ) { this.responses.add(new JaxbHistoryLogList((List<AuditEvent>) result)); } else if( listType.equals(Comment.class) ) { this.responses.add(new JaxbTaskCommentListResponse((List<Comment>) result)); } else { throw new IllegalStateException(listType.getSimpleName() + " should be handled but is not in " + this.getClass().getSimpleName() + "!" ); } } else if (result.getClass().isPrimitive() || Boolean.class.getName().equals(className) || Byte.class.getName().equals(className) || Short.class.getName().equals(className) || Integer.class.getName().equals(className) || Character.class.getName().equals(className) || Long.class.getName().equals(className) || Float.class.getName().equals(className) || Double.class.getName().equals(className) ) { this.responses.add(new JaxbPrimitiveResponse(result, i, cmd)); } else if( result instanceof WorkItem ) { this.responses.add(new JaxbWorkItemResponse((WorkItem) result, i, cmd)); } else if( result instanceof ProcessInstanceLog ) { this.responses.add(new JaxbProcessInstanceLog((ProcessInstanceLog) result)); } else if( result instanceof NodeInstanceLog ) { this.responses.add(new JaxbNodeInstanceLog((NodeInstanceLog) result)); } else if( result instanceof VariableInstanceLog ) { this.responses.add(new JaxbVariableInstanceLog((VariableInstanceLog) result)); } else if( result instanceof DefaultFactHandle ) { this.responses.add(new JaxbOtherResponse(result, i, cmd)); } else if( cmd instanceof GetTaskContentCommand || cmd instanceof GetContentMapForUserCommand ) { this.responses.add(new JaxbTaskContentResponse((Map<String, Object>) result, i, cmd)); } else if( Comment.class.isAssignableFrom(result.getClass()) ) { System.out.println( ">> Adding JaxbTaskCommentResponse to response list"); this.responses.add(new JaxbTaskCommentResponse((Comment) result, i, cmd)); } // Other else if( result instanceof JaxbExceptionResponse ) { this.responses.add((JaxbExceptionResponse) result); } else { unknownResultType = true; } if (unknownResultType) { System.out.println( this.getClass().getSimpleName() + ": unknown result type " + result.getClass().getSimpleName() + " from command " + cmd.getClass().getSimpleName() + " added."); } } static Class getListType( Command cmd ) { Class cmdClass = cmd.getClass(); Type genSuper = cmdClass.getGenericSuperclass(); if( genSuper != null ) { if( genSuper instanceof ParameterizedType ) { return getClassFromParameterizedListCmd(genSuper, cmdClass); } } Type [] genInts = cmdClass.getGenericInterfaces(); if( genInts.length > 0 ) { if( genInts[0] instanceof ParameterizedType ) { return getClassFromParameterizedListCmd(genInts[0], cmdClass); } } throw new IllegalStateException("No list type could be found for " + cmd.getClass().getSimpleName() ); } private static Class getClassFromParameterizedListCmd(Type genericIntOrSuper, Class cmdClass) { Type[] listTypes = ((ParameterizedType) genericIntOrSuper).getActualTypeArguments(); if( listTypes.length > 0 ) { if( listTypes[0] instanceof ParameterizedType ) { Type rawType = ((ParameterizedType) listTypes[0]).getRawType(); if( Collection.class.isAssignableFrom((Class) rawType) ) { Type[] returnTypeParamTypes = ((ParameterizedType) listTypes[0]).getActualTypeArguments(); if( returnTypeParamTypes.length > 0 ) { return (Class) returnTypeParamTypes[0]; } } } } throw new IllegalStateException("No list type could be found for " + cmdClass.getSimpleName() ); } }
// Copyright 2017 The Bazel 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. package com.google.devtools.build.lib.exec; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.actions.ActionInput; import com.google.devtools.build.lib.actions.ActionInputHelper; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.Artifact.ArtifactExpander; import com.google.devtools.build.lib.actions.Artifact.TreeFileArtifact; import com.google.devtools.build.lib.actions.FileArtifactValue; import com.google.devtools.build.lib.actions.FilesetOutputSymlink; import com.google.devtools.build.lib.actions.MetadataProvider; import com.google.devtools.build.lib.actions.RunfilesSupplier; import com.google.devtools.build.lib.actions.Spawn; import com.google.devtools.build.lib.actions.cache.VirtualActionInput.EmptyActionInput; import com.google.devtools.build.lib.exec.FilesetManifest.RelativeSymlinkBehavior; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.PathFragment; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; /** * A helper class for spawn strategies to turn runfiles suppliers into input mappings. This class * performs no I/O operations, but only rearranges the files according to how the runfiles should be * laid out. */ public class SpawnInputExpander { @VisibleForTesting static final ActionInput EMPTY_FILE = new EmptyActionInput("/dev/null"); private final Path execRoot; private final boolean strict; private final RelativeSymlinkBehavior relSymlinkBehavior; /** * Creates a new instance. If strict is true, then the expander checks for directories in runfiles * and throws an exception if it finds any. Otherwise it silently ignores directories in runfiles * and adds a mapping for them. At this time, directories in filesets are always silently added as * mappings. * * <p>Directories in inputs are a correctness issue: Bazel only tracks dependencies at the action * level, and it does not track dependencies on directories. Making a directory available to a * spawn even though it's contents are not tracked as dependencies leads to incorrect incremental * builds, since changes to the contents do not trigger action invalidation. * * <p>As such, all spawn strategies should always be strict and not make directories available to * the subprocess. However, that's a breaking change, and therefore we make it depend on this flag * for now. */ public SpawnInputExpander(Path execRoot, boolean strict) { this(execRoot, strict, RelativeSymlinkBehavior.ERROR); } /** * Creates a new instance. If strict is true, then the expander checks for directories in runfiles * and throws an exception if it finds any. Otherwise it silently ignores directories in runfiles * and adds a mapping for them. At this time, directories in filesets are always silently added as * mappings. * * <p>Directories in inputs are a correctness issue: Bazel only tracks dependencies at the action * level, and it does not track dependencies on directories. Making a directory available to a * spawn even though it's contents are not tracked as dependencies leads to incorrect incremental * builds, since changes to the contents do not trigger action invalidation. * * <p>As such, all spawn strategies should always be strict and not make directories available to * the subprocess. However, that's a breaking change, and therefore we make it depend on this flag * for now. */ public SpawnInputExpander( Path execRoot, boolean strict, RelativeSymlinkBehavior relSymlinkBehavior) { this.execRoot = execRoot; this.strict = strict; this.relSymlinkBehavior = relSymlinkBehavior; } private void addMapping( Map<PathFragment, ActionInput> inputMappings, PathFragment targetLocation, ActionInput input) { Preconditions.checkArgument(!targetLocation.isAbsolute(), targetLocation); if (!inputMappings.containsKey(targetLocation)) { inputMappings.put(targetLocation, input); } } /** Adds runfiles inputs from runfilesSupplier to inputMappings. */ @VisibleForTesting void addRunfilesToInputs( Map<PathFragment, ActionInput> inputMap, RunfilesSupplier runfilesSupplier, MetadataProvider actionFileCache, ArtifactExpander artifactExpander) throws IOException { Map<PathFragment, Map<PathFragment, Artifact>> rootsAndMappings = runfilesSupplier.getMappings(); for (Map.Entry<PathFragment, Map<PathFragment, Artifact>> rootAndMappings : rootsAndMappings.entrySet()) { PathFragment root = rootAndMappings.getKey(); Preconditions.checkState(!root.isAbsolute(), root); for (Map.Entry<PathFragment, Artifact> mapping : rootAndMappings.getValue().entrySet()) { PathFragment location = root.getRelative(mapping.getKey()); Artifact localArtifact = mapping.getValue(); if (localArtifact != null) { Preconditions.checkState(!localArtifact.isMiddlemanArtifact()); if (localArtifact.isTreeArtifact()) { List<ActionInput> expandedInputs = ActionInputHelper.expandArtifacts( Collections.singletonList(localArtifact), artifactExpander); for (ActionInput input : expandedInputs) { addMapping( inputMap, location.getRelative(((TreeFileArtifact) input).getParentRelativePath()), input); } } else { if (strict) { failIfDirectory(actionFileCache, localArtifact); } addMapping(inputMap, location, localArtifact); } } else { addMapping(inputMap, location, EMPTY_FILE); } } } } private static void failIfDirectory(MetadataProvider actionFileCache, ActionInput input) throws IOException { FileArtifactValue metadata = actionFileCache.getMetadata(input); if (metadata != null && !metadata.getType().isFile()) { throw new IOException("Not a file: " + input.getExecPathString()); } } /** * Parses the fileset manifest file, adding to the inputMappings where appropriate. Lines * referring to directories are recursed. */ // TODO(kush): make tests use the method with in-memory fileset data. @VisibleForTesting void parseFilesetManifest( Map<PathFragment, ActionInput> inputMappings, Artifact manifest, String workspaceName) throws IOException { FilesetManifest filesetManifest = FilesetManifest.parseManifestFile( manifest.getExecPath(), execRoot, workspaceName, relSymlinkBehavior); for (Map.Entry<PathFragment, String> mapping : filesetManifest.getEntries().entrySet()) { String value = mapping.getValue(); ActionInput artifact = value == null ? EMPTY_FILE : ActionInputHelper.fromPath(value); addMapping(inputMappings, mapping.getKey(), artifact); } } @VisibleForTesting void addFilesetManifests( Map<PathFragment, ImmutableList<FilesetOutputSymlink>> filesetMappings, Map<PathFragment, ActionInput> inputMappings) throws IOException { for (PathFragment manifestExecpath : filesetMappings.keySet()) { ImmutableList<FilesetOutputSymlink> outputSymlinks = filesetMappings.get(manifestExecpath); FilesetManifest filesetManifest = FilesetManifest.constructFilesetManifest( outputSymlinks, manifestExecpath, relSymlinkBehavior); for (Map.Entry<PathFragment, String> mapping : filesetManifest.getEntries().entrySet()) { String value = mapping.getValue(); ActionInput artifact = value == null ? EMPTY_FILE : ActionInputHelper.fromPath(value); addMapping(inputMappings, mapping.getKey(), artifact); } } } private void addInputs( Map<PathFragment, ActionInput> inputMap, Spawn spawn, ArtifactExpander artifactExpander) { List<ActionInput> inputs = ActionInputHelper.expandArtifacts(spawn.getInputFiles(), artifactExpander); for (ActionInput input : inputs) { addMapping(inputMap, input.getExecPath(), input); } } /** * Convert the inputs and runfiles of the given spawn to a map from exec-root relative paths to * {@link ActionInput}s. The returned map does not contain tree artifacts as they are expanded * to file artifacts. * * <p>The returned map never contains {@code null} values; it uses {@link #EMPTY_FILE} for empty * files, which is an instance of {@link * com.google.devtools.build.lib.actions.cache.VirtualActionInput}. * * <p>The returned map contains all runfiles, but not the {@code MANIFEST}. */ public SortedMap<PathFragment, ActionInput> getInputMapping( Spawn spawn, ArtifactExpander artifactExpander, MetadataProvider actionInputFileCache) throws IOException { TreeMap<PathFragment, ActionInput> inputMap = new TreeMap<>(); addInputs(inputMap, spawn, artifactExpander); addRunfilesToInputs( inputMap, spawn.getRunfilesSupplier(), actionInputFileCache, artifactExpander); addFilesetManifests(spawn.getFilesetMappings(), inputMap); return inputMap; } }
/* * 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.tomcat.dbcp.dbcp2; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.ClientInfoStatus; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; /** * A base delegating implementation of {@link Connection}. * <p> * All of the methods from the {@link Connection} interface * simply check to see that the {@link Connection} is active, * and call the corresponding method on the "delegate" * provided in my constructor. * <p> * Extends AbandonedTrace to implement Connection tracking and * logging of code which created the Connection. Tracking the * Connection ensures that the AbandonedObjectPool can close * this connection and recycle it if its pool of connections * is nearing exhaustion and this connection's last usage is * older than the removeAbandonedTimeout. * * @param <C> the Connection type * * @author Rodney Waldhoff * @author Glenn L. Nielsen * @author James House * @author Dirk Verbeeck * @since 2.0 */ public class DelegatingConnection<C extends Connection> extends AbandonedTrace implements Connection { private static final Map<String, ClientInfoStatus> EMPTY_FAILED_PROPERTIES = Collections.<String, ClientInfoStatus>emptyMap(); /** My delegate {@link Connection}. */ private volatile C _conn = null; private volatile boolean _closed = false; private boolean _cacheState = true; private Boolean _autoCommitCached = null; private Boolean _readOnlyCached = null; private Integer defaultQueryTimeout = null; /** * Create a wrapper for the Connection which traces this * Connection in the AbandonedObjectPool. * * @param c the {@link Connection} to delegate all calls to. */ public DelegatingConnection(C c) { super(); _conn = c; } /** * Returns a string representation of the metadata associated with * the innnermost delegate connection. */ @Override public String toString() { String s = null; Connection c = this.getInnermostDelegateInternal(); if (c != null) { try { if (c.isClosed()) { s = "connection is closed"; } else { StringBuffer sb = new StringBuffer(); sb.append(hashCode()); DatabaseMetaData meta = c.getMetaData(); if (meta != null) { sb.append(", URL="); sb.append(meta.getURL()); sb.append(", UserName="); sb.append(meta.getUserName()); sb.append(", "); sb.append(meta.getDriverName()); s = sb.toString(); } } } catch (SQLException ex) { // Ignore } } if (s == null) { s = super.toString(); } return s; } /** * Returns my underlying {@link Connection}. * @return my underlying {@link Connection}. */ public C getDelegate() { return getDelegateInternal(); } protected final C getDelegateInternal() { return _conn; } /** * Compares innermost delegate to the given connection. * * @param c connection to compare innermost delegate with * @return true if innermost delegate equals <code>c</code> */ public boolean innermostDelegateEquals(Connection c) { Connection innerCon = getInnermostDelegateInternal(); if (innerCon == null) { return c == null; } return innerCon.equals(c); } /** * If my underlying {@link Connection} is not a * {@code DelegatingConnection}, returns it, * otherwise recursively invokes this method on * my delegate. * <p> * Hence this method will return the first * delegate that is not a {@code DelegatingConnection}, * or {@code null} when no non-{@code DelegatingConnection} * delegate can be found by traversing this chain. * <p> * This method is useful when you may have nested * {@code DelegatingConnection}s, and you want to make * sure to obtain a "genuine" {@link Connection}. */ public Connection getInnermostDelegate() { return getInnermostDelegateInternal(); } /** * Although this method is public, it is part of the internal API and should * not be used by clients. The signature of this method may change at any * time including in ways that break backwards compatibility. */ public final Connection getInnermostDelegateInternal() { Connection c = _conn; while(c != null && c instanceof DelegatingConnection) { c = ((DelegatingConnection<?>)c).getDelegateInternal(); if(this == c) { return null; } } return c; } /** Sets my delegate. */ public void setDelegate(C c) { _conn = c; } /** * Closes the underlying connection, and close any Statements that were not * explicitly closed. Sub-classes that override this method must: * <ol> * <li>Call passivate()</li> * <li>Call close (or the equivalent appropriate action) on the wrapped * connection</li> * <li>Set _closed to <code>false</code></li> * </ol> */ @Override public void close() throws SQLException { if (!_closed) { closeInternal(); } } protected boolean isClosedInternal() { return _closed; } protected void setClosedInternal(boolean closed) { this._closed = closed; } protected final void closeInternal() throws SQLException { try { passivate(); } finally { try { _conn.close(); } finally { _closed = true; } } } protected void handleException(SQLException e) throws SQLException { throw e; } private void initializeStatement(DelegatingStatement ds) throws SQLException { if (defaultQueryTimeout != null && defaultQueryTimeout.intValue() != ds.getQueryTimeout()) { ds.setQueryTimeout(defaultQueryTimeout.intValue()); } } @Override public Statement createStatement() throws SQLException { checkOpen(); try { DelegatingStatement ds = new DelegatingStatement(this, _conn.createStatement()); initializeStatement(ds); return ds; } catch (SQLException e) { handleException(e); return null; } } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { checkOpen(); try { DelegatingStatement ds = new DelegatingStatement( this, _conn.createStatement(resultSetType,resultSetConcurrency)); initializeStatement(ds); return ds; } catch (SQLException e) { handleException(e); return null; } } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { checkOpen(); try { DelegatingPreparedStatement dps = new DelegatingPreparedStatement( this, _conn.prepareStatement(sql)); initializeStatement(dps); return dps; } catch (SQLException e) { handleException(e); return null; } } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkOpen(); try { DelegatingPreparedStatement dps = new DelegatingPreparedStatement( this, _conn.prepareStatement(sql,resultSetType,resultSetConcurrency)); initializeStatement(dps); return dps; } catch (SQLException e) { handleException(e); return null; } } @Override public CallableStatement prepareCall(String sql) throws SQLException { checkOpen(); try { DelegatingCallableStatement dcs = new DelegatingCallableStatement(this, _conn.prepareCall(sql)); initializeStatement(dcs); return dcs; } catch (SQLException e) { handleException(e); return null; } } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkOpen(); try { DelegatingCallableStatement dcs = new DelegatingCallableStatement( this, _conn.prepareCall(sql, resultSetType,resultSetConcurrency)); initializeStatement(dcs); return dcs; } catch (SQLException e) { handleException(e); return null; } } @Override public void clearWarnings() throws SQLException { checkOpen(); try { _conn.clearWarnings(); } catch (SQLException e) { handleException(e); } } @Override public void commit() throws SQLException { checkOpen(); try { _conn.commit(); } catch (SQLException e) { handleException(e); } } /** * Returns the state caching flag. * * @return the state caching flag */ public boolean getCacheState() { return _cacheState; } @Override public boolean getAutoCommit() throws SQLException { checkOpen(); if (_cacheState && _autoCommitCached != null) { return _autoCommitCached.booleanValue(); } try { _autoCommitCached = Boolean.valueOf(_conn.getAutoCommit()); return _autoCommitCached.booleanValue(); } catch (SQLException e) { handleException(e); return false; } } @Override public String getCatalog() throws SQLException { checkOpen(); try { return _conn.getCatalog(); } catch (SQLException e) { handleException(e); return null; } } @Override public DatabaseMetaData getMetaData() throws SQLException { checkOpen(); try { return new DelegatingDatabaseMetaData(this, _conn.getMetaData()); } catch (SQLException e) { handleException(e); return null; } } @Override public int getTransactionIsolation() throws SQLException { checkOpen(); try { return _conn.getTransactionIsolation(); } catch (SQLException e) { handleException(e); return -1; } } @Override public Map<String,Class<?>> getTypeMap() throws SQLException { checkOpen(); try { return _conn.getTypeMap(); } catch (SQLException e) { handleException(e); return null; } } @Override public SQLWarning getWarnings() throws SQLException { checkOpen(); try { return _conn.getWarnings(); } catch (SQLException e) { handleException(e); return null; } } @Override public boolean isReadOnly() throws SQLException { checkOpen(); if (_cacheState && _readOnlyCached != null) { return _readOnlyCached.booleanValue(); } try { _readOnlyCached = Boolean.valueOf(_conn.isReadOnly()); return _readOnlyCached.booleanValue(); } catch (SQLException e) { handleException(e); return false; } } @Override public String nativeSQL(String sql) throws SQLException { checkOpen(); try { return _conn.nativeSQL(sql); } catch (SQLException e) { handleException(e); return null; } } @Override public void rollback() throws SQLException { checkOpen(); try { _conn.rollback(); } catch (SQLException e) { handleException(e); } } /** * Obtain the default query timeout that will be used for {@link Statement}s * created from this connection. <code>null</code> means that the driver * default will be used. */ public Integer getDefaultQueryTimeout() { return defaultQueryTimeout; } /** * Set the default query timeout that will be used for {@link Statement}s * created from this connection. <code>null</code> means that the driver * default will be used. */ public void setDefaultQueryTimeout(Integer defaultQueryTimeout) { this.defaultQueryTimeout = defaultQueryTimeout; } /** * Sets the state caching flag. * * @param cacheState The new value for the state caching flag */ public void setCacheState(boolean cacheState) { this._cacheState = cacheState; } /** * Can be used to clear cached state when it is known that the underlying * connection may have been accessed directly. */ public void clearCachedState() { _autoCommitCached = null; _readOnlyCached = null; if (_conn instanceof DelegatingConnection) { ((DelegatingConnection<?>)_conn).clearCachedState(); } } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { checkOpen(); try { _conn.setAutoCommit(autoCommit); if (_cacheState) { _autoCommitCached = Boolean.valueOf(autoCommit); } } catch (SQLException e) { _autoCommitCached = null; handleException(e); } } @Override public void setCatalog(String catalog) throws SQLException { checkOpen(); try { _conn.setCatalog(catalog); } catch (SQLException e) { handleException(e); } } @Override public void setReadOnly(boolean readOnly) throws SQLException { checkOpen(); try { _conn.setReadOnly(readOnly); if (_cacheState) { _readOnlyCached = Boolean.valueOf(readOnly); } } catch (SQLException e) { _readOnlyCached = null; handleException(e); } } @Override public void setTransactionIsolation(int level) throws SQLException { checkOpen(); try { _conn.setTransactionIsolation(level); } catch (SQLException e) { handleException(e); } } @Override public void setTypeMap(Map<String,Class<?>> map) throws SQLException { checkOpen(); try { _conn.setTypeMap(map); } catch (SQLException e) { handleException(e); } } @Override public boolean isClosed() throws SQLException { return _closed || _conn.isClosed(); } protected void checkOpen() throws SQLException { if(_closed) { if (null != _conn) { String label = ""; try { label = _conn.toString(); } catch (Exception ex) { // ignore, leave label empty } throw new SQLException ("Connection " + label + " is closed."); } throw new SQLException ("Connection is null."); } } protected void activate() { _closed = false; setLastUsed(); if(_conn instanceof DelegatingConnection) { ((DelegatingConnection<?>)_conn).activate(); } } protected void passivate() throws SQLException { // The JDBC spec requires that a Connection close any open // Statement's when it is closed. // DBCP-288. Not all the traced objects will be statements List<AbandonedTrace> traces = getTrace(); if(traces != null && traces.size() > 0) { Iterator<AbandonedTrace> traceIter = traces.iterator(); while (traceIter.hasNext()) { Object trace = traceIter.next(); if (trace instanceof Statement) { ((Statement) trace).close(); } else if (trace instanceof ResultSet) { // DBCP-265: Need to close the result sets that are // generated via DatabaseMetaData ((ResultSet) trace).close(); } } clearTrace(); } setLastUsed(0); } @Override public int getHoldability() throws SQLException { checkOpen(); try { return _conn.getHoldability(); } catch (SQLException e) { handleException(e); return 0; } } @Override public void setHoldability(int holdability) throws SQLException { checkOpen(); try { _conn.setHoldability(holdability); } catch (SQLException e) { handleException(e); } } @Override public Savepoint setSavepoint() throws SQLException { checkOpen(); try { return _conn.setSavepoint(); } catch (SQLException e) { handleException(e); return null; } } @Override public Savepoint setSavepoint(String name) throws SQLException { checkOpen(); try { return _conn.setSavepoint(name); } catch (SQLException e) { handleException(e); return null; } } @Override public void rollback(Savepoint savepoint) throws SQLException { checkOpen(); try { _conn.rollback(savepoint); } catch (SQLException e) { handleException(e); } } @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { checkOpen(); try { _conn.releaseSavepoint(savepoint); } catch (SQLException e) { handleException(e); } } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkOpen(); try { DelegatingStatement ds = new DelegatingStatement(this, _conn.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability)); initializeStatement(ds); return ds; } catch (SQLException e) { handleException(e); return null; } } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkOpen(); try { DelegatingPreparedStatement dps = new DelegatingPreparedStatement( this, _conn.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability)); initializeStatement(dps); return dps; } catch (SQLException e) { handleException(e); return null; } } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkOpen(); try { DelegatingCallableStatement dcs = new DelegatingCallableStatement( this, _conn.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability)); initializeStatement(dcs); return dcs; } catch (SQLException e) { handleException(e); return null; } } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { checkOpen(); try { DelegatingPreparedStatement dps = new DelegatingPreparedStatement( this, _conn.prepareStatement(sql, autoGeneratedKeys)); initializeStatement(dps); return dps; } catch (SQLException e) { handleException(e); return null; } } @Override public PreparedStatement prepareStatement(String sql, int columnIndexes[]) throws SQLException { checkOpen(); try { DelegatingPreparedStatement dps = new DelegatingPreparedStatement( this, _conn.prepareStatement(sql, columnIndexes)); initializeStatement(dps); return dps; } catch (SQLException e) { handleException(e); return null; } } @Override public PreparedStatement prepareStatement(String sql, String columnNames[]) throws SQLException { checkOpen(); try { DelegatingPreparedStatement dps = new DelegatingPreparedStatement( this, _conn.prepareStatement(sql, columnNames)); initializeStatement(dps); return dps; } catch (SQLException e) { handleException(e); return null; } } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { if (iface.isAssignableFrom(getClass())) { return true; } else if (iface.isAssignableFrom(_conn.getClass())) { return true; } else { return _conn.isWrapperFor(iface); } } @Override public <T> T unwrap(Class<T> iface) throws SQLException { if (iface.isAssignableFrom(getClass())) { return iface.cast(this); } else if (iface.isAssignableFrom(_conn.getClass())) { return iface.cast(_conn); } else { return _conn.unwrap(iface); } } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { checkOpen(); try { return _conn.createArrayOf(typeName, elements); } catch (SQLException e) { handleException(e); return null; } } @Override public Blob createBlob() throws SQLException { checkOpen(); try { return _conn.createBlob(); } catch (SQLException e) { handleException(e); return null; } } @Override public Clob createClob() throws SQLException { checkOpen(); try { return _conn.createClob(); } catch (SQLException e) { handleException(e); return null; } } @Override public NClob createNClob() throws SQLException { checkOpen(); try { return _conn.createNClob(); } catch (SQLException e) { handleException(e); return null; } } @Override public SQLXML createSQLXML() throws SQLException { checkOpen(); try { return _conn.createSQLXML(); } catch (SQLException e) { handleException(e); return null; } } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { checkOpen(); try { return _conn.createStruct(typeName, attributes); } catch (SQLException e) { handleException(e); return null; } } @Override public boolean isValid(int timeout) throws SQLException { if (isClosed()) { return false; } try { return _conn.isValid(timeout); } catch (SQLException e) { handleException(e); return false; } } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { try { checkOpen(); _conn.setClientInfo(name, value); } catch (SQLClientInfoException e) { throw e; } catch (SQLException e) { throw new SQLClientInfoException("Connection is closed.", EMPTY_FAILED_PROPERTIES, e); } } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { try { checkOpen(); _conn.setClientInfo(properties); } catch (SQLClientInfoException e) { throw e; } catch (SQLException e) { throw new SQLClientInfoException("Connection is closed.", EMPTY_FAILED_PROPERTIES, e); } } @Override public Properties getClientInfo() throws SQLException { checkOpen(); try { return _conn.getClientInfo(); } catch (SQLException e) { handleException(e); return null; } } @Override public String getClientInfo(String name) throws SQLException { checkOpen(); try { return _conn.getClientInfo(name); } catch (SQLException e) { handleException(e); return null; } } @Override public void setSchema(String schema) throws SQLException { checkOpen(); try { _conn.setSchema(schema); } catch (SQLException e) { handleException(e); } } @Override public String getSchema() throws SQLException { checkOpen(); try { return _conn.getSchema(); } catch (SQLException e) { handleException(e); return null; } } @Override public void abort(Executor executor) throws SQLException { checkOpen(); try { _conn.abort(executor); } catch (SQLException e) { handleException(e); } } @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { checkOpen(); try { _conn.setNetworkTimeout(executor, milliseconds); } catch (SQLException e) { handleException(e); } } @Override public int getNetworkTimeout() throws SQLException { checkOpen(); try { return _conn.getNetworkTimeout(); } catch (SQLException e) { handleException(e); return 0; } } }
package hex.naivebayes; import hex.*; import hex.schemas.ModelBuilderSchema; import hex.schemas.NaiveBayesV3; import hex.naivebayes.NaiveBayesModel.NaiveBayesOutput; import hex.naivebayes.NaiveBayesModel.NaiveBayesParameters; import water.*; import water.exceptions.H2OModelBuilderIllegalArgumentException; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.Vec; import water.util.ArrayUtils; import water.util.Log; import water.util.PrettyPrint; import water.util.TwoDimTable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Naive Bayes * This is an algorithm for computing the conditional a-posterior probabilities of a categorical * response from independent predictors using Bayes rule. * <a href = "http://en.wikipedia.org/wiki/Naive_Bayes_classifier">Naive Bayes on Wikipedia</a> * <a href = "http://cs229.stanford.edu/notes/cs229-notes2.pdf">Lecture Notes by Andrew Ng</a> * @author anqi_fu * */ public class NaiveBayes extends ModelBuilder<NaiveBayesModel,NaiveBayesParameters,NaiveBayesOutput> { @Override public ModelBuilderSchema schema() { return new NaiveBayesV3(); } public boolean isSupervised(){return true;} @Override public Job<NaiveBayesModel> trainModelImpl(long work, boolean restartTimer) { return start(new NaiveBayesDriver(), work, restartTimer); } @Override public long progressUnits() { return 6; } @Override public ModelCategory[] can_build() { return new ModelCategory[]{ ModelCategory.Unknown }; } @Override public BuilderVisibility builderVisibility() { return BuilderVisibility.Stable; }; @Override protected void checkMemoryFootPrint() { // compute memory usage for pcond matrix long mem_usage = (_train.numCols() - 1) * _train.lastVec().cardinality(); String[][] domains = _train.domains(); long count = 0; for (int i = 0; i < _train.numCols() - 1; i++) { count += domains[i] == null ? 2 : domains[i].length; } mem_usage *= count; mem_usage *= 8; //doubles long max_mem = H2O.SELF.get_max_mem(); if (mem_usage > max_mem) { String msg = "Conditional probabilities won't fit in the driver node's memory (" + PrettyPrint.bytes(mem_usage) + " > " + PrettyPrint.bytes(max_mem) + ") - try reducing the number of columns, the number of response classes or the number of categorical factors of the predictors."; error("_train", msg); cancel(msg); } } // Called from an http request public NaiveBayes(NaiveBayesModel.NaiveBayesParameters parms) { super("NaiveBayes", parms); init(false); } @Override public void init(boolean expensive) { super.init(expensive); if (_response != null) { if (!_response.isEnum()) error("_response", "Response must be a categorical column"); else if (_response.isConst()) error("_response", "Response must have at least two unique categorical levels"); } if (_parms._laplace < 0) error("_laplace", "Laplace smoothing must be an integer >= 0"); if (_parms._min_sdev < 1e-10) error("_min_sdev", "Min. standard deviation must be at least 1e-10"); if (_parms._eps_sdev < 0) error("_eps_sdev", "Threshold for standard deviation must be positive"); if (_parms._min_prob < 1e-10) error("_min_prob", "Min. probability must be at least 1e-10"); if (_parms._eps_prob < 0) error("_eps_prob", "Threshold for probability must be positive"); hide("_balance_classes", "Balance classes is not applicable to NaiveBayes."); hide("_class_sampling_factors", "Class sampling factors is not applicable to NaiveBayes."); hide("_max_after_balance_size", "Max after balance size is not applicable to NaiveBayes."); if (expensive && error_count() == 0) checkMemoryFootPrint(); } private static boolean couldBeBool(Vec v) { return v != null && v.isInt() && v.min()+1==v.max(); } class NaiveBayesDriver extends H2O.H2OCountedCompleter<NaiveBayesDriver> { public boolean computeStatsFillModel(NaiveBayesModel model, DataInfo dinfo, NBTask tsk) { model._output._levels = _response.domain(); model._output._rescnt = tsk._rescnt; model._output._ncats = dinfo._cats; if(!isRunning(_key)) return false; update(1, "Initializing arrays for model statistics"); // String[][] domains = dinfo._adaptedFrame.domains(); String[][] domains = model._output._domains; double[] apriori = new double[tsk._nrescat]; double[][][] pcond = new double[tsk._npreds][][]; for(int i = 0; i < pcond.length; i++) { int ncnt = domains[i] == null ? 2 : domains[i].length; pcond[i] = new double[tsk._nrescat][ncnt]; } if(!isRunning(_key)) return false; update(1, "Computing probabilities for categorical cols"); // A-priori probability of response y for(int i = 0; i < apriori.length; i++) apriori[i] = ((double)tsk._rescnt[i] + _parms._laplace)/(tsk._nobs + tsk._nrescat * _parms._laplace); // apriori[i] = tsk._rescnt[i]/tsk._nobs; // Note: R doesn't apply laplace smoothing to priors, even though this is textbook definition // Probability of categorical predictor x_j conditional on response y for(int col = 0; col < dinfo._cats; col++) { assert pcond[col].length == tsk._nrescat; for(int i = 0; i < pcond[col].length; i++) { for(int j = 0; j < pcond[col][i].length; j++) pcond[col][i][j] = ((double)tsk._jntcnt[col][i][j] + _parms._laplace)/((double)tsk._rescnt[i] + domains[col].length * _parms._laplace); } } if(!isRunning(_key)) return false; update(1, "Computing mean and standard deviation for numeric cols"); // Mean and standard deviation of numeric predictor x_j for every level of response y for(int col = 0; col < dinfo._nums; col++) { for(int i = 0; i < pcond[0].length; i++) { int cidx = dinfo._cats + col; double num = tsk._rescnt[i]; double pmean = tsk._jntsum[col][i][0]/num; pcond[cidx][i][0] = pmean; // double pvar = tsk._jntsum[col][i][1]/num - pmean * pmean; double pvar = tsk._jntsum[col][i][1]/(num - 1) - pmean * pmean * num/(num - 1); pcond[cidx][i][1] = Math.sqrt(pvar); } } model._output._apriori_raw = apriori; model._output._pcond_raw = pcond; // Create table of conditional probabilities for every predictor model._output._pcond = new TwoDimTable[pcond.length]; String[] rowNames = _response.domain(); for(int col = 0; col < dinfo._cats; col++) { String[] colNames = _train.vec(col).domain(); String[] colTypes = new String[colNames.length]; String[] colFormats = new String[colNames.length]; Arrays.fill(colTypes, "double"); Arrays.fill(colFormats, "%5f"); model._output._pcond[col] = new TwoDimTable(_train.name(col), null, rowNames, colNames, colTypes, colFormats, "Y_by_" + _train.name(col), new String[rowNames.length][], pcond[col]); } for(int col = 0; col < dinfo._nums; col++) { int cidx = dinfo._cats + col; model._output._pcond[cidx] = new TwoDimTable(_train.name(cidx), null, rowNames, new String[] {"Mean", "Std_Dev"}, new String[] {"double", "double"}, new String[] {"%5f", "%5f"}, "Y_by_" + _train.name(cidx), new String[rowNames.length][], pcond[cidx]); } // Create table of a-priori probabilities for the response String[] colTypes = new String[_response.cardinality()]; String[] colFormats = new String[_response.cardinality()]; Arrays.fill(colTypes, "double"); Arrays.fill(colFormats, "%5f"); model._output._apriori = new TwoDimTable("A Priori Response Probabilities", null, new String[1], _response.domain(), colTypes, colFormats, "", new String[1][], new double[][] {apriori}); model._output._model_summary = createModelSummaryTable(model._output); if(!isRunning(_key)) return false; update(1, "Scoring and computing metrics on training data"); if (_parms._compute_metrics) { model.score(_parms.train()).delete(); // This scores on the training data and appends a ModelMetrics ModelMetricsSupervised mm = DKV.getGet(model._output._model_metrics[model._output._model_metrics.length - 1]); model._output._training_metrics = mm; } // At the end: validation scoring (no need to gather scoring history) if(!isRunning(_key)) return false; update(1, "Scoring and computing metrics on validation data"); if (_valid != null) { Frame pred = model.score(_parms.valid()); //this appends a ModelMetrics on the validation set model._output._validation_metrics = DKV.getGet(model._output._model_metrics[model._output._model_metrics.length - 1]); pred.delete(); } return true; } @Override protected void compute2() { NaiveBayesModel model = null; DataInfo dinfo = null; try { init(true); // Initialize parameters _parms.read_lock_frames(NaiveBayes.this); // Fetch & read-lock input frames if (error_count() > 0) throw H2OModelBuilderIllegalArgumentException.makeFromBuilder(NaiveBayes.this); dinfo = new DataInfo(Key.make(), _train, _valid, 1, false, DataInfo.TransformType.NONE, DataInfo.TransformType.NONE, true, false, false, false, false, false); // The model to be built model = new NaiveBayesModel(dest(), _parms, new NaiveBayesOutput(NaiveBayes.this)); model.delete_and_lock(_key); _train.read_lock(_key); update(1, "Begin distributed Naive Bayes calculation"); NBTask tsk = new NBTask(_key, dinfo, _response.cardinality()).doAll(dinfo._adaptedFrame); if (computeStatsFillModel(model, dinfo, tsk)) model.update(_key); done(); } catch (Throwable t) { Job thisJob = DKV.getGet(_key); if (thisJob._state == JobState.CANCELLED) { Log.info("Job cancelled by user."); } else { t.printStackTrace(); failed(t); throw t; } } finally { updateModelOutput(); _train.unlock(_key); if (model != null) model.unlock(_key); if (dinfo != null) dinfo.remove(); _parms.read_unlock_frames(NaiveBayes.this); } tryComplete(); } } private TwoDimTable createModelSummaryTable(NaiveBayesOutput output) { List<String> colHeaders = new ArrayList<>(); List<String> colTypes = new ArrayList<>(); List<String> colFormat = new ArrayList<>(); colHeaders.add("Number of Response Levels"); colTypes.add("long"); colFormat.add("%d"); colHeaders.add("Min Apriori Probability"); colTypes.add("double"); colFormat.add("%.5f"); colHeaders.add("Max Apriori Probability"); colTypes.add("double"); colFormat.add("%.5f"); double apriori_min = output._apriori_raw[0]; double apriori_max = output._apriori_raw[0]; for(int i = 1; i < output._apriori_raw.length; i++) { if(output._apriori_raw[i] < apriori_min) apriori_min = output._apriori_raw[i]; else if(output._apriori_raw[i] > apriori_max) apriori_max = output._apriori_raw[i]; } final int rows = 1; TwoDimTable table = new TwoDimTable( "Model Summary", null, new String[rows], colHeaders.toArray(new String[0]), colTypes.toArray(new String[0]), colFormat.toArray(new String[0]), ""); int row = 0; int col = 0; table.set(row, col++, output._apriori_raw.length); table.set(row, col++, apriori_min); table.set(row, col++, apriori_max); return table; } // Note: NA handling differs from R for efficiency purposes // R's method: For each predictor x_j, skip counting that row for p(x_j|y) calculation if x_j = NA. // If response y = NA, skip counting row entirely in all calculations // H2O's method: Just skip all rows where any x_j = NA or y = NA. Should be more memory-efficient, but results incomparable with R. private static class NBTask extends MRTask<NBTask> { final protected Key _jobKey; final DataInfo _dinfo; final String[][] _domains; // Domains of the training frame final int _nrescat; // Number of levels for the response y final int _npreds; // Number of predictors in the training frame public int _nobs; // Number of rows counted in calculation public int[/*nrescat*/] _rescnt; // Count of each level in the response public int[/*npreds*/][/*nrescat*/][] _jntcnt; // For each categorical predictor, joint count of response and predictor levels public double[/*npreds*/][/*nrescat*/][] _jntsum; // For each numeric predictor, sum and squared sum of entries for every response level public NBTask(Key jobKey, DataInfo dinfo, int nres) { _jobKey = jobKey; _dinfo = dinfo; _nrescat = nres; _domains = dinfo._adaptedFrame.domains(); _npreds = dinfo._adaptedFrame.numCols()-1; assert _npreds == dinfo._nums + dinfo._cats; assert _nrescat == _domains[_npreds].length; // Response in last vec of adapted frame } @Override public void map(Chunk[] chks) { if(_jobKey != null && !isRunning(_jobKey)) { throw new JobCancelledException(); } _nobs = 0; _rescnt = new int[_nrescat]; if(_dinfo._cats > 0) { _jntcnt = new int[_dinfo._cats][][]; for (int i = 0; i < _dinfo._cats; i++) { _jntcnt[i] = new int[_nrescat][_domains[i].length]; } } if(_dinfo._nums > 0) { _jntsum = new double[_dinfo._nums][][]; for (int i = 0; i < _dinfo._nums; i++) { _jntsum[i] = new double[_nrescat][2]; } } Chunk res = chks[_npreds]; // Response at the end OUTER: for(int row = 0; row < chks[0]._len; row++) { // Skip row if any entries in it are NA for(int col = 0; col < chks.length; col++) { if(Double.isNaN(chks[col].atd(row))) continue OUTER; } // Record joint counts of categorical predictors and response int rlevel = (int)res.atd(row); for(int col = 0; col < _dinfo._cats; col++) { int plevel = (int)chks[col].atd(row); _jntcnt[col][rlevel][plevel]++; } // Record sum for each pair of numerical predictors and response for(int col = 0; col < _dinfo._nums; col++) { int cidx = _dinfo._cats + col; double x = chks[cidx].atd(row); _jntsum[col][rlevel][0] += x; _jntsum[col][rlevel][1] += x*x; } _rescnt[rlevel]++; _nobs++; } } @Override public void reduce(NBTask nt) { _nobs += nt._nobs; ArrayUtils.add(_rescnt, nt._rescnt); if(null != _jntcnt) { for (int col = 0; col < _jntcnt.length; col++) ArrayUtils.add(_jntcnt[col], nt._jntcnt[col]); } if(null != _jntsum) { for (int col = 0; col < _jntsum.length; col++) ArrayUtils.add(_jntsum[col], nt._jntsum[col]); } } } }
// Copyright (C) 2020 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.google.gerrit.plugins.codeowners.backend; import static com.google.common.truth.Truth.assertThat; import static com.google.gerrit.testing.GerritJUnit.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.google.gerrit.acceptance.config.GerritConfig; import com.google.gerrit.entities.BranchNameKey; import com.google.gerrit.entities.RefNames; import com.google.gerrit.plugins.codeowners.acceptance.AbstractCodeOwnersTest; import com.google.gerrit.plugins.codeowners.acceptance.testsuite.CodeOwnerConfigOperations; import java.nio.file.Paths; import org.eclipse.jgit.junit.TestRepository; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.mockito.quality.Strictness; /** Tests for {@link CodeOwnerConfigScanner}. */ public class CodeOwnerConfigScannerTest extends AbstractCodeOwnersTest { @Rule public final MockitoRule mockito = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); @Mock private CodeOwnerConfigVisitor visitor; @Mock private InvalidCodeOwnerConfigCallback invalidCodeOwnerConfigCallback; private CodeOwnerConfigOperations codeOwnerConfigOperations; private CodeOwnerConfigScanner.Factory codeOwnerConfigScannerFactory; @Before public void setUpCodeOwnersPlugin() throws Exception { codeOwnerConfigOperations = plugin.getSysInjector().getInstance(CodeOwnerConfigOperations.class); codeOwnerConfigScannerFactory = plugin.getSysInjector().getInstance(CodeOwnerConfigScanner.Factory.class); } @Test public void cannotVisitCodeOwnerConfigsForNullBranch() throws Exception { NullPointerException npe = assertThrows( NullPointerException.class, () -> codeOwnerConfigScannerFactory .create() .visit(/* branchNameKey= */ null, visitor, invalidCodeOwnerConfigCallback)); assertThat(npe).hasMessageThat().isEqualTo("branchNameKey"); } @Test public void cannotVisitCodeOwnerConfigsWithNullVisitor() throws Exception { BranchNameKey branchNameKey = BranchNameKey.create(project, "master"); NullPointerException npe = assertThrows( NullPointerException.class, () -> codeOwnerConfigScannerFactory .create() .visit( branchNameKey, /* codeOwnerConfigVisitor= */ null, invalidCodeOwnerConfigCallback)); assertThat(npe).hasMessageThat().isEqualTo("codeOwnerConfigVisitor"); } @Test public void cannotVisitCodeOwnerConfigsWithNullCallback() throws Exception { BranchNameKey branchNameKey = BranchNameKey.create(project, "master"); NullPointerException npe = assertThrows( NullPointerException.class, () -> codeOwnerConfigScannerFactory .create() .visit(branchNameKey, visitor, /* invalidCodeOwnerConfigCallback= */ null)); assertThat(npe).hasMessageThat().isEqualTo("invalidCodeOwnerConfigCallback"); } @Test public void cannotVisitCodeOwnerConfigsForNonExistingBranch() throws Exception { BranchNameKey branchNameKey = BranchNameKey.create(project, "non-existing"); IllegalStateException exception = assertThrows( IllegalStateException.class, () -> codeOwnerConfigScannerFactory .create() .visit(branchNameKey, visitor, invalidCodeOwnerConfigCallback)); assertThat(exception) .hasMessageThat() .isEqualTo( String.format( "branch %s of project %s not found", branchNameKey.branch(), project.get())); } @Test public void visitorNotInvokedIfNoCodeOwnerConfigFilesExists() throws Exception { visit(); verifyNoInteractions(visitor); verifyNoInteractions(invalidCodeOwnerConfigCallback); } @Test public void visitorNotInvokedForNonCodeOwnerConfigFiles() throws Exception { // Create some non code owner config files. try (TestRepository<Repository> testRepo = new TestRepository<>(repoManager.openRepository(project))) { Ref ref = testRepo.getRepository().exactRef("refs/heads/master"); RevCommit head = testRepo.getRevWalk().parseCommit(ref.getObjectId()); testRepo.update( "refs/heads/master", testRepo .commit() .parent(head) .message("Add some non code owner config files") .add("owners.txt", "some content") .add("owners", "some content") .add("foo/bar/owners.txt", "some content") .add("foo/bar/owners", "some content")); } visit(); verifyNoInteractions(visitor); verifyNoInteractions(invalidCodeOwnerConfigCallback); } @Test public void visitorNotInvokedForInvalidCodeOwnerConfigFiles() throws Exception { createNonParseableCodeOwnerConfig("/OWNERS"); visit(); verifyNoInteractions(visitor); // Verify that we received the expected callbacks for the invalid code onwer config. Mockito.verify(invalidCodeOwnerConfigCallback) .onInvalidCodeOwnerConfig( eq(Paths.get("/OWNERS")), any(InvalidCodeOwnerConfigException.class)); verifyNoMoreInteractions(invalidCodeOwnerConfigCallback); } @Test public void visitorInvokedForValidCodeOwnerConfigFilesEvenIfInvalidCodeOwnerConfigFileExist() throws Exception { createNonParseableCodeOwnerConfig("/OWNERS"); // Create a valid code owner config file. CodeOwnerConfig.Key codeOwnerConfigKey = codeOwnerConfigOperations .newCodeOwnerConfig() .project(project) .branch("master") .folderPath("/foo/") .fileName("OWNERS") .addCodeOwnerEmail(admin.email()) .create(); when(visitor.visit(any(CodeOwnerConfig.class))).thenReturn(true); visit(); // Verify that we received the expected callbacks. Mockito.verify(visitor) .visit(codeOwnerConfigOperations.codeOwnerConfig(codeOwnerConfigKey).get()); verifyNoMoreInteractions(visitor); // Verify that we received the expected callbacks for the invalid code onwer config. Mockito.verify(invalidCodeOwnerConfigCallback) .onInvalidCodeOwnerConfig( eq(Paths.get("/OWNERS")), any(InvalidCodeOwnerConfigException.class)); verifyNoMoreInteractions(invalidCodeOwnerConfigCallback); } @Test public void visitorInvokedForCodeOwnerConfigFileAtRoot() throws Exception { testVisitorInvoked("/", "OWNERS"); } @Test public void visitorInvokedForCodeOwnerConfigFileWithPostFixAtRoot() throws Exception { testVisitorInvoked("/", "OWNERS_post_fix"); } @Test public void visitorInvokedForCodeOwnerConfigFileWithPreFixAtRoot() throws Exception { testVisitorInvoked("/", "pre_fix_OWNERS"); } @Test @GerritConfig(name = "plugin.code-owners.fileExtension", value = "foo") public void visitorInvokedForCodeOwnerConfigFileWithExtensionAtRoot() throws Exception { testVisitorInvoked("/", "OWNERS.foo"); } @Test @GerritConfig(name = "plugin.code-owners.fileExtension", value = "foo") public void visitorInvokedForCodeOwnerConfigFileWithPostFixAndExtensionAtRoot() throws Exception { testVisitorInvoked("/", "OWNERS_post_fix.foo"); } @Test @GerritConfig(name = "plugin.code-owners.fileExtension", value = "foo") public void visitorInvokedForCodeOwnerConfigFileWithPreFixAndExtensionAtRoot() throws Exception { testVisitorInvoked("/", "pre_fix_OWNERS.foo"); } @Test public void visitorInvokedForCodeOwnerConfigFileInSubfolder() throws Exception { testVisitorInvoked("/foo/bar/", "OWNERS"); } @Test public void visitorInvokedForCodeOwnerConfigFileWithPostFixInSubfolder() throws Exception { testVisitorInvoked("/foo/bar/", "OWNERS_post_fix"); } @Test public void visitorInvokedForCodeOwnerConfigFileWithPreFixInSubfolder() throws Exception { testVisitorInvoked("/foo/bar/", "pre_fix_OWNERS"); } @Test @GerritConfig(name = "plugin.code-owners.fileExtension", value = "foo") public void visitorInvokedForCodeOwnerConfigFileWithExtensionInSubfolder() throws Exception { testVisitorInvoked("/foo/bar/", "OWNERS.foo"); } @Test @GerritConfig(name = "plugin.code-owners.fileExtension", value = "foo") public void visitorInvokedForCodeOwnerConfigFileWithPostFixAndExtensionInSubfolder() throws Exception { testVisitorInvoked("/foo/bar/", "OWNERS_post_fix.foo"); } @Test @GerritConfig(name = "plugin.code-owners.fileExtension", value = "foo") public void visitorInvokedForCodeOwnerConfigFileWithPreFixAndExtensionInSubfolder() throws Exception { testVisitorInvoked("/foo/bar/", "pre_fix_OWNERS.foo"); } private void testVisitorInvoked(String folderPath, String fileName) throws Exception { CodeOwnerConfig.Key codeOwnerConfigKey = codeOwnerConfigOperations .newCodeOwnerConfig() .project(project) .branch("master") .folderPath(folderPath) .fileName(fileName) .addCodeOwnerEmail(admin.email()) .create(); when(visitor.visit(any(CodeOwnerConfig.class))).thenReturn(true); visit(); // Verify that we received the expected callbacks. Mockito.verify(visitor) .visit(codeOwnerConfigOperations.codeOwnerConfig(codeOwnerConfigKey).get()); verifyNoMoreInteractions(visitor); verifyNoInteractions(invalidCodeOwnerConfigCallback); } @Test public void visitorInvokedForDefaultCodeOwnerConfigFileInRefsMetaConfig() throws Exception { CodeOwnerConfig.Key codeOwnerConfigKey = codeOwnerConfigOperations .newCodeOwnerConfig() .project(project) .branch(RefNames.REFS_CONFIG) .folderPath("/") .fileName("OWNERS") .addCodeOwnerEmail(admin.email()) .create(); when(visitor.visit(any(CodeOwnerConfig.class))).thenReturn(true); visit(); // Verify that we received the expected callback. Mockito.verify(visitor) .visit(codeOwnerConfigOperations.codeOwnerConfig(codeOwnerConfigKey).get()); verifyNoMoreInteractions(visitor); verifyNoInteractions(invalidCodeOwnerConfigCallback); } @Test public void visitorNotInvokedForDefaulCodeOwnerConfigFileInRefsMetaConfigIfSkipped() throws Exception { codeOwnerConfigOperations .newCodeOwnerConfig() .project(project) .branch(RefNames.REFS_CONFIG) .folderPath("/") .addCodeOwnerEmail(admin.email()) .create(); visit( /** includeDefaultCodeOwnerConfig */ false); // Verify that we did not receive any callback. verifyNoInteractions(visitor); verifyNoInteractions(invalidCodeOwnerConfigCallback); } @Test public void visitorIsInvokedForAllCodeOwnerConfigFiles() throws Exception { CodeOwnerConfig.Key metaCodeOwnerConfigKey = codeOwnerConfigOperations .newCodeOwnerConfig() .project(project) .branch(RefNames.REFS_CONFIG) .folderPath("/") .fileName("OWNERS") .addCodeOwnerEmail(admin.email()) .create(); CodeOwnerConfig.Key rootCodeOwnerConfigKey = codeOwnerConfigOperations .newCodeOwnerConfig() .project(project) .branch("master") .folderPath("/") .fileName("OWNERS") .addCodeOwnerEmail(admin.email()) .create(); CodeOwnerConfig.Key fooCodeOwnerConfigKey = codeOwnerConfigOperations .newCodeOwnerConfig() .project(project) .branch("master") .folderPath("/foo/") .fileName("OWNERS") .addCodeOwnerEmail(admin.email()) .create(); CodeOwnerConfig.Key fooBarCodeOwnerConfigKey = codeOwnerConfigOperations .newCodeOwnerConfig() .project(project) .branch("master") .folderPath("/foo/bar/") .fileName("OWNERS") .addCodeOwnerEmail(admin.email()) .create(); when(visitor.visit(any(CodeOwnerConfig.class))).thenReturn(true); visit(); // Verify that we received the expected callbacks. InOrder orderVerifier = Mockito.inOrder(visitor); orderVerifier .verify(visitor) .visit(codeOwnerConfigOperations.codeOwnerConfig(metaCodeOwnerConfigKey).get()); orderVerifier .verify(visitor) .visit(codeOwnerConfigOperations.codeOwnerConfig(rootCodeOwnerConfigKey).get()); orderVerifier .verify(visitor) .visit(codeOwnerConfigOperations.codeOwnerConfig(fooCodeOwnerConfigKey).get()); orderVerifier .verify(visitor) .visit(codeOwnerConfigOperations.codeOwnerConfig(fooBarCodeOwnerConfigKey).get()); verifyNoMoreInteractions(visitor); verifyNoInteractions(invalidCodeOwnerConfigCallback); } @Test public void skipDefaultCodeOwnerConfigFile() throws Exception { codeOwnerConfigOperations .newCodeOwnerConfig() .project(project) .branch(RefNames.REFS_CONFIG) .folderPath("/") .addCodeOwnerEmail(admin.email()) .create(); CodeOwnerConfig.Key rootCodeOwnerConfigKey = codeOwnerConfigOperations .newCodeOwnerConfig() .project(project) .branch("master") .folderPath("/") .fileName("OWNERS") .addCodeOwnerEmail(admin.email()) .create(); CodeOwnerConfig.Key fooCodeOwnerConfigKey = codeOwnerConfigOperations .newCodeOwnerConfig() .project(project) .branch("master") .folderPath("/foo/") .fileName("OWNERS") .addCodeOwnerEmail(admin.email()) .create(); when(visitor.visit(any(CodeOwnerConfig.class))).thenReturn(true); visit( /** includeDefaultCodeOwnerConfig */ false); // Verify that we received only the expected callbacks (e.g. no callback for the default code // owner config in refs/meta/config). InOrder orderVerifier = Mockito.inOrder(visitor); orderVerifier .verify(visitor) .visit(codeOwnerConfigOperations.codeOwnerConfig(rootCodeOwnerConfigKey).get()); orderVerifier .verify(visitor) .visit(codeOwnerConfigOperations.codeOwnerConfig(fooCodeOwnerConfigKey).get()); verifyNoMoreInteractions(visitor); verifyNoInteractions(invalidCodeOwnerConfigCallback); } @Test public void visitorCanStopTheIterationOverCodeOwnerConfigsByReturningFalse() throws Exception { CodeOwnerConfig.Key rootCodeOwnerConfigKey = codeOwnerConfigOperations .newCodeOwnerConfig() .project(project) .branch("master") .folderPath("/") .fileName("OWNERS") .addCodeOwnerEmail(admin.email()) .create(); CodeOwnerConfig.Key fooCodeOwnerConfigKey = codeOwnerConfigOperations .newCodeOwnerConfig() .project(project) .branch("master") .folderPath("/foo/") .fileName("OWNERS") .addCodeOwnerEmail(admin.email()) .create(); codeOwnerConfigOperations .newCodeOwnerConfig() .project(project) .branch("master") .folderPath("/foo/bar/") .fileName("OWNERS") .addCodeOwnerEmail(admin.email()) .create(); // Return true for the first time the visitor is invoked, and false for all further invocations. when(visitor.visit(any(CodeOwnerConfig.class))).thenReturn(true).thenReturn(false); visit(); // Verify that we received the callbacks in the right order, starting from the folder of the // given path up to the root folder. We expect only 2 callbacks, since the visitor returns false // for the second invocation. InOrder orderVerifier = Mockito.inOrder(visitor); orderVerifier .verify(visitor) .visit(codeOwnerConfigOperations.codeOwnerConfig(rootCodeOwnerConfigKey).get()); orderVerifier .verify(visitor) .visit(codeOwnerConfigOperations.codeOwnerConfig(fooCodeOwnerConfigKey).get()); verifyNoMoreInteractions(visitor); verifyNoInteractions(invalidCodeOwnerConfigCallback); } @Test public void visitorIsOnlyInvokedOnceForDefaultCodeOnwerConfigFileIfRefsMetaConfigIsScanned() throws Exception { CodeOwnerConfig.Key codeOwnerConfigKey = codeOwnerConfigOperations .newCodeOwnerConfig() .project(project) .branch(RefNames.REFS_CONFIG) .folderPath("/") .fileName("OWNERS") .addCodeOwnerEmail(admin.email()) .create(); when(visitor.visit(any(CodeOwnerConfig.class))).thenReturn(true); codeOwnerConfigScannerFactory .create() .includeDefaultCodeOwnerConfig(true) .visit( BranchNameKey.create(project, RefNames.REFS_CONFIG), visitor, invalidCodeOwnerConfigCallback); // Verify that we received the callback for the code owner config only once. Mockito.verify(visitor) .visit(codeOwnerConfigOperations.codeOwnerConfig(codeOwnerConfigKey).get()); verifyNoMoreInteractions(visitor); verifyNoInteractions(invalidCodeOwnerConfigCallback); } private void visit() { visit( /** includeDefaultCodeOwnerConfig */ true); } private void visit(boolean includeDefaultCodeOwnerConfig) { codeOwnerConfigScannerFactory .create() .includeDefaultCodeOwnerConfig(includeDefaultCodeOwnerConfig) .visit(BranchNameKey.create(project, "master"), visitor, invalidCodeOwnerConfigCallback); } }
/* * 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.camel.catalog; import java.io.FileInputStream; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.camel.catalog.CatalogHelper.loadText; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class CamelCatalogTest { static CamelCatalog catalog; private static final Logger LOG = LoggerFactory.getLogger(CamelCatalogTest.class); @BeforeClass public static void createCamelCatalog() { catalog = new DefaultCamelCatalog(); } @Test public void testGetVersion() throws Exception { String version = catalog.getCatalogVersion(); assertNotNull(version); String loaded = catalog.getLoadedVersion(); assertNotNull(loaded); assertEquals(version, loaded); } @Test public void testLoadVersion() throws Exception { boolean result = catalog.loadVersion("1.0"); assertFalse(result); String version = catalog.getCatalogVersion(); result = catalog.loadVersion(version); assertTrue(result); } @Test public void testFindComponentNames() throws Exception { List<String> names = catalog.findComponentNames(); assertNotNull(names); assertTrue(names.contains("file")); assertTrue(names.contains("log")); assertTrue(names.contains("docker")); assertTrue(names.contains("jms")); assertTrue(names.contains("activemq")); assertTrue(names.contains("zookeeper-master")); } @Test public void testFindOtherNames() throws Exception { List<String> names = catalog.findOtherNames(); assertTrue(names.contains("hystrix")); assertTrue(names.contains("leveldb")); assertTrue(names.contains("kura")); assertTrue(names.contains("swagger-java")); assertTrue(names.contains("test-spring")); assertFalse(names.contains("http-common")); assertFalse(names.contains("core-osgi")); assertFalse(names.contains("file")); assertFalse(names.contains("ftp")); assertFalse(names.contains("jetty")); } @Test public void testFindDataFormatNames() throws Exception { List<String> names = catalog.findDataFormatNames(); assertNotNull(names); assertTrue(names.contains("bindy-csv")); assertTrue(names.contains("hl7")); assertTrue(names.contains("jaxb")); assertTrue(names.contains("syslog")); assertTrue(names.contains("asn1")); assertTrue(names.contains("zipfile")); } @Test public void testFindLanguageNames() throws Exception { List<String> names = catalog.findLanguageNames(); assertTrue(names.contains("simple")); assertTrue(names.contains("groovy")); assertTrue(names.contains("mvel")); assertTrue(names.contains("bean")); assertTrue(names.contains("file")); assertTrue(names.contains("xtokenize")); assertTrue(names.contains("hl7terser")); } @Test public void testFindModelNames() throws Exception { List<String> names = catalog.findModelNames(); assertNotNull(names); assertTrue(names.contains("from")); assertTrue(names.contains("to")); assertTrue(names.contains("recipientList")); assertTrue(names.contains("aggregate")); assertTrue(names.contains("split")); assertTrue(names.contains("loadBalance")); assertTrue(names.contains("circuitBreaker")); assertTrue(names.contains("saga")); } @Test public void testJsonSchema() throws Exception { String schema = catalog.componentJSonSchema("docker"); assertNotNull(schema); schema = catalog.dataFormatJSonSchema("hl7"); assertNotNull(schema); schema = catalog.languageJSonSchema("groovy"); assertNotNull(schema); schema = catalog.modelJSonSchema("aggregate"); assertNotNull(schema); schema = catalog.otherJSonSchema("swagger-java"); assertNotNull(schema); // lets make it possible to find bean/method using both names schema = catalog.modelJSonSchema("method"); assertNotNull(schema); schema = catalog.modelJSonSchema("bean"); assertNotNull(schema); } @Test public void testXmlSchema() throws Exception { String schema = catalog.blueprintSchemaAsXml(); assertNotNull(schema); schema = catalog.springSchemaAsXml(); assertNotNull(schema); } @Test public void testArchetypeCatalog() throws Exception { String schema = catalog.archetypeCatalogAsXml(); assertNotNull(schema); } @Test public void testAsEndpointUriMapFile() throws Exception { Map<String, String> map = new HashMap<>(); map.put("directoryName", "src/data/inbox"); map.put("noop", "true"); map.put("delay", "5000"); String uri = catalog.asEndpointUri("file", map, true); assertEquals("file:src/data/inbox?delay=5000&noop=true", uri); String uri2 = catalog.asEndpointUriXml("file", map, true); assertEquals("file:src/data/inbox?delay=5000&amp;noop=true", uri2); } @Test public void testAsEndpointUriMapFtp() throws Exception { Map<String, String> map = new HashMap<>(); map.put("host", "someserver"); map.put("port", "21"); map.put("directoryName", "foo"); map.put("connectTimeout", "5000"); String uri = catalog.asEndpointUri("ftp", map, true); assertEquals("ftp:someserver:21/foo?connectTimeout=5000", uri); String uri2 = catalog.asEndpointUriXml("ftp", map, true); assertEquals("ftp:someserver:21/foo?connectTimeout=5000", uri2); } @Test public void testAsEndpointUriMapJms() throws Exception { Map<String, String> map = new HashMap<>(); map.put("destinationType", "queue"); map.put("destinationName", "foo"); String uri = catalog.asEndpointUri("jms", map, true); assertEquals("jms:queue:foo", uri); } @Test public void testAsEndpointUriNettyhttp() throws Exception { Map<String, String> map = new HashMap<>(); // use http protocol map.put("protocol", "http"); map.put("host", "localhost"); map.put("port", "8080"); map.put("path", "foo/bar"); map.put("disconnect", "true"); String uri = catalog.asEndpointUri("netty-http", map, true); assertEquals("netty-http:http:localhost:8080/foo/bar?disconnect=true", uri); // lets switch protocol map.put("protocol", "https"); uri = catalog.asEndpointUri("netty-http", map, true); assertEquals("netty-http:https:localhost:8080/foo/bar?disconnect=true", uri); // lets set a query parameter in the path map.put("path", "foo/bar?verbose=true"); map.put("disconnect", "true"); uri = catalog.asEndpointUri("netty-http", map, true); assertEquals("netty-http:https:localhost:8080/foo/bar?verbose=true&disconnect=true", uri); } @Test public void testAsEndpointUriTimer() throws Exception { Map<String, String> map = new HashMap<>(); map.put("timerName", "foo"); map.put("period", "5000"); String uri = catalog.asEndpointUri("timer", map, true); assertEquals("timer:foo?period=5000", uri); } @Test public void testAsEndpointDefaultValue() throws Exception { Map<String, String> map = new HashMap<>(); map.put("destinationName", "cheese"); map.put("maxMessagesPerTask", "-1"); String uri = catalog.asEndpointUri("jms", map, true); assertEquals("jms:cheese?maxMessagesPerTask=-1", uri); } @Test public void testAsEndpointUriPropertiesPlaceholders() throws Exception { Map<String, String> map = new HashMap<>(); map.put("timerName", "foo"); map.put("period", "{{howoften}}"); map.put("repeatCount", "5"); String uri = catalog.asEndpointUri("timer", map, true); assertEquals("timer:foo?period=%7B%7Bhowoften%7D%7D&repeatCount=5", uri); uri = catalog.asEndpointUri("timer", map, false); assertEquals("timer:foo?period={{howoften}}&repeatCount=5", uri); } @Test public void testAsEndpointUriBeanLookup() throws Exception { Map<String, String> map = new HashMap<>(); map.put("resourceUri", "foo.xslt"); map.put("converter", "#myConverter"); String uri = catalog.asEndpointUri("xslt", map, true); assertEquals("xslt:foo.xslt?converter=%23myConverter", uri); uri = catalog.asEndpointUri("xslt", map, false); assertEquals("xslt:foo.xslt?converter=#myConverter", uri); } @Test public void testAsEndpointUriMapJmsRequiredOnly() throws Exception { Map<String, String> map = new HashMap<>(); map.put("destinationName", "foo"); String uri = catalog.asEndpointUri("jms", map, true); assertEquals("jms:foo", uri); map.put("deliveryPersistent", "false"); map.put("allowNullBody", "true"); uri = catalog.asEndpointUri("jms", map, true); assertEquals("jms:foo?allowNullBody=true&deliveryPersistent=false", uri); String uri2 = catalog.asEndpointUriXml("jms", map, true); assertEquals("jms:foo?allowNullBody=true&amp;deliveryPersistent=false", uri2); } @Test public void testAsEndpointUriRestUriTemplate() throws Exception { Map<String, String> map = new LinkedHashMap<>(); map.put("method", "get"); map.put("path", "api"); map.put("uriTemplate", "user/{id}"); String uri = catalog.asEndpointUri("rest", map, true); assertEquals("rest:get:api:user/{id}", uri); } @Test public void testAsEndpointUriNettyHttpHostnameWithDash() throws Exception { Map<String, String> map = new LinkedHashMap<>(); map.put("protocol", "http"); map.put("host", "a-b-c.hostname.tld"); map.put("port", "8080"); map.put("path", "anything"); String uri = catalog.asEndpointUri("netty-http", map, false); assertEquals("netty-http:http:a-b-c.hostname.tld:8080/anything", uri); map = new LinkedHashMap<>(); map.put("protocol", "http"); map.put("host", "a-b-c.server.net"); map.put("port", "8888"); map.put("path", "service/v3"); uri = catalog.asEndpointUri("netty-http", map, true); assertEquals("netty-http:http:a-b-c.server.net:8888/service/v3", uri); } @Test public void testNettyHttpDynamicToIssueHost() throws Exception { String uri = "netty-http:http://a-b-c.hostname.tld:8080/anything"; Map<String, String> params = catalog.endpointProperties(uri); assertEquals("http", params.get("protocol")); assertEquals("a-b-c.hostname.tld", params.get("host")); assertEquals("8080", params.get("port")); assertEquals("anything", params.get("path")); // remove path params.remove("path"); String resolved = catalog.asEndpointUri("netty-http", params, false); assertEquals("netty-http:http:a-b-c.hostname.tld:8080", resolved); } @Test public void testEndpointProperties() throws Exception { Map<String, String> map = catalog.endpointProperties("ftp:someserver:21/foo?connectTimeout=5000"); assertNotNull(map); assertEquals(4, map.size()); assertEquals("someserver", map.get("host")); assertEquals("21", map.get("port")); assertEquals("foo", map.get("directoryName")); assertEquals("5000", map.get("connectTimeout")); } @Test public void testEndpointLenientProperties() throws Exception { Map<String, String> map = catalog.endpointLenientProperties("http:myserver?throwExceptionOnFailure=false&foo=123&bar=456"); assertNotNull(map); assertEquals(2, map.size()); assertEquals("123", map.get("foo")); assertEquals("456", map.get("bar")); map = catalog.endpointLenientProperties("http:myserver?throwExceptionOnFailure=false&foo=123&bar=456&httpClient.timeout=5000&httpClient.soTimeout=10000"); assertNotNull(map); assertEquals(2, map.size()); assertEquals("123", map.get("foo")); assertEquals("456", map.get("bar")); map = catalog.endpointLenientProperties("http:myserver?throwExceptionOnFailure=false&foo=123&bar=456&httpClient.timeout=5000&httpClient.soTimeout=10000&myPrefix.baz=beer"); assertNotNull(map); assertEquals(3, map.size()); assertEquals("123", map.get("foo")); assertEquals("456", map.get("bar")); assertEquals("beer", map.get("myPrefix.baz")); } @Test public void testEndpointPropertiesPlaceholders() throws Exception { Map<String, String> map = catalog.endpointProperties("timer:foo?period={{howoften}}&repeatCount=5"); assertNotNull(map); assertEquals(3, map.size()); assertEquals("foo", map.get("timerName")); assertEquals("{{howoften}}", map.get("period")); assertEquals("5", map.get("repeatCount")); } @Test public void testEndpointPropertiesNettyHttp() throws Exception { Map<String, String> map = catalog.endpointProperties("netty-http:http:localhost:8080/foo/bar?disconnect=true&keepAlive=false"); assertNotNull(map); assertEquals(6, map.size()); assertEquals("http", map.get("protocol")); assertEquals("localhost", map.get("host")); assertEquals("8080", map.get("port")); assertEquals("foo/bar", map.get("path")); assertEquals("true", map.get("disconnect")); assertEquals("false", map.get("keepAlive")); } @Test public void testEndpointPropertiesNettyHttpDefaultPort() throws Exception { Map<String, String> map = catalog.endpointProperties("netty-http:http:localhost/foo/bar?disconnect=true&keepAlive=false"); assertNotNull(map); assertEquals(5, map.size()); assertEquals("http", map.get("protocol")); assertEquals("localhost", map.get("host")); assertEquals("foo/bar", map.get("path")); assertEquals("true", map.get("disconnect")); assertEquals("false", map.get("keepAlive")); } @Test public void testEndpointPropertiesNettyHttpPlaceholder() throws Exception { Map<String, String> map = catalog.endpointProperties("netty-http:http:{{myhost}}:{{myport}}/foo/bar?disconnect=true&keepAlive=false"); assertNotNull(map); assertEquals(6, map.size()); assertEquals("http", map.get("protocol")); assertEquals("{{myhost}}", map.get("host")); assertEquals("{{myport}}", map.get("port")); assertEquals("foo/bar", map.get("path")); assertEquals("true", map.get("disconnect")); assertEquals("false", map.get("keepAlive")); } @Test public void testEndpointPropertiesNettyHttpWithDoubleSlash() throws Exception { Map<String, String> map = catalog.endpointProperties("netty-http:http://localhost:8080/foo/bar?disconnect=true&keepAlive=false"); assertNotNull(map); assertEquals(6, map.size()); assertEquals("http", map.get("protocol")); assertEquals("localhost", map.get("host")); assertEquals("8080", map.get("port")); assertEquals("foo/bar", map.get("path")); assertEquals("true", map.get("disconnect")); assertEquals("false", map.get("keepAlive")); } @Test public void testAsEndpointUriLog() throws Exception { Map<String, String> map = new HashMap<>(); map.put("loggerName", "foo"); map.put("loggerLevel", "WARN"); map.put("multiline", "true"); map.put("showAll", "true"); map.put("showBody", "false"); map.put("showBodyType", "false"); map.put("showExchangePattern", "false"); map.put("style", "Tab"); assertEquals("log:foo?loggerLevel=WARN&multiline=true&showAll=true&style=Tab", catalog.asEndpointUri("log", map, false)); } @Test public void testAsEndpointUriLogShort() throws Exception { Map<String, String> map = new HashMap<>(); map.put("loggerName", "foo"); map.put("loggerLevel", "DEBUG"); assertEquals("log:foo?loggerLevel=DEBUG", catalog.asEndpointUri("log", map, false)); } @Test public void testAsEndpointUriWithplaceholder() throws Exception { Map<String, String> map = new HashMap<>(); map.put("query", "{{insert}}"); assertEquals("sql:{{insert}}", catalog.asEndpointUri("sql", map, false)); map.put("useMessageBodyForSql", "true"); assertEquals("sql:{{insert}}?useMessageBodyForSql=true", catalog.asEndpointUri("sql", map, false)); map.put("parametersCount", "{{count}}"); assertEquals("sql:{{insert}}?parametersCount={{count}}&useMessageBodyForSql=true", catalog.asEndpointUri("sql", map, false)); } @Test public void testAsEndpointUriStream() throws Exception { Map<String, String> map = new LinkedHashMap<>(); map.put("kind", "url"); map.put("url", "http://camel.apache.org"); assertEquals("stream:url?url=http://camel.apache.org", catalog.asEndpointUri("stream", map, false)); } @Test public void testEndpointPropertiesJms() throws Exception { Map<String, String> map = catalog.endpointProperties("jms:queue:foo"); assertNotNull(map); assertEquals(2, map.size()); assertEquals("queue", map.get("destinationType")); assertEquals("foo", map.get("destinationName")); map = catalog.endpointProperties("jms:foo"); assertNotNull(map); assertEquals(1, map.size()); assertEquals("foo", map.get("destinationName")); } @Test public void testEndpointPropertiesJmsWithDotInName() throws Exception { Map<String, String> map = catalog.endpointProperties("jms:browse.me"); assertNotNull(map); assertEquals(1, map.size()); assertEquals("browse.me", map.get("destinationName")); map = catalog.endpointProperties("jms:browse.me"); assertNotNull(map); assertEquals(1, map.size()); assertEquals("browse.me", map.get("destinationName")); } @Test public void testEndpointPropertiesJmsRequired() throws Exception { Map<String, String> map = catalog.endpointProperties("jms:foo"); assertNotNull(map); assertEquals(1, map.size()); assertEquals("foo", map.get("destinationName")); map = catalog.endpointProperties("jms:foo?allowNullBody=true&deliveryPersistent=false"); assertNotNull(map); assertEquals(3, map.size()); assertEquals("foo", map.get("destinationName")); assertEquals("true", map.get("allowNullBody")); assertEquals("false", map.get("deliveryPersistent")); } @Test public void testEndpointPropertiesAtom() throws Exception { Map<String, String> map = catalog.endpointProperties("atom:file:src/test/data/feed.atom"); assertNotNull(map); assertEquals(1, map.size()); assertEquals("file:src/test/data/feed.atom", map.get("feedUri")); map = catalog.endpointProperties("atom:file:src/test/data/feed.atom?splitEntries=false&delay=5000"); assertNotNull(map); assertEquals(3, map.size()); assertEquals("file:src/test/data/feed.atom", map.get("feedUri")); assertEquals("false", map.get("splitEntries")); assertEquals("5000", map.get("delay")); } @Test public void testEndpointPropertiesMultiValued() throws Exception { Map<String, String> map = catalog.endpointProperties("http:helloworld?httpClientOptions=httpClient.foo=123&httpClient.bar=456"); assertNotNull(map); assertEquals(2, map.size()); assertEquals("helloworld", map.get("httpUri")); assertEquals("httpClient.foo=123&httpClient.bar=456", map.get("httpClientOptions")); } @Test public void testEndpointPropertiesSshWithUserInfo() throws Exception { Map<String, String> map = catalog.endpointProperties("ssh:localhost:8101?username=scott&password=tiger"); assertNotNull(map); assertEquals(4, map.size()); assertEquals("8101", map.get("port")); assertEquals("localhost", map.get("host")); assertEquals("scott", map.get("username")); assertEquals("tiger", map.get("password")); map = catalog.endpointProperties("ssh://scott:tiger@localhost:8101"); assertNotNull(map); assertEquals(4, map.size()); assertEquals("8101", map.get("port")); assertEquals("localhost", map.get("host")); assertEquals("scott", map.get("username")); assertEquals("tiger", map.get("password")); } @Test public void validateActiveMQProperties() throws Exception { // add activemq as known component catalog.addComponent("activemq", "org.apache.camel.component.activemq.ActiveMQComponent"); // activemq EndpointValidationResult result = catalog.validateEndpointProperties("activemq:temp-queue:cheese?jmsMessageType=Bytes"); assertTrue(result.isSuccess()); result = catalog.validateEndpointProperties("activemq:temp-queue:cheese?jmsMessageType=Bytes"); assertTrue(result.isSuccess()); result = catalog.validateEndpointProperties("activemq:temp-queue:cheese?jmsMessageType=Bytes", false, true, false); assertTrue(result.isSuccess()); result = catalog.validateEndpointProperties("activemq:temp-queue:cheese?jmsMessageType=Bytes", false, false, true); assertTrue(result.isSuccess()); // connection factory result = catalog.validateEndpointProperties("activemq:Consumer.Baz.VirtualTopic.FooRequest?connectionFactory=#pooledJmsConnectionFactory"); assertTrue(result.isSuccess()); } @Test public void validateJmsProperties() throws Exception { // jms EndpointValidationResult result = catalog.validateEndpointProperties("jms:temp-queue:cheese?jmsMessageType=Bytes"); assertTrue(result.isSuccess()); result = catalog.validateEndpointProperties("jms:temp-queue:cheese?jmsMessageType=Bytes"); assertTrue(result.isSuccess()); result = catalog.validateEndpointProperties("jms:temp-queue:cheese?jmsMessageType=Bytes", false, true, false); assertTrue(result.isSuccess()); result = catalog.validateEndpointProperties("jms:temp-queue:cheese?jmsMessageType=Bytes", false, false, true); assertTrue(result.isSuccess()); } @Test public void validateProperties() throws Exception { // valid EndpointValidationResult result = catalog.validateEndpointProperties("log:mylog"); assertTrue(result.isSuccess()); // unknown result = catalog.validateEndpointProperties("log:mylog?level=WARN&foo=bar"); assertFalse(result.isSuccess()); assertTrue(result.getUnknown().contains("foo")); assertEquals(1, result.getNumberOfErrors()); // enum result = catalog.validateEndpointProperties("jms:unknown:myqueue"); assertFalse(result.isSuccess()); assertEquals("unknown", result.getInvalidEnum().get("destinationType")); assertEquals("queue", result.getDefaultValues().get("destinationType")); assertEquals(1, result.getNumberOfErrors()); // reference okay result = catalog.validateEndpointProperties("jms:queue:myqueue?jmsKeyFormatStrategy=#key"); assertTrue(result.isSuccess()); assertEquals(0, result.getNumberOfErrors()); // reference result = catalog.validateEndpointProperties("jms:queue:myqueue?jmsKeyFormatStrategy=foo"); assertFalse(result.isSuccess()); assertEquals("foo", result.getInvalidEnum().get("jmsKeyFormatStrategy")); assertEquals(1, result.getNumberOfErrors()); // okay result = catalog.validateEndpointProperties("yammer:MESSAGES?accessToken=aaa&consumerKey=bbb&consumerSecret=ccc&useJson=true&initialDelay=500"); assertTrue(result.isSuccess()); // required / boolean / integer result = catalog.validateEndpointProperties("yammer:MESSAGES?accessToken=aaa&consumerKey=&useJson=no&initialDelay=five"); assertFalse(result.isSuccess()); assertEquals(4, result.getNumberOfErrors()); assertTrue(result.getRequired().contains("consumerKey")); assertTrue(result.getRequired().contains("consumerSecret")); assertEquals("no", result.getInvalidBoolean().get("useJson")); assertEquals("five", result.getInvalidInteger().get("initialDelay")); // unknown component result = catalog.validateEndpointProperties("foo:bar?me=you"); assertTrue(result.isSuccess()); assertTrue(result.hasWarnings()); assertTrue(result.getUnknownComponent().equals("foo")); assertEquals(0, result.getNumberOfErrors()); assertEquals(1, result.getNumberOfWarnings()); // invalid boolean but default value result = catalog.validateEndpointProperties("log:output?showAll=ggg"); assertFalse(result.isSuccess()); assertEquals("ggg", result.getInvalidBoolean().get("showAll")); assertEquals(1, result.getNumberOfErrors()); // dataset result = catalog.validateEndpointProperties("dataset:foo?minRate=50"); assertTrue(result.isSuccess()); // time pattern result = catalog.validateEndpointProperties("timer://foo?fixedRate=true&delay=0&period=2s"); assertTrue(result.isSuccess()); // reference lookup result = catalog.validateEndpointProperties("timer://foo?fixedRate=#fixed&delay=#myDelay"); assertTrue(result.isSuccess()); // optional consumer. prefix result = catalog.validateEndpointProperties("file:inbox?consumer.delay=5000&consumer.greedy=true"); assertTrue(result.isSuccess()); // optional without consumer. prefix result = catalog.validateEndpointProperties("file:inbox?delay=5000&greedy=true"); assertTrue(result.isSuccess()); // mixed optional without consumer. prefix result = catalog.validateEndpointProperties("file:inbox?delay=5000&consumer.greedy=true"); assertTrue(result.isSuccess()); // prefix result = catalog.validateEndpointProperties("file:inbox?delay=5000&scheduler.foo=123&scheduler.bar=456"); assertTrue(result.isSuccess()); // stub result = catalog.validateEndpointProperties("stub:foo?me=123&you=456"); assertTrue(result.isSuccess()); // lenient on result = catalog.validateEndpointProperties("dataformat:string:marshal?foo=bar"); assertTrue(result.isSuccess()); // lenient off result = catalog.validateEndpointProperties("dataformat:string:marshal?foo=bar", true); assertFalse(result.isSuccess()); assertTrue(result.getUnknown().contains("foo")); // lenient off consumer only result = catalog.validateEndpointProperties("netty-http:http://myserver?foo=bar", false, true, false); assertFalse(result.isSuccess()); // consumer should still fail because we cannot use lenient option in consumer mode assertEquals("foo", result.getUnknown().iterator().next()); assertNull(result.getLenient()); // lenient off producer only result = catalog.validateEndpointProperties("netty-http:http://myserver?foo=bar", false, false, true); assertTrue(result.isSuccess()); // foo is the lenient option assertEquals(1, result.getLenient().size()); assertEquals("foo", result.getLenient().iterator().next()); // lenient on consumer only result = catalog.validateEndpointProperties("netty-http:http://myserver?foo=bar", true, true, false); assertFalse(result.isSuccess()); // consumer should still fail because we cannot use lenient option in consumer mode assertEquals("foo", result.getUnknown().iterator().next()); assertNull(result.getLenient()); // lenient on producer only result = catalog.validateEndpointProperties("netty-http:http://myserver?foo=bar", true, false, true); assertFalse(result.isSuccess()); assertEquals("foo", result.getUnknown().iterator().next()); assertNull(result.getLenient()); // lenient on rss consumer only result = catalog.validateEndpointProperties("rss:file:src/test/data/rss20.xml?splitEntries=true&sortEntries=true&consumer.delay=50&foo=bar", false, true, false); assertTrue(result.isSuccess()); assertEquals("foo", result.getLenient().iterator().next()); // data format result = catalog.validateEndpointProperties("dataformat:zipdeflater:marshal?compressionLevel=2", true); assertTrue(result.isSuccess()); // 2 slash after component name result = catalog.validateEndpointProperties("atmos://put?remotePath=/dummy.txt"); assertTrue(result.isSuccess()); // userinfo in authority with username and password result = catalog.validateEndpointProperties("ssh://karaf:karaf@localhost:8101"); assertTrue(result.isSuccess()); // userinfo in authority without password result = catalog.validateEndpointProperties("ssh://scott@localhost:8101?certResource=classpath:test_rsa&useFixedDelay=true&delay=5000&pollCommand=features:list%0A"); assertTrue(result.isSuccess()); // userinfo with both user and password and placeholder result = catalog.validateEndpointProperties("ssh://smx:smx@localhost:8181?timeout=3000"); assertTrue(result.isSuccess()); // and should also work when port is using a placeholder result = catalog.validateEndpointProperties("ssh://smx:smx@localhost:{{port}}?timeout=3000"); assertTrue(result.isSuccess()); // placeholder for a bunch of optional options result = catalog.validateEndpointProperties("aws-swf://activity?{{options}}"); assertTrue(result.isSuccess()); // incapable to parse result = catalog.validateEndpointProperties("{{getFtpUrl}}?recursive=true"); assertTrue(result.isSuccess()); assertTrue(result.hasWarnings()); assertTrue(result.getIncapable() != null); } @Test public void validatePropertiesSummary() throws Exception { EndpointValidationResult result = catalog.validateEndpointProperties("yammer:MESSAGES?blah=yada&accessToken=aaa&consumerKey=&useJson=no&initialDelay=five&pollStrategy=myStrategy"); assertFalse(result.isSuccess()); String reason = result.summaryErrorMessage(true); LOG.info(reason); result = catalog.validateEndpointProperties("jms:unknown:myqueue"); assertFalse(result.isSuccess()); reason = result.summaryErrorMessage(false); LOG.info(reason); } @Test public void validateTimePattern() throws Exception { assertTrue(catalog.validateTimePattern("0")); assertTrue(catalog.validateTimePattern("500")); assertTrue(catalog.validateTimePattern("10000")); assertTrue(catalog.validateTimePattern("5s")); assertTrue(catalog.validateTimePattern("5sec")); assertTrue(catalog.validateTimePattern("5secs")); assertTrue(catalog.validateTimePattern("3m")); assertTrue(catalog.validateTimePattern("3min")); assertTrue(catalog.validateTimePattern("3minutes")); assertTrue(catalog.validateTimePattern("5m15s")); assertTrue(catalog.validateTimePattern("1h")); assertTrue(catalog.validateTimePattern("1hour")); assertTrue(catalog.validateTimePattern("2hours")); assertFalse(catalog.validateTimePattern("bla")); assertFalse(catalog.validateTimePattern("2year")); assertFalse(catalog.validateTimePattern("60darn")); } @Test public void testEndpointComponentName() throws Exception { String name = catalog.endpointComponentName("jms:queue:foo"); assertEquals("jms", name); } @Test public void testListComponentsAsJson() throws Exception { String json = catalog.listComponentsAsJson(); assertNotNull(json); // validate we can parse the json ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.readTree(json); assertNotNull(tree); } @Test public void testListDataFormatsAsJson() throws Exception { String json = catalog.listDataFormatsAsJson(); assertNotNull(json); // validate we can parse the json ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.readTree(json); assertNotNull(tree); } @Test public void testListLanguagesAsJson() throws Exception { String json = catalog.listLanguagesAsJson(); assertNotNull(json); // validate we can parse the json ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.readTree(json); assertNotNull(tree); } @Test public void testListModelsAsJson() throws Exception { String json = catalog.listModelsAsJson(); assertNotNull(json); // validate we can parse the json ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.readTree(json); assertNotNull(tree); } @Test public void testListOthersAsJson() throws Exception { String json = catalog.listOthersAsJson(); assertNotNull(json); // validate we can parse the json ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.readTree(json); assertNotNull(tree); } @Test public void testSummaryAsJson() throws Exception { String json = catalog.summaryAsJson(); assertNotNull(json); // validate we can parse the json ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.readTree(json); assertNotNull(tree); } @Test public void testAddComponent() throws Exception { catalog.addComponent("dummy", "org.foo.camel.DummyComponent"); assertTrue(catalog.findComponentNames().contains("dummy")); String json = catalog.componentJSonSchema("dummy"); assertNotNull(json); // validate we can parse the json ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.readTree(json); assertNotNull(tree); } @Test public void testAddComponentWithJson() throws Exception { String json = loadText(new FileInputStream("src/test/resources/org/foo/camel/dummy.json")); assertNotNull(json); catalog.addComponent("dummy", "org.foo.camel.DummyComponent", json); assertTrue(catalog.findComponentNames().contains("dummy")); json = catalog.componentJSonSchema("dummy"); assertNotNull(json); // validate we can parse the json ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.readTree(json); assertNotNull(tree); } @Test public void testAddComponentWithPrettyJson() throws Exception { String json = loadText(new FileInputStream("src/test/resources/org/foo/camel/dummy-pretty.json")); assertNotNull(json); catalog.addComponent("dummy", "org.foo.camel.DummyComponent", json); assertTrue(catalog.findComponentNames().contains("dummy")); json = catalog.componentJSonSchema("dummy"); assertNotNull(json); // validate we can parse the json ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.readTree(json); assertNotNull(tree); } @Test public void testAddDataFormat() throws Exception { catalog.addDataFormat("dummyformat", "org.foo.camel.DummyDataFormat"); assertTrue(catalog.findDataFormatNames().contains("dummyformat")); String json = catalog.dataFormatJSonSchema("dummyformat"); assertNotNull(json); // validate we can parse the json ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.readTree(json); assertNotNull(tree); } @Test public void testAddDataFormatWithJSon() throws Exception { String json = loadText(new FileInputStream("src/test/resources/org/foo/camel/dummyformat.json")); assertNotNull(json); catalog.addDataFormat("dummyformat", "org.foo.camel.DummyDataFormat", json); assertTrue(catalog.findDataFormatNames().contains("dummyformat")); json = catalog.dataFormatJSonSchema("dummyformat"); assertNotNull(json); // validate we can parse the json ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.readTree(json); assertNotNull(tree); } @Test public void testAddDataFormatWithPrettyJSon() throws Exception { String json = loadText(new FileInputStream("src/test/resources/org/foo/camel/dummyformat-pretty.json")); assertNotNull(json); catalog.addDataFormat("dummyformat", "org.foo.camel.DummyDataFormat", json); assertTrue(catalog.findDataFormatNames().contains("dummyformat")); json = catalog.dataFormatJSonSchema("dummyformat"); assertNotNull(json); // validate we can parse the json ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.readTree(json); assertNotNull(tree); } @Test public void testSimpleExpression() throws Exception { LanguageValidationResult result = catalog.validateLanguageExpression(null, "simple", "${body}"); assertTrue(result.isSuccess()); assertEquals("${body}", result.getText()); result = catalog.validateLanguageExpression(null, "simple", "${body"); assertFalse(result.isSuccess()); assertEquals("${body", result.getText()); LOG.info(result.getError()); assertTrue(result.getError().startsWith("expected symbol functionEnd but was eol at location 5")); assertEquals("expected symbol functionEnd but was eol", result.getShortError()); assertEquals(5, result.getIndex()); result = catalog.validateLanguageExpression(null, "simple", "${bodyxxx}"); assertFalse(result.isSuccess()); assertEquals("${bodyxxx}", result.getText()); LOG.info(result.getError()); assertEquals("Valid syntax: ${body.OGNL} was: bodyxxx", result.getShortError()); assertEquals(0, result.getIndex()); } @Test public void testSimplePredicate() throws Exception { LanguageValidationResult result = catalog.validateLanguagePredicate(null, "simple", "${body} == 'abc'"); assertTrue(result.isSuccess()); assertEquals("${body} == 'abc'", result.getText()); result = catalog.validateLanguagePredicate(null, "simple", "${body} > ${header.size"); assertFalse(result.isSuccess()); assertEquals("${body} > ${header.size", result.getText()); LOG.info(result.getError()); assertTrue(result.getError().startsWith("expected symbol functionEnd but was eol at location 22")); assertEquals("expected symbol functionEnd but was eol", result.getShortError()); assertEquals(22, result.getIndex()); } @Test public void testPredicatePlaceholder() throws Exception { LanguageValidationResult result = catalog.validateLanguagePredicate(null, "simple", "${body} contains '{{danger}}'"); assertTrue(result.isSuccess()); assertEquals("${body} contains '{{danger}}'", result.getText()); result = catalog.validateLanguagePredicate(null, "simple", "${bdy} contains '{{danger}}'"); assertFalse(result.isSuccess()); assertEquals("${bdy} contains '{{danger}}'", result.getText()); LOG.info(result.getError()); assertTrue(result.getError().startsWith("Unknown function: bdy at location 0")); assertTrue(result.getError().contains("'{{danger}}'")); assertEquals("Unknown function: bdy", result.getShortError()); assertEquals(0, result.getIndex()); } @Test public void testValidateLanguage() throws Exception { LanguageValidationResult result = catalog.validateLanguageExpression(null, "simple", "${body}"); assertTrue(result.isSuccess()); assertEquals("${body}", result.getText()); result = catalog.validateLanguageExpression(null, "header", "foo"); assertTrue(result.isSuccess()); assertEquals("foo", result.getText()); result = catalog.validateLanguagePredicate(null, "simple", "${body} > 10"); assertTrue(result.isSuccess()); assertEquals("${body} > 10", result.getText()); result = catalog.validateLanguagePredicate(null, "header", "bar"); assertTrue(result.isSuccess()); assertEquals("bar", result.getText()); result = catalog.validateLanguagePredicate(null, "foobar", "bar"); assertFalse(result.isSuccess()); assertEquals("Unknown language foobar", result.getError()); } @Test public void testValidateJSonPathLanguage() throws Exception { LanguageValidationResult result = catalog.validateLanguageExpression(null, "jsonpath", "$.store.book[?(@.price < 10)]"); assertTrue(result.isSuccess()); assertEquals("$.store.book[?(@.price < 10)]", result.getText()); result = catalog.validateLanguageExpression(null, "jsonpath", "$.store.book[?(@.price ^^^ 10)]"); assertFalse(result.isSuccess()); assertEquals("$.store.book[?(@.price ^^^ 10)]", result.getText()); assertEquals("Illegal syntax: $.store.book[?(@.price ^^^ 10)]", result.getError()); } @Test public void testSpringCamelContext() throws Exception { String json = catalog.modelJSonSchema("camelContext"); assertNotNull(json); // validate we can parse the json ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.readTree(json); assertNotNull(tree); assertTrue(json.contains("CamelContext using XML configuration")); } @Test public void testComponentAsciiDoc() throws Exception { String doc = catalog.componentAsciiDoc("mock"); assertNotNull(doc); assertTrue(doc.contains("mock:someName")); doc = catalog.componentAsciiDoc("geocoder"); assertNotNull(doc); assertTrue(doc.contains("looking up geocodes")); doc = catalog.componentAsciiDoc("smtp"); assertNotNull(doc); assertTrue(doc.contains("The mail component")); doc = catalog.componentAsciiDoc("unknown"); assertNull(doc); } @Test public void testTransactedAndPolicyNoOutputs() throws Exception { String json = catalog.modelJSonSchema("transacted"); assertNotNull(json); assertTrue(json.contains("\"output\": false")); assertFalse(json.contains("\"outputs\":")); json = catalog.modelJSonSchema("policy"); assertNotNull(json); assertTrue(json.contains("\"output\": false")); assertFalse(json.contains("\"outputs\":")); } @Test public void testDataFormatAsciiDoc() throws Exception { String doc = catalog.dataFormatAsciiDoc("json-jackson"); assertNotNull(doc); assertTrue(doc.contains("Jackson dataformat")); doc = catalog.dataFormatAsciiDoc("bindy-csv"); assertNotNull(doc); assertTrue(doc.contains("CsvRecord")); } @Test public void testLanguageAsciiDoc() throws Exception { String doc = catalog.languageAsciiDoc("jsonpath"); assertNotNull(doc); assertTrue(doc.contains("JSonPath language")); } @Test public void testOtherAsciiDoc() throws Exception { String doc = catalog.otherAsciiDoc("swagger-java"); assertNotNull(doc); assertTrue(doc.contains("Swagger")); } @Test public void testValidateEndpointTwitterSpecial() throws Exception { String uri = "twitter-search://java?{{%s}}"; EndpointValidationResult result = catalog.validateEndpointProperties(uri); assertTrue(result.isSuccess()); } @Test public void testValidateEndpointHttpPropertyPlaceholder() throws Exception { String uri = "http://api.openweathermap.org/data/2.5/weather?{{property.weatherUri}}"; EndpointValidationResult result = catalog.validateEndpointProperties(uri); assertTrue(result.isSuccess()); result = catalog.validateEndpointProperties(uri, true); assertTrue(result.isSuccess()); // use incorrect style using ${ } as placeholder uri = "http://api.openweathermap.org/data/2.5/weather?${property.weatherUri}"; result = catalog.validateEndpointProperties(uri); assertTrue(result.isSuccess()); result = catalog.validateEndpointProperties(uri, true); assertFalse(result.isSuccess()); assertEquals("${property.weatherUri}", result.getUnknown().iterator().next()); } @Test public void testValidateEndpointJmsDefault() throws Exception { String uri = "jms:cheese?maxMessagesPerTask=-1"; EndpointValidationResult result = catalog.validateEndpointProperties(uri); assertTrue(result.isSuccess()); assertEquals(1, result.getDefaultValues().size()); assertEquals("-1", result.getDefaultValues().get("maxMessagesPerTask")); } @Test public void testValidateEndpointConsumerOnly() throws Exception { String uri = "file:inbox?bufferSize=4096&readLock=changed&delete=true"; EndpointValidationResult result = catalog.validateEndpointProperties(uri, false, true, false); assertTrue(result.isSuccess()); uri = "file:inbox?bufferSize=4096&readLock=changed&delete=true&fileExist=Append"; result = catalog.validateEndpointProperties(uri, false, true, false); assertFalse(result.isSuccess()); assertEquals("fileExist", result.getNotConsumerOnly().iterator().next()); } @Test public void testValidateEndpointProducerOnly() throws Exception { String uri = "file:outbox?bufferSize=4096&fileExist=Append"; EndpointValidationResult result = catalog.validateEndpointProperties(uri, false, false, true); assertTrue(result.isSuccess()); uri = "file:outbox?bufferSize=4096&fileExist=Append&delete=true"; result = catalog.validateEndpointProperties(uri, false, false, true); assertFalse(result.isSuccess()); assertEquals("delete", result.getNotProducerOnly().iterator().next()); } @Test public void testNettyHttpDynamicToIssue() throws Exception { String uri = "netty-http:http://10.192.1.10:8080/client/alerts/summary?throwExceptionOnFailure=false"; Map<String, String> params = catalog.endpointProperties(uri); params.remove("path"); params.remove("throwExceptionOnFailure"); String resolved = catalog.asEndpointUri("netty-http", params, false); assertEquals("netty-http:http:10.192.1.10:8080", resolved); // another example with dash in hostname uri = "netty-http:http://a-b-c.hostname.tld:8080/anything"; params = catalog.endpointProperties(uri); resolved = catalog.asEndpointUri("netty-http", params, false); assertEquals("netty-http:http:a-b-c.hostname.tld:8080/anything", resolved); } @Test public void testJSonSchemaHelper() throws Exception { String json = loadText(new FileInputStream("src/test/resources/org/foo/camel/dummy.json")); assertNotNull(json); // component List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("component", json, false); assertEquals(12, rows.size()); assertTrue(JSonSchemaHelper.isComponentProducerOnly(rows)); assertFalse(JSonSchemaHelper.isComponentConsumerOnly(rows)); String desc = null; for (Map<String, String> row : rows) { if (row.containsKey("description")) { desc = row.get("description"); break; } } assertEquals("The dummy component logs message exchanges to the underlying logging mechanism.", desc); // componentProperties rows = JSonSchemaHelper.parseJsonSchema("componentProperties", json, true); assertEquals(1, rows.size()); Map<String, String> row = JSonSchemaHelper.getRow(rows, "exchangeFormatter"); assertNotNull(row); assertEquals("org.apache.camel.spi.ExchangeFormatter", row.get("javaType")); assertEquals("Exchange Formatter", row.get("displayName")); // properties rows = JSonSchemaHelper.parseJsonSchema("properties", json, true); assertEquals(31, rows.size()); row = JSonSchemaHelper.getRow(rows, "level"); assertNotNull(row); assertEquals("INFO", row.get("defaultValue")); String enums = JSonSchemaHelper.getPropertyEnum(rows, "level"); assertEquals("ERROR,WARN,INFO,DEBUG,TRACE,OFF", enums); assertEquals("Level", row.get("displayName")); row = JSonSchemaHelper.getRow(rows, "amount"); assertNotNull(row); assertEquals("1", row.get("defaultValue")); assertEquals("Number of drinks in the order", row.get("description")); assertEquals("Amount", row.get("displayName")); row = JSonSchemaHelper.getRow(rows, "maxChars"); assertNotNull(row); assertEquals("false", row.get("deprecated")); assertEquals("10000", row.get("defaultValue")); assertEquals("Max Chars", row.get("displayName")); row = JSonSchemaHelper.getRow(rows, "repeatCount"); assertNotNull(row); assertEquals("long", row.get("javaType")); assertEquals("0", row.get("defaultValue")); assertEquals("Repeat Count", row.get("displayName")); row = JSonSchemaHelper.getRow(rows, "fontSize"); assertNotNull(row); assertEquals("false", row.get("deprecated")); assertEquals("14", row.get("defaultValue")); assertEquals("Font Size", row.get("displayName")); row = JSonSchemaHelper.getRow(rows, "kerberosRenewJitter"); assertNotNull(row); assertEquals("java.lang.Double", row.get("javaType")); assertEquals("0.05", row.get("defaultValue")); assertEquals("Kerberos Renew Jitter", row.get("displayName")); } }
/* * 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. */ // Contributors: Mathias Rupprecht <[email protected]> package org.apache.log4j.spi; import java.io.StringWriter; import java.io.PrintWriter; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.Layout; /** The internal representation of caller location information. @since 0.8.3 */ public class LocationInfo implements java.io.Serializable { /** Caller's line number. */ transient String lineNumber; /** Caller's file name. */ transient String fileName; /** Caller's fully qualified class name. */ transient String className; /** Caller's method name. */ transient String methodName; /** All available caller information, in the format <code>fully.qualified.classname.of.caller.methodName(Filename.java:line)</code> */ public String fullInfo; private static StringWriter sw = new StringWriter(); private static PrintWriter pw = new PrintWriter(sw); /** When location information is not available the constant <code>NA</code> is returned. Current value of this string constant is <b>?</b>. */ public final static String NA = "?"; static final long serialVersionUID = -1325822038990805636L; /** * NA_LOCATION_INFO is provided for compatibility with log4j 1.3. * @since 1.2.15 */ public static final LocationInfo NA_LOCATION_INFO = new LocationInfo(NA, NA, NA, NA); // Check if we are running in IBM's visual age. static boolean inVisualAge = false; static { try { inVisualAge = Class.forName("com.ibm.uvm.tools.DebugSupport") != null; LogLog.debug("Detected IBM VisualAge environment."); } catch(Throwable e) { // nothing to do } } /** Instantiate location information based on a Throwable. We expect the Throwable <code>t</code>, to be in the format <pre> java.lang.Throwable ... at org.apache.log4j.PatternLayout.format(PatternLayout.java:413) at org.apache.log4j.FileAppender.doAppend(FileAppender.java:183) at org.apache.log4j.Category.callAppenders(Category.java:131) at org.apache.log4j.Category.log(Category.java:512) at callers.fully.qualified.className.methodName(FileName.java:74) ... </pre> <p>However, we can also deal with JIT compilers that "lose" the location information, especially between the parentheses. */ public LocationInfo(Throwable t, String fqnOfCallingClass) { if(t == null || fqnOfCallingClass == null) return; String s; // Protect against multiple access to sw. synchronized(sw) { t.printStackTrace(pw); s = sw.toString(); sw.getBuffer().setLength(0); } //System.out.println("s is ["+s+"]."); int ibegin, iend; // Given the current structure of the package, the line // containing "org.apache.log4j.Category." should be printed just // before the caller. // This method of searching may not be fastest but it's safer // than counting the stack depth which is not guaranteed to be // constant across JVM implementations. ibegin = s.lastIndexOf(fqnOfCallingClass); if(ibegin == -1) return; ibegin = s.indexOf(Layout.LINE_SEP, ibegin); if(ibegin == -1) return; ibegin+= Layout.LINE_SEP_LEN; // determine end of line iend = s.indexOf(Layout.LINE_SEP, ibegin); if(iend == -1) return; // VA has a different stack trace format which doesn't // need to skip the inital 'at' if(!inVisualAge) { // back up to first blank character ibegin = s.lastIndexOf("at ", iend); if(ibegin == -1) return; // Add 3 to skip "at "; ibegin += 3; } // everything between is the requested stack item this.fullInfo = s.substring(ibegin, iend); } /** * Appends a location fragment to a buffer to build the * full location info. * @param buf StringBuffer to receive content. * @param fragment fragment of location (class, method, file, line), * if null the value of NA will be appended. * @since 1.2.15 */ private static final void appendFragment(final StringBuffer buf, final String fragment) { if (fragment == null) { buf.append(NA); } else { buf.append(fragment); } } /** * Create new instance. * @param file source file name * @param classname class name * @param method method * @param line source line number * * @since 1.2.15 */ public LocationInfo( final String file, final String classname, final String method, final String line) { this.fileName = file; this.className = classname; this.methodName = method; this.lineNumber = line; StringBuffer buf = new StringBuffer(); appendFragment(buf, classname); buf.append("."); appendFragment(buf, method); buf.append("("); appendFragment(buf, file); buf.append(":"); appendFragment(buf, line); buf.append(")"); this.fullInfo = buf.toString(); } /** Return the fully qualified class name of the caller making the logging request. */ public String getClassName() { if(fullInfo == null) return NA; if(className == null) { // Starting the search from '(' is safer because there is // potentially a dot between the parentheses. int iend = fullInfo.lastIndexOf('('); if(iend == -1) className = NA; else { iend =fullInfo.lastIndexOf('.', iend); // This is because a stack trace in VisualAge looks like: //java.lang.RuntimeException // java.lang.Throwable() // java.lang.Exception() // java.lang.RuntimeException() // void test.test.B.print() // void test.test.A.printIndirect() // void test.test.Run.main(java.lang.String []) int ibegin = 0; if (inVisualAge) { ibegin = fullInfo.lastIndexOf(' ', iend)+1; } if(iend == -1) className = NA; else className = this.fullInfo.substring(ibegin, iend); } } return className; } /** Return the file name of the caller. <p>This information is not always available. */ public String getFileName() { if(fullInfo == null) return NA; if(fileName == null) { int iend = fullInfo.lastIndexOf(':'); if(iend == -1) fileName = NA; else { int ibegin = fullInfo.lastIndexOf('(', iend - 1); fileName = this.fullInfo.substring(ibegin + 1, iend); } } return fileName; } /** Returns the line number of the caller. <p>This information is not always available. */ public String getLineNumber() { if(fullInfo == null) return NA; if(lineNumber == null) { int iend = fullInfo.lastIndexOf(')'); int ibegin = fullInfo.lastIndexOf(':', iend -1); if(ibegin == -1) lineNumber = NA; else lineNumber = this.fullInfo.substring(ibegin + 1, iend); } return lineNumber; } /** Returns the method name of the caller. */ public String getMethodName() { if(fullInfo == null) return NA; if(methodName == null) { int iend = fullInfo.lastIndexOf('('); int ibegin = fullInfo.lastIndexOf('.', iend); if(ibegin == -1) methodName = NA; else methodName = this.fullInfo.substring(ibegin + 1, iend); } return methodName; } }
/* * Copyright 2000-2013 JetBrains s.r.o. * * 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.siyeh.ig.bugs; import com.intellij.codeInspection.dataFlow.CommonDataflow; import com.intellij.codeInspection.dataFlow.TypeConstraint; import com.intellij.codeInspection.ui.ListTable; import com.intellij.codeInspection.ui.ListWrappingTableModel; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; import com.intellij.psi.*; import com.intellij.psi.util.ConstantExpressionUtil; import com.intellij.psi.util.PsiUtil; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.psiutils.ExpressionUtils; import com.siyeh.ig.psiutils.FormatUtils; import com.siyeh.ig.ui.UiUtils; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.ArrayList; import java.util.List; public class MalformedFormatStringInspection extends BaseInspection { final List<String> classNames; final List<String> methodNames; /** * @noinspection PublicField */ @NonNls public String additionalClasses = ""; /** * @noinspection PublicField */ @NonNls public String additionalMethods = ""; public MalformedFormatStringInspection() { classNames = new ArrayList<>(); methodNames = new ArrayList<>(); parseString(additionalClasses, classNames); parseString(additionalMethods, methodNames); } @Override public JComponent createOptionsPanel() { ListWrappingTableModel classTableModel = new ListWrappingTableModel(classNames, InspectionGadgetsBundle.message("string.format.class.column.name")); JPanel classChooserPanel = UiUtils .createAddRemoveTreeClassChooserPanel(new ListTable(classTableModel), InspectionGadgetsBundle.message("string.format.choose.class")); ListWrappingTableModel methodTableModel = new ListWrappingTableModel(methodNames, InspectionGadgetsBundle.message("string.format.class.method.name")); JPanel methodPanel = UiUtils.createAddRemovePanel(new ListTable(methodTableModel)); final JPanel panel = new JPanel(); BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.Y_AXIS); panel.setLayout(boxLayout); panel.add(classChooserPanel); panel.add(methodPanel); return panel; } @Override public void readSettings(@NotNull Element node) throws InvalidDataException { super.readSettings(node); parseString(additionalClasses, classNames); parseString(additionalMethods, methodNames); } @Override public void writeSettings(@NotNull Element node) throws WriteExternalException { additionalClasses = formatString(classNames); additionalMethods = formatString(methodNames); super.writeSettings(node); } @Override @NotNull public String buildErrorString(Object... infos) { final Object value = infos[0]; if (value instanceof Exception) { final Exception exception = (Exception)value; final String message = exception.getMessage(); if (message != null) { return InspectionGadgetsBundle.message("malformed.format.string.problem.descriptor.illegal", message); } return InspectionGadgetsBundle.message("malformed.format.string.problem.descriptor.malformed"); } final FormatDecode.Validator[] validators = (FormatDecode.Validator[])value; final int argumentCount = ((Integer)infos[1]).intValue(); if (validators.length < argumentCount) { return InspectionGadgetsBundle.message("malformed.format.string.problem.descriptor.too.many.arguments", argumentCount, validators.length); } if (validators.length > argumentCount) { return InspectionGadgetsBundle.message("malformed.format.string.problem.descriptor.too.few.arguments", argumentCount, validators.length); } final PsiType argumentType = (PsiType)infos[2]; final FormatDecode.Validator validator = (FormatDecode.Validator)infos[3]; return InspectionGadgetsBundle.message("malformed.format.string.problem.descriptor.arguments.do.not.match.type", argumentType.getPresentableText(), validator.getSpecifier()); } @Override public boolean isEnabledByDefault() { return true; } @Override public BaseInspectionVisitor buildVisitor() { return new MalformedFormatStringVisitor(); } private class MalformedFormatStringVisitor extends BaseInspectionVisitor { private int findFirstStringArgumentIndex(PsiExpression[] expressions) { for (int i = 0, length = expressions.length; i < length; i++) { final PsiExpression expression = expressions[i]; if (ExpressionUtils.hasStringType(expression)) { return i; } } return -1; } @Override public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) { super.visitMethodCallExpression(expression); final PsiExpressionList argumentList = expression.getArgumentList(); PsiExpression[] arguments = argumentList.getExpressions(); final PsiExpression formatArgument; int formatArgumentIndex; if (FormatUtils.STRING_FORMATTED.matches(expression)) { formatArgument = expression.getMethodExpression().getQualifierExpression(); formatArgumentIndex = 0; } else { if (!FormatUtils.isFormatCall(expression, methodNames, classNames)) { return; } formatArgumentIndex = findFirstStringArgumentIndex(arguments); if (formatArgumentIndex < 0) { return; } formatArgument = arguments[formatArgumentIndex]; formatArgumentIndex++; } if (!ExpressionUtils.hasStringType(formatArgument) || !PsiUtil.isConstantExpression(formatArgument)) { return; } final PsiType formatType = formatArgument.getType(); if (formatType == null) { return; } final String value = (String)ConstantExpressionUtil.computeCastTo(formatArgument, formatType); if (value == null) { return; } int argumentCount = arguments.length - formatArgumentIndex; final FormatDecode.Validator[] validators; try { validators = FormatDecode.decode(value, argumentCount); } catch (FormatDecode.IllegalFormatException e) { registerError(formatArgument, e); return; } if (argumentCount == 1) { final PsiExpression argument = resolveIfPossible(arguments[formatArgumentIndex]); final PsiType argumentType = argument.getType(); if (argumentType instanceof PsiArrayType) { final PsiArrayInitializerExpression arrayInitializer; if (argument instanceof PsiNewExpression) { final PsiNewExpression newExpression = (PsiNewExpression)argument; arrayInitializer = newExpression.getArrayInitializer(); } else if (argument instanceof PsiArrayInitializerExpression) { arrayInitializer = (PsiArrayInitializerExpression)argument; } else { return; } if (arrayInitializer == null) { return; } arguments = arrayInitializer.getInitializers(); argumentCount = arguments.length; formatArgumentIndex = 0; } } if (validators.length != argumentCount) { registerMethodCallError(expression, validators, Integer.valueOf(argumentCount)); return; } for (int i = 0; i < validators.length; i++) { final FormatDecode.Validator validator = validators[i]; final PsiExpression argument = arguments[i + formatArgumentIndex]; final PsiType argumentType = argument.getType(); if (argumentType == null) { continue; } if (validator != null && !validator.valid(argumentType)) { PsiType preciseType = TypeConstraint.fromDfType(CommonDataflow.getDfType(argument)).getPsiType(expression.getProject()); if (preciseType == null || !validator.valid(preciseType)) { registerError(argument, validators, Integer.valueOf(argumentCount), argumentType, validator); } } } } private PsiExpression resolveIfPossible(PsiExpression expression) { expression = PsiUtil.skipParenthesizedExprDown(expression); if (expression instanceof PsiReferenceExpression) { final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)expression; final PsiElement target = referenceExpression.resolve(); if (target instanceof PsiVariable && target.getContainingFile() == expression.getContainingFile()) { final PsiVariable variable = (PsiVariable)target; final PsiExpression initializer = variable.getInitializer(); if (initializer != null) { return initializer; } } } return expression; } } }
/* * Copyright 1995-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ /*- * Reads GIF images from an InputStream and reports the * image data to an InputStreamImageSource object. * * The algorithm is copyright of CompuServe. */ package sun.awt.image; import java.util.Vector; import java.util.Hashtable; import java.io.InputStream; import java.io.IOException; import java.awt.image.*; /** * Gif Image converter * * @version 1.62 05/05/07 * @author Arthur van Hoff * @author Jim Graham */ public class GifImageDecoder extends ImageDecoder { private static final boolean verbose = false; private static final int IMAGESEP = 0x2c; private static final int EXBLOCK = 0x21; private static final int EX_GRAPHICS_CONTROL = 0xf9; private static final int EX_COMMENT = 0xfe; private static final int EX_APPLICATION = 0xff; private static final int TERMINATOR = 0x3b; private static final int TRANSPARENCYMASK = 0x01; private static final int INTERLACEMASK = 0x40; private static final int COLORMAPMASK = 0x80; int num_global_colors; byte[] global_colormap; int trans_pixel = -1; IndexColorModel global_model; Hashtable props = new Hashtable(); byte[] saved_image; IndexColorModel saved_model; int global_width; int global_height; int global_bgpixel; GifFrame curframe; public GifImageDecoder(InputStreamImageSource src, InputStream is) { super (src, is); } /** * An error has occurred. Throw an exception. */ private static void error(String s1) throws ImageFormatException { throw new ImageFormatException(s1); } /** * Read a number of bytes into a buffer. * @return number of bytes that were not read due to EOF or error */ private int readBytes(byte buf[], int off, int len) { while (len > 0) { try { int n = input.read(buf, off, len); if (n < 0) { break; } off += n; len -= n; } catch (IOException e) { break; } } return len; } private static final int ExtractByte(byte buf[], int off) { return (buf[off] & 0xFF); } private static final int ExtractWord(byte buf[], int off) { return (buf[off] & 0xFF) | ((buf[off + 1] & 0xFF) << 8); } /** * produce an image from the stream. */ public void produceImage() throws IOException, ImageFormatException { try { readHeader(); int totalframes = 0; int frameno = 0; int nloops = -1; int disposal_method = 0; int delay = -1; boolean loopsRead = false; boolean isAnimation = false; while (!aborted) { int code; switch (code = input.read()) { case EXBLOCK: switch (code = input.read()) { case EX_GRAPHICS_CONTROL: { byte buf[] = new byte[6]; if (readBytes(buf, 0, 6) != 0) { return;//error("corrupt GIF file"); } if ((buf[0] != 4) || (buf[5] != 0)) { return;//error("corrupt GIF file (GCE size)"); } // Get the index of the transparent color delay = ExtractWord(buf, 2) * 10; if (delay > 0 && !isAnimation) { isAnimation = true; ImageFetcher.startingAnimation(); } disposal_method = (buf[1] >> 2) & 7; if ((buf[1] & TRANSPARENCYMASK) != 0) { trans_pixel = ExtractByte(buf, 4); } else { trans_pixel = -1; } break; } case EX_COMMENT: case EX_APPLICATION: default: boolean loop_tag = false; String comment = ""; while (true) { int n = input.read(); if (n <= 0) { break; } byte buf[] = new byte[n]; if (readBytes(buf, 0, n) != 0) { return;//error("corrupt GIF file"); } if (code == EX_COMMENT) { comment += new String(buf, 0); } else if (code == EX_APPLICATION) { if (loop_tag) { if (n == 3 && buf[0] == 1) { if (loopsRead) { ExtractWord(buf, 1); } else { nloops = ExtractWord(buf, 1); loopsRead = true; } } else { loop_tag = false; } } if ("NETSCAPE2.0".equals(new String( buf, 0))) { loop_tag = true; } } } if (code == EX_COMMENT) { props.put("comment", comment); } if (loop_tag && !isAnimation) { isAnimation = true; ImageFetcher.startingAnimation(); } break; case -1: return; //error("corrupt GIF file"); } break; case IMAGESEP: if (!isAnimation) { input.mark(0); // we don't need the mark buffer } try { if (!readImage(totalframes == 0, disposal_method, delay)) { return; } } catch (Exception e) { if (verbose) { e.printStackTrace(); } return; } frameno++; totalframes++; break; default: case -1: if (verbose) { if (code == -1) { System.err .println("Premature EOF in GIF file," + " frame " + frameno); } else { System.err .println("corrupt GIF file (parse) [" + code + "]."); } } if (frameno == 0) { return; } // NOBREAK case TERMINATOR: if (nloops == 0 || nloops-- >= 0) { try { if (curframe != null) { curframe.dispose(); curframe = null; } input.reset(); saved_image = null; saved_model = null; frameno = 0; break; } catch (IOException e) { return; // Unable to reset input buffer } } if (verbose && frameno != 1) { System.out.println("processing GIF terminator," + " frames: " + frameno + " total: " + totalframes); } imageComplete(ImageConsumer.STATICIMAGEDONE, true); return; } } } finally { close(); } } /** * Read Image header */ private void readHeader() throws IOException, ImageFormatException { // Create a buffer byte buf[] = new byte[13]; // Read the header if (readBytes(buf, 0, 13) != 0) { throw new IOException(); } // Check header if ((buf[0] != 'G') || (buf[1] != 'I') || (buf[2] != 'F')) { error("not a GIF file."); } // Global width&height global_width = ExtractWord(buf, 6); global_height = ExtractWord(buf, 8); // colormap info int ch = ExtractByte(buf, 10); if ((ch & COLORMAPMASK) == 0) { // no global colormap so make up our own // If there is a local colormap, it will override what we // have here. If there is not a local colormap, the rules // for GIF89 say that we can use whatever colormap we want. // This means that we should probably put in a full 256 colormap // at some point. REMIND! num_global_colors = 2; global_bgpixel = 0; global_colormap = new byte[2 * 3]; global_colormap[0] = global_colormap[1] = global_colormap[2] = (byte) 0; global_colormap[3] = global_colormap[4] = global_colormap[5] = (byte) 255; } else { num_global_colors = 1 << ((ch & 0x7) + 1); global_bgpixel = ExtractByte(buf, 11); if (buf[12] != 0) { props.put("aspectratio", "" + ((ExtractByte(buf, 12) + 15) / 64.0)); } // Read colors global_colormap = new byte[num_global_colors * 3]; if (readBytes(global_colormap, 0, num_global_colors * 3) != 0) { throw new IOException(); } } input.mark(Integer.MAX_VALUE); // set this mark in case this is an animated GIF } /** * The ImageConsumer hints flag for a non-interlaced GIF image. */ private static final int normalflags = ImageConsumer.TOPDOWNLEFTRIGHT | ImageConsumer.COMPLETESCANLINES | ImageConsumer.SINGLEPASS | ImageConsumer.SINGLEFRAME; /** * The ImageConsumer hints flag for an interlaced GIF image. */ private static final int interlaceflags = ImageConsumer.RANDOMPIXELORDER | ImageConsumer.COMPLETESCANLINES | ImageConsumer.SINGLEPASS | ImageConsumer.SINGLEFRAME; private short prefix[] = new short[4096]; private byte suffix[] = new byte[4096]; private byte outCode[] = new byte[4097]; private static native void initIDs(); static { /* ensure that the necessary native libraries are loaded */ NativeLibLoader.loadLibraries(); initIDs(); } private native boolean parseImage(int x, int y, int width, int height, boolean interlace, int initCodeSize, byte block[], byte rasline[], IndexColorModel model); private int sendPixels(int x, int y, int width, int height, byte rasline[], ColorModel model) { int rasbeg, rasend, x2; if (y < 0) { height += y; y = 0; } if (y + height > global_height) { height = global_height - y; } if (height <= 0) { return 1; } // rasline[0] == pixel at coordinate (x,y) // rasline[width] == pixel at coordinate (x+width, y) if (x < 0) { rasbeg = -x; width += x; // same as (width -= rasbeg) x2 = 0; // same as (x2 = x + rasbeg) } else { rasbeg = 0; // width -= 0; // same as (width -= rasbeg) x2 = x; // same as (x2 = x + rasbeg) } // rasline[rasbeg] == pixel at coordinate (x2,y) // rasline[width] == pixel at coordinate (x+width, y) // rasline[rasbeg + width] == pixel at coordinate (x2+width, y) if (x2 + width > global_width) { width = global_width - x2; } if (width <= 0) { return 1; } rasend = rasbeg + width; // rasline[rasbeg] == pixel at coordinate (x2,y) // rasline[rasend] == pixel at coordinate (x2+width, y) int off = y * global_width + x2; boolean save = (curframe.disposal_method == GifFrame.DISPOSAL_SAVE); if (trans_pixel >= 0 && !curframe.initialframe) { if (saved_image != null && model.equals(saved_model)) { for (int i = rasbeg; i < rasend; i++, off++) { byte pixel = rasline[i]; if ((pixel & 0xff) == trans_pixel) { rasline[i] = saved_image[off]; } else if (save) { saved_image[off] = pixel; } } } else { // We have to do this the hard way - only transmit // the non-transparent sections of the line... // Fix for 6301050: the interlacing is ignored in this case // in order to avoid artefacts in case of animated images. int runstart = -1; int count = 1; for (int i = rasbeg; i < rasend; i++, off++) { byte pixel = rasline[i]; if ((pixel & 0xff) == trans_pixel) { if (runstart >= 0) { count = setPixels(x + runstart, y, i - runstart, 1, model, rasline, runstart, 0); if (count == 0) { break; } } runstart = -1; } else { if (runstart < 0) { runstart = i; } if (save) { saved_image[off] = pixel; } } } if (runstart >= 0) { count = setPixels(x + runstart, y, rasend - runstart, 1, model, rasline, runstart, 0); } return count; } } else if (save) { System.arraycopy(rasline, rasbeg, saved_image, off, width); } int count = setPixels(x2, y, width, height, model, rasline, rasbeg, 0); return count; } /** * Read Image data */ private boolean readImage(boolean first, int disposal_method, int delay) throws IOException { if (curframe != null && !curframe.dispose()) { abort(); return false; } long tm = 0; if (verbose) { tm = System.currentTimeMillis(); } // Allocate the buffer byte block[] = new byte[256 + 3]; // Read the image descriptor if (readBytes(block, 0, 10) != 0) { throw new IOException(); } int x = ExtractWord(block, 0); int y = ExtractWord(block, 2); int width = ExtractWord(block, 4); int height = ExtractWord(block, 6); /* * Majority of gif images have * same logical screen and frame dimensions. * Also, Photoshop and Mozilla seem to use the logical * screen dimension (from the global stream header) * if frame dimension is invalid. * * We use similar heuristic and trying to recover * frame width from logical screen dimension and * frame offset. */ if (width == 0 && global_width != 0) { width = global_width - x; } if (height == 0 && global_height != 0) { height = global_height - y; } boolean interlace = (block[8] & INTERLACEMASK) != 0; IndexColorModel model = global_model; if ((block[8] & COLORMAPMASK) != 0) { // We read one extra byte above so now when we must // transfer that byte as the first colormap byte // and manually read the code size when we are done int num_local_colors = 1 << ((block[8] & 0x7) + 1); // Read local colors byte[] local_colormap = new byte[num_local_colors * 3]; local_colormap[0] = block[9]; if (readBytes(local_colormap, 1, num_local_colors * 3 - 1) != 0) { throw new IOException(); } // Now read the "real" code size byte which follows // the local color table if (readBytes(block, 9, 1) != 0) { throw new IOException(); } if (trans_pixel >= num_local_colors) { // Fix for 4233748: extend colormap to contain transparent pixel num_local_colors = trans_pixel + 1; local_colormap = grow_colormap(local_colormap, num_local_colors); } model = new IndexColorModel(8, num_local_colors, local_colormap, 0, false, trans_pixel); } else if (model == null || trans_pixel != model.getTransparentPixel()) { if (trans_pixel >= num_global_colors) { // Fix for 4233748: extend colormap to contain transparent pixel num_global_colors = trans_pixel + 1; global_colormap = grow_colormap(global_colormap, num_global_colors); } model = new IndexColorModel(8, num_global_colors, global_colormap, 0, false, trans_pixel); global_model = model; } // Notify the consumers if (first) { if (global_width == 0) global_width = width; if (global_height == 0) global_height = height; setDimensions(global_width, global_height); setProperties(props); setColorModel(model); headerComplete(); } if (disposal_method == GifFrame.DISPOSAL_SAVE && saved_image == null) { saved_image = new byte[global_width * global_height]; /* * If height of current image is smaller than the global height, * fill the gap with transparent pixels. */ if ((height < global_height) && (model != null)) { byte tpix = (byte) model.getTransparentPixel(); if (tpix >= 0) { byte trans_rasline[] = new byte[global_width]; for (int i = 0; i < global_width; i++) { trans_rasline[i] = tpix; } setPixels(0, 0, global_width, y, model, trans_rasline, 0, 0); setPixels(0, y + height, global_width, global_height - height - y, model, trans_rasline, 0, 0); } } } int hints = (interlace ? interlaceflags : normalflags); setHints(hints); curframe = new GifFrame(this , disposal_method, delay, (curframe == null), model, x, y, width, height); // allocate the raster data byte rasline[] = new byte[width]; if (verbose) { System.out.print("Reading a " + width + " by " + height + " " + (interlace ? "" : "non-") + "interlaced image..."); } boolean ret = parseImage(x, y, width, height, interlace, ExtractByte(block, 9), block, rasline, model); if (!ret) { abort(); } if (verbose) { System.out.println("done in " + (System.currentTimeMillis() - tm) + "ms"); } return ret; } public static byte[] grow_colormap(byte[] colormap, int newlen) { byte[] newcm = new byte[newlen * 3]; System.arraycopy(colormap, 0, newcm, 0, colormap.length); return newcm; } } class GifFrame { private static final boolean verbose = false; private static IndexColorModel trans_model; static final int DISPOSAL_NONE = 0x00; static final int DISPOSAL_SAVE = 0x01; static final int DISPOSAL_BGCOLOR = 0x02; static final int DISPOSAL_PREVIOUS = 0x03; GifImageDecoder decoder; int disposal_method; int delay; IndexColorModel model; int x; int y; int width; int height; boolean initialframe; public GifFrame(GifImageDecoder id, int dm, int dl, boolean init, IndexColorModel cm, int x, int y, int w, int h) { this .decoder = id; this .disposal_method = dm; this .delay = dl; this .model = cm; this .initialframe = init; this .x = x; this .y = y; this .width = w; this .height = h; } private void setPixels(int x, int y, int w, int h, ColorModel cm, byte[] pix, int off, int scan) { decoder.setPixels(x, y, w, h, cm, pix, off, scan); } public boolean dispose() { if (decoder.imageComplete(ImageConsumer.SINGLEFRAMEDONE, false) == 0) { return false; } else { if (delay > 0) { try { if (verbose) { System.out.println("sleeping: " + delay); } Thread.sleep(delay); } catch (InterruptedException e) { return false; } } else { Thread.yield(); } if (verbose && disposal_method != 0) { System.out.println("disposal method: " + disposal_method); } int global_width = decoder.global_width; int global_height = decoder.global_height; if (x < 0) { width += x; x = 0; } if (x + width > global_width) { width = global_width - x; } if (width <= 0) { disposal_method = DISPOSAL_NONE; } else { if (y < 0) { height += y; y = 0; } if (y + height > global_height) { height = global_height - y; } if (height <= 0) { disposal_method = DISPOSAL_NONE; } } switch (disposal_method) { case DISPOSAL_PREVIOUS: byte[] saved_image = decoder.saved_image; IndexColorModel saved_model = decoder.saved_model; if (saved_image != null) { setPixels(x, y, width, height, saved_model, saved_image, y * global_width + x, global_width); } break; case DISPOSAL_BGCOLOR: byte tpix; if (model.getTransparentPixel() < 0) { model = trans_model; if (model == null) { model = new IndexColorModel(8, 1, new byte[4], 0, true); trans_model = model; } tpix = 0; } else { tpix = (byte) model.getTransparentPixel(); } byte[] rasline = new byte[width]; if (tpix != 0) { for (int i = 0; i < width; i++) { rasline[i] = tpix; } } // clear saved_image using transparent pixels // this will be used as the background in the next display if (decoder.saved_image != null) { for (int i = 0; i < global_width * global_height; i++) decoder.saved_image[i] = tpix; } setPixels(x, y, width, height, model, rasline, 0, 0); break; case DISPOSAL_SAVE: decoder.saved_model = model; break; } } return true; } }
/* * File: LinearVectorScalarFunctionTest.java * Authors: Justin Basilico * Company: Sandia National Laboratories * Project: Cognitive Foundry * * Copyright December 3, 2007, Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000, there is a non-exclusive license for use of this work by * or on behalf of the U.S. Government. Export of this program may require a * license from the United States Government. See CopyrightHistory.txt for * complete details. * */ package gov.sandia.cognition.learning.function.scalar; import gov.sandia.cognition.math.matrix.DimensionalityMismatchException; import gov.sandia.cognition.math.matrix.Vector; import gov.sandia.cognition.math.matrix.mtj.Vector2; import gov.sandia.cognition.math.matrix.mtj.Vector3; import java.util.Random; import junit.framework.TestCase; /** * This class implements JUnit tests for the following classes: * * LinearVectorScalarFunction * * @author Justin Basilico */ public class LinearVectorScalarFunctionTest extends TestCase { public final Random RANDOM = new Random(1); public LinearVectorScalarFunctionTest( String testName) { super(testName); } public void testConstants() { assertEquals(0.0, LinearVectorScalarFunction.DEFAULT_BIAS); } public void testConstructors() { LinearVectorScalarFunction instance = new LinearVectorScalarFunction(); assertNull(instance.getWeights()); assertEquals(0.0, instance.getBias()); Vector weights = Vector3.createRandom(RANDOM); double bias = RANDOM.nextGaussian(); instance = new LinearVectorScalarFunction(weights, bias); assertEquals(weights, instance.getWeights()); assertEquals(bias, instance.getBias()); LinearVectorScalarFunction copy = new LinearVectorScalarFunction(instance); assertEquals(instance.getWeights(), copy.getWeights()); assertNotSame(instance.getWeights(), copy.getWeights()); assertEquals(instance.getBias(), copy.getBias()); instance = new LinearVectorScalarFunction(); copy = new LinearVectorScalarFunction(instance); assertEquals(instance.getWeights(), copy.getWeights()); assertNull(copy.getWeights()); assertEquals(instance.getBias(), copy.getBias()); } /** * Test of clone method, of class LinearVectorScalarFunction. */ public void testClone() { LinearVectorScalarFunction instance = new LinearVectorScalarFunction( new Vector3(1.0, 0.0, -2.0), 4.0); LinearVectorScalarFunction clone = instance.clone(); assertNotSame(instance, clone); assertEquals(instance.getWeights(), clone.getWeights()); assertEquals(instance.getBias(), clone.getBias()); instance = new LinearVectorScalarFunction(); clone = instance.clone(); assertNotSame(instance, clone); assertEquals(instance.getWeights(), clone.getWeights()); assertEquals(instance.getBias(), clone.getBias()); } /** * Test of evaluate method, of class LinearVectorScalarFunction. */ public void testEvaluate() { LinearVectorScalarFunction instance = new LinearVectorScalarFunction( new Vector3(1.0, 0.0, -2.0), 4.0); Vector input = new Vector3(1.0, 1.0, 1.0); double output = 3.0; assertEquals(output, instance.evaluate(input)); input = new Vector3(0.0, 7.0, 3.0); output = -2.0; assertEquals(output, instance.evaluate(input)); input = new Vector3(0.0, 0.0, 0.0); output = 4.0; assertEquals(output, instance.evaluate(input)); boolean exceptionThrown = false; try { instance.evaluate(null); } catch ( NullPointerException e ) { exceptionThrown = true; } finally { assertTrue(exceptionThrown); } exceptionThrown = false; try { instance.evaluate(new Vector2(1.0, 2.0)); } catch ( DimensionalityMismatchException e ) { exceptionThrown = true; } finally { assertTrue(exceptionThrown); } } /** * Test of evaluateAsDouble method, of class LinearVectorScalarFunction. */ public void testEvaluateAsDouble() { LinearVectorScalarFunction instance = new LinearVectorScalarFunction( new Vector3(1.0, 0.0, -2.0), 4.0); Vector input = new Vector3(1.0, 1.0, 1.0); double output = 3.0; assertEquals(output, instance.evaluateAsDouble(input)); input = new Vector3(0.0, 7.0, 3.0); output = -2.0; assertEquals(output, instance.evaluateAsDouble(input)); input = new Vector3(0.0, 0.0, 0.0); output = 4.0; assertEquals(output, instance.evaluateAsDouble(input)); boolean exceptionThrown = false; try { instance.evaluateAsDouble(null); } catch ( NullPointerException e ) { exceptionThrown = true; } finally { assertTrue(exceptionThrown); } exceptionThrown = false; try { instance.evaluateAsDouble(new Vector2(1.0, 2.0)); } catch ( DimensionalityMismatchException e ) { exceptionThrown = true; } finally { assertTrue(exceptionThrown); } instance = new LinearVectorScalarFunction(); assertEquals(0.0, instance.evaluateAsDouble(input), 0.0); instance.setBias(3.4); assertEquals(3.4, instance.evaluateAsDouble(input), 0.0); } /** * Test of getWeights method, of class LinearVectorScalarFunction. */ public void testGetWeights() { this.testSetWeights(); } /** * Test of setWeights method, of class LinearVectorScalarFunction. */ public void testSetWeights() { Vector weights = null; LinearVectorScalarFunction instance = new LinearVectorScalarFunction(); assertNull(instance.getWeights()); weights = new Vector3(); instance.setWeights(weights); assertSame(weights, instance.getWeights()); weights = Vector3.createRandom(RANDOM); instance.setWeights(weights); assertSame(weights, instance.getWeights()); weights = null; instance.setWeights(weights); assertNull(weights); } /** * Test of getBias method, of class LinearVectorScalarFunction. */ public void testGetBias() { this.testSetBias(); } /** * Test of setBias method, of class LinearVectorScalarFunction. */ public void testSetBias() { double bias = 0.0; LinearVectorScalarFunction instance = new LinearVectorScalarFunction(); assertEquals(bias, instance.getBias()); bias = 4.0; instance.setBias(bias); assertEquals(bias, instance.getBias()); bias = -7.0; instance.setBias(bias); assertEquals(bias, instance.getBias()); bias = 0.0; instance.setBias(bias); assertEquals(bias, instance.getBias()); } /** * Test of toString method, of class LinearVectorScalarFunction. */ public void testToString() { LinearVectorScalarFunction instance = new LinearVectorScalarFunction(); assertNotNull(instance.toString()); } }
/* * 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.zeppelin.interpreter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * InterpreterOutput is OutputStream that supposed to print content on notebook * in addition to InterpreterResult which used to return from Interpreter.interpret(). */ public class InterpreterOutput extends OutputStream { Logger logger = LoggerFactory.getLogger(InterpreterOutput.class); private final int NEW_LINE_CHAR = '\n'; private final int LINE_FEED_CHAR = '\r'; private List<InterpreterResultMessageOutput> resultMessageOutputs = new LinkedList<>(); private InterpreterResultMessageOutput currentOut; private List<String> resourceSearchPaths = Collections.synchronizedList(new LinkedList<String>()); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private final InterpreterOutputListener flushListener; private final InterpreterOutputChangeListener changeListener; private int size = 0; private int lastCRIndex = -1; // change static var to set interpreter output limit // limit will be applied to all InterpreterOutput object. // so we can expect the consistent behavior public static int limit = Constants.ZEPPELIN_INTERPRETER_OUTPUT_LIMIT; public InterpreterOutput(InterpreterOutputListener flushListener) { this.flushListener = flushListener; changeListener = null; clear(); } public InterpreterOutput(InterpreterOutputListener flushListener, InterpreterOutputChangeListener listener) throws IOException { this.flushListener = flushListener; this.changeListener = listener; clear(); } public void setType(InterpreterResult.Type type) throws IOException { InterpreterResultMessageOutput out = null; synchronized (resultMessageOutputs) { int index = resultMessageOutputs.size(); InterpreterResultMessageOutputListener listener = createInterpreterResultMessageOutputListener(index); if (changeListener == null) { out = new InterpreterResultMessageOutput(type, listener); } else { out = new InterpreterResultMessageOutput(type, listener, changeListener); } out.setResourceSearchPaths(resourceSearchPaths); buffer.reset(); size = 0; lastCRIndex = -1; if (currentOut != null) { currentOut.flush(); } resultMessageOutputs.add(out); currentOut = out; } } public InterpreterResultMessageOutputListener createInterpreterResultMessageOutputListener( final int index) { return new InterpreterResultMessageOutputListener() { final int idx = index; @Override public void onAppend(InterpreterResultMessageOutput out, byte[] line) { if (flushListener != null) { flushListener.onAppend(idx, out, line); } } @Override public void onUpdate(InterpreterResultMessageOutput out) { if (flushListener != null) { flushListener.onUpdate(idx, out); } } }; } public List<InterpreterResultMessage> getInterpreterResultMessages() throws IOException { synchronized (resultMessageOutputs) { List<InterpreterResultMessage> resultMessages = new ArrayList<>(); for (InterpreterResultMessageOutput output : this.resultMessageOutputs) { resultMessages.add(output.toInterpreterResultMessage()); } return resultMessages; } } public InterpreterResultMessageOutput getCurrentOutput() { synchronized (resultMessageOutputs) { return currentOut; } } public InterpreterResultMessageOutput getOutputAt(int index) { synchronized (resultMessageOutputs) { return resultMessageOutputs.get(index); } } public int size() { synchronized (resultMessageOutputs) { return resultMessageOutputs.size(); } } public void clear() { size = 0; lastCRIndex = -1; truncated = false; buffer.reset(); synchronized (resultMessageOutputs) { for (InterpreterResultMessageOutput out : resultMessageOutputs) { out.clear(); try { out.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } // clear all ResultMessages resultMessageOutputs.clear(); currentOut = null; startOfTheNewLine = true; firstCharIsPercentSign = false; updateAllResultMessages(); } } private void updateAllResultMessages() { if (flushListener != null) { flushListener.onUpdateAll(this); } } int previousChar = 0; boolean startOfTheNewLine = true; boolean firstCharIsPercentSign = false; boolean truncated = false; @Override public void write(int b) throws IOException { InterpreterResultMessageOutput out; if (truncated) { return; } synchronized (resultMessageOutputs) { currentOut = getCurrentOutput(); if (++size > limit) { if (b == NEW_LINE_CHAR && currentOut != null) { InterpreterResult.Type type = currentOut.getType(); if (type == InterpreterResult.Type.TEXT || type == InterpreterResult.Type.TABLE) { setType(InterpreterResult.Type.HTML); getCurrentOutput().write(ResultMessages.getExceedsLimitSizeMessage(limit, "ZEPPELIN_INTERPRETER_OUTPUT_LIMIT").getData().getBytes()); truncated = true; return; } } } if (b == LINE_FEED_CHAR) { if (lastCRIndex == -1) { lastCRIndex = size; } // reset size to index of last carriage return size = lastCRIndex; } if (startOfTheNewLine) { if (b == '%') { startOfTheNewLine = false; firstCharIsPercentSign = true; buffer.write(b); previousChar = b; return; } else if (b != NEW_LINE_CHAR) { startOfTheNewLine = false; } } if (b == NEW_LINE_CHAR) { if (currentOut != null && currentOut.getType() == InterpreterResult.Type.TABLE) { if (previousChar == NEW_LINE_CHAR) { startOfTheNewLine = true; return; } } else { startOfTheNewLine = true; } } boolean flushBuffer = false; if (firstCharIsPercentSign) { if (b == ' ' || b == NEW_LINE_CHAR || b == '\t') { firstCharIsPercentSign = false; String displaySystem = buffer.toString(); for (InterpreterResult.Type type : InterpreterResult.Type.values()) { if (displaySystem.equals('%' + type.name().toLowerCase())) { // new type detected setType(type); previousChar = b; return; } } // not a defined display system flushBuffer = true; } else { buffer.write(b); previousChar = b; return; } } out = getCurrentOutputForWriting(); if (flushBuffer) { out.write(buffer.toByteArray()); buffer.reset(); } out.write(b); previousChar = b; } } private InterpreterResultMessageOutput getCurrentOutputForWriting() throws IOException { synchronized (resultMessageOutputs) { InterpreterResultMessageOutput out = getCurrentOutput(); if (out == null) { // add text type result message setType(InterpreterResult.Type.TEXT); out = getCurrentOutput(); } return out; } } @Override public void write(byte [] b) throws IOException { write(b, 0, b.length); } @Override public void write(byte [] b, int off, int len) throws IOException { for (int i = off; i < len; i++) { write(b[i]); } } /** * In dev mode, it monitors file and update ZeppelinServer * @param file * @throws IOException */ public void write(File file) throws IOException { InterpreterResultMessageOutput out = getCurrentOutputForWriting(); out.write(file); } public void write(String string) throws IOException { write(string.getBytes()); } /** * write contents in the resource file in the classpath * @param url * @throws IOException */ public void write(URL url) throws IOException { InterpreterResultMessageOutput out = getCurrentOutputForWriting(); out.write(url); } public void addResourceSearchPath(String path) { resourceSearchPaths.add(path); } public void writeResource(String resourceName) throws IOException { InterpreterResultMessageOutput out = getCurrentOutputForWriting(); out.writeResource(resourceName); } public List<InterpreterResultMessage> toInterpreterResultMessage() throws IOException { List<InterpreterResultMessage> list = new LinkedList<>(); synchronized (resultMessageOutputs) { for (InterpreterResultMessageOutput out : resultMessageOutputs) { list.add(out.toInterpreterResultMessage()); } } return list; } public void flush() throws IOException { InterpreterResultMessageOutput out = getCurrentOutput(); if (out != null) { out.flush(); } } public byte[] toByteArray() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); synchronized (resultMessageOutputs) { for (InterpreterResultMessageOutput m : resultMessageOutputs) { out.write(m.toByteArray()); } } return out.toByteArray(); } @Override public void close() throws IOException { synchronized (resultMessageOutputs) { for (InterpreterResultMessageOutput out : resultMessageOutputs) { out.close(); } } } }
package fr.jrds.snmpcodec.parsing; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import org.antlr.v4.runtime.Parser; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.TerminalNode; import fr.jrds.snmpcodec.MibException; import fr.jrds.snmpcodec.parsing.ASNParser.AccessContext; import fr.jrds.snmpcodec.parsing.ASNParser.AssignmentContext; import fr.jrds.snmpcodec.parsing.ASNParser.BitDescriptionContext; import fr.jrds.snmpcodec.parsing.ASNParser.BitsTypeContext; import fr.jrds.snmpcodec.parsing.ASNParser.BooleanValueContext; import fr.jrds.snmpcodec.parsing.ASNParser.ChoiceTypeContext; import fr.jrds.snmpcodec.parsing.ASNParser.ComplexAssignementContext; import fr.jrds.snmpcodec.parsing.ASNParser.ComplexAttributContext; import fr.jrds.snmpcodec.parsing.ASNParser.ConstraintContext; import fr.jrds.snmpcodec.parsing.ASNParser.ElementsContext; import fr.jrds.snmpcodec.parsing.ASNParser.EnterpriseAttributeContext; import fr.jrds.snmpcodec.parsing.ASNParser.IntegerTypeContext; import fr.jrds.snmpcodec.parsing.ASNParser.IntegerValueContext; import fr.jrds.snmpcodec.parsing.ASNParser.ModuleComplianceAssignementContext; import fr.jrds.snmpcodec.parsing.ASNParser.ModuleDefinitionContext; import fr.jrds.snmpcodec.parsing.ASNParser.ModuleIdentityAssignementContext; import fr.jrds.snmpcodec.parsing.ASNParser.ModuleRevisionContext; import fr.jrds.snmpcodec.parsing.ASNParser.ModuleRevisionsContext; import fr.jrds.snmpcodec.parsing.ASNParser.ObjIdComponentsListContext; import fr.jrds.snmpcodec.parsing.ASNParser.ObjectIdentifierValueContext; import fr.jrds.snmpcodec.parsing.ASNParser.ObjectTypeAssignementContext; import fr.jrds.snmpcodec.parsing.ASNParser.ReferencedTypeContext; import fr.jrds.snmpcodec.parsing.ASNParser.SequenceOfTypeContext; import fr.jrds.snmpcodec.parsing.ASNParser.SequenceTypeContext; import fr.jrds.snmpcodec.parsing.ASNParser.SizeConstraintContext; import fr.jrds.snmpcodec.parsing.ASNParser.StatusContext; import fr.jrds.snmpcodec.parsing.ASNParser.StringValueContext; import fr.jrds.snmpcodec.parsing.ASNParser.SymbolsFromModuleContext; import fr.jrds.snmpcodec.parsing.ASNParser.TextualConventionAssignementContext; import fr.jrds.snmpcodec.parsing.ASNParser.TrapTypeAssignementContext; import fr.jrds.snmpcodec.parsing.ASNParser.TypeAssignmentContext; import fr.jrds.snmpcodec.parsing.ASNParser.TypeContext; import fr.jrds.snmpcodec.parsing.ASNParser.ValueAssignmentContext; import fr.jrds.snmpcodec.parsing.MibObject.MappedObject; import fr.jrds.snmpcodec.parsing.MibObject.ModuleIdentityObject; import fr.jrds.snmpcodec.parsing.MibObject.ObjectTypeObject; import fr.jrds.snmpcodec.parsing.MibObject.OtherMacroObject; import fr.jrds.snmpcodec.parsing.MibObject.Revision; import fr.jrds.snmpcodec.parsing.MibObject.TextualConventionObject; import fr.jrds.snmpcodec.parsing.MibObject.TrapTypeObject; import fr.jrds.snmpcodec.parsing.ValueType.OidValue; import fr.jrds.snmpcodec.parsing.ValueType.StringValue; import fr.jrds.snmpcodec.smi.Constraint; import fr.jrds.snmpcodec.smi.Symbol; import fr.jrds.snmpcodec.smi.Syntax; public class ModuleListener extends ASNBaseListener { Parser parser; boolean firstError = true; private final Deque<Object> stack = new ArrayDeque<>(); private final Map<String, Symbol> symbols = new HashMap<>(); private final Map<String, String> importedFrom = new HashMap<>(); private String currentModule = null; final MibLoader store; ModuleListener(MibLoader store) { this.store = store; } Symbol resolveSymbol(String name) { Symbol newSymbol; if (importedFrom.containsKey(name)) { newSymbol = new Symbol(importedFrom.get(name), name); } else { newSymbol = new Symbol(currentModule, name); } symbols.put(name, newSymbol); return newSymbol; } private Number fitNumber(BigInteger v) { Number finalV = null; int bitLength = v.bitLength(); if (bitLength < 7) { finalV = Byte.valueOf((byte) v.intValue()); } else if (bitLength < 15) { finalV = Short.valueOf((short)v.intValue()); } else if (bitLength < 31) { finalV = Integer.valueOf((int)v.intValue()); } else if (bitLength < 63) { finalV = Long.valueOf((long)v.longValue()); } else { finalV = v; } return finalV; } @Override public void enterModuleDefinition(ModuleDefinitionContext ctx) { currentModule = ctx.IDENTIFIER().getText(); symbols.clear(); //The root symbols are often forgotten Symbol ccitt = new Symbol("ccitt"); Symbol iso = new Symbol("iso"); Symbol joint = new Symbol("joint-iso-ccitt"); symbols.put(ccitt.name, ccitt); symbols.put(iso.name, iso); symbols.put(joint.name, joint); importedFrom.clear(); try { store.newModule(currentModule); } catch (MibException e) { parser.notifyErrorListeners(ctx.start, e.getMessage(), new WrappedException(e, parser, parser.getInputStream(), ctx)); } } @Override public void enterSymbolsFromModule(SymbolsFromModuleContext ctx) { ctx.symbolList().symbol().stream() .forEach( i-> { String name = i.getText(); String module = ctx.globalModuleReference().getText(); importedFrom.put(name, module); symbols.put(name, new Symbol(module, name)); }); } /**************************************** * Manage assignments and push them on stack * assignments: objectTypeAssignement, valueAssignment, typeAssignment, textualConventionAssignement, macroAssignement ***************************************/ @Override public void enterAssignment(AssignmentContext ctx) { stack.clear(); stack.push(resolveSymbol(ctx.identifier.getText())); } @Override public void enterComplexAssignement(ComplexAssignementContext ctx) { stack.push(new OtherMacroObject(ctx.macroName().getText())); } @Override public void exitComplexAssignement(ComplexAssignementContext ctx) { OidValue value = (OidValue) stack.pop(); OtherMacroObject macro = (OtherMacroObject) stack.pop(); Symbol s = (Symbol) stack.pop(); macro.value = value; try { store.addMacroValue(s, macro.values, macro.value.value); } catch (MibException e) { parser.notifyErrorListeners(ctx.start, e.getMessage(), new WrappedException(e, parser, parser.getInputStream(), ctx)); } } @Override public void enterTrapTypeAssignement(TrapTypeAssignementContext ctx) { stack.push(new TrapTypeObject()); } @Override public void exitTrapTypeAssignement(TrapTypeAssignementContext ctx) { @SuppressWarnings("unchecked") ValueType<Number> value = (ValueType<Number>) stack.pop(); TrapTypeObject macro = (TrapTypeObject) stack.pop(); Symbol s = (Symbol) stack.pop(); try { if (macro.enterprise != null) { store.addTrapType(s, macro.enterprise, macro.values, value.value); } } catch (MibException e) { parser.notifyErrorListeners(ctx.start, e.getMessage(), new WrappedException(e, parser, parser.getInputStream(), ctx)); } } @Override public void enterObjectTypeAssignement(ObjectTypeAssignementContext ctx) { stack.push(new ObjectTypeObject()); } @Override public void exitObjectTypeAssignement(ObjectTypeAssignementContext ctx) { OidValue vt = (OidValue) stack.pop(); ObjectTypeObject macro = (ObjectTypeObject) stack.pop(); Symbol s = (Symbol) stack.pop(); try { store.addObjectType(s, macro.values, vt.value); } catch (MibException e) { parser.notifyErrorListeners(ctx.start, e.getMessage(), new WrappedException(e, parser, parser.getInputStream(), ctx)); } } @Override public void enterTextualConventionAssignement(TextualConventionAssignementContext ctx) { stack.push(new TextualConventionObject()); } @Override public void exitTextualConventionAssignement(TextualConventionAssignementContext ctx) { TextualConventionObject tc = (TextualConventionObject) stack.pop(); Symbol s = (Symbol) stack.pop(); try { store.addTextualConvention(s, tc.values); } catch (MibException e) { parser.notifyErrorListeners(ctx.start, e.getMessage(), new WrappedException(e, parser, parser.getInputStream(), ctx)); } } @Override public void enterModuleIdentityAssignement(ModuleIdentityAssignementContext ctx) { stack.push(new ModuleIdentityObject()); } @Override public void exitModuleIdentityAssignement(ModuleIdentityAssignementContext ctx) { OidValue vt = (OidValue) stack.pop(); Object revisions = stack.pop(); while ( ! (stack.peek() instanceof ModuleIdentityObject)) { stack.pop(); } ModuleIdentityObject mi = (ModuleIdentityObject) stack.pop(); Symbol s = (Symbol) stack.pop(); mi.values.put("revisions", revisions); try { store.addModuleIdentity(s, vt.value); } catch (MibException e) { parser.notifyErrorListeners(ctx.start, e.getMessage(), new WrappedException(e, parser, parser.getInputStream(), ctx)); } } @Override public void exitTypeAssignment(TypeAssignmentContext ctx) { TypeDescription td = (TypeDescription) stack.pop(); Symbol s = (Symbol) stack.pop(); try { store.addType(s, td.getSyntax(this)); } catch (MibException e) { parser.notifyErrorListeners(ctx.start, e.getMessage(), new WrappedException(e, parser, parser.getInputStream(), ctx)); } } @Override public void exitValueAssignment(ValueAssignmentContext ctx) { ValueType<?> vt = (ValueType<?>) stack.pop(); // Removed the unused TypeDescription stack.pop(); Symbol s = (Symbol) stack.pop(); try { if (vt.value instanceof OidPath) { OidPath path = (OidPath) vt.value; store.addValue(s, path); } } catch (MibException e) { parser.notifyErrorListeners(ctx.start, e.getMessage(), new WrappedException(e, parser, parser.getInputStream(), ctx)); } } /**************************************** * Manage values and push them on stack ***************************************/ @Override public void exitObjectIdentifierValue(ObjectIdentifierValueContext ctx) { OidValue stackval = (OidValue) stack.peek(); OidPath oidParts = stackval.value; if (ctx.IDENTIFIER() != null) { String name = ctx.IDENTIFIER().getText(); if (symbols.containsKey(name)) { oidParts.root = symbols.get(name); } else { oidParts.root = new Symbol(currentModule, name); } } } @Override public void enterObjIdComponentsList(ObjIdComponentsListContext ctx) { OidPath oidParts = ctx.objIdComponents().stream().map( i-> { String name = null; int number; if( i.identifier != null) { name = i.identifier.getText(); } number = Integer.parseInt(i.NUMBER().getText()); OidPath.OidComponent oidc = new OidPath.OidComponent(name, number); return oidc; }) .collect(OidPath::new, OidPath::add, OidPath::addAll); stack.push(new OidValue(oidParts)); } @Override public void enterBooleanValue(BooleanValueContext ctx) { boolean value; if ("true".equalsIgnoreCase(ctx.getText())) { value = true; } else { value = false; } ValueType.BooleanValue v = new ValueType.BooleanValue(value); stack.push(v); } @Override public void enterIntegerValue(IntegerValueContext ctx) { BigInteger v = null; try { if (ctx.signedNumber() != null) { v = new BigInteger(ctx.signedNumber().getText()); } else if (ctx.hexaNumber() != null) { String hexanumber = ctx.hexaNumber().HEXANUMBER().getText(); hexanumber = hexanumber.substring(1, hexanumber.length() - 2); if (! hexanumber.isEmpty()) { v = new BigInteger(hexanumber, 16); } else { v = BigInteger.valueOf(0); } } else { //Binary number case String binarynumber = ctx.binaryNumber().BINARYNUMBER().getText(); binarynumber = binarynumber.substring(1, binarynumber.length() - 2); if (! binarynumber.isEmpty()) { v = new BigInteger(binarynumber, 2); } else { v = BigInteger.valueOf(0); } } stack.push(new ValueType.IntegerValue(fitNumber(v))); } catch (Exception e) { parser.notifyErrorListeners(ctx.start, e.getMessage(), new WrappedException(e, parser, parser.getInputStream(), ctx)); } } @Override public void enterStringValue(StringValueContext ctx) { try { if (ctx.CSTRING() == null || ctx.CSTRING().getText() == null) { Exception e = new NullPointerException(); parser.notifyErrorListeners(ctx.start, e.getMessage(), new WrappedException(e, parser, parser.getInputStream(), ctx)); } String cstring = ctx.CSTRING().getText(); cstring = cstring.substring(1, cstring.length() - 1); ValueType.StringValue v = new ValueType.StringValue(cstring); stack.push(v); } catch (Exception e) { parser.notifyErrorListeners(ctx.start, e.getMessage(), new WrappedException(e, parser, parser.getInputStream(), ctx)); } } /**************************************** * Manage complex attributes and push them on stack ***************************************/ @Override public void exitComplexAttribut(ComplexAttributContext ctx) { if (ctx.name == null) { return; } String name = ctx.name.getText(); Object value = null; if (ctx.IDENTIFIER() != null) { value = resolveSymbol(ctx.IDENTIFIER().getText()); } else if (ctx.objects() != null) { List<ValueType<?>> objects = new ArrayList<>(); while( (stack.peek() instanceof ValueType)) { ValueType<?> vt = (ValueType<?>) stack.pop(); objects.add(vt); } value = objects; } else if (ctx.groups() != null) { value = ctx.groups().IDENTIFIER().stream().map(TerminalNode::getText).collect(ArrayList::new, ArrayList::add, ArrayList::addAll); } else if (ctx.variables() != null) { value = ctx.variables().IDENTIFIER().stream().map(TerminalNode::getText).collect(ArrayList::new, ArrayList::add, ArrayList::addAll); } else if (ctx.notifications() != null) { value = ctx.notifications().IDENTIFIER().stream().map(TerminalNode::getText).collect(ArrayList::new, ArrayList::add, ArrayList::addAll); } else if (ctx.augments() != null) { value = resolveSymbol(ctx.augments().IDENTIFIER().getText()); } else if (ctx.index() != null) { LinkedList<Symbol> types = new LinkedList<>(); while (stack.peek() instanceof TypeDescription) { TypeDescription td = (TypeDescription) stack.pop(); if (td.typeDescription != null) { types.addFirst(resolveSymbol(td.typeDescription.toString())); } } value = new ArrayList<Symbol>(types); } else if (stack.peek() instanceof ValueType) { ValueType<?> vt = (ValueType<?>)stack.pop(); value = vt.value; } else if (stack.peek() instanceof TypeDescription) { value = ((TypeDescription)stack.pop()).getSyntax(this); } MappedObject co = (MappedObject) stack.peek(); co.values.put(name.intern(), value); } @Override public void exitEnterpriseAttribute(EnterpriseAttributeContext ctx) { Object enterprise; if (ctx.IDENTIFIER() != null) { enterprise = resolveSymbol(ctx.IDENTIFIER().getText()); } else if ( ctx.objectIdentifierValue() != null){ OidValue value = (OidValue) stack.pop(); enterprise = value.value; } else { MibException e = new MibException("Invalid trap"); parser.notifyErrorListeners(ctx.start, e.getMessage(), new WrappedException(e, parser, parser.getInputStream(), ctx)); return; } TrapTypeObject co = (TrapTypeObject) stack.peek(); co.enterprise = enterprise; } @Override public void exitAccess(AccessContext ctx) { String name = ctx.name.getText(); String value = ctx.IDENTIFIER().getText().intern(); MappedObject co = (MappedObject) stack.peek(); co.values.put(name.intern(), value); } @Override public void exitStatus(StatusContext ctx) { String name = ctx.name.getText(); String value = ctx.IDENTIFIER().getText().intern(); MappedObject co = (MappedObject) stack.peek(); co.values.put(name.intern(), value); } @Override public void enterModuleRevisions(ModuleRevisionsContext ctx) { stack.push(new ArrayList<Revision>()); } @Override public void exitModuleRevision(ModuleRevisionContext ctx) { StringValue description = (StringValue)stack.pop(); StringValue revision = (StringValue)stack.pop(); @SuppressWarnings("unchecked") List<Revision> revisions = (List<Revision>) stack.peek(); revisions.add(new Revision(description.value, revision.value)); } @Override public void enterModuleComplianceAssignement(ModuleComplianceAssignementContext ctx) { stack.push(new MappedObject("MODULE-COMPLIANCE")); } @Override public void exitModuleComplianceAssignement(ModuleComplianceAssignementContext ctx) { OidValue value = (OidValue) stack.pop(); while(! (stack.peek() instanceof Symbol)) { stack.pop().getClass(); } Symbol s = (Symbol) stack.pop(); try { store.addMacroValue(s, Collections.emptyMap(), value.value); } catch (MibException e) { parser.notifyErrorListeners(ctx.start, e.getMessage(), new WrappedException(e, parser, parser.getInputStream(), ctx)); } } /**************************************** * Manage type ***************************************/ @Override public void enterType(TypeContext ctx) { TypeDescription td = new TypeDescription(); if (ctx.builtinType() != null) { switch(ctx.builtinType().getChild(ParserRuleContext.class, 0).getRuleIndex()) { case ASNParser.RULE_integerType: td.type = Asn1Type.integerType; break; case ASNParser.RULE_octetStringType: td.type = Asn1Type.octetStringType; break; case ASNParser.RULE_bitStringType: td.type = Asn1Type.bitStringType; break; case ASNParser.RULE_choiceType: td.type = Asn1Type.choiceType; break; case ASNParser.RULE_sequenceType: td.type = Asn1Type.sequenceType; break; case ASNParser.RULE_sequenceOfType: td.type = Asn1Type.sequenceOfType; break; case ASNParser.RULE_objectIdentifierType: td.type = Asn1Type.objectidentifiertype; break; case ASNParser.RULE_nullType: td.type = Asn1Type.nullType; break; case ASNParser.RULE_bitsType: td.type = Asn1Type.bitsType; break; default: throw new ParseCancellationException(); } } else if (ctx.referencedType() != null) { td.type = Asn1Type.referencedType; td.typeDescription = ctx.referencedType(); } stack.push(td); } @Override public void exitType(TypeContext ctx) { Constraint constrains = null; if (stack.peek() instanceof Constraint) { constrains = (Constraint) stack.pop(); } TypeDescription td = (TypeDescription) stack.peek(); td.constraints = constrains; } @Override public void enterConstraint(ConstraintContext ctx) { stack.push(new Constraint(false)); } @Override public void exitConstraint(ConstraintContext ctx) { Constraint constrains = (Constraint) stack.peek(); constrains.finish(); } @Override public void enterSizeConstraint(SizeConstraintContext ctx) { stack.push(new Constraint(true)); } @Override public void exitSizeConstraint(SizeConstraintContext ctx) { Constraint constrains = (Constraint) stack.peek(); constrains.finish(); } @Override public void exitElements(ElementsContext ctx) { List<Number> values = new ArrayList<>(2); while( stack.peek() instanceof ValueType.IntegerValue) { ValueType.IntegerValue val = (ValueType.IntegerValue) stack.pop(); values.add(val.value); } Constraint.ConstraintElement c; if (values.size() == 1) { c = new Constraint.ConstraintElement(values.get(0)); } else { c = new Constraint.ConstraintElement(values.get(1), values.get(0)); } Constraint constrains = (Constraint) stack.peek(); constrains.add(c); } @Override public void enterSequenceType(SequenceTypeContext ctx) { TypeDescription td = (TypeDescription) stack.peek(); Map<String, Syntax> content = new LinkedHashMap<>(); td.type = Asn1Type.sequenceType; ctx.namedType().forEach( i -> content.put(i.IDENTIFIER().getText(), null)); td.typeDescription = content; } @Override public void exitSequenceType(SequenceTypeContext ctx) { List<TypeDescription> nt = new ArrayList<>(); int namedTypeCount = ctx.namedType().size(); for (int i = 0; i < namedTypeCount; i++ ) { nt.add((TypeDescription)stack.pop()); } AtomicInteger i = new AtomicInteger(nt.size() - 1); TypeDescription td = (TypeDescription) stack.peek(); @SuppressWarnings("unchecked") Map<String, Syntax> content = (Map<String, Syntax>) td.typeDescription; content.keySet().forEach( name -> content.put(name, nt.get(i.getAndDecrement()).getSyntax(this))); } @Override public void exitSequenceOfType(SequenceOfTypeContext ctx) { TypeDescription seqtd = (TypeDescription) stack.pop(); TypeDescription td = (TypeDescription) stack.peek(); td.typeDescription = seqtd; } @Override public void enterChoiceType(ChoiceTypeContext ctx) { TypeDescription td = (TypeDescription) stack.peek(); Map<String, Syntax> content = new LinkedHashMap<>(); td.type = Asn1Type.choiceType; ctx.namedType().forEach( i -> content.put(i.IDENTIFIER().getText(), null)); td.typeDescription = content; stack.push("CHOICE"); } @Override public void exitChoiceType(ChoiceTypeContext ctx) { List<TypeDescription> nt = new ArrayList<>(); while ( ! ("CHOICE".equals(stack.peek()))) { nt.add((TypeDescription)stack.pop()); } stack.pop(); int i = nt.size() - 1; TypeDescription td = (TypeDescription) stack.peek(); @SuppressWarnings("unchecked") Map<String, Syntax> content = (Map<String, Syntax>) td.typeDescription; content.keySet().forEach( name -> content.put(name, nt.get(i).getSyntax(this))); } @Override public void enterIntegerType(IntegerTypeContext ctx) { TypeDescription td = (TypeDescription) stack.peek(); if (ctx.namedNumberList() != null) { Map<Number, String> names = new HashMap<>(); ctx.namedNumberList().namedNumber().forEach( i -> { BigInteger value = new BigInteger(i.signedNumber().getText()); String name = i.name.getText(); names.put(fitNumber(value), name); }); td.names = names; } } @Override public void enterBitsType(BitsTypeContext ctx) { TypeDescription td = (TypeDescription) stack.peek(); Map<String, Integer> bits; if (ctx.bitsEnumeration() != null && ctx.bitsEnumeration().bitDescription() != null) { List<BitDescriptionContext> descriptions = ctx.bitsEnumeration().bitDescription(); bits = new LinkedHashMap<>(descriptions.size()); IntStream.range(0, descriptions.size()).forEach( i-> { bits.put(descriptions.get(i).IDENTIFIER().getText(), Integer.parseUnsignedInt(descriptions.get(i).NUMBER().getText())); }); } else { bits = Collections.emptyMap(); } td.typeDescription = bits; } @Override public void enterReferencedType(ReferencedTypeContext ctx) { TypeDescription td = (TypeDescription) stack.peek(); td.typeDescription = ctx.getText(); } }
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver12; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import org.jboss.netty.buffer.ChannelBuffer; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFGroupModFailedErrorMsgVer12 implements OFGroupModFailedErrorMsg { private static final Logger logger = LoggerFactory.getLogger(OFGroupModFailedErrorMsgVer12.class); // version: 1.2 final static byte WIRE_VERSION = 3; final static int MINIMUM_LENGTH = 12; private final static long DEFAULT_XID = 0x0L; private final static OFErrorCauseData DEFAULT_DATA = OFErrorCauseData.NONE; // OF message fields private final long xid; private final OFGroupModFailedCode code; private final OFErrorCauseData data; // // package private constructor - used by readers, builders, and factory OFGroupModFailedErrorMsgVer12(long xid, OFGroupModFailedCode code, OFErrorCauseData data) { if(code == null) { throw new NullPointerException("OFGroupModFailedErrorMsgVer12: property code cannot be null"); } if(data == null) { throw new NullPointerException("OFGroupModFailedErrorMsgVer12: property data cannot be null"); } this.xid = xid; this.code = code; this.data = data; } // Accessors for OF message fields @Override public OFVersion getVersion() { return OFVersion.OF_12; } @Override public OFType getType() { return OFType.ERROR; } @Override public long getXid() { return xid; } @Override public OFErrorType getErrType() { return OFErrorType.GROUP_MOD_FAILED; } @Override public OFGroupModFailedCode getCode() { return code; } @Override public OFErrorCauseData getData() { return data; } public OFGroupModFailedErrorMsg.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFGroupModFailedErrorMsg.Builder { final OFGroupModFailedErrorMsgVer12 parentMessage; // OF message fields private boolean xidSet; private long xid; private boolean codeSet; private OFGroupModFailedCode code; private boolean dataSet; private OFErrorCauseData data; BuilderWithParent(OFGroupModFailedErrorMsgVer12 parentMessage) { this.parentMessage = parentMessage; } @Override public OFVersion getVersion() { return OFVersion.OF_12; } @Override public OFType getType() { return OFType.ERROR; } @Override public long getXid() { return xid; } @Override public OFGroupModFailedErrorMsg.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public OFErrorType getErrType() { return OFErrorType.GROUP_MOD_FAILED; } @Override public OFGroupModFailedCode getCode() { return code; } @Override public OFGroupModFailedErrorMsg.Builder setCode(OFGroupModFailedCode code) { this.code = code; this.codeSet = true; return this; } @Override public OFErrorCauseData getData() { return data; } @Override public OFGroupModFailedErrorMsg.Builder setData(OFErrorCauseData data) { this.data = data; this.dataSet = true; return this; } @Override public OFGroupModFailedErrorMsg build() { long xid = this.xidSet ? this.xid : parentMessage.xid; OFGroupModFailedCode code = this.codeSet ? this.code : parentMessage.code; if(code == null) throw new NullPointerException("Property code must not be null"); OFErrorCauseData data = this.dataSet ? this.data : parentMessage.data; if(data == null) throw new NullPointerException("Property data must not be null"); // return new OFGroupModFailedErrorMsgVer12( xid, code, data ); } } static class Builder implements OFGroupModFailedErrorMsg.Builder { // OF message fields private boolean xidSet; private long xid; private boolean codeSet; private OFGroupModFailedCode code; private boolean dataSet; private OFErrorCauseData data; @Override public OFVersion getVersion() { return OFVersion.OF_12; } @Override public OFType getType() { return OFType.ERROR; } @Override public long getXid() { return xid; } @Override public OFGroupModFailedErrorMsg.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public OFErrorType getErrType() { return OFErrorType.GROUP_MOD_FAILED; } @Override public OFGroupModFailedCode getCode() { return code; } @Override public OFGroupModFailedErrorMsg.Builder setCode(OFGroupModFailedCode code) { this.code = code; this.codeSet = true; return this; } @Override public OFErrorCauseData getData() { return data; } @Override public OFGroupModFailedErrorMsg.Builder setData(OFErrorCauseData data) { this.data = data; this.dataSet = true; return this; } // @Override public OFGroupModFailedErrorMsg build() { long xid = this.xidSet ? this.xid : DEFAULT_XID; if(!this.codeSet) throw new IllegalStateException("Property code doesn't have default value -- must be set"); if(code == null) throw new NullPointerException("Property code must not be null"); OFErrorCauseData data = this.dataSet ? this.data : DEFAULT_DATA; if(data == null) throw new NullPointerException("Property data must not be null"); return new OFGroupModFailedErrorMsgVer12( xid, code, data ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFGroupModFailedErrorMsg> { @Override public OFGroupModFailedErrorMsg readFrom(ChannelBuffer bb) throws OFParseError { int start = bb.readerIndex(); // fixed value property version == 3 byte version = bb.readByte(); if(version != (byte) 0x3) throw new OFParseError("Wrong version: Expected=OFVersion.OF_12(3), got="+version); // fixed value property type == 1 byte type = bb.readByte(); if(type != (byte) 0x1) throw new OFParseError("Wrong type: Expected=OFType.ERROR(1), got="+type); int length = U16.f(bb.readShort()); if(length < MINIMUM_LENGTH) throw new OFParseError("Wrong length: Expected to be >= " + MINIMUM_LENGTH + ", was: " + length); if(bb.readableBytes() + (bb.readerIndex() - start) < length) { // Buffer does not have all data yet bb.readerIndex(start); return null; } if(logger.isTraceEnabled()) logger.trace("readFrom - length={}", length); long xid = U32.f(bb.readInt()); // fixed value property errType == 6 short errType = bb.readShort(); if(errType != (short) 0x6) throw new OFParseError("Wrong errType: Expected=OFErrorType.GROUP_MOD_FAILED(6), got="+errType); OFGroupModFailedCode code = OFGroupModFailedCodeSerializerVer12.readFrom(bb); OFErrorCauseData data = OFErrorCauseData.read(bb, length - (bb.readerIndex() - start), OFVersion.OF_12); OFGroupModFailedErrorMsgVer12 groupModFailedErrorMsgVer12 = new OFGroupModFailedErrorMsgVer12( xid, code, data ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", groupModFailedErrorMsgVer12); return groupModFailedErrorMsgVer12; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFGroupModFailedErrorMsgVer12Funnel FUNNEL = new OFGroupModFailedErrorMsgVer12Funnel(); static class OFGroupModFailedErrorMsgVer12Funnel implements Funnel<OFGroupModFailedErrorMsgVer12> { private static final long serialVersionUID = 1L; @Override public void funnel(OFGroupModFailedErrorMsgVer12 message, PrimitiveSink sink) { // fixed value property version = 3 sink.putByte((byte) 0x3); // fixed value property type = 1 sink.putByte((byte) 0x1); // FIXME: skip funnel of length sink.putLong(message.xid); // fixed value property errType = 6 sink.putShort((short) 0x6); OFGroupModFailedCodeSerializerVer12.putTo(message.code, sink); message.data.putTo(sink); } } public void writeTo(ChannelBuffer bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFGroupModFailedErrorMsgVer12> { @Override public void write(ChannelBuffer bb, OFGroupModFailedErrorMsgVer12 message) { int startIndex = bb.writerIndex(); // fixed value property version = 3 bb.writeByte((byte) 0x3); // fixed value property type = 1 bb.writeByte((byte) 0x1); // length is length of variable message, will be updated at the end int lengthIndex = bb.writerIndex(); bb.writeShort(U16.t(0)); bb.writeInt(U32.t(message.xid)); // fixed value property errType = 6 bb.writeShort((short) 0x6); OFGroupModFailedCodeSerializerVer12.writeTo(bb, message.code); message.data.writeTo(bb); // update length field int length = bb.writerIndex() - startIndex; bb.setShort(lengthIndex, length); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFGroupModFailedErrorMsgVer12("); b.append("xid=").append(xid); b.append(", "); b.append("code=").append(code); b.append(", "); b.append("data=").append(data); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFGroupModFailedErrorMsgVer12 other = (OFGroupModFailedErrorMsgVer12) obj; if( xid != other.xid) return false; if (code == null) { if (other.code != null) return false; } else if (!code.equals(other.code)) return false; if (data == null) { if (other.data != null) return false; } else if (!data.equals(other.data)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * (int) (xid ^ (xid >>> 32)); result = prime * result + ((code == null) ? 0 : code.hashCode()); result = prime * result + ((data == null) ? 0 : data.hashCode()); return result; } }
package de.espend.idea.php.toolbox.symfony.util; import com.intellij.psi.PsiElement; import com.jetbrains.php.lang.psi.elements.*; import de.espend.idea.php.toolbox.symfony.Symfony2InterfacesUtil; import de.espend.idea.php.toolbox.symfony.utils.PhpElementsUtil; import de.espend.idea.php.toolbox.symfony.dic.MethodReferenceBag; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; public class MethodMatcher { @Nullable public static MethodMatchParameter getMatchedSignatureWithDepth(PsiElement psiElement, CallToSignature... callToSignatures) { return getMatchedSignatureWithDepth(psiElement, callToSignatures, 0); } @Nullable public static MethodMatchParameter getMatchedSignatureWithDepth(PsiElement psiElement, CallToSignature[] callToSignatures, int defaultParameterIndex) { MethodMatchParameter methodMatchParameter = new StringParameterMatcher(psiElement, defaultParameterIndex) .withSignature(callToSignatures) .match(); if(methodMatchParameter != null) { return methodMatchParameter; } // try on resolved method return new StringParameterRecursiveMatcher(psiElement, defaultParameterIndex) .withSignature(callToSignatures) .match(); } public static class CallToSignature { private final String instance; private final String method; public CallToSignature(String instance, String method) { this.instance = instance; this.method = method; } public String getInstance() { return instance; } public String getMethod() { return method; } } public static class MethodMatchParameter { final private CallToSignature signature; final private ParameterBag parameterBag; final private PsiElement[] parameters; final private MethodReference methodReference; public MethodMatchParameter(CallToSignature signature, ParameterBag parameterBag, PsiElement[] parameters, MethodReference methodReference) { this.signature = signature; this.parameterBag = parameterBag; this.parameters = parameters; this.methodReference = methodReference; } @Nullable public CallToSignature getSignature() { return signature; } public ParameterBag getParameterBag() { return this.parameterBag; } public PsiElement[] getParameters() { return parameters; } public MethodReference getMethodReference() { return methodReference; } } public static class StringParameterMatcher extends AbstractMethodParameterMatcher { public StringParameterMatcher(PsiElement psiElement, int parameterIndex) { super(psiElement, parameterIndex); } @Nullable public MethodMatchParameter match() { MethodReferenceBag bag = PhpElementsUtil.getMethodParameterReferenceBag(psiElement, this.parameterIndex); if(bag == null) { return null; } CallToSignature matchedMethodSignature = this.isCallTo(bag.getMethodReference()); if(matchedMethodSignature == null) { return null; } return new MethodMatchParameter(matchedMethodSignature, bag.getParameterBag(), bag.getParameterList().getParameters(), bag.getMethodReference()); } } public static class StringParameterAnyMatcher extends AbstractMethodParameterMatcher { public StringParameterAnyMatcher(PsiElement psiElement) { super(psiElement, -1); } @Nullable public MethodMatchParameter match() { MethodReferenceBag bag = PhpElementsUtil.getMethodParameterReferenceBag(psiElement); if(bag == null) { return null; } CallToSignature matchedMethodSignature = this.isCallTo(bag.getMethodReference()); if(matchedMethodSignature == null) { return null; } return new MethodMatchParameter(matchedMethodSignature, bag.getParameterBag(), bag.getParameterList().getParameters(), bag.getMethodReference()); } } public static class StringParameterRecursiveMatcher extends AbstractMethodParameterMatcher { public StringParameterRecursiveMatcher(PsiElement psiElement, int parameterIndex) { super(psiElement, parameterIndex); } @Nullable public MethodMatchParameter match() { MethodReferenceBag bag = PhpElementsUtil.getMethodParameterReferenceBag(psiElement); if(bag == null) { return null; } // try on current method MethodMatchParameter methodMatchParameter = new StringParameterMatcher(psiElement, parameterIndex) .withSignature(this.signatures) .match(); if(methodMatchParameter != null) { return methodMatchParameter; } // walk down next method MethodReference methodReference = bag.getMethodReference(); Method[] methods = Symfony2InterfacesUtil.getMultiResolvedMethod(methodReference); if(methods == null) { return null; } for (Method method : methods) { PsiElement[] parameterReferences = PhpElementsUtil.getMethodParameterReferences(method, bag.getParameterBag().getIndex()); if(parameterReferences == null || parameterReferences.length == 0) { continue; } for(PsiElement var: parameterReferences) { MethodMatcher.MethodMatchParameter methodMatchParameterRef = new MethodMatcher.StringParameterMatcher(var, parameterIndex) .withSignature(this.signatures) .match(); if(methodMatchParameterRef != null) { return methodMatchParameterRef; } } } return null; } } /** * Matches: new \DateTime('FOO') */ public static class NewExpressionParameterMatcher extends AbstractMethodParameterMatcher { public NewExpressionParameterMatcher(PsiElement psiElement, int parameterIndex) { super(psiElement, parameterIndex); } @Nullable public MethodMatchParameter match() { for (CallToSignature signature : this.signatures) { if(matchInstance(psiElement, signature.getInstance(), this.parameterIndex)) { return new MethodMatchParameter(signature, null, null, null); } } return null; } private boolean matchInstance(PsiElement psiElement, String instance, int index) { PsiElement parameterList = psiElement.getParent(); if(parameterList instanceof ParameterList) { ParameterBag currentParameterIndex = PhpElementsUtil.getCurrentParameterIndex(psiElement); if(currentParameterIndex != null && currentParameterIndex.getIndex() == index) { PsiElement newExpression = parameterList.getParent(); if(newExpression instanceof NewExpression) { ClassReference classReference = ((NewExpression) newExpression).getClassReference(); if(classReference != null) { String fqn = classReference.getFQN(); if(fqn != null) { return new Symfony2InterfacesUtil().isInstanceOf(psiElement.getProject(), fqn, instance); } } } } } return false; } } public static class ArrayParameterMatcher extends AbstractMethodParameterMatcher { public ArrayParameterMatcher(PsiElement psiElement, int parameterIndex) { super(psiElement, parameterIndex); } @Nullable public MethodMatchParameter match() { ArrayCreationExpression arrayCreationExpression = PhpElementsUtil.getCompletableArrayCreationElement(this.psiElement); if (arrayCreationExpression == null) { return null; } PsiElement parameterList = arrayCreationExpression.getContext(); if (!(parameterList instanceof ParameterList)) { return null; } PsiElement methodParameters[] = ((ParameterList) parameterList).getParameters(); if (methodParameters.length < this.parameterIndex) { return null; } if (!(parameterList.getContext() instanceof MethodReference)) { return null; } MethodReference methodReference = (MethodReference) parameterList.getContext(); ParameterBag currentIndex = PsiElementUtils.getCurrentParameterIndex(arrayCreationExpression); if (currentIndex == null || currentIndex.getIndex() != this.parameterIndex) { return null; } CallToSignature matchedMethodSignature = this.isCallTo(methodReference); if(matchedMethodSignature == null) { return null; } return new MethodMatchParameter(matchedMethodSignature, currentIndex, methodParameters, methodReference); } } public interface MethodParameterMatcherInterface { @Nullable public MethodMatchParameter match(); } public abstract static class AbstractMethodParameterMatcher implements MethodParameterMatcherInterface { final protected List<CallToSignature> signatures; final protected int parameterIndex; final protected PsiElement psiElement; public AbstractMethodParameterMatcher(PsiElement psiElement, int parameterIndex) { this.signatures = new ArrayList<>(); this.parameterIndex = parameterIndex; this.psiElement = psiElement; } public AbstractMethodParameterMatcher withSignature(String instance, String method) { this.signatures.add(new CallToSignature(instance, method)); return this; } public AbstractMethodParameterMatcher withSignature(Collection<CallToSignature> signatures) { this.signatures.addAll(signatures); return this; } public AbstractMethodParameterMatcher withSignature(CallToSignature[] callToSignatures) { this.signatures.addAll(Arrays.asList(callToSignatures)); return this; } @Nullable protected CallToSignature isCallTo(MethodReference methodReference) { Symfony2InterfacesUtil interfacesUtil = new Symfony2InterfacesUtil(); for(CallToSignature signature: this.signatures) { if(interfacesUtil.isCallTo(methodReference, signature.getInstance(), signature.getMethod())) { return signature; } } return null; } } }
/* * Copyright (C) 2015 Google 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.google.cloud.dataflow.sdk.transforms; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.WindowingInternals; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.TupleTag; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; import com.google.common.base.MoreObjects; import org.joda.time.Duration; import org.joda.time.Instant; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.UUID; /** * The argument to {@link ParDo} providing the code to use to process * elements of the input * {@link com.google.cloud.dataflow.sdk.values.PCollection}. * * <p>See {@link ParDo} for more explanation, examples of use, and * discussion of constraints on {@code DoFn}s, including their * serializability, lack of access to global shared mutable state, * requirements for failure tolerance, and benefits of optimization. * * <p>{@code DoFn}s can be tested in the context of a particular * {@code Pipeline} by running that {@code Pipeline} on sample input * and then checking its output. Unit testing of a {@code DoFn}, * separately from any {@code ParDo} transform or {@code Pipeline}, * can be done via the {@link DoFnTester} harness. * * <p>{@link DoFnWithContext} (currently experimental) offers an alternative * mechanism for accessing {@link ProcessContext#window()} without the need * to implement {@link RequiresWindowAccess}. * * <p>See also {@link #processElement} for details on implementing the transformation * from {@code InputT} to {@code OutputT}. * * @param <InputT> the type of the (main) input elements * @param <OutputT> the type of the (main) output elements */ public abstract class DoFn<InputT, OutputT> implements Serializable, HasDisplayData { /** * Information accessible to all methods in this {@code DoFn}. * Used primarily to output elements. */ public abstract class Context { /** * Returns the {@code PipelineOptions} specified with the * {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner} * invoking this {@code DoFn}. The {@code PipelineOptions} will * be the default running via {@link DoFnTester}. */ public abstract PipelineOptions getPipelineOptions(); /** * Adds the given element to the main output {@code PCollection}. * * <p>Once passed to {@code output} the element should be considered * immutable and not be modified in any way. It may be cached or retained * by the Dataflow runtime or later steps in the pipeline, or used in * other unspecified ways. * * <p>If invoked from {@link DoFn#processElement processElement}, the output * element will have the same timestamp and be in the same windows * as the input element passed to {@link DoFn#processElement processElement}. * * <p>If invoked from {@link #startBundle startBundle} or {@link #finishBundle finishBundle}, * this will attempt to use the * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} * of the input {@code PCollection} to determine what windows the element * should be in, throwing an exception if the {@code WindowFn} attempts * to access any information about the input element. The output element * will have a timestamp of negative infinity. */ public abstract void output(OutputT output); /** * Adds the given element to the main output {@code PCollection}, * with the given timestamp. * * <p>Once passed to {@code outputWithTimestamp} the element should not be * modified in any way. * * <p>If invoked from {@link DoFn#processElement processElement}, the timestamp * must not be older than the input element's timestamp minus * {@link DoFn#getAllowedTimestampSkew getAllowedTimestampSkew}. The output element will * be in the same windows as the input element. * * <p>If invoked from {@link #startBundle startBundle} or {@link #finishBundle finishBundle}, * this will attempt to use the * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} * of the input {@code PCollection} to determine what windows the element * should be in, throwing an exception if the {@code WindowFn} attempts * to access any information about the input element except for the * timestamp. */ public abstract void outputWithTimestamp(OutputT output, Instant timestamp); /** * Adds the given element to the side output {@code PCollection} with the * given tag. * * <p>Once passed to {@code sideOutput} the element should not be modified * in any way. * * <p>The caller of {@code ParDo} uses {@link ParDo#withOutputTags withOutputTags} to * specify the tags of side outputs that it consumes. Non-consumed side * outputs, e.g., outputs for monitoring purposes only, don't necessarily * need to be specified. * * <p>The output element will have the same timestamp and be in the same * windows as the input element passed to {@link DoFn#processElement processElement}. * * <p>If invoked from {@link #startBundle startBundle} or {@link #finishBundle finishBundle}, * this will attempt to use the * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} * of the input {@code PCollection} to determine what windows the element * should be in, throwing an exception if the {@code WindowFn} attempts * to access any information about the input element. The output element * will have a timestamp of negative infinity. * * @see ParDo#withOutputTags */ public abstract <T> void sideOutput(TupleTag<T> tag, T output); /** * Adds the given element to the specified side output {@code PCollection}, * with the given timestamp. * * <p>Once passed to {@code sideOutputWithTimestamp} the element should not be * modified in any way. * * <p>If invoked from {@link DoFn#processElement processElement}, the timestamp * must not be older than the input element's timestamp minus * {@link DoFn#getAllowedTimestampSkew getAllowedTimestampSkew}. The output element will * be in the same windows as the input element. * * <p>If invoked from {@link #startBundle startBundle} or {@link #finishBundle finishBundle}, * this will attempt to use the * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} * of the input {@code PCollection} to determine what windows the element * should be in, throwing an exception if the {@code WindowFn} attempts * to access any information about the input element except for the * timestamp. * * @see ParDo#withOutputTags */ public abstract <T> void sideOutputWithTimestamp( TupleTag<T> tag, T output, Instant timestamp); /** * Creates an {@link Aggregator} in the {@link DoFn} context with the * specified name and aggregation logic specified by {@link CombineFn}. * * <p>For internal use only. * * @param name the name of the aggregator * @param combiner the {@link CombineFn} to use in the aggregator * @return an aggregator for the provided name and {@link CombineFn} in this * context */ @Experimental(Kind.AGGREGATOR) protected abstract <AggInputT, AggOutputT> Aggregator<AggInputT, AggOutputT> createAggregatorInternal(String name, CombineFn<AggInputT, ?, AggOutputT> combiner); /** * Sets up {@link Aggregator}s created by the {@link DoFn} so they are * usable within this context. * * <p>This method should be called by runners before {@link DoFn#startBundle} * is executed. */ @Experimental(Kind.AGGREGATOR) protected final void setupDelegateAggregators() { for (DelegatingAggregator<?, ?> aggregator : aggregators.values()) { setupDelegateAggregator(aggregator); } aggregatorsAreFinal = true; } private final <AggInputT, AggOutputT> void setupDelegateAggregator( DelegatingAggregator<AggInputT, AggOutputT> aggregator) { Aggregator<AggInputT, AggOutputT> delegate = createAggregatorInternal( aggregator.getName(), aggregator.getCombineFn()); aggregator.setDelegate(delegate); } } /** * Information accessible when running {@link DoFn#processElement}. */ public abstract class ProcessContext extends Context { /** * Returns the input element to be processed. * * <p>The element should be considered immutable. The Dataflow runtime will not mutate the * element, so it is safe to cache, etc. The element should not be mutated by any of the * {@link DoFn} methods, because it may be cached elsewhere, retained by the Dataflow runtime, * or used in other unspecified ways. */ public abstract InputT element(); /** * Returns the value of the side input for the window corresponding to the * window of the main input element. * * <p>See * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn#getSideInputWindow} * for how this corresponding window is determined. * * @throws IllegalArgumentException if this is not a side input * @see ParDo#withSideInputs */ public abstract <T> T sideInput(PCollectionView<T> view); /** * Returns the timestamp of the input element. * * <p>See {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window} * for more information. */ public abstract Instant timestamp(); /** * Returns the window into which the input element has been assigned. * * <p>See {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window} * for more information. * * @throws UnsupportedOperationException if this {@link DoFn} does * not implement {@link RequiresWindowAccess}. */ public abstract BoundedWindow window(); /** * Returns information about the pane within this window into which the * input element has been assigned. * * <p>Generally all data is in a single, uninteresting pane unless custom * triggering and/or late data has been explicitly requested. * See {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window} * for more information. */ public abstract PaneInfo pane(); /** * Returns the process context to use for implementing windowing. */ @Experimental public abstract WindowingInternals<InputT, OutputT> windowingInternals(); } /** * Returns the allowed timestamp skew duration, which is the maximum * duration that timestamps can be shifted backward in * {@link DoFn.Context#outputWithTimestamp}. * * <p>The default value is {@code Duration.ZERO}, in which case * timestamps can only be shifted forward to future. For infinite * skew, return {@code Duration.millis(Long.MAX_VALUE)}. * * <p> Note that producing an element whose timestamp is less than the * current timestamp may result in late data, i.e. returning a non-zero * value here does not impact watermark calculations used for firing * windows. * * @deprecated does not interact well with the watermark. */ @Deprecated public Duration getAllowedTimestampSkew() { return Duration.ZERO; } /** * Interface for signaling that a {@link DoFn} needs to access the window the * element is being processed in, via {@link DoFn.ProcessContext#window}. */ @Experimental public interface RequiresWindowAccess {} public DoFn() { this(new HashMap<String, DelegatingAggregator<?, ?>>()); } DoFn(Map<String, DelegatingAggregator<?, ?>> aggregators) { this.aggregators = aggregators; } ///////////////////////////////////////////////////////////////////////////// private final Map<String, DelegatingAggregator<?, ?>> aggregators; /** * Protects aggregators from being created after initialization. */ private boolean aggregatorsAreFinal; /** * Prepares this {@code DoFn} instance for processing a batch of elements. * * <p>By default, does nothing. */ public void startBundle(Context c) throws Exception { } /** * Processes one input element. * * <p>The current element of the input {@code PCollection} is returned by * {@link ProcessContext#element() c.element()}. It should be considered immutable. The Dataflow * runtime will not mutate the element, so it is safe to cache, etc. The element should not be * mutated by any of the {@link DoFn} methods, because it may be cached elsewhere, retained by the * Dataflow runtime, or used in other unspecified ways. * * <p>A value is added to the main output {@code PCollection} by {@link ProcessContext#output}. * Once passed to {@code output} the element should be considered immutable and not be modified in * any way. It may be cached elsewhere, retained by the Dataflow runtime, or used in other * unspecified ways. * * @see ProcessContext */ public abstract void processElement(ProcessContext c) throws Exception; /** * Finishes processing this batch of elements. * * <p>By default, does nothing. */ public void finishBundle(Context c) throws Exception { } /** * {@inheritDoc} * * <p>By default, does not register any display data. Implementors may override this method * to provide their own display data. */ @Override public void populateDisplayData(DisplayData.Builder builder) { } ///////////////////////////////////////////////////////////////////////////// /** * Returns a {@link TypeDescriptor} capturing what is known statically * about the input type of this {@code DoFn} instance's most-derived * class. * * <p>See {@link #getOutputTypeDescriptor} for more discussion. */ protected TypeDescriptor<InputT> getInputTypeDescriptor() { return new TypeDescriptor<InputT>(getClass()) {}; } /** * Returns a {@link TypeDescriptor} capturing what is known statically * about the output type of this {@code DoFn} instance's * most-derived class. * * <p>In the normal case of a concrete {@code DoFn} subclass with * no generic type parameters of its own (including anonymous inner * classes), this will be a complete non-generic type, which is good * for choosing a default output {@code Coder<OutputT>} for the output * {@code PCollection<OutputT>}. */ protected TypeDescriptor<OutputT> getOutputTypeDescriptor() { return new TypeDescriptor<OutputT>(getClass()) {}; } /** * Returns an {@link Aggregator} with aggregation logic specified by the * {@link CombineFn} argument. The name provided must be unique across * {@link Aggregator}s created within the DoFn. Aggregators can only be created * during pipeline construction. * * @param name the name of the aggregator * @param combiner the {@link CombineFn} to use in the aggregator * @return an aggregator for the provided name and combiner in the scope of * this DoFn * @throws NullPointerException if the name or combiner is null * @throws IllegalArgumentException if the given name collides with another * aggregator in this scope * @throws IllegalStateException if called during pipeline processing. */ protected final <AggInputT, AggOutputT> Aggregator<AggInputT, AggOutputT> createAggregator(String name, CombineFn<? super AggInputT, ?, AggOutputT> combiner) { checkNotNull(name, "name cannot be null"); checkNotNull(combiner, "combiner cannot be null"); checkArgument(!aggregators.containsKey(name), "Cannot create aggregator with name %s." + " An Aggregator with that name already exists within this scope.", name); checkState(!aggregatorsAreFinal, "Cannot create an aggregator during DoFn processing." + " Aggregators should be registered during pipeline construction."); DelegatingAggregator<AggInputT, AggOutputT> aggregator = new DelegatingAggregator<>(name, combiner); aggregators.put(name, aggregator); return aggregator; } /** * Returns an {@link Aggregator} with the aggregation logic specified by the * {@link SerializableFunction} argument. The name provided must be unique * across {@link Aggregator}s created within the DoFn. Aggregators can only be * created during pipeline construction. * * @param name the name of the aggregator * @param combiner the {@link SerializableFunction} to use in the aggregator * @return an aggregator for the provided name and combiner in the scope of * this DoFn * @throws NullPointerException if the name or combiner is null * @throws IllegalArgumentException if the given name collides with another * aggregator in this scope * @throws IllegalStateException if called during pipeline processing. */ protected final <AggInputT> Aggregator<AggInputT, AggInputT> createAggregator(String name, SerializableFunction<Iterable<AggInputT>, AggInputT> combiner) { checkNotNull(combiner, "combiner cannot be null."); return createAggregator(name, Combine.IterableCombineFn.of(combiner)); } /** * Returns the {@link Aggregator Aggregators} created by this {@code DoFn}. */ Collection<Aggregator<?, ?>> getAggregators() { return Collections.<Aggregator<?, ?>>unmodifiableCollection(aggregators.values()); } /** * An {@link Aggregator} that delegates calls to addValue to another * aggregator. * * @param <AggInputT> the type of input element * @param <AggOutputT> the type of output element */ static class DelegatingAggregator<AggInputT, AggOutputT> implements Aggregator<AggInputT, AggOutputT>, Serializable { private final UUID id; private final String name; private final CombineFn<AggInputT, ?, AggOutputT> combineFn; private Aggregator<AggInputT, ?> delegate; public DelegatingAggregator(String name, CombineFn<? super AggInputT, ?, AggOutputT> combiner) { this.id = UUID.randomUUID(); this.name = checkNotNull(name, "name cannot be null"); // Safe contravariant cast @SuppressWarnings("unchecked") CombineFn<AggInputT, ?, AggOutputT> specificCombiner = (CombineFn<AggInputT, ?, AggOutputT>) checkNotNull(combiner, "combineFn cannot be null"); this.combineFn = specificCombiner; } @Override public void addValue(AggInputT value) { if (delegate == null) { throw new IllegalStateException( "addValue cannot be called on Aggregator outside of the execution of a DoFn."); } else { delegate.addValue(value); } } @Override public String getName() { return name; } @Override public CombineFn<AggInputT, ?, AggOutputT> getCombineFn() { return combineFn; } /** * Sets the current delegate of the Aggregator. * * @param delegate the delegate to set in this aggregator */ public void setDelegate(Aggregator<AggInputT, ?> delegate) { this.delegate = delegate; } @Override public String toString() { return MoreObjects.toStringHelper(getClass()) .add("name", name) .add("combineFn", combineFn) .toString(); } @Override public int hashCode() { return Objects.hash(id, name, combineFn.getClass()); } /** * Indicates whether some other object is "equal to" this one. * * <p>{@code DelegatingAggregator} instances are equal if they have the same name, their * CombineFns are the same class, and they have identical IDs. */ @Override public boolean equals(Object o) { if (o == this) { return true; } if (o == null) { return false; } if (o instanceof DelegatingAggregator) { DelegatingAggregator<?, ?> that = (DelegatingAggregator<?, ?>) o; return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name) && Objects.equals(this.combineFn.getClass(), that.combineFn.getClass()); } return false; } } }
// // Copyright (c) 2014 Limit Point Systems, 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 tools.viewer.application; import bindings.java.*; import tools.common.gui.*; import tools.common.util.*; import tools.viewer.user.*; import tools.viewer.render.*; import tools.viewer.common.*; import tools.viewer.table.*; import java.awt.*; import java.awt.event.*; import java.lang.reflect.*; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; /** * Dialog for choicing the viewer to open up a FieldActor in. */ public class ViewerDialog extends GenericDialog { protected JComboBox viewersComboBox; protected Hashtable<Class, Vector<Viewer> > viewersMap; protected Viewer selectedViewer = null; protected Class viewerClass = null; protected FieldActorDescriptor actor = null; /** * Constructor */ public ViewerDialog(Frame xowner) { super(xowner, "Open Viewer"); setModal(true); viewersMap = new Hashtable<Class, Vector<Viewer> >(); addPane(createContentPane(), 0); } /** * Create the content panel. */ protected JPanel createContentPane() { // Layout the content panel. viewersComboBox = new JComboBox(); viewersComboBox.setPreferredSize(new Dimension(200, 20)); viewersComboBox.setMaximumSize(new Dimension(200, 20)); viewersComboBox.setMinimumSize(new Dimension(200, 20)); viewersComboBox.setToolTipText("Select Viewer"); JPanel result = new JPanel(); result.setLayout(new BoxLayout(result, BoxLayout.Y_AXIS)); Box box = Box.createHorizontalBox(); box.add(Box.createHorizontalStrut(10)); box.add(viewersComboBox); box.add(Box.createHorizontalStrut(10)); result.add(Box.createVerticalStrut(10)); result.add(box); result.add(Box.createVerticalStrut(10)); return result; } /** * Clear the opened viewers. */ public void clearViewers() { // Hide all viewers. Enumeration<Class> keys = viewersMap.keys(); Vector<Viewer> viewers; while(keys.hasMoreElements()) { viewers = viewersMap.get(keys.nextElement()); for(int i=0; i<viewers.size(); i++) { Viewer viewer = viewers.get(i); viewer.setVisible(false); viewer.detachStates(); } } // Clear the viewer map. viewersMap.clear(); viewersComboBox.removeAllItems(); } /** * True, if there is at least one viewer open. */ public boolean hasOpenViewer() { return (viewersMap.size() > 0); } /** * Open existing viewer. */ public void open() { viewerClass = null; actor = null; Enumeration<Class> keys = viewersMap.keys(); Vector<Viewer> viewers; viewersComboBox.removeAllItems(); while(keys.hasMoreElements()) { viewers = viewersMap.get(keys.nextElement()); for(int i=0; i<viewers.size(); i++) { viewersComboBox.addItem(viewers.get(i)); } } setVisible(true); } /** * Open this <code>ViewerDialog</code> for viewer type, xviewerClass * with the <code>FieldActorDescriptor</code>, xactor. If xviewerClass * is null, give the user a choice to open any existing viewer. */ public void open(Class xviewerClass, FieldActorDescriptor xactor) { viewerClass = xviewerClass; actor = xactor; // Get the viewer vector and initialize the combo box. Vector<Viewer> viewers = viewersMap.get(viewerClass); int selected = -1; viewersComboBox.removeAllItems(); if(viewers != null) { Viewer viewer; for(int i=0; i<viewers.size(); i++) { viewer = viewers.get(i); viewersComboBox.addItem(viewer); if(viewer == selectedViewer) selected = i; } } viewersComboBox.addItem("New Viewer"); // Set the selected viewer. if(selected >= 0) viewersComboBox.setSelectedIndex(selected); else viewersComboBox.setSelectedIndex(viewersComboBox.getItemCount()-1); setVisible(true); } /** * Set the selected viewer */ public void setSelectedViewer(Viewer xselectedViewer) { selectedViewer = xselectedViewer; } /** * Cancels the dialog. */ public void cancelPressed() { setVisible(false); } /** * Accepts the selected filter. */ public void okPressed() { setVisible(false); Object item = viewersComboBox.getSelectedItem(); if(item instanceof Viewer) { // An existing viewer has been selected. Viewer viewer = (Viewer) item; if(actor != null) { // Add the field actor if(!viewer.addFieldActor(actor)) { toFront(); return; } } viewer.setVisible(true); viewer.setExtendedState(JFrame.NORMAL); viewer.toFront(); } else { try { // Create a new viewer. Viewer viewer = createViewer(viewerClass, FieldActorDescriptor.class, actor); if(viewer == null) return; // Add viewer to the list addViewer(viewer); } catch(Exception e) { // $$HACK: Need better error handling. e.printStackTrace(); } } } /** * Create and return a <code>Viewer</code> */ public Viewer createViewer(Class xviewerClass, Class xinputClass, Object xinput) throws IOException { try { // Create a new viewer. Vector<Viewer> viewers = viewersMap.get(xviewerClass); // Get the title constructor. Constructor constructor = xviewerClass.getConstructor(Integer.class, xinputClass); // Instantiate the viewer int index = 1; if(viewers != null) index = viewers.size() + 1; Integer id = new Integer(index); Viewer viewer = (Viewer) constructor.newInstance(id, xinput); return viewer; } catch(InvocationTargetException e) { // Throw the cause of an invocation exception to // the client if it is an IOException. This will allow // the user interface to catch Script reading problems // and report them to the user. Otherwise, the // invocation exception is an error in the code // and should be dumped. if(e.getCause() instanceof IOException) throw (IOException) e.getCause(); // $$HACK: Need better error handling e.printStackTrace(); } catch(Exception e) { // $$HACK: Need better error handling. e.printStackTrace(); } return null; } /** * Add a viewer to this dialog */ public void addViewer(Viewer xviewer) { // Show viewer xviewer.setVisible(true); // Add viewer to the list Vector<Viewer> viewers = viewersMap.get(xviewer.getClass()); if(viewers == null) { // Viewer list is not available for the class type. Make // such a list. viewers = new Vector<Viewer>(); viewersMap.put(xviewer.getClass(), viewers); } viewers.add(xviewer); } }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002-2010 Oracle. All rights reserved. * * $Id: ReflectionAccessor.java,v 1.30 2010/01/04 15:50:55 cwl Exp $ */ package com.sleepycat.persist.impl; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.List; import com.sleepycat.compat.DbCompat; /** * Implements Accessor using reflection. * * @author Mark Hayes */ class ReflectionAccessor implements Accessor { private static final FieldAccess[] EMPTY_KEYS = {}; private Class type; private Accessor superAccessor; private Constructor constructor; private FieldAccess priKey; private FieldAccess[] secKeys; private FieldAccess[] nonKeys; private ReflectionAccessor(Class type, Accessor superAccessor) { this.type = type; this.superAccessor = superAccessor; try { constructor = type.getDeclaredConstructor(); } catch (NoSuchMethodException e) { throw DbCompat.unexpectedState(type.getName()); } if (!Modifier.isPublic(constructor.getModifiers())) { setAccessible(constructor, type.getName() + "()"); } } /** * Creates an accessor for a complex type. */ ReflectionAccessor(Catalog catalog, Class type, Accessor superAccessor, FieldInfo priKeyField, List<FieldInfo> secKeyFields, List<FieldInfo> nonKeyFields) { this(type, superAccessor); if (priKeyField != null) { priKey = getField(catalog, priKeyField, true /*isRequiredKeyField*/, false /*isCompositeKey*/); } else { priKey = null; } if (secKeyFields.size() > 0) { secKeys = getFields(catalog, secKeyFields, false /*isRequiredKeyField*/, false /*isCompositeKey*/); } else { secKeys = EMPTY_KEYS; } if (nonKeyFields.size() > 0) { nonKeys = getFields(catalog, nonKeyFields, false /*isRequiredKeyField*/, false /*isCompositeKey*/); } else { nonKeys = EMPTY_KEYS; } } /** * Creates an accessor for a composite key type. */ ReflectionAccessor(Catalog catalog, Class type, List<FieldInfo> fieldInfos) { this(type, null); priKey = null; secKeys = EMPTY_KEYS; nonKeys = getFields(catalog, fieldInfos, true /*isRequiredKeyField*/, true /*isCompositeKey*/); } private FieldAccess[] getFields(Catalog catalog, List<FieldInfo> fieldInfos, boolean isRequiredKeyField, boolean isCompositeKey) { int index = 0; FieldAccess[] fields = new FieldAccess[fieldInfos.size()]; for (FieldInfo info : fieldInfos) { fields[index] = getField (catalog, info, isRequiredKeyField, isCompositeKey); index += 1; } return fields; } private FieldAccess getField(Catalog catalog, FieldInfo fieldInfo, boolean isRequiredKeyField, boolean isCompositeKey) { Field field; try { field = type.getDeclaredField(fieldInfo.getName()); } catch (NoSuchFieldException e) { throw DbCompat.unexpectedException(e); } if (!Modifier.isPublic(field.getModifiers())) { setAccessible(field, field.getName()); } Class fieldCls = field.getType(); if (fieldCls.isPrimitive()) { assert SimpleCatalog.isSimpleType(fieldCls); return new PrimitiveAccess (field, SimpleCatalog.getSimpleFormat(fieldCls)); } else if (isRequiredKeyField) { Format format = catalog.getFormat(fieldInfo.getClassName()); assert format != null; return new KeyObjectAccess(field, format); } else { return new ObjectAccess(field); } } private void setAccessible(AccessibleObject object, String memberName) { try { object.setAccessible(true); } catch (SecurityException e) { throw new IllegalStateException ("Unable to access non-public member: " + type.getName() + '.' + memberName + ". Please configure the Java Security Manager setting: " + " ReflectPermission suppressAccessChecks", e); } } public Object newInstance() { try { return constructor.newInstance(); } catch (IllegalAccessException e) { throw DbCompat.unexpectedException(e); } catch (InstantiationException e) { throw DbCompat.unexpectedException(e); } catch (InvocationTargetException e) { throw DbCompat.unexpectedException(e); } } public Object newArray(int len) { return Array.newInstance(type, len); } public boolean isPriKeyFieldNullOrZero(Object o) { try { if (priKey != null) { return priKey.isNullOrZero(o); } else if (superAccessor != null) { return superAccessor.isPriKeyFieldNullOrZero(o); } else { throw DbCompat.unexpectedState("No primary key field"); } } catch (IllegalAccessException e) { throw DbCompat.unexpectedException(e); } } public void writePriKeyField(Object o, EntityOutput output) { try { if (priKey != null) { priKey.write(o, output); } else if (superAccessor != null) { superAccessor.writePriKeyField(o, output); } else { throw DbCompat.unexpectedState("No primary key field"); } } catch (IllegalAccessException e) { throw DbCompat.unexpectedException(e); } } public void readPriKeyField(Object o, EntityInput input) { try { if (priKey != null) { priKey.read(o, input); } else if (superAccessor != null) { superAccessor.readPriKeyField(o, input); } else { throw DbCompat.unexpectedState("No primary key field"); } } catch (IllegalAccessException e) { throw DbCompat.unexpectedException(e); } } public void writeSecKeyFields(Object o, EntityOutput output) { try { if (priKey != null && !priKey.isPrimitive) { output.registerPriKeyObject(priKey.field.get(o)); } if (superAccessor != null) { superAccessor.writeSecKeyFields(o, output); } for (int i = 0; i < secKeys.length; i += 1) { secKeys[i].write(o, output); } } catch (IllegalAccessException e) { throw DbCompat.unexpectedException(e); } } public void readSecKeyFields(Object o, EntityInput input, int startField, int endField, int superLevel) { try { if (priKey != null && !priKey.isPrimitive) { input.registerPriKeyObject(priKey.field.get(o)); } if (superLevel != 0 && superAccessor != null) { superAccessor.readSecKeyFields (o, input, startField, endField, superLevel - 1); } else { if (superLevel > 0) { throw DbCompat.unexpectedState ("Superclass does not exist"); } } if (superLevel <= 0) { for (int i = startField; i <= endField && i < secKeys.length; i += 1) { secKeys[i].read(o, input); } } } catch (IllegalAccessException e) { throw DbCompat.unexpectedException(e); } } public void writeNonKeyFields(Object o, EntityOutput output) { try { if (superAccessor != null) { superAccessor.writeNonKeyFields(o, output); } for (int i = 0; i < nonKeys.length; i += 1) { nonKeys[i].write(o, output); } } catch (IllegalAccessException e) { throw DbCompat.unexpectedException(e); } } public void readNonKeyFields(Object o, EntityInput input, int startField, int endField, int superLevel) { try { if (superLevel != 0 && superAccessor != null) { superAccessor.readNonKeyFields (o, input, startField, endField, superLevel - 1); } else { if (superLevel > 0) { throw DbCompat.unexpectedState ("Superclass does not exist"); } } if (superLevel <= 0) { for (int i = startField; i <= endField && i < nonKeys.length; i += 1) { nonKeys[i].read(o, input); } } } catch (IllegalAccessException e) { throw DbCompat.unexpectedException(e); } } public void writeCompositeKeyFields(Object o, EntityOutput output) { try { for (int i = 0; i < nonKeys.length; i += 1) { nonKeys[i].write(o, output); } } catch (IllegalAccessException e) { throw DbCompat.unexpectedException(e); } } public void readCompositeKeyFields(Object o, EntityInput input) { try { for (int i = 0; i < nonKeys.length; i += 1) { nonKeys[i].read(o, input); } } catch (IllegalAccessException e) { throw DbCompat.unexpectedException(e); } } public Object getField(Object o, int field, int superLevel, boolean isSecField) { if (superLevel > 0) { return superAccessor.getField (o, field, superLevel - 1, isSecField); } try { Field fld = isSecField ? secKeys[field].field : nonKeys[field].field; return fld.get(o); } catch (IllegalAccessException e) { throw DbCompat.unexpectedException(e); } } public void setField(Object o, int field, int superLevel, boolean isSecField, Object value) { if (superLevel > 0) { superAccessor.setField (o, field, superLevel - 1, isSecField, value); return; } try { Field fld = isSecField ? secKeys[field].field : nonKeys[field].field; fld.set(o, value); } catch (IllegalAccessException e) { throw DbCompat.unexpectedException(e); } } /** * Abstract base class for field access classes. */ private static abstract class FieldAccess { Field field; boolean isPrimitive; FieldAccess(Field field) { this.field = field; isPrimitive = field.getType().isPrimitive(); } /** * Writes a field. */ abstract void write(Object o, EntityOutput out) throws IllegalAccessException; /** * Reads a field. */ abstract void read(Object o, EntityInput in) throws IllegalAccessException; /** * Returns whether a field is null (for reference types) or zero (for * primitive integer types). This implementation handles the reference * types. */ boolean isNullOrZero(Object o) throws IllegalAccessException { return field.get(o) == null; } } /** * Access for fields with object types. */ private static class ObjectAccess extends FieldAccess { ObjectAccess(Field field) { super(field); } @Override void write(Object o, EntityOutput out) throws IllegalAccessException { out.writeObject(field.get(o), null); } @Override void read(Object o, EntityInput in) throws IllegalAccessException { field.set(o, in.readObject()); } } /** * Access for primary key fields and composite key fields with object * types. */ private static class KeyObjectAccess extends FieldAccess { private Format format; KeyObjectAccess(Field field, Format format) { super(field); this.format = format; } @Override void write(Object o, EntityOutput out) throws IllegalAccessException { out.writeKeyObject(field.get(o), format); } @Override void read(Object o, EntityInput in) throws IllegalAccessException { field.set(o, in.readKeyObject(format)); } } /** * Access for fields with primitive types. */ private static class PrimitiveAccess extends FieldAccess { private SimpleFormat format; PrimitiveAccess(Field field, SimpleFormat format) { super(field); this.format = format; } @Override void write(Object o, EntityOutput out) throws IllegalAccessException { format.writePrimitiveField(o, out, field); } @Override void read(Object o, EntityInput in) throws IllegalAccessException { format.readPrimitiveField(o, in, field); } @Override boolean isNullOrZero(Object o) throws IllegalAccessException { return field.getLong(o) == 0; } } }
/** * 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.hadoop.hdfs.server.blockmanagement; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.EnumSet; import java.util.List; import java.util.Random; import org.apache.commons.logging.impl.Log4JLogger; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.BlockReader; import org.apache.hadoop.hdfs.BlockReaderFactory; import org.apache.hadoop.hdfs.ClientContext; import org.apache.hadoop.hdfs.DFSClient; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.DFSTestUtil; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.RemotePeerFactory; import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys; import org.apache.hadoop.hdfs.net.Peer; import org.apache.hadoop.hdfs.net.TcpPeerServer; import org.apache.hadoop.hdfs.protocol.DatanodeID; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.ExtendedBlock; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier; import org.apache.hadoop.hdfs.security.token.block.BlockTokenSecretManager; import org.apache.hadoop.hdfs.security.token.block.InvalidBlockTokenException; import org.apache.hadoop.hdfs.security.token.block.SecurityTestUtil; import org.apache.hadoop.hdfs.server.balancer.TestBalancer; import org.apache.hadoop.hdfs.server.common.HdfsServerConstants; import org.apache.hadoop.hdfs.server.datanode.CachingStrategy; import org.apache.hadoop.hdfs.server.namenode.NameNode; import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.token.Token; import org.apache.log4j.Level; import org.junit.Assert; import org.junit.Test; public class TestBlockTokenWithDFS { private static final int BLOCK_SIZE = 1024; private static final int FILE_SIZE = 2 * BLOCK_SIZE; private static final String FILE_TO_READ = "/fileToRead.dat"; private static final String FILE_TO_WRITE = "/fileToWrite.dat"; private static final String FILE_TO_APPEND = "/fileToAppend.dat"; private final byte[] rawData = new byte[FILE_SIZE]; { ((Log4JLogger) DFSClient.LOG).getLogger().setLevel(Level.ALL); Random r = new Random(); r.nextBytes(rawData); } private void createFile(FileSystem fs, Path filename) throws IOException { FSDataOutputStream out = fs.create(filename); out.write(rawData); out.close(); } // read a file using blockSeekTo() private boolean checkFile1(FSDataInputStream in) { byte[] toRead = new byte[FILE_SIZE]; int totalRead = 0; int nRead = 0; try { while ((nRead = in.read(toRead, totalRead, toRead.length - totalRead)) > 0) { totalRead += nRead; } } catch (IOException e) { return false; } assertEquals("Cannot read file.", toRead.length, totalRead); return checkFile(toRead); } // read a file using fetchBlockByteRange() private boolean checkFile2(FSDataInputStream in) { byte[] toRead = new byte[FILE_SIZE]; try { assertEquals("Cannot read file", toRead.length, in.read(0, toRead, 0, toRead.length)); } catch (IOException e) { return false; } return checkFile(toRead); } private boolean checkFile(byte[] fileToCheck) { if (fileToCheck.length != rawData.length) { return false; } for (int i = 0; i < fileToCheck.length; i++) { if (fileToCheck[i] != rawData[i]) { return false; } } return true; } // creates a file and returns a descriptor for writing to it private static FSDataOutputStream writeFile(FileSystem fileSys, Path name, short repl, long blockSize) throws IOException { FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf() .getInt(CommonConfigurationKeys.IO_FILE_BUFFER_SIZE_KEY, 4096), repl, blockSize); return stm; } // try reading a block using a BlockReader directly private static void tryRead(final Configuration conf, LocatedBlock lblock, boolean shouldSucceed) { InetSocketAddress targetAddr = null; IOException ioe = null; BlockReader blockReader = null; ExtendedBlock block = lblock.getBlock(); try { DatanodeInfo[] nodes = lblock.getLocations(); targetAddr = NetUtils.createSocketAddr(nodes[0].getXferAddr()); blockReader = new BlockReaderFactory(new DFSClient.Conf(conf)). setFileName(BlockReaderFactory.getFileName(targetAddr, "test-blockpoolid", block.getBlockId())). setBlock(block). setBlockToken(lblock.getBlockToken()). setInetSocketAddress(targetAddr). setStartOffset(0). setLength(-1). setVerifyChecksum(true). setClientName("TestBlockTokenWithDFS"). setDatanodeInfo(nodes[0]). setCachingStrategy(CachingStrategy.newDefaultStrategy()). setClientCacheContext(ClientContext.getFromConf(conf)). setConfiguration(conf). setRemotePeerFactory(new RemotePeerFactory() { @Override public Peer newConnectedPeer(InetSocketAddress addr, Token<BlockTokenIdentifier> blockToken, DatanodeID datanodeId) throws IOException { Peer peer = null; Socket sock = NetUtils.getDefaultSocketFactory(conf).createSocket(); try { sock.connect(addr, HdfsServerConstants.READ_TIMEOUT); sock.setSoTimeout(HdfsServerConstants.READ_TIMEOUT); peer = TcpPeerServer.peerFromSocket(sock); } finally { if (peer == null) { IOUtils.closeSocket(sock); } } return peer; } }). build(); } catch (IOException ex) { ioe = ex; } finally { if (blockReader != null) { try { blockReader.close(); } catch (IOException e) { throw new RuntimeException(e); } } } if (shouldSucceed) { Assert.assertNotNull("OP_READ_BLOCK: access token is invalid, " + "when it is expected to be valid", blockReader); } else { Assert.assertNotNull("OP_READ_BLOCK: access token is valid, " + "when it is expected to be invalid", ioe); Assert.assertTrue( "OP_READ_BLOCK failed due to reasons other than access token: ", ioe instanceof InvalidBlockTokenException); } } // get a conf for testing private static Configuration getConf(int numDataNodes) { Configuration conf = new Configuration(); conf.setBoolean(DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, true); conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE); conf.setInt("io.bytes.per.checksum", BLOCK_SIZE); conf.setInt(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1); conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, numDataNodes); conf.setInt("ipc.client.connect.max.retries", 0); // Set short retry timeouts so this test runs faster conf.setInt(HdfsClientConfigKeys.Retry.WINDOW_BASE_KEY, 10); return conf; } /** * testing that APPEND operation can handle token expiration when * re-establishing pipeline is needed */ @Test public void testAppend() throws Exception { MiniDFSCluster cluster = null; int numDataNodes = 2; Configuration conf = getConf(numDataNodes); try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDataNodes).build(); cluster.waitActive(); assertEquals(numDataNodes, cluster.getDataNodes().size()); final NameNode nn = cluster.getNameNode(); final BlockManager bm = nn.getNamesystem().getBlockManager(); final BlockTokenSecretManager sm = bm.getBlockTokenSecretManager(); // set a short token lifetime (1 second) SecurityTestUtil.setBlockTokenLifetime(sm, 1000L); Path fileToAppend = new Path(FILE_TO_APPEND); FileSystem fs = cluster.getFileSystem(); // write a one-byte file FSDataOutputStream stm = writeFile(fs, fileToAppend, (short) numDataNodes, BLOCK_SIZE); stm.write(rawData, 0, 1); stm.close(); // open the file again for append stm = fs.append(fileToAppend); int mid = rawData.length - 1; stm.write(rawData, 1, mid - 1); stm.hflush(); /* * wait till token used in stm expires */ Token<BlockTokenIdentifier> token = DFSTestUtil.getBlockToken(stm); while (!SecurityTestUtil.isBlockTokenExpired(token)) { try { Thread.sleep(10); } catch (InterruptedException ignored) { } } // remove a datanode to force re-establishing pipeline cluster.stopDataNode(0); // append the rest of the file stm.write(rawData, mid, rawData.length - mid); stm.close(); // check if append is successful FSDataInputStream in5 = fs.open(fileToAppend); assertTrue(checkFile1(in5)); } finally { if (cluster != null) { cluster.shutdown(); } } } /** * testing that WRITE operation can handle token expiration when * re-establishing pipeline is needed */ @Test public void testWrite() throws Exception { MiniDFSCluster cluster = null; int numDataNodes = 2; Configuration conf = getConf(numDataNodes); try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDataNodes).build(); cluster.waitActive(); assertEquals(numDataNodes, cluster.getDataNodes().size()); final NameNode nn = cluster.getNameNode(); final BlockManager bm = nn.getNamesystem().getBlockManager(); final BlockTokenSecretManager sm = bm.getBlockTokenSecretManager(); // set a short token lifetime (1 second) SecurityTestUtil.setBlockTokenLifetime(sm, 1000L); Path fileToWrite = new Path(FILE_TO_WRITE); FileSystem fs = cluster.getFileSystem(); FSDataOutputStream stm = writeFile(fs, fileToWrite, (short) numDataNodes, BLOCK_SIZE); // write a partial block int mid = rawData.length - 1; stm.write(rawData, 0, mid); stm.hflush(); /* * wait till token used in stm expires */ Token<BlockTokenIdentifier> token = DFSTestUtil.getBlockToken(stm); while (!SecurityTestUtil.isBlockTokenExpired(token)) { try { Thread.sleep(10); } catch (InterruptedException ignored) { } } // remove a datanode to force re-establishing pipeline cluster.stopDataNode(0); // write the rest of the file stm.write(rawData, mid, rawData.length - mid); stm.close(); // check if write is successful FSDataInputStream in4 = fs.open(fileToWrite); assertTrue(checkFile1(in4)); } finally { if (cluster != null) { cluster.shutdown(); } } } @Test public void testRead() throws Exception { MiniDFSCluster cluster = null; int numDataNodes = 2; Configuration conf = getConf(numDataNodes); try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDataNodes).build(); cluster.waitActive(); assertEquals(numDataNodes, cluster.getDataNodes().size()); final NameNode nn = cluster.getNameNode(); final NamenodeProtocols nnProto = nn.getRpcServer(); final BlockManager bm = nn.getNamesystem().getBlockManager(); final BlockTokenSecretManager sm = bm.getBlockTokenSecretManager(); // set a short token lifetime (1 second) initially SecurityTestUtil.setBlockTokenLifetime(sm, 1000L); Path fileToRead = new Path(FILE_TO_READ); FileSystem fs = cluster.getFileSystem(); createFile(fs, fileToRead); /* * setup for testing expiration handling of cached tokens */ // read using blockSeekTo(). Acquired tokens are cached in in1 FSDataInputStream in1 = fs.open(fileToRead); assertTrue(checkFile1(in1)); // read using blockSeekTo(). Acquired tokens are cached in in2 FSDataInputStream in2 = fs.open(fileToRead); assertTrue(checkFile1(in2)); // read using fetchBlockByteRange(). Acquired tokens are cached in in3 FSDataInputStream in3 = fs.open(fileToRead); assertTrue(checkFile2(in3)); /* * testing READ interface on DN using a BlockReader */ DFSClient client = null; try { client = new DFSClient(new InetSocketAddress("localhost", cluster.getNameNodePort()), conf); } finally { if (client != null) client.close(); } List<LocatedBlock> locatedBlocks = nnProto.getBlockLocations( FILE_TO_READ, 0, FILE_SIZE).getLocatedBlocks(); LocatedBlock lblock = locatedBlocks.get(0); // first block Token<BlockTokenIdentifier> myToken = lblock.getBlockToken(); // verify token is not expired assertFalse(SecurityTestUtil.isBlockTokenExpired(myToken)); // read with valid token, should succeed tryRead(conf, lblock, true); /* * wait till myToken and all cached tokens in in1, in2 and in3 expire */ while (!SecurityTestUtil.isBlockTokenExpired(myToken)) { try { Thread.sleep(10); } catch (InterruptedException ignored) { } } /* * continue testing READ interface on DN using a BlockReader */ // verify token is expired assertTrue(SecurityTestUtil.isBlockTokenExpired(myToken)); // read should fail tryRead(conf, lblock, false); // use a valid new token lblock.setBlockToken(sm.generateToken(lblock.getBlock(), EnumSet.of(BlockTokenSecretManager.AccessMode.READ))); // read should succeed tryRead(conf, lblock, true); // use a token with wrong blockID ExtendedBlock wrongBlock = new ExtendedBlock(lblock.getBlock() .getBlockPoolId(), lblock.getBlock().getBlockId() + 1); lblock.setBlockToken(sm.generateToken(wrongBlock, EnumSet.of(BlockTokenSecretManager.AccessMode.READ))); // read should fail tryRead(conf, lblock, false); // use a token with wrong access modes lblock.setBlockToken(sm.generateToken(lblock.getBlock(), EnumSet.of(BlockTokenSecretManager.AccessMode.WRITE, BlockTokenSecretManager.AccessMode.COPY, BlockTokenSecretManager.AccessMode.REPLACE))); // read should fail tryRead(conf, lblock, false); // set a long token lifetime for future tokens SecurityTestUtil.setBlockTokenLifetime(sm, 600 * 1000L); /* * testing that when cached tokens are expired, DFSClient will re-fetch * tokens transparently for READ. */ // confirm all tokens cached in in1 are expired by now List<LocatedBlock> lblocks = DFSTestUtil.getAllBlocks(in1); for (LocatedBlock blk : lblocks) { assertTrue(SecurityTestUtil.isBlockTokenExpired(blk.getBlockToken())); } // verify blockSeekTo() is able to re-fetch token transparently in1.seek(0); assertTrue(checkFile1(in1)); // confirm all tokens cached in in2 are expired by now List<LocatedBlock> lblocks2 = DFSTestUtil.getAllBlocks(in2); for (LocatedBlock blk : lblocks2) { assertTrue(SecurityTestUtil.isBlockTokenExpired(blk.getBlockToken())); } // verify blockSeekTo() is able to re-fetch token transparently (testing // via another interface method) assertTrue(in2.seekToNewSource(0)); assertTrue(checkFile1(in2)); // confirm all tokens cached in in3 are expired by now List<LocatedBlock> lblocks3 = DFSTestUtil.getAllBlocks(in3); for (LocatedBlock blk : lblocks3) { assertTrue(SecurityTestUtil.isBlockTokenExpired(blk.getBlockToken())); } // verify fetchBlockByteRange() is able to re-fetch token transparently assertTrue(checkFile2(in3)); /* * testing that after datanodes are restarted on the same ports, cached * tokens should still work and there is no need to fetch new tokens from * namenode. This test should run while namenode is down (to make sure no * new tokens can be fetched from namenode). */ // restart datanodes on the same ports that they currently use assertTrue(cluster.restartDataNodes(true)); cluster.waitActive(); assertEquals(numDataNodes, cluster.getDataNodes().size()); cluster.shutdownNameNode(0); // confirm tokens cached in in1 are still valid lblocks = DFSTestUtil.getAllBlocks(in1); for (LocatedBlock blk : lblocks) { assertFalse(SecurityTestUtil.isBlockTokenExpired(blk.getBlockToken())); } // verify blockSeekTo() still works (forced to use cached tokens) in1.seek(0); assertTrue(checkFile1(in1)); // confirm tokens cached in in2 are still valid lblocks2 = DFSTestUtil.getAllBlocks(in2); for (LocatedBlock blk : lblocks2) { assertFalse(SecurityTestUtil.isBlockTokenExpired(blk.getBlockToken())); } // verify blockSeekTo() still works (forced to use cached tokens) in2.seekToNewSource(0); assertTrue(checkFile1(in2)); // confirm tokens cached in in3 are still valid lblocks3 = DFSTestUtil.getAllBlocks(in3); for (LocatedBlock blk : lblocks3) { assertFalse(SecurityTestUtil.isBlockTokenExpired(blk.getBlockToken())); } // verify fetchBlockByteRange() still works (forced to use cached tokens) assertTrue(checkFile2(in3)); /* * testing that when namenode is restarted, cached tokens should still * work and there is no need to fetch new tokens from namenode. Like the * previous test, this test should also run while namenode is down. The * setup for this test depends on the previous test. */ // restart the namenode and then shut it down for test cluster.restartNameNode(0); cluster.shutdownNameNode(0); // verify blockSeekTo() still works (forced to use cached tokens) in1.seek(0); assertTrue(checkFile1(in1)); // verify again blockSeekTo() still works (forced to use cached tokens) in2.seekToNewSource(0); assertTrue(checkFile1(in2)); // verify fetchBlockByteRange() still works (forced to use cached tokens) assertTrue(checkFile2(in3)); /* * testing that after both namenode and datanodes got restarted (namenode * first, followed by datanodes), DFSClient can't access DN without * re-fetching tokens and is able to re-fetch tokens transparently. The * setup of this test depends on the previous test. */ // restore the cluster and restart the datanodes for test cluster.restartNameNode(0); assertTrue(cluster.restartDataNodes(true)); cluster.waitActive(); assertEquals(numDataNodes, cluster.getDataNodes().size()); // shutdown namenode so that DFSClient can't get new tokens from namenode cluster.shutdownNameNode(0); // verify blockSeekTo() fails (cached tokens become invalid) in1.seek(0); assertFalse(checkFile1(in1)); // verify fetchBlockByteRange() fails (cached tokens become invalid) assertFalse(checkFile2(in3)); // restart the namenode to allow DFSClient to re-fetch tokens cluster.restartNameNode(0); // verify blockSeekTo() works again (by transparently re-fetching // tokens from namenode) in1.seek(0); assertTrue(checkFile1(in1)); in2.seekToNewSource(0); assertTrue(checkFile1(in2)); // verify fetchBlockByteRange() works again (by transparently // re-fetching tokens from namenode) assertTrue(checkFile2(in3)); /* * testing that when datanodes are restarted on different ports, DFSClient * is able to re-fetch tokens transparently to connect to them */ // restart datanodes on newly assigned ports assertTrue(cluster.restartDataNodes(false)); cluster.waitActive(); assertEquals(numDataNodes, cluster.getDataNodes().size()); // verify blockSeekTo() is able to re-fetch token transparently in1.seek(0); assertTrue(checkFile1(in1)); // verify blockSeekTo() is able to re-fetch token transparently in2.seekToNewSource(0); assertTrue(checkFile1(in2)); // verify fetchBlockByteRange() is able to re-fetch token transparently assertTrue(checkFile2(in3)); } finally { if (cluster != null) { cluster.shutdown(); } } } /** * Integration testing of access token, involving NN, DN, and Balancer */ @Test public void testEnd2End() throws Exception { Configuration conf = new Configuration(); conf.setBoolean(DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, true); new TestBalancer().integrationTest(conf); } }