index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/CassJMeter/src/main/java/com/netflix/jmeter
Create_ds/CassJMeter/src/main/java/com/netflix/jmeter/report/ServoSummariserGui.java
package com.netflix.jmeter.report; import java.awt.BorderLayout; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.visualizers.gui.AbstractListenerGui; public class ServoSummariserGui extends AbstractListenerGui { private static final long serialVersionUID = 1L; private static final String LABEL = "Epic Summariser"; public ServoSummariserGui() { super(); init(); } public String getLabelResource() { return LABEL; } @Override public String getStaticLabel() { return LABEL; } @Override public void configure(TestElement el) { super.configure(el); } public TestElement createTestElement() { AbstractSummariser summariser = new ServoSummariser(); modifyTestElement(summariser); return summariser; } public void modifyTestElement(TestElement summariser) { super.configureTestElement(summariser); } private void init() { setLayout(new BorderLayout()); setBorder(makeBorder()); add(makeTitlePanel(), BorderLayout.NORTH); } }
7,600
0
Create_ds/pytheas/pytheas-helloworld/src/test/java/com/netflix/explorers
Create_ds/pytheas/pytheas-helloworld/src/test/java/com/netflix/explorers/helloworld/ExplorerAppTest.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.helloworld; import static org.junit.Assert.assertEquals; import com.google.common.collect.ImmutableMap; import com.google.inject.servlet.GuiceFilter; import com.netflix.karyon.server.guice.KaryonGuiceContextListener; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.ServletContextHandler; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.ServerSocket; import java.util.Map; import javax.ws.rs.core.MediaType; public class ExplorerAppTest { private static final Logger LOG = LoggerFactory.getLogger(ExplorerAppTest.class); private static final Map<String, String> REST_END_POINTS = new ImmutableMap.Builder<String, String>() .put("/", MediaType.TEXT_HTML) .put("/helloworld", MediaType.TEXT_HTML) .put("/helloworld/list", MediaType.APPLICATION_JSON) .build(); private static int TEST_LOCAL_PORT; static { try { TEST_LOCAL_PORT = getLocalPort(); } catch (IOException e) { LOG.error("IOException in finding local port for starting jetty ", e); } } private static int getLocalPort() throws IOException { ServerSocket ss = new ServerSocket(0); ss.setReuseAddress(true); return ss.getLocalPort(); } private Server server; @Before public void init() throws Exception { System.setProperty("archaius.deployment.applicationId","helloworld-app"); System.setProperty("archaius.deployment.environment","dev"); server = new Server(TEST_LOCAL_PORT); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); context.addEventListener(new KaryonGuiceContextListener()); context.addFilter(GuiceFilter.class, "/*", 1); context.addServlet(DefaultServlet.class, "/"); server.setHandler(context); server.start(); } @After public void cleanup() throws Exception { if (server != null) { server.stop(); } } @Test public void verifyRESTEndpoints() throws Exception { HttpClient client = new DefaultHttpClient(); for (Map.Entry<String, String> restEndPoint : REST_END_POINTS.entrySet()) { final String endPoint = buildLocalHostEndpoint(restEndPoint.getKey()); LOG.info("REST endpoint " + endPoint); HttpGet restGet = new HttpGet(endPoint); HttpResponse response = client.execute(restGet); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(restEndPoint.getValue(), response.getEntity().getContentType().getValue()); // need to consume full response before make another rest call with // the default SingleClientConnManager used with DefaultHttpClient EntityUtils.consume(response.getEntity()); } } private String buildLocalHostEndpoint(String endPoint) { return "http://localhost:" + TEST_LOCAL_PORT + endPoint; } }
7,601
0
Create_ds/pytheas/pytheas-helloworld/src/test/java/com/netflix/explorers
Create_ds/pytheas/pytheas-helloworld/src/test/java/com/netflix/explorers/providers/MyFreemarkerTemplateProvider.java
package com.netflix.explorers.providers; import com.netflix.explorers.ExplorerManager; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.ext.Provider; @Provider @Singleton public class MyFreemarkerTemplateProvider extends FreemarkerTemplateProvider { @Inject public MyFreemarkerTemplateProvider(ExplorerManager manager) { super(manager); } }
7,602
0
Create_ds/pytheas/pytheas-helloworld/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-helloworld/src/main/java/com/netflix/explorers/helloworld/HelloWorldExplorer.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.helloworld; import com.google.inject.Singleton; import com.netflix.explorers.AbstractExplorerModule; @Singleton public class HelloWorldExplorer extends AbstractExplorerModule { public HelloWorldExplorer() { super("helloworld"); } }
7,603
0
Create_ds/pytheas/pytheas-helloworld/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-helloworld/src/main/java/com/netflix/explorers/helloworld/HelloWorldGuiceModule.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.helloworld; import com.google.inject.AbstractModule; import com.google.inject.multibindings.Multibinder; import com.netflix.explorers.Explorer; import com.netflix.explorers.annotations.ExplorerGuiceModule; @ExplorerGuiceModule(jerseyPackagePath = "com.netflix.explorers.helloworld.resources") public class HelloWorldGuiceModule extends AbstractModule { @Override protected void configure() { Multibinder<Explorer> explorersBinder = Multibinder.newSetBinder(binder(), Explorer.class); explorersBinder.addBinding().to(HelloWorldExplorer.class); } }
7,604
0
Create_ds/pytheas/pytheas-helloworld/src/main/java/com/netflix/explorers/helloworld
Create_ds/pytheas/pytheas-helloworld/src/main/java/com/netflix/explorers/helloworld/resources/HelloWorldResource.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.helloworld.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.sun.jersey.api.view.Viewable; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.HashMap; import java.util.Map; @Path("/helloworld") public class HelloWorldResource { private Logger LOG = LoggerFactory.getLogger(HelloWorldResource.class); @GET @Produces( MediaType.TEXT_HTML ) public Viewable showIndex() { LOG.info("showIndex"); Map<String, Object> model = new HashMap<String, Object>(); return new Viewable( "/helloworld/index.ftl", model ); } @Produces({"application/json"}) @Path("/list") @GET public Response getCountryList() { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream resourceAsStream = classLoader.getResourceAsStream("country-list"); BufferedReader br = new BufferedReader(new InputStreamReader(resourceAsStream)); JSONObject output = new JSONObject(); String line = null; try { JSONArray countryList = new JSONArray(); while ((line = br.readLine()) != null) { int firstSpaceCharIndex = line.indexOf(" "); final String code = line.substring(0, firstSpaceCharIndex); final String countryName = line.substring(firstSpaceCharIndex + 1); if (code != null && ! code.isEmpty() && countryName != null && ! countryName.isEmpty()) { JSONObject countryObj = new JSONObject(); countryObj.put("code", code); countryObj.put("name", countryName); countryList.put(countryObj); } } output.put("countries", countryList); } catch (IOException e) { LOG.error("IOException in reading country list", e); } catch (JSONException e) { LOG.error("JSONException in building country list ", e); } return Response.ok(output.toString()).build(); } }
7,605
0
Create_ds/pytheas/pytheas-helloworld/src/main/java/com/netflix/explorers/helloworld
Create_ds/pytheas/pytheas-helloworld/src/main/java/com/netflix/explorers/helloworld/resources/HelloWorldAppResource.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.helloworld.resources; import com.sun.jersey.api.view.Viewable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.HashMap; import java.util.Map; @Path("/") public class HelloWorldAppResource { private Logger LOG = LoggerFactory.getLogger(HelloWorldAppResource.class); @GET @Produces( MediaType.TEXT_HTML ) public Viewable showIndex() { LOG.info("home page"); Map<String, Object> model = new HashMap<String, Object>(); return new Viewable( "/helloworld/home.ftl", model ); } }
7,606
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/ExplorersManagerImpl.java
/** * Copyright 2014 Netflix, 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.netflix.explorers; import com.google.common.base.Supplier; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.config.ConfigurationManager; import com.netflix.explorers.context.GlobalModelContext; import com.netflix.explorers.services.ExplorerServiceCachedFactorySupplier; import com.netflix.explorers.services.ExplorerServiceInstanceSupplier; import com.netflix.explorers.sso.SsoAuthProviderWrapper; import org.apache.commons.configuration.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import java.util.*; import java.util.concurrent.ConcurrentMap; @Singleton public class ExplorersManagerImpl implements ExplorerManager { private static final Logger LOG = LoggerFactory.getLogger(ExplorersManagerImpl.class); private final ConcurrentMap<String, Explorer> explorers = Maps.newConcurrentMap(); private final ConcurrentMap<Class<?>, Supplier<?>> services = Maps.newConcurrentMap(); private final GlobalModelContext globalContext; @Inject(optional = true) private Set<Explorer> explorerModules; @Inject(optional=true) private SsoAuthProviderWrapper autoProvider; @Inject public ExplorersManagerImpl(GlobalModelContext globalContext) { this.globalContext = globalContext; } @Override @PostConstruct public synchronized void initialize() { // register explorer instance if (explorerModules != null) { for (Explorer explorer : explorerModules) { registerExplorer(explorer); } } } @Override public synchronized void shutdown() { } @Override public synchronized void registerExplorersFromClassNames(Set<String> classNames) { } @Override public synchronized void registerExplorerFromClassName(String className) throws Exception { } @Override public synchronized void registerExplorer(Explorer explorer) { if (explorers.containsKey(explorer.getName())) { throw new RuntimeException("Already exists"); } explorers.put(explorer.getName(), explorer); } public Collection<Explorer> getExplorers() { ArrayList<Explorer> modules = new ArrayList<Explorer>(this.explorers.values()); Collections.sort(modules, new Comparator<Explorer>() { @Override public int compare(Explorer arg0, Explorer arg1) { return String.valueOf(arg0.getTitle()).compareToIgnoreCase(String.valueOf(arg1.getTitle())); } }); return modules; } @Override public Explorer getExplorer(String name) { return explorers.get(name); } @Override public String getDefaultModule() { String defaultExplorer = globalContext.getDefaultExplorerName(); if (String.valueOf(defaultExplorer).equals("")) { if (!explorers.isEmpty()) { defaultExplorer = explorers.keySet().iterator().next(); } } return defaultExplorer; } @Override public GlobalModelContext getGlobalModel() { return globalContext; } @SuppressWarnings("unchecked") @Override public <T> T getService(Class<T> className) { Supplier<?> supplier = services.get(className); if (supplier == null) return null; return (T)supplier.get(); } @Override public <T> void registerService(Class<T> serviceClass, T instance) { registerService(serviceClass, new ExplorerServiceInstanceSupplier<T>(instance)); } @Override public <T> void registerService(Class<T> serviceClass, Supplier<T> supplier) { if (null != services.putIfAbsent(serviceClass, supplier)) { throw new RuntimeException("Service for " + serviceClass.getCanonicalName() + " already registered"); } } @Override public <T> void registerService(Class<T> serviceClass, Class<? extends T> serviceImplClassName) { registerService(serviceClass, new ExplorerServiceCachedFactorySupplier<T>(serviceImplClassName)); } @Override public Configuration getConfiguration() { return null; } @Override public boolean getHasAuthProvider() { return autoProvider != null && autoProvider.hasSsoAuthProvider(); } @Override public String toString() { return "ExplorersManagerImpl [explorers=" + explorers + ", ExplorerGlobalContext=" + globalContext + "]"; } @Override public void unregisterExplorer(Explorer module) { LOG.info("Removing explorer module " + module.getName()); explorers.remove(module); } }
7,607
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/RemoteExplorerModule.java
/** * Copyright 2014 Netflix, 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.netflix.explorers; import java.util.Map; import java.util.Properties; import java.util.Set; import com.netflix.explorers.model.ExplorerInfoEntity; import com.netflix.explorers.model.MenuItem; public class RemoteExplorerModule implements Explorer { private final ExplorerManager manager; private final ExplorerInfoEntity entity; public RemoteExplorerModule(ExplorerManager manager, ExplorerInfoEntity entity) { this.manager = manager; this.entity = entity; } @Override public void initialize() { manager.registerExplorer(this); } @Override public void initialize(ExplorerManager manager) { } @Override public void shutdown() { manager.unregisterExplorer(this); } @Override public void suspend() { } @Override public void resume() { } @Override public String getName() { return entity.getName(); } @Override public String getTitle() { return entity.getTitle(); } @Override public String getDescription() { return entity.getName(); } @Override public String getAlertMessage() { return null; } @Override public boolean getIsSecure() { return false; } @Override @Deprecated public Map<String, String> getMenuLayout() { return null; } @Override public MenuItem getMenu() { return null; } @Override public String getLayoutName() { return null; } @Override public Properties getProperties() { return null; } @Override public Set<String> getRolesAllowed() { return null; } @Override public boolean getCmcEnabled() { return false; } @Override public String getHome() { return entity.getHome(); } @Override public String toString() { return "RemoteExplorerModule entity = " + entity; } }
7,608
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/PropertiesGlobalModelContext.java
/** * Copyright 2014 Netflix, 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.netflix.explorers; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.util.Map; import java.util.Properties; import java.util.Map.Entry; import com.netflix.config.ConfigurationManager; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.configuration.ConfigurationConverter; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Maps; import com.netflix.explorers.context.GlobalModelContext; import com.netflix.explorers.model.CrossLink; public class PropertiesGlobalModelContext implements GlobalModelContext { private static final Logger LOG = LoggerFactory.getLogger(PropertiesGlobalModelContext.class); public static String PROPERTY_ENVIRONMENT_NAME = "com.netflix.explorers.environmentName"; public static String PROPERTY_CURRENT_REGION = "com.netflix.explorers.currentRegion"; public static String PROPERTY_APPLICATION_NAME = "com.netflix.explorers.applicationName"; public static String PROPERTY_APPLICATION_VERSION = "com.netflix.explorers.applicationVersion"; public static String PROPERTY_IS_LOCAL = "com.netflix.explorers.local"; public static String PROPERTY_HOME_PAGE = "com.netflix.explorers.homepage"; public static String PROPERTY_DEFAULT_PORT = "com.netflix.explorers.defaultPort"; public static String PROPERTY_DATA_CENTER = "com.netflix.explorers.dataCenter"; public static String PROPERTY_DEFAULT_EXPLORER = "com.netflix.explorers.defaultExplorer"; private static final String PROPERTIES_PREFIX = "netflix.explorers"; private final String environmentName; private final String currentRegion; private final String applicationVersion; private final String applicationName; private final Boolean isLocal; // this should be moved outside private final String homePageUrl; private final short defaultPort; private final String defaultExplorerName; private final String dataCenter; private final Map<String, CrossLink> links = Maps.newTreeMap(); private final Properties properties; public PropertiesGlobalModelContext(Properties props) { this.properties = props; environmentName = props.getProperty(PROPERTY_ENVIRONMENT_NAME); currentRegion = props.getProperty(PROPERTY_CURRENT_REGION); applicationVersion = props.getProperty(PROPERTY_APPLICATION_VERSION); applicationName = props.getProperty(PROPERTY_APPLICATION_NAME); isLocal = Boolean.parseBoolean(props.getProperty(PROPERTY_IS_LOCAL, "false")); homePageUrl = props.getProperty(PROPERTY_HOME_PAGE); defaultPort = Short.parseShort(props.getProperty(PROPERTY_DEFAULT_PORT, "8080")); dataCenter = props.getProperty(PROPERTY_DATA_CENTER); defaultExplorerName = props.getProperty(PROPERTY_DEFAULT_EXPLORER); try { Map<Object, Object> dcs = ConfigurationConverter.getMap(ConfigurationConverter.getConfiguration(props).subset(PROPERTIES_PREFIX + ".dc")); for (Entry<Object, Object> dc : dcs.entrySet()) { String key = StringUtils.substringBefore(dc.getKey().toString(), "."); String attr = StringUtils.substringAfter (dc.getKey().toString(), "."); CrossLink link = links.get(key); if (link == null) { link = new CrossLink(); links.put(key, link); } BeanUtils.setProperty(link, attr, dc.getValue()); } } catch (Exception e) { throw new RuntimeException(e); } } @Override public String getEnvironmentName() { return environmentName; } @Override public Map<String, String> getEnvironment() { return System.getenv(); } @Override public Map<String, CrossLink> getCrosslinks() { return links; } @Override public String getCurrentRegion() { return currentRegion; } @Override public Properties getGlobalProperties() { return properties; } @Override public String getApplicationVersion() { return this.applicationVersion; } @Override public String getApplicationName() { return this.applicationName; } @Override public boolean getIsLocalExplorer() { return isLocal; } @Override public String getHomePageUrl() { return this.homePageUrl; } @Override public short getDefaultPort() { return this.defaultPort; } @Override public String getDataCenter() { return this.dataCenter; } @Override public long getStartTime() { RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean(); return rb.getStartTime(); } @Override public String getDefaultExplorerName() { return this.defaultExplorerName; } @Override public String toString() { return "PropertiesGlobalModelContext [environmentName=" + environmentName + ", currentRegion=" + currentRegion + ", applicationVersion=" + applicationVersion + ", applicationName=" + applicationName + ", isLocal=" + isLocal + ", homePageUrl=" + homePageUrl + ", defaultPort=" + defaultPort + ", defaultExplorerName=" + defaultExplorerName + ", dataCenter=" + dataCenter + ", links=" + links + ", properties=" + properties + "]"; } }
7,609
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/AbstractExplorerModule.java
/** * Copyright 2014 Netflix, 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.netflix.explorers; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import com.netflix.config.ConfigurationManager; import com.netflix.config.DynamicPropertyFactory; import org.apache.commons.configuration.AbstractConfiguration; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Sets; import com.netflix.explorers.model.MenuItem; import javax.annotation.PostConstruct; import com.google.inject.Singleton; import com.netflix.config.DynamicBooleanProperty; public class AbstractExplorerModule implements Explorer { private static Logger LOG = LoggerFactory.getLogger(AbstractExplorerModule.class); private final String name; private String title; private String description; private String layoutName; private boolean isSecure; private MenuItem rootMenu; private Set<String> rolesAllowed; private boolean isCmcEnabled; private static final String[] propertyNameForms = { "/$NAME$-explorer.properties", "/$NAME$explorer.properties", "$NAME$-explorer.properties", "$NAME$explorer.properties" }; private AbstractConfiguration config; public AbstractExplorerModule(String name) { this.name = name; } @Override public void initialize(ExplorerManager manager) { LOG.info("Initialize with manager " + name); initialize(); } public void loadPropertiesFile(String filename) throws IOException { ConfigurationManager.loadPropertiesFromResources(filename); } @Override @PostConstruct public void initialize() { LOG.info("Initialize " + name); loadPropertiesFileFromForms(); String prefix = "com.netflix.explorers." + name + "."; config = getConfigInstance(); title = config.getString(prefix + "title", name + " (MissingTitle)"); description = config.getString(prefix + "description", name + " (MissingDescription)"); layoutName = config.getString(prefix + "pageLayout"); isCmcEnabled = config.getBoolean(prefix + "cmcEnabled", false); isSecure = config.getBoolean(prefix + "secure", false); rolesAllowed = Sets.newHashSet(StringUtils.split(config.getString(prefix + "rolesAllowed", ""), ",")); String items = config.getString(prefix + "menu"); Map<String, String> menuLayout = getMenuLayout(); if (menuLayout != null) { rootMenu = new MenuItem().setName("root").setTitle("root"); for (Entry<String, String> item : menuLayout.entrySet()) { // Parse the menu hierarchy and build it if necessary String[] nameComponents = StringUtils.split(item.getKey(), "/"); String[] pathComponents = StringUtils.split(item.getValue(), "/"); if (nameComponents.length == 1) { rootMenu.addChild(new MenuItem() .setName(item.getKey()) .setHref(item.getValue()) .setTitle(item.getKey())); } else { if (nameComponents.length != pathComponents.length) LOG.error("Name and path must have same number of components: " + item.getKey() + " -> " + item.getValue()); MenuItem node = rootMenu; for (int i = 0; i < nameComponents.length - 1; i++) { MenuItem next = node.getChild(pathComponents[i]); if (next == null) { next = new MenuItem() .setName(pathComponents[i]) .setTitle(nameComponents[i]); node.addChild(next); } node = next; } MenuItem leaf = new MenuItem() .setName(pathComponents[pathComponents.length - 1]) .setHref(item.getValue()) .setTitle(nameComponents[nameComponents.length - 1]); // Add the menu item to the leaf node.addChild(leaf); } } } else if (items != null) { rootMenu = new MenuItem().setName("root").setTitle("root"); for (String item : StringUtils.split(items, ",")) { String[] parts = StringUtils.splitByWholeSeparator(item, "->"); try { String[] nameComponents = StringUtils.split(parts[0].trim(), "/"); MenuItem node = rootMenu; for (int i = 0; i < nameComponents.length; i++) { MenuItem next = node.getChild(nameComponents[i]); if (next == null) { next = new MenuItem() .setName(nameComponents[i]) .setTitle(nameComponents[i]); node.addChild(next); } node = next; } node.setHref(parts[1].trim()); } catch (Exception e) { LOG.error("Failed to load menu for explorer " + name, e); } } } LOG.info(toString()); } protected void loadPropertiesFileFromForms() { for ( int i = 0; i < propertyNameForms.length; ++i ) { String form = propertyNameForms[i]; try { loadPropertiesFile(form.replace("$NAME$", name)); break; } catch (Exception e) { if ( (i + 1) >= propertyNameForms.length ) { LOG.error("Failed to open property file for " + name, e); } } } } protected AbstractConfiguration getConfigInstance() { return ConfigurationManager.getConfigInstance(); } @Override public void shutdown() { } @Override public void suspend() { } @Override public void resume() { } @Override public final String getName() { return name; } @Override public String getTitle() { return title; } @Override public final String getDescription() { return description; } @Override public String getAlertMessage() { return config.getString("com.netflix.explorers." + name + ".alert_message"); } @Override public Map<String, String> getMenuLayout() { return null; } @Override public String getLayoutName() { return layoutName; } @Override public MenuItem getMenu() { return rootMenu; } @Override public boolean getIsSecure() { // get value from netflixConfiguration as it can be overridden for debugging / testing applications String propName = "com.netflix.explorers." + name + "." + "secure"; try { final DynamicBooleanProperty isSecureDynamicProperty = DynamicPropertyFactory.getInstance().getBooleanProperty(propName, isSecure); isSecure = isSecureDynamicProperty.get(); return isSecure; } catch (Exception ex) { return isSecure; } } @Override public Properties getProperties() { return null; } @Override public Set<String> getRolesAllowed() { return rolesAllowed; } @Override public boolean getCmcEnabled() { return isCmcEnabled; } @Override public String getHome() { return name; // by default home = /<exp-name> } @Override public String toString() { return "AbstractExplorerModule [name=" + name + ", title=" + title + ", description=" + description + ", layoutName=" + layoutName + ", isSecure=" + isSecure + ", rootMenu=" + rootMenu + ", rolesAllowed=" + rolesAllowed + "]"; } }
7,610
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/AppConfigGlobalModelContext.java
/** * Copyright 2014 Netflix, 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.netflix.explorers; import com.google.common.collect.Maps; import com.google.inject.name.Named; import com.netflix.config.ConfigurationManager; import com.netflix.explorers.context.GlobalModelContext; import com.netflix.explorers.model.CrossLink; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.configuration.AbstractConfiguration; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.util.Iterator; import java.util.Map; import java.util.Properties; import com.google.inject.Singleton; import com.google.inject.Inject; @Singleton public class AppConfigGlobalModelContext implements GlobalModelContext { private static final Logger LOG = LoggerFactory.getLogger(PropertiesGlobalModelContext.class); public static String PROPERTY_ENVIRONMENT_NAME = "com.netflix.explorers.environmentName"; public static String PROPERTY_CURRENT_REGION = "com.netflix.explorers.currentRegion"; public static String PROPERTY_APPLICATION_NAME = "com.netflix.explorers.applicationName"; public static String PROPERTY_APPLICATION_VERSION = "com.netflix.explorers.applicationVersion"; public static String PROPERTY_IS_LOCAL = "com.netflix.explorers.local"; public static String PROPERTY_HOME_PAGE = "com.netflix.explorers.homepage"; public static String PROPERTY_DEFAULT_PORT = "com.netflix.explorers.defaultPort"; public static String PROPERTY_DATA_CENTER = "com.netflix.explorers.dataCenter"; public static String PROPERTY_DEFAULT_EXPLORER = "com.netflix.explorers.defaultExplorer"; private static final String PROPERTIES_PREFIX = "netflix.explorers"; private final String environmentName; private final String currentRegion; private final String applicationVersion; private final String applicationName; private final Boolean isLocal; // this should be moved outside private final String homePageUrl; private final short defaultPort; private final String defaultExplorerName; private final String dataCenter; private final Map<String, CrossLink> links = Maps.newHashMap(); @Inject public AppConfigGlobalModelContext(@Named("explorerAppName") String appName) { final String propertiesFileName = appName + "-explorers.properties"; try { ConfigurationManager.loadPropertiesFromResources(propertiesFileName); } catch (IOException e) { LOG.error(String.format("Exception loading properties file - %s, Explorers application may not work correctly ", propertiesFileName)); } AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); environmentName = configuration.getString(PROPERTY_ENVIRONMENT_NAME); currentRegion = configuration.getString(PROPERTY_CURRENT_REGION); applicationVersion = (String) configuration.getProperty(PROPERTY_APPLICATION_VERSION); applicationName = (String) configuration.getProperty(PROPERTY_APPLICATION_NAME); isLocal = configuration.getBoolean(PROPERTY_IS_LOCAL, false); homePageUrl = configuration.getString(PROPERTY_HOME_PAGE); defaultPort = configuration.getShort(PROPERTY_DEFAULT_PORT, (short) 8080); dataCenter = configuration.getString(PROPERTY_DATA_CENTER); defaultExplorerName = configuration.getString(PROPERTY_DEFAULT_EXPLORER); try { Iterator<String> dcKeySet = configuration.getKeys(PROPERTIES_PREFIX + ".dc"); while (dcKeySet.hasNext()) { String dcKey = dcKeySet.next(); String key = StringUtils.substringBefore(dcKey, "."); String attr = StringUtils.substringAfter (dcKey, "."); CrossLink link = links.get(key); if (link == null) { link = new CrossLink(); links.put(key, link); } BeanUtils.setProperty(link, attr, configuration.getProperty(dcKey)); } } catch (Exception e) { LOG.error("Exception in constructing links map ", e); throw new RuntimeException(e); } } @Override public String getEnvironmentName() { return environmentName; } @Override public Map<String, String> getEnvironment() { return System.getenv(); } @Override public Map<String, CrossLink> getCrosslinks() { return links; } @Override public String getCurrentRegion() { return currentRegion; } @Override public Properties getGlobalProperties() { return null; } @Override public String getApplicationVersion() { return this.applicationVersion; } @Override public String getApplicationName() { return this.applicationName; } @Override public boolean getIsLocalExplorer() { return isLocal; } @Override public String getHomePageUrl() { return this.homePageUrl; } @Override public short getDefaultPort() { return this.defaultPort; } @Override public String getDataCenter() { return this.dataCenter; } @Override public long getStartTime() { RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean(); return rb.getStartTime(); } @Override public String getDefaultExplorerName() { return this.defaultExplorerName; } @Override public String toString() { return "PropertiesGlobalModelContext [environmentName=" + environmentName + ", currentRegion=" + currentRegion + ", applicationVersion=" + applicationVersion + ", applicationName=" + applicationName + ", isLocal=" + isLocal + ", homePageUrl=" + homePageUrl + ", defaultPort=" + defaultPort + ", defaultExplorerName=" + defaultExplorerName + ", dataCenter=" + dataCenter + ", links=" + links + "]"; } }
7,611
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/sse/EventChannelBroadcaster.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.sse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CopyOnWriteArraySet; public class EventChannelBroadcaster { private static final Logger LOG = LoggerFactory.getLogger(EventChannelBroadcaster.class); private CopyOnWriteArraySet<EventChannel> channels = new CopyOnWriteArraySet<EventChannel>(); public void registerEventChannel(final EventChannel channel) { channels.add(channel); channel.registerListener(new EventChannelListener() { @Override public void onChannelClosing(EventChannel eventChannel) { channels.remove(channel); } }); } public void write(OutboundEvent event) { LOG.info("write to " + channels.size() + " channels"); for (EventChannel channel : channels) { try { channel.write(event); } catch (Throwable t) { channels.remove(channel); } } } }
7,612
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/sse/EventChannelListener.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.sse; public interface EventChannelListener { void onChannelClosing(EventChannel eventChannel); }
7,613
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/sse/OutboundEvent.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.sse; public class OutboundEvent { /** * Used for creating {@link OutboundEvent} instances. */ public static class Builder { private String name; private String comment; private String id; private String data; /** * Set event name. * * Will be send as field name "event". * * @param name field name "event" value. * @return updated builder instance. */ public Builder name(String name) { this.name = name; return this; } /** * Set event id. * * @param id event id. * @return updated builder instance. */ public Builder id(String id) { this.id = id; return this; } /** * Set comment. It will be send before serialized event if it contains data or as a separate "event". * * @param comment comment string. * @return updated builder instance. */ public Builder comment(String comment) { this.comment = comment; return this; } /** * Set event data and java type of event data. Type will be used for {@link javax.ws.rs.ext.MessageBodyWriter} * lookup. * * @param data event data. MUST NOT be {@code null}. * @return updated builder instance. */ public Builder data(String data) { if(data == null) { throw new IllegalArgumentException(); } this.data = data; return this; } /** * Build {@link OutboundEvent}. * * There are two valid configurations: * <ul> * <li>when {@link Builder#comment} is set, all other parameters are optional. If {@link Builder#data(String)} * is set, event will be serialized after comment.</li> * <li>when {@link Builder#comment} is not set, {@link Builder#data(String)} HAVE TO * be set, all other parameters are optional.</li> * </ul> * * @return new {@link OutboundEvent} instance. * @throws IllegalStateException when called with invalid configuration. */ public OutboundEvent build() throws IllegalStateException { if(comment == null) { if(data == null) { throw new IllegalStateException(); } } return new OutboundEvent(name, id, data, comment); } } private final String name; private final String comment; private final String id; private final String data; /** * Create new OutboundEvent with given properties. * * @param name event name (field name "event"). * @param id event id. * @param data events data. * @param comment comment. */ public OutboundEvent(String name, String id, String data, String comment) { this.name = name; this.comment = comment; this.id = id; this.data = data; } /** * Get event name. * * @return event name. */ public String getName() { return name; } /** * Get event id. * * @return event id. */ public String getId() { return id; } /** * Get comment * * @return comment. */ public String getComment() { return comment; } /** * Get event data. * * @return event data. */ public String getData() { return data; } }
7,614
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/sse/EventChannelWriter.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.sse; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; @Produces({EventChannel.SERVER_SENT_EVENTS}) @Provider public class EventChannelWriter implements MessageBodyWriter<EventChannel> { private static final Logger LOG = LoggerFactory.getLogger(EventChannel.class); private static final OutboundEventWriter eventWriter = new OutboundEventWriter(); @Override public long getSize(EventChannel t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return (type.equals(EventChannel.class)); } @Override public void writeTo(EventChannel channel, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { OutboundEvent event; try { while (null != (event = channel.pop())) { eventWriter.writeTo(event, type, genericType, annotations, mediaType, httpHeaders, entityStream); } } catch (Throwable t) { LOG.info("Channel not writable - need to close"); channel.close(); } } }
7,615
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/sse/OutboundEventWriter.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.sse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.OutputStream; import java.io.StringReader; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; public class OutboundEventWriter implements MessageBodyWriter<OutboundEvent> { private static final Logger LOG = LoggerFactory.getLogger(OutboundEventWriter.class); @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return (type.equals(OutboundEvent.class)); } @Override public long getSize(OutboundEvent outboundEvent, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public void writeTo(OutboundEvent outboundEvent, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException { LOG.info("HTTP headers sent " + httpHeaders.keySet()); httpHeaders.putSingle("Access-Control-Allow-Origin","*"); if(outboundEvent.getComment() != null) { entityStream.write(String.format(": %s\n", outboundEvent.getComment()).getBytes()); } if(outboundEvent.getName() != null) { entityStream.write(String.format("event: %s\n", outboundEvent.getName()).getBytes()); } if(outboundEvent.getId() != null) { entityStream.write(String.format("id: %s\n", outboundEvent.getId()).getBytes()); } String line; BufferedReader reader = new BufferedReader(new StringReader(outboundEvent.getData().toString())); try { while ((line = reader.readLine()) != null) { entityStream.write(String.format("data: %s\n", line).getBytes()); } } catch(IOException e) { e.printStackTrace(); } entityStream.write("\n\n".getBytes()); entityStream.flush(); } }
7,616
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/sse/EventChannel.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.sse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MediaType; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.BlockingDeque; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingDeque; public class EventChannel implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(EventChannel.class); /** * {@link String} representation of Server sent events media type. ("{@value}"). */ public static final String SERVER_SENT_EVENTS = "text/event-stream"; /** * Server sent events media type. */ public static final MediaType SERVER_SENT_EVENTS_TYPE = MediaType.valueOf(SERVER_SENT_EVENTS); private final static OutboundEvent shutdownEvent = new OutboundEvent(null, null, null, null); private final BlockingDeque<OutboundEvent> queue = new LinkedBlockingDeque<OutboundEvent>(); private boolean closed = false; private CopyOnWriteArraySet<EventChannelListener> listeners = new CopyOnWriteArraySet<EventChannelListener>(); public EventChannel() { } public void registerListener(EventChannelListener listener) { listeners.add(listener); } public void removeListener(EventChannelListener listener) { listeners.remove(listener); } public void notifyClosing() { for (EventChannelListener listener : listeners) { listener.onChannelClosing(this); } } public void write(OutboundEvent event) { if (closed == false) queue.add(event); } /** * Return the next event or null if closed * @return */ public OutboundEvent pop() { OutboundEvent event; try { event = queue.take(); if (closed || event == shutdownEvent) return null; if (closed) return null; return event; } catch (InterruptedException e) { return null; } } @Override public void close() throws IOException { LOG.info("Closing event channel"); closed = true; queue.add(shutdownEvent); notifyClosing(); } public boolean isClosed() { return closed; } }
7,617
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/context/RequestContext.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.context; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; public class RequestContext { private String explorerName = ""; private String pathToRoot = ""; private String explorerSubPath = ""; private String currentMenu = ""; private boolean isAjaxRequest = false; private HttpServletRequest requestInvoker = null; public RequestContext() { } public RequestContext(HttpServletRequest requestInvoker) { setHttpServletRequest(requestInvoker); } public void setHttpServletRequest(HttpServletRequest requestInvoker) { this.requestInvoker = requestInvoker; if (requestInvoker != null) { String requestedWith = requestInvoker.getHeader("X-Requested-With"); isAjaxRequest = requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest"); pathToRoot = this.getContextPath() + this.getServletPath(); if (!pathToRoot.endsWith("/")) { pathToRoot += "/"; } String pathInfo = getPathInfo(); if (pathInfo != null) { String parts[] = StringUtils.split(pathInfo, "/"); explorerSubPath = pathInfo; if (parts.length > 0) { explorerName = parts[0]; explorerSubPath = pathInfo.substring(Math.min(pathInfo.length(), explorerName.length() + 2)); if (parts.length > 1) { currentMenu = parts[1]; } } } } } public String getServletPath() { return requestInvoker.getServletPath(); } public String getContextPath() { return requestInvoker.getContextPath(); } public String getExplorerName() { return explorerName; } public RequestContext setExplorerName(String explorerName) { this.explorerName = explorerName; return this; } public String getPathToRoot() { return pathToRoot; } public String getPathInfo() { return requestInvoker.getPathInfo(); } public String getSubPath() { return explorerSubPath; } public String getCurrentMenu() { return currentMenu; } public boolean getIsAjaxRequest() { return isAjaxRequest; } /** * Return the path to the main FTL template based on the given layout * * @param layout layout * @return path to main FTL template */ public String getMainTemplatePath(String layout) { return "/layout/" + layout + "/main.ftl"; } @Override public String toString() { return "Context [servletPath=" + getServletPath() + ", contextPath=" + getContextPath() + ", explorerName=" + explorerName + ", pathToRoot=" + pathToRoot + ", pathInfo=" + getPathInfo() + ", explorerSubPath=" + explorerSubPath + "]"; } }
7,618
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/context/ExplorerPropertiesConfiguration.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.context; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; @Singleton public class ExplorerPropertiesConfiguration extends PropertiesConfiguration { public static final String EXPLORERS_CONFIG_FILE_SUFFIX = "-explorers-config.properties"; @Inject public ExplorerPropertiesConfiguration(@Named("explorerAppName") String explorerAppName) throws ConfigurationException { super(explorerAppName + EXPLORERS_CONFIG_FILE_SUFFIX); } }
7,619
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/jersey/ViewableResource.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.jersey; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.ws.rs.GET; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.netflix.explorers.Explorer; import com.netflix.explorers.annotations.Controller; import com.sun.jersey.api.view.Viewable; @Produces( MediaType.TEXT_HTML ) public class ViewableResource { private static final Logger LOG = LoggerFactory.getLogger(ViewableResource.class); private static final String DEFAULT_ACTION = "index"; private @Inject UriInfo uriInfo; private String name; private String defaultAction; private Explorer explorer; public ViewableResource(Explorer explorer) { this.name = getName(); this.defaultAction = DEFAULT_ACTION; this.explorer = explorer; } @GET public Response defaultPage() throws Exception { return this.redirect(defaultAction); } public Viewable view(String page) { return view(page, new HashMap<String, Object>()); } public Viewable view(String page, Map<String, Object> model) { return new Viewable( "/" + explorer.getName() + "/" + name + "/" + page + ".ftl", model ); } public Response redirect(String resource) { try { String redirect = StringUtils.join( Arrays.asList(uriInfo.getRequestUri().toString(), resource), "/"); return Response.temporaryRedirect(new URI(redirect)).build(); } catch (URISyntaxException e) { return Response.serverError().build(); } } public String getName() { if (this.name == null) { Controller controller = this.getClass().getAnnotation(Controller.class); if (controller != null) { return controller.value(); } } return this.name; } }
7,620
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/jersey/ExplorerResource.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.jersey; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.inject.Provider; import com.netflix.explorers.AbstractExplorerModule; import com.netflix.explorers.ExplorerManager; import com.netflix.explorers.rest.RestKey; import com.netflix.explorers.rest.RestResource; import com.sun.jersey.api.NotFoundException; import com.sun.jersey.api.core.ResourceContext; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import java.util.Map; /** * Higher level explorer module that auto creates jersey path bindings for * entities managed by an explorer. The ExplorerResource will be registered with * Jersey as a Singleton and will serve as the entry point to creating endpoints * for managed resources. * * @author elandau * */ public class ExplorerResource extends AbstractExplorerModule { private static final Logger LOG = LoggerFactory.getLogger(ExplorerResource.class); private static final String DEFAULT_CONTROLLER = "home"; @Context private ResourceContext resourceContext; @Context private ThreadLocal<HttpServletRequest> requestInvoker; private final Map<String, Provider<ViewableResource>> controllers; private final Map<RestKey, Provider<RestResource>> restResources; private String defaultController = DEFAULT_CONTROLLER; public ExplorerResource(String name, Map<String, Provider<ViewableResource>> controllers, Map<RestKey, Provider<RestResource>> restResources) { super(name); this.controllers = controllers; this.restResources = restResources; if (!controllers.isEmpty()) { LOG.info(String.format("Explorer '%s' initialized with controllers '%s'", name, this.controllers.keySet())); defaultController = Iterables.getFirst(controllers.keySet(), null); } if (restResources != null) { LOG.info(String.format("Explorer '%s' initialized with r '%s'", name, this.restResources.keySet())); } } public void initialize(ExplorerManager manager) { super.initialize(manager); } /** * Get all controllers associated with this explorer * * @return A mapping of controller name (used as url path) and the handling * class */ public Map<String, Provider<ViewableResource>> getControllers() { return controllers; } /** * Get all classes that should be registered with jersey and made avaialble * for instatiation with dependency injection * @return */ @Deprecated public List<Class<?>> getClasses() { return Lists.newArrayList(); } /** * URL routing entry point for rest endpoints belonging to this explorer * * @return * @throws Exception */ @Path("rest/{version}/{endpoint}") public Object rest(@PathParam("version") String version, @PathParam("endpoint") String endpoint) throws Exception { if (restResources != null) { RestKey key = new RestKey(version, endpoint); Provider<RestResource> provider = restResources.get(key); if (provider == null) { throw new NotFoundException(String.format("No rest resource found for '%s:%s'", version, endpoint )); } return provider.get(); } throw new NotFoundException(String.format("No rest resource for explorer", getName(), endpoint)); } @Path("{controller}") public Object controller(@PathParam("controller") String controllerName) throws Exception { Provider<ViewableResource> provider = controllers.get(controllerName); if (provider != null) { return provider.get(); } return new NotFoundException(String.format( "Controller for '%s' not found", controllerName)); } /** * Default implementation of the explorer home page * * @return * @throws Exception */ @GET public Response showHome() throws Exception { if (defaultController != null) { try { String redirect = StringUtils.join(Arrays.asList(requestInvoker.get().getPathInfo().toString(), defaultController), "/"); return Response.temporaryRedirect(new URI(redirect)).build(); } catch (URISyntaxException e) { return Response.serverError().build(); } } return Response.ok(DEFAULT_CONTROLLER).build(); } }
7,621
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/web/StaticResourceServlet.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.web; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Deprecated public class StaticResourceServlet extends HttpServlet { private static final long serialVersionUID = 751025548152775434L; @Override @SuppressWarnings("unchecked") protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String resource = request.getRequestURI().substring(request.getContextPath().length()); resource = resource.substring("/res".length()); InputStream is = getClass().getResourceAsStream(resource); if (is == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { if (resource.endsWith(".js")) { response.setContentType("text/javascript"); } out.print(convertStreamToString(is)); } } public String convertStreamToString(InputStream is) throws IOException { if (is != null) { Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader( new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } return writer.toString(); } else { return ""; } } }
7,622
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/web/IndexRedirectFilter.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.web; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Very simple filter to redirect the root page to the default explorer * @author elandau */ public class IndexRedirectFilter implements Filter { private final String defaultExplorer; public IndexRedirectFilter(String defaultExplorer) { this.defaultExplorer = defaultExplorer; } @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; if (httpRequest.getRequestURI().equals("/")) { ((HttpServletResponse) response).sendRedirect("/" + defaultExplorer); return; } chain.doFilter(httpRequest, response); } @Override public void init(FilterConfig config) throws ServletException { // no op } }
7,623
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/providers/FreemarkerTemplateProvider.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.providers; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.explorers.Explorer; import com.netflix.explorers.ExplorerManager; import com.netflix.explorers.context.GlobalModelContext; import com.netflix.explorers.context.RequestContext; import com.netflix.explorers.model.EmptyExplorer; import com.sun.jersey.api.view.Viewable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.net.URL; import java.net.URLStreamHandler; import java.security.Principal; import java.util.HashMap; import java.util.Map; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.ext.MessageBodyWriter; import freemarker.cache.ClassTemplateLoader; import freemarker.cache.MultiTemplateLoader; import freemarker.cache.TemplateLoader; import freemarker.cache.URLTemplateLoader; import freemarker.cache.WebappTemplateLoader; import freemarker.template.Configuration; import freemarker.template.TemplateModelException; @Singleton public class FreemarkerTemplateProvider implements MessageBodyWriter<Viewable> { private static final Logger LOG = LoggerFactory.getLogger(FreemarkerTemplateProvider.class); private static Map<String, URLStreamHandler> urlHandlers = Maps.newConcurrentMap(); public static void addUrlHandler(String protocol, URLStreamHandler handler) { urlHandlers.put(protocol, handler); } private static final String ROOT_PATH = "/WEB-INF/templates"; private static final String DEFAULT_LAYOUT = "main"; private Configuration fmConfig = new Configuration(); private boolean servletMode = false; private ExplorerManager manager; @Context private ThreadLocal<HttpServletRequest> requestInvoker; @Inject public FreemarkerTemplateProvider(ExplorerManager manager) { this.manager = manager; } public void setRequestInvoker(ThreadLocal<HttpServletRequest> requestInvoker) { this.requestInvoker = requestInvoker; } @PostConstruct public void commonConstruct() { if (!servletMode) { // Just look for files in the class path TemplateLoader loader = fmConfig.getTemplateLoader(); fmConfig.setTemplateLoader( new MultiTemplateLoader( new TemplateLoader[]{ new ClassTemplateLoader( getClass(), "/")}) ); } fmConfig.setNumberFormat( "0" ); fmConfig.setLocalizedLookup( false ); fmConfig.setTemplateUpdateDelay(0); try { fmConfig.setSharedVariable("Global", manager.getGlobalModel()); fmConfig.setSharedVariable("Explorers", manager); fmConfig.setSharedVariable("toJson", new ToJsonMethod()); } catch (TemplateModelException e) { throw new RuntimeException(e); } } @Override public long getSize(Viewable t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { if ( !( mediaType.isCompatible(MediaType.TEXT_HTML_TYPE) || mediaType.isCompatible(MediaType.APPLICATION_XHTML_XML_TYPE)) || !Viewable.class.isAssignableFrom(type)) { return false; } return true; } /** * Write the HTML by invoking the FTL template * * Variables accessibile to the template * * it - The 'model' provided by the controller * Explorer - IExplorerModule reference * Explorers - Map of all explorer modules * Global - Global variables from the ExploreModule manager * Request - The HTTPRequestHandler * Instance - Information about the running instance * Headers - HTTP headers * Parameters - HTTP parameters */ @SuppressWarnings( { "unchecked" } ) @Override public void writeTo(Viewable viewable, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream out) throws IOException, WebApplicationException { String resolvedPath = viewable.getTemplateName(); Object model = viewable.getModel(); LOG.debug( "Evaluating freemarker template (" + resolvedPath + ") with model of type " + ( model == null ? "null" : model.getClass().getSimpleName() ) ); // Build the model context that will be passed to the page final Map<String,Object> vars; if ( model instanceof Map ) { vars = new HashMap<String, Object>( (Map<String, Object>)model ); } else { vars = new HashMap<String, Object>(); vars.put("it", model); } RequestContext requestContext = new RequestContext(); requestContext.setHttpServletRequest(requestInvoker != null ? requestInvoker.get() : null); vars.put("RequestContext", requestContext); vars.put("Request", requestInvoker != null ? requestInvoker.get() : null); Principal ctx = null; if (requestInvoker.get() != null) { ctx = requestInvoker.get().getUserPrincipal(); if (ctx == null && requestInvoker.get().getSession(false) != null) { final String username = (String) requestInvoker.get().getSession().getAttribute("SSO_UserName"); if (username != null) { ctx = new Principal() { @Override public String getName() { return username; } }; } } } vars.put("Principal", ctx); // The following are here for backward compatibility and should be deprecated as soon as possible Map<String, Object> global = Maps.newHashMap(); if (manager != null) { GlobalModelContext globalModel = manager.getGlobalModel(); global.put("sysenv", globalModel.getEnvironment()); // TODO: DEPRECATE } vars.put("global", global); // TODO: DEPRECATE vars.put("pathToRoot", requestContext.getPathToRoot()); // TODO: DEPRECATE String layout = DEFAULT_LAYOUT; Explorer explorer = null; final boolean hasExplorerName = !requestContext.getExplorerName().isEmpty(); try { if (hasExplorerName) { explorer = manager.getExplorer(requestContext.getExplorerName()); } } catch (Exception e) { LOG.warn(e.getMessage()); } if (explorer == null) { if (hasExplorerName) { throw new WebApplicationException(new RuntimeException("Invalid explorer"), Response.Status.NOT_FOUND); } else { explorer = EmptyExplorer.getInstance(); } } layout = explorer.getLayoutName(); vars.put("Explorer", explorer); if (vars.containsKey("layout")) { layout = (String) vars.get("layout"); } final StringWriter stringWriter = new StringWriter(); try { if (requestContext.getIsAjaxRequest()) { fmConfig.getTemplate(resolvedPath).process(vars, stringWriter); } else { if (layout == null) { layout = DEFAULT_LAYOUT; } vars.put("nestedpage", resolvedPath); fmConfig.getTemplate("/layout/" + layout + "/main.ftl").process(vars, stringWriter); } if ( LOG.isDebugEnabled() ) { LOG.debug( "OK: Resolved freemarker template" ); } final OutputStreamWriter writer = new OutputStreamWriter( out ); writer.write(stringWriter.getBuffer().toString()); writer.flush(); } catch ( Throwable t ) { LOG.error("Error processing freemarker template @ " + resolvedPath + ": " + t.getMessage(), t); throw new WebApplicationException(t, Response.Status.INTERNAL_SERVER_ERROR); } } @Context public void setServletContext( final ServletContext context ) { // Suppress the templateLoader override in commonConstruct, which is executed after this method in Guice. servletMode = true; fmConfig.setTemplateLoader( new MultiTemplateLoader( new TemplateLoader[]{ new WebappTemplateLoader( context, ROOT_PATH ), new ClassTemplateLoader( getClass(), "/"), new URLTemplateLoader() { @Override protected URL getURL(String url) { // Load from URL. try { String split[] = url.split(":", 2); return new URL(null, url, urlHandlers.get(split[0])); } catch (Exception x) { LOG.error("Unable to handle url=" + url, x); return null; } } // Force reload each time. public long getLastModified(Object templateSource) { // TOOO: keep a running time delay to allow for some caching. return System.currentTimeMillis(); } } }) ); fmConfig.addAutoInclude("/layout/bootstrap/form.ftl"); } }
7,624
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/providers/SharedFreemarker.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.providers; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Map; import freemarker.cache.ClassTemplateLoader; import freemarker.cache.MultiTemplateLoader; import freemarker.cache.TemplateLoader; import freemarker.template.Configuration; import freemarker.template.TemplateException; public class SharedFreemarker { private static SharedFreemarker instance = new SharedFreemarker(); public static SharedFreemarker getInstance() { return instance; } private Configuration fmConfig = new Configuration(); public SharedFreemarker() { fmConfig.setTemplateLoader( new MultiTemplateLoader( new TemplateLoader[]{ new ClassTemplateLoader( getClass(), "/")}) ); fmConfig.setNumberFormat( "0" ); fmConfig.setLocalizedLookup( false ); fmConfig.setTemplateUpdateDelay(0); } public String render(String path, Map<String, Object> model) throws TemplateException, IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter( out ); fmConfig.getTemplate(path).process(model, writer); return out.toString(); } }
7,625
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/providers/NaturalNotationContextResolver.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.providers; import com.netflix.explorers.annotations.ExplorerEntity; import com.sun.jersey.api.json.JSONJAXBContext; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; class NaturalNotationContextResolver implements ContextResolver<JAXBContext> { private JAXBContext context; NaturalNotationContextResolver() { try { this.context = new JSONJAXBContext(); } catch ( JAXBException e ) { throw new RuntimeException(e); } } public JAXBContext getContext(Class<?> objectType) { if (objectType.isAnnotationPresent(ExplorerEntity.class)) return context; return null; } }
7,626
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/providers/WebApplicationExceptionMapper.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.providers; import com.google.inject.Singleton; import com.sun.jersey.api.core.HttpContext; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Variant; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.List; @Singleton public class WebApplicationExceptionMapper implements ExceptionMapper<WebApplicationException> { private static final Logger LOG = LoggerFactory.getLogger(WebApplicationExceptionMapper.class); private static List<Variant> supportedMediaTypes = Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE, MediaType.TEXT_HTML_TYPE).add().build(); @Context private HttpContext context; public WebApplicationExceptionMapper() { LOG.info("GenericExceptionMapper Created"); } @Override public Response toResponse(WebApplicationException error) { if (error.getResponse() != null && (error.getResponse().getStatus() / 100) == 3) { LOG.warn("Code: " + error.getResponse().getStatus()); return error.getResponse(); } MediaType mediaType = context.getRequest().selectVariant(supportedMediaTypes).getMediaType(); if (mediaType != null && MediaType.APPLICATION_JSON_TYPE == mediaType) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); error.printStackTrace(ps); return Response .status(error.getResponse().getStatus()) .type(MediaType.APPLICATION_JSON_TYPE) .entity(new JSONObject() .put("code", error.getResponse().getStatus()) .put("url", context.getUriInfo().getPath()) .put("error", error.toString()) .put("message", error.getMessage()) .put("trace", baos.toString()) ) .build(); } catch (JSONException e) { // TODO: } } // do not log 404 if (! is404(error)) { LOG.warn(String.format("WebApplicationExceptionMapper status='%s' message='%s' url='%s'", error.getResponse().getStatus(), error.getMessage(), context.getRequest().getPath()), error); } return Response.status(error.getResponse().getStatus()).build(); } private boolean is404(WebApplicationException error) { return error.getResponse().getStatus() == Response.Status.NOT_FOUND.getStatusCode(); } }
7,627
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/providers/JsonMessageBodyReader.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.providers; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.Consumes; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; import com.netflix.explorers.annotations.ExplorerEntity; @Consumes({"application/json"}) public class JsonMessageBodyReader implements MessageBodyReader<Object> { private final ObjectMapper mapper; public JsonMessageBodyReader() { mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); } @Override public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (type.isAnnotationPresent(ExplorerEntity.class)) return mapper.canSerialize(type); return false; } @Override public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> arg4, InputStream is) throws IOException, WebApplicationException { return mapper.readValue(is, type); } }
7,628
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/providers/ExplorerManagerContextInjectable.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.providers; import java.lang.reflect.Type; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Context; import com.netflix.explorers.ExplorerManager; import com.sun.jersey.api.core.HttpContext; import com.sun.jersey.core.spi.component.ComponentContext; import com.sun.jersey.core.spi.component.ComponentScope; import com.sun.jersey.server.impl.inject.AbstractHttpContextInjectable; import com.sun.jersey.spi.inject.Injectable; import com.sun.jersey.spi.inject.InjectableProvider; public class ExplorerManagerContextInjectable extends AbstractHttpContextInjectable<ExplorerManager> implements InjectableProvider<Context, Type> { private ExplorerManager manager; @Context private ThreadLocal<HttpServletRequest> requestInvoker; public ExplorerManagerContextInjectable(ExplorerManager manager) { this.manager = manager; } @Override public Injectable<?> getInjectable(ComponentContext ic, Context a, Type c) { if (c.equals(ExplorerManager.class)) { return this; } return null; } @Override public ComponentScope getScope() { return ComponentScope.PerRequest; } @Override public ExplorerManager getValue(HttpContext c) { return manager; } }
7,629
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/providers/ToJsonMethod.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.providers; import java.io.ByteArrayOutputStream; import java.util.List; import freemarker.template.TemplateMethodModelEx; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import freemarker.template.utility.DeepUnwrap; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; public class ToJsonMethod implements TemplateMethodModelEx { private final ObjectMapper mapper; public ToJsonMethod() { mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); } @Override public Object exec(List args) throws TemplateModelException { if (args.size() != 1) { throw new TemplateModelException("Invalid syntax: ${toJson(model)}"); } Object obj = DeepUnwrap.unwrap((TemplateModel) args.get(0)); if (obj == null) obj = args.get(0); ByteArrayOutputStream strm = new ByteArrayOutputStream(); try { mapper.writeValue(strm, obj); return strm.toString(); } catch (Exception e) { throw new TemplateModelException("Error converting object to JSON String ", e); } } }
7,630
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/providers/JsonMessageBodyWriter.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.providers; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; import com.netflix.explorers.annotations.ExplorerEntity; /** * A MessageBodyWriter implementation that uses Jackson ObjectMapper to serialize objects to JSON. */ @Produces({"application/json"}) public class JsonMessageBodyWriter implements MessageBodyWriter<Object> { private final ObjectMapper mapper; public JsonMessageBodyWriter() { mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); } public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (type.isAnnotationPresent(ExplorerEntity.class)) return mapper.canSerialize(type); return false; } public long getSize(Object data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } public void writeTo(Object data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out) throws IOException, WebApplicationException { mapper.writeValue(out, data); out.flush(); } }
7,631
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/providers/ToJsonArrayOfArrays.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.providers; import java.io.ByteArrayOutputStream; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Nullable; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig.Feature; import org.codehaus.jackson.map.annotate.JsonSerialize; import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import freemarker.template.ObjectWrapper; import freemarker.template.TemplateMethodModelEx; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import freemarker.template.utility.DeepUnwrap; public class ToJsonArrayOfArrays implements TemplateMethodModelEx { private final ObjectMapper mapper; public ToJsonArrayOfArrays() { mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Object exec(List args) throws TemplateModelException { if (args.size() != 1) { throw new TemplateModelException("Invalid syntax: ${toJson(model)}"); } Map map; if (args.get(0) instanceof ObjectWrapper) { map = (Map)DeepUnwrap.unwrap((TemplateModel) args.get(0)); } else { map = (Map)args.get(0); } ByteArrayOutputStream strm = new ByteArrayOutputStream(); try { List ar = Lists.newArrayList(Collections2.transform(map.entrySet(), new Function<Map.Entry, List<String>>() { @Override public List<String> apply(@Nullable Entry input) { return Lists.newArrayList(input.getKey().toString(), input.getValue().toString()); } })); mapper.writeValue(strm, ar); return strm.toString(); } catch (Exception e) { throw new TemplateModelException("Error converting object to JSON String ", e); } } }
7,632
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/providers/ExplorerContextInjectable.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.providers; import java.lang.reflect.Type; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Context; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.explorers.Explorer; import com.netflix.explorers.ExplorerManager; import com.netflix.explorers.context.RequestContext; import com.sun.jersey.api.core.HttpContext; import com.sun.jersey.core.spi.component.ComponentContext; import com.sun.jersey.core.spi.component.ComponentScope; import com.sun.jersey.server.impl.inject.AbstractHttpContextInjectable; import com.sun.jersey.spi.inject.Injectable; import com.sun.jersey.spi.inject.InjectableProvider; public class ExplorerContextInjectable extends AbstractHttpContextInjectable<Explorer> implements InjectableProvider<Context, Type> { private static final Logger LOG = LoggerFactory.getLogger(ExplorerContextInjectable.class); private ExplorerManager manager; @Context private ThreadLocal<HttpServletRequest> requestInvoker; public ExplorerContextInjectable(ExplorerManager manager) { this.manager = manager; } @Override public Injectable<?> getInjectable(ComponentContext ic, Context a, Type c) { if (c.equals(Explorer.class)) { return this; } return null; } @Override public ComponentScope getScope() { return ComponentScope.PerRequest; } @Override public Explorer getValue(HttpContext c) { RequestContext request = new RequestContext(); request.setHttpServletRequest(requestInvoker.get()); try { return manager.getExplorer(request.getExplorerName()); } catch (Exception e) { LOG.warn("Failed to get UserProfileDao", e); return null; } } }
7,633
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/providers/GenericExceptionMapper.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.providers; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.List; import java.util.Map; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.Variant; import javax.ws.rs.ext.ExceptionMapper; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Maps; import com.sun.jersey.api.core.HttpContext; import com.sun.jersey.api.view.Viewable; public class GenericExceptionMapper implements ExceptionMapper<Exception> { private static final Logger LOG = LoggerFactory.getLogger( GenericExceptionMapper.class ); private static List<Variant> supportedMediaTypes = Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE, MediaType.TEXT_HTML_TYPE).add().build(); @Context private HttpContext context; public GenericExceptionMapper() { LOG.info("GenericExceptionMapper Created"); } @Override public Response toResponse(Exception error) { LOG.warn("GenericExceptionMapper", error); MediaType mediaType = context.getRequest().selectVariant(supportedMediaTypes).getMediaType(); if (mediaType != null && MediaType.APPLICATION_JSON_TYPE == mediaType) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); error.printStackTrace(ps); return Response .status(Status.INTERNAL_SERVER_ERROR) .entity(new JSONObject() .put("code", 500) .put("url", context.getUriInfo().getPath()) .put("error", error.toString()) .put("message", error.getMessage()) .put("trace", baos.toString())) .build(); } catch (JSONException e) { LOG.warn("Exception processing JSON ", e); } } Map<String, Object> model = Maps.newHashMap(); model.put("exception", error); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(new Viewable("/errors/internal_error.ftl", model)).build(); } }
7,634
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/resources/MinifiedContentResource.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.resources; import com.google.common.collect.ImmutableMap; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.config.DynamicIntProperty; import com.netflix.config.DynamicPropertyFactory; import com.netflix.explorers.ExplorerManager; import com.netflix.explorers.context.RequestContext; import com.netflix.explorers.providers.SharedFreemarker; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.Response; import java.security.MessageDigest; import java.util.Date; import java.util.HashMap; import java.util.Map; @Singleton @Path("/min") public class MinifiedContentResource { private static final Logger LOG = LoggerFactory.getLogger(MinifiedContentResource.class); private static final ImmutableMap<String, String> EXT_TO_MEDIATYPE = new ImmutableMap.Builder<String, String>() .put("js", "text/javascript") .put("css", "text/css") .build(); private static final DynamicIntProperty MAX_AGE = DynamicPropertyFactory.getInstance().getIntProperty("netflix.explorers.resources.cache.maxAge", 3600); @Inject(optional=true) ExplorerManager manager; @GET @Path("/{subResources:.*}") public Response get(@PathParam("subResources") String subResources) throws Exception { LOG.debug(subResources); String ext = StringUtils.substringAfterLast(subResources, "."); String mediaType = EXT_TO_MEDIATYPE.get(ext); final Map<String,Object> vars = new HashMap<String, Object>(); RequestContext requestContext = new RequestContext(); vars.put("RequestContext", requestContext); if (manager != null) { vars.put("Global", manager.getGlobalModel()); vars.put("Explorers", manager); } try { CacheControl cc = new CacheControl(); cc.setMaxAge(MAX_AGE.get()); cc.setNoCache(false); return Response .ok(SharedFreemarker.getInstance().render(subResources + ".ftl", vars), mediaType) .cacheControl(cc) .expires(new Date(System.currentTimeMillis() + 3600 * 1000)) .tag(new String(Hex.encodeHex(MessageDigest.getInstance("MD5").digest(subResources.getBytes())))) .build(); } catch (Exception e) { LOG.error(e.getMessage()); throw e; } } }
7,635
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/resources/ExplorerAdminResource.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.resources; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.apache.commons.configuration.ConfigurationConverter; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.netflix.explorers.Explorer; import com.netflix.explorers.ExplorerManager; import com.netflix.explorers.RemoteExplorerModule; import com.netflix.explorers.model.ExplorerInfoEntity; import com.netflix.explorers.model.ExplorerInfoListEntity; import com.netflix.explorers.model.MapEntity; @Path("pytheas-admin") @Produces( MediaType.APPLICATION_JSON ) @Consumes( MediaType.APPLICATION_JSON ) public class ExplorerAdminResource { @Inject(optional=true) ExplorerManager manager; @GET @Path("explorers/list") public ExplorerInfoListEntity listExplorers() { List<ExplorerInfoEntity> list = Lists.newArrayList(); for (Explorer explorer : manager.getExplorers()) { if (!(explorer instanceof RemoteExplorerModule)) { list.add(new ExplorerInfoEntity(explorer)); } } ExplorerInfoListEntity response = new ExplorerInfoListEntity(); response.setExplorers(list); return response; } @GET @Path("explorers/config") public MapEntity getConfig() { return new MapEntity(ConfigurationConverter.getMap(manager.getConfiguration())); } }
7,636
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/resources/EmbeddedContentResource.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.resources; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.util.Date; import java.net.URLConnection; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.netflix.config.DynamicBooleanProperty; import com.netflix.config.DynamicIntProperty; import com.netflix.config.DynamicPropertyFactory; import org.apache.commons.codec.binary.Hex; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableMap; import com.google.common.io.ByteStreams; import com.sun.jersey.api.NotFoundException; @Path("/res") public class EmbeddedContentResource { private static final Logger LOG = LoggerFactory.getLogger(EmbeddedContentResource.class); private static final ImmutableMap<String, String> EXT_TO_MEDIATYPE = new ImmutableMap.Builder<String, String>() .put("js", "text/javascript") .put("png", "image/png") .put("gif", "image/gif") .put("css", "text/css") .put("jpg", "image/jpeg") .put("jpeg", "image/jpeg") .put("csv", "text/csv") .put("map", "application/x-navimap") .put("ico", "image/x-icon") .put("json", MediaType.APPLICATION_JSON) .put("swf", "application/x-shockwave-flash") .build(); private static final DynamicBooleanProperty CACHE_ENABLED = DynamicPropertyFactory.getInstance().getBooleanProperty("netflix.explorers.resources.cache.enabled", true); private static final DynamicIntProperty MAX_AGE = DynamicPropertyFactory.getInstance().getIntProperty("netflix.explorers.resources.cache.maxAge", 3600); @GET @Path("/{subResources:.*}") public Response get(@PathParam("subResources") String subResources) throws Exception { LOG.debug(subResources); String ext = StringUtils.substringAfterLast(subResources, "."); String mediaType = EXT_TO_MEDIATYPE.get(ext); byte[] buffer = null; try { if (! CACHE_ENABLED.get()) { final URLConnection urlConnection = getClass().getResource("/" + subResources).openConnection(); if (urlConnection != null) { urlConnection.setUseCaches(false); buffer = ByteStreams.toByteArray(urlConnection.getInputStream()); } } else { buffer = ByteStreams.toByteArray(this.getClass().getResourceAsStream("/" + subResources)); } } catch (IOException e) { throw new WebApplicationException(404); } if (buffer == null) throw new NotFoundException(); else { if (CACHE_ENABLED.get()) { CacheControl cc = new CacheControl(); cc.setMaxAge(MAX_AGE.get()); cc.setNoCache(false); return Response .ok(buffer, mediaType) .cacheControl(cc) .expires(new Date(System.currentTimeMillis() + 3600 * 1000)) .tag(new String(Hex.encodeHex(MessageDigest.getInstance("MD5").digest(subResources.getBytes())))) .build(); } else { return Response.ok(buffer, mediaType).build(); } } } }
7,637
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/guice/BaseExplorerGuiceModule.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.guice; import com.google.inject.AbstractModule; import com.google.inject.name.Names; import com.netflix.config.ConfigurationManager; import com.netflix.explorers.AppConfigGlobalModelContext; import com.netflix.explorers.ExplorerManager; import com.netflix.explorers.ExplorersManagerImpl; import com.netflix.explorers.annotations.ExplorerGuiceModule; import com.netflix.explorers.context.GlobalModelContext; @ExplorerGuiceModule public class BaseExplorerGuiceModule extends AbstractModule { public static final String APP_ID = "archaius.deployment.applicationId"; @Override protected void configure() { final String appId = ConfigurationManager.getConfigInstance().getString(APP_ID); bind(String.class).annotatedWith(Names.named("explorerAppName")).toInstance(appId); bind(GlobalModelContext.class).to(AppConfigGlobalModelContext.class); bind(ExplorerManager.class).to(ExplorersManagerImpl.class); } }
7,638
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/sso/SsoAuthProviderWrapperMockImpl.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.sso; public class SsoAuthProviderWrapperMockImpl implements SsoAuthProviderWrapper { @Override public boolean hasSsoAuthProvider() { return false; } }
7,639
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/sso/SsoAuthProviderWrapper.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.sso; public interface SsoAuthProviderWrapper { boolean hasSsoAuthProvider(); }
7,640
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/services/ExplorerServiceInstanceSupplier.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.services; import com.google.common.base.Supplier; public class ExplorerServiceInstanceSupplier<T> implements Supplier<T> { private final T instance; public ExplorerServiceInstanceSupplier(T instance) { this.instance = instance; } @Override public T get() { return instance; } }
7,641
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/services/ExplorerServiceCachedFactorySupplier.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.services; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Supplier; public class ExplorerServiceCachedFactorySupplier<T> implements Supplier<T> { private static final Logger LOG = LoggerFactory.getLogger(ExplorerServiceCachedFactorySupplier.class); private Class<? extends T> implementationClass; private AtomicReference<T> ref; public ExplorerServiceCachedFactorySupplier(Class<? extends T> implementationClass) { this.implementationClass = implementationClass; ref = new AtomicReference<T>(); } @Override public T get() { T instance = ref.get(); if (instance == null) { try { instance = implementationClass.newInstance(); } catch (Throwable t) { LOG.error("Error instantiating " + implementationClass.getCanonicalName(), t); throw new RuntimeException(t); } if (ref.compareAndSet(null, instance)) { return instance; } return ref.get(); } return instance; } }
7,642
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/services/ReferenceCountingExplorerService.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.services; import java.util.concurrent.atomic.AtomicInteger; public abstract class ReferenceCountingExplorerService implements ExplorerService { protected abstract void initialize(); protected abstract void shutdown(); private final AtomicInteger initCounter = new AtomicInteger(); @Override public final void start() { if (initCounter.getAndIncrement() == 0) { initialize(); } } @Override public final void stop() { if (initCounter.getAndDecrement() == 0) { shutdown(); } } }
7,643
0
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-core/src/main/java/com/netflix/explorers/rest/RestKey.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.rest; public class RestKey { private String version; private String name; public RestKey(String version, String name) { this.name = name; this.version = version; } @Override public String toString() { return "RestKey [version=" + version + ", name=" + name + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RestKey other = (RestKey) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } public String getVersion() { return version; } public String getName() { return name; } }
7,644
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/Explorer.java
/** * Copyright 2014 Netflix, 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.netflix.explorers; import java.util.Map; import java.util.Properties; import java.util.Set; import com.netflix.explorers.model.MenuItem; public interface Explorer { /** * Initialize the explorer module. Called once at startup */ void initialize(); /** * Initialize the module within the context of the provided manager. * @param manager */ void initialize(ExplorerManager manager); /** * Shutdown the explorer module. Called once at shutdown */ void shutdown(); /** * Suspend any threads in the module and remove it from the UI without actually shutting it down */ void suspend(); /** * Resume a suspended module */ void resume(); /** * System unique internal explorer name * @return */ String getName(); /** * Get the title to display in the UI * @return */ String getTitle(); /** * Get the explorer description to display in the UI * @return */ String getDescription(); /** * Get the alert message to display at the top of the UI. * * TOOD: May want to make this a template * @return */ String getAlertMessage(); /** * Determines if the explorer is secure and requires authentication * @return */ boolean getIsSecure(); /** * Return the explorer's menu layout. The mapping is from menu name to relative * path in the explorer. * * menu1title : menu1 * menu2title/submenu1title : menu2/submenu1 * menu2title/submenu2title : menu2/submenu2 * * @return */ Map<String, String> getMenuLayout(); MenuItem getMenu(); /** * Return a layout name override specifically for this explorer * @return * */ String getLayoutName(); /** * Get properties specific to this explorer * @return */ Properties getProperties(); /** * Get the set of allowed roles to access this explorer. If this set is empty then all * users are allowed * @return */ Set<String> getRolesAllowed(); /** * Return true if this explorer uses CMCs. * @return */ boolean getCmcEnabled(); /** * Returns home url for the explorer * @return */ String getHome(); }
7,645
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/ExplorerManager.java
/** * Copyright 2014 Netflix, 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.netflix.explorers; import java.util.Collection; import java.util.Set; import org.apache.commons.configuration.Configuration; import com.google.common.base.Supplier; import com.netflix.explorers.context.GlobalModelContext; /** * Manages all explorer modules * @author elandau * */ //@ImplementedBy(AbstractExplorerManager.class) public interface ExplorerManager { /** * Initialize the module manager */ void initialize(); /** * Shut down the module manager */ void shutdown(); /** * Return the default module to show when no other module is selected * @return */ String getDefaultModule(); /** * Add a module to the list of modules * @param module */ void registerExplorer(Explorer module); /** * Remove a previously registered explorer * @param module */ void unregisterExplorer(Explorer module); /** * Register an explorer at runtime by giving a class name * @param className * @throws Exception */ void registerExplorerFromClassName(String className) throws Exception; /** * Return the module for this name * @param name * @return */ Explorer getExplorer(String name); /** * Retrieve a collection of all registered modules. */ Collection<Explorer> getExplorers(); /** * Get the global model for templates * @return */ GlobalModelContext getGlobalModel(); /** * Get configuration properties for this instance of explorers * @return */ Configuration getConfiguration(); /** * Register a set of explorers from a set of class names * @param classNames */ void registerExplorersFromClassNames(Set<String> classNames); /** * Get an instance of an explorer singleton * @param <T> * @param className * @return */ <T> T getService(Class<T> className); /** * Register a service class with an existing instance * @param <T> * @param serviceClass * @param instance */ <T> void registerService(Class<T> serviceClass, T instance); /** * Register a service class with a provider user to allocate an instance once requested * @param <T> * @param serviceClass * @param supplier */ <T> void registerService(Class<T> serviceClass, Supplier<T> supplier); /** * Register a service class with it's implementation * @param <T> * @param serviceClass * @param serviceImplClassName */ <T> void registerService(Class<T> serviceClass, Class<? extends T> serviceImplClassName); /** * True if an auth provider was associated with ths explorer * @return */ boolean getHasAuthProvider(); }
7,646
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/context/GlobalModelContext.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.context; import java.util.Map; import java.util.Properties; import com.netflix.explorers.model.CrossLink; /** * Inteface provding global context to FTL templates * @author elandau * */ public interface GlobalModelContext { /** * PROD, TEST, DEV, INT * @return */ String getEnvironmentName(); /** * * @return */ Map<String, String> getEnvironment(); /** * Map of datacenter names (us-east.rod, us-west, ...) to base url * @return */ Map<String, CrossLink> getCrosslinks(); /** * us-east, eu-west, ... * @return */ String getCurrentRegion(); /** * Global set of properties * @return */ Properties getGlobalProperties(); /** * @return */ String getApplicationVersion(); /** * * @return */ String getApplicationName(); /** * True if this explorer only references the local instance, as apposed to a global explorer that can * access all instances. * @return */ boolean getIsLocalExplorer(); /** * Home page for the this explorer * @return */ String getHomePageUrl(); /** * Default HTTP access port * @return */ short getDefaultPort(); /** * Return the datacenter for this instance * @return */ String getDataCenter(); long getStartTime(); String getDefaultExplorerName(); }
7,647
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/annotations/Controller.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface Controller { String value(); }
7,648
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/annotations/ExplorerEntity.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface ExplorerEntity { }
7,649
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/annotations/ExplorerGuiceModule.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface ExplorerGuiceModule { String disableProperty() default ""; String jerseyPackagePath() default ""; }
7,650
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/model/MapEntity.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.model; import java.util.Map; import javax.xml.bind.annotation.XmlRootElement; import com.netflix.explorers.annotations.ExplorerEntity; @XmlRootElement(name = "map") @ExplorerEntity public class MapEntity { private Map<Object, Object> map; public MapEntity() { } public MapEntity(Map<Object, Object> map) { super(); this.map = map; } public Map<Object, Object> getMap() { return map; } public void setMap(Map<Object, Object> map) { this.map = map; } }
7,651
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/model/EntityNotFoundException.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.model; public class EntityNotFoundException extends Exception { private static final long serialVersionUID = -3983735082048371603L; private String entityType; private String entityName; private String error; public EntityNotFoundException(String entityType, String entityName) { this.entityName = entityName; this.entityType = entityType; } public String getEntityName() { return entityName; } public EntityNotFoundException setEntityName(String entityName) { this.entityName = entityName; return this; } public String getEntityType() { return entityType; } public EntityNotFoundException setEntityType(String entityType) { this.entityType = entityType; return this; } public String getError() { return error; } public EntityNotFoundException setError(String error) { this.error = error; return this; } @Override public String getMessage() { return toString(); } @Override public String toString() { return "ExceptionEntity [error=" + error + ", entityType=" + entityType+ ", entityName=" + entityName + "]"; } }
7,652
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/model/EmptyExplorer.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.model; import java.util.Map; import java.util.Properties; import java.util.Set; import com.google.common.collect.Sets; import com.netflix.explorers.Explorer; import com.netflix.explorers.ExplorerManager; public class EmptyExplorer implements Explorer { private static final Set<String> EMPTY_SET = Sets.newHashSet(); private static final EmptyExplorer instance = new EmptyExplorer(); public static final EmptyExplorer getInstance() { return instance; } private EmptyExplorer() { } @Override public void initialize() { } @Override public void initialize(ExplorerManager manager) { } @Override public void shutdown() { } @Override public void suspend() { } @Override public void resume() { } @Override public String getName() { return ""; } @Override public String getTitle() { return "Home"; } @Override public String getDescription() { return ""; } @Override public String getAlertMessage() { return ""; } @Override public boolean getIsSecure() { return false; } @Override @Deprecated public Map<String, String> getMenuLayout() { return null; } @Override public MenuItem getMenu() { return null; } @Override public String getLayoutName() { return "bootstrap"; } @Override public Properties getProperties() { return new Properties(); } @Override public Set<String> getRolesAllowed() { return EMPTY_SET; } @Override public boolean getCmcEnabled() { return false; } @Override public String getHome() { return ""; } }
7,653
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/model/DynaTreeNode.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.model; import java.util.Map; import java.util.TreeMap; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; /** * Represents a single node in a tree and simplifies adding children and serializing the final * tree into JSON. * @author elandau */ public class DynaTreeNode { private String title; private String key; private String mode; private Map<String, DynaTreeNode> children; private boolean noLink = true; public DynaTreeNode() { } public DynaTreeNode setTitle(String title) { this.title = title; return this; } public String getTitle() { return this.title; } public DynaTreeNode setNoLink(boolean noLink) { this.noLink = noLink; return this; } public boolean getNoLink() { return this.noLink; } public DynaTreeNode setKey(String key) { this.key = key; return this; } public String getKey() { return this.key; } public DynaTreeNode setMode(String mode) { this.mode = mode; return this; } public String getMode() { return this.mode; } public Map<String, DynaTreeNode> getChildren() { if (children == null) { children = new TreeMap<String, DynaTreeNode>(); } return children; } public DynaTreeNode getChild(String title) { return getChildren().get(title); } public void putChild(DynaTreeNode child) { getChildren().put(child.title, child); } public JSONObject toJSONObject() { JSONObject obj = new JSONObject(); try { obj.put("title", title); obj.put("key", key); obj.put("noLink", noLink); obj.put("mode", mode); obj.put("expand", true); obj.put("children", getChildrenJSONArray()); } catch (JSONException e) { try { obj.put("error", e.getMessage()); } catch (JSONException e1) { } } return obj; } public JSONArray getChildrenJSONArray() { JSONArray ar = null; if (children != null) { ar = new JSONArray(); for (DynaTreeNode a : children.values()) { ar.put(a.toJSONObject()); } } return ar; } }
7,654
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/model/CrossLink.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.model; public class CrossLink { private String href; private String title; private String region; private String env; public String getHref() { return href; } public void setHref(String href) { this.href = href; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getEnv() { return env; } public void setEnv(String env) { this.env = env; } @Override public String toString() { return "CrossLink [href=" + href + ", title=" + title + ", region=" + region + ", env=" + env + "]"; } }
7,655
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/model/MenuItem.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.model; import java.util.Map; import org.apache.commons.lang.StringUtils; import com.google.common.collect.Maps; public class MenuItem { private String title; private String name; private String href; private Map<String, MenuItem> children; public String getTitle() { return title; } public MenuItem setName(String name) { this.name = name; return this; } public String getName() { return this.name; } public MenuItem setTitle(String title) { this.title = title; return this; } public String getHref() { return href; } public MenuItem setHref(String href) { this.href = href; return this; } public Map<String, MenuItem> getChildren() { return children; } public MenuItem addChild(MenuItem child) { if (this.children == null) this.children = Maps.newLinkedHashMap(); this.children.put(child.getName(), child); return this; } public MenuItem getChild(String name) { if (this.children == null) return null; return this.children.get(name); } public boolean hasChildren() { return this.children != null && !this.children.isEmpty(); } public String toString() { return new StringBuilder().append("MenuItem[name=").append(name) .append(",title=").append(title) .append(",href=").append(href) .append(",children=").append(childrenToString()) .append("]").toString(); } private String childrenToString() { StringBuilder sb = new StringBuilder(); sb.append("["); if (children != null) { sb.append(StringUtils.join(children.values(), ",")); } sb.append("]"); return sb.toString(); } }
7,656
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/model/ExplorerInfoListEntity.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.model; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; import com.netflix.explorers.annotations.ExplorerEntity; @ExplorerEntity @XmlRootElement(name="explorer_list") public class ExplorerInfoListEntity { private List<ExplorerInfoEntity> explorers; public List<ExplorerInfoEntity> getExplorers() { return explorers; } public void setExplorers(List<ExplorerInfoEntity> explorers) { this.explorers = explorers; } }
7,657
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/model/ExplorerInfoEntity.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.model; import javax.xml.bind.annotation.XmlRootElement; import com.netflix.explorers.Explorer; import com.netflix.explorers.annotations.ExplorerEntity; @XmlRootElement(name = "explorer") @ExplorerEntity public class ExplorerInfoEntity { private String name; private String description; private String title; private String home; public ExplorerInfoEntity() { } public ExplorerInfoEntity(Explorer explorer) { name = explorer.getName(); description = explorer.getDescription(); title = explorer.getTitle(); home = explorer.getHome(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getHome() { return home; } public void setHome(String home) { this.home = home; } @Override public String toString() { return "ExplorerInfoEntity [name=" + name + ", description=" + description + ", title=" + title + ", home=" + home + "]"; } }
7,658
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/services/ExplorerService.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.services; /** * Interface for a singleton service within the explorer framework. * Services are a mechanism to add singletons that may be shared by * multiple explorers. Services are registered with the ExplorerManager * and should be started by any explorer that needs it. The service * should support multiple starts and stops. * * @author elandau * */ public interface ExplorerService { void start(); void stop(); }
7,659
0
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-api/src/main/java/com/netflix/explorers/rest/RestResource.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.rest; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Produces( MediaType.APPLICATION_JSON ) @Consumes( MediaType.APPLICATION_JSON ) public interface RestResource { }
7,660
0
Create_ds/pytheas/pytheas-karyon/src/main/java/com/netflix/explorers
Create_ds/pytheas/pytheas-karyon/src/main/java/com/netflix/explorers/karyon/ExplorerKaryonServerBootstrap.java
/** * Copyright 2014 Netflix, 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.netflix.explorers.karyon; import com.google.common.collect.Lists; import com.google.inject.Module; import com.netflix.config.ConfigurationManager; import com.netflix.explorers.annotations.ExplorerGuiceModule; import com.netflix.governator.guice.LifecycleInjectorBuilder; import com.netflix.governator.lifecycle.ClasspathScanner; import com.netflix.karyon.server.ServerBootstrap; import com.netflix.karyon.spi.PropertyNames; import com.sun.jersey.guice.JerseyServletModule; import com.sun.jersey.guice.spi.container.servlet.GuiceContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.annotation.Annotation; import java.util.*; /** * ServerBootstrap implementation for pytheas based application. * It scans classpath for GuiceModules marked with ExplorerGuiceModule annotation * and adds them to Karyon's LifecycleInjectorBuilder. * It also adds a JerseyServletModule exporting a list of package names containing jersey resources * contained in a pytheas application */ public class ExplorerKaryonServerBootstrap extends ServerBootstrap { private static final Logger LOG = LoggerFactory.getLogger(ExplorerKaryonServerBootstrap.class); @Override protected void beforeInjectorCreation(@SuppressWarnings("unused") LifecycleInjectorBuilder builderToBeUsed) { List<Class<? extends Annotation>> explorerGuiceAnnotations = Lists.newArrayList(); explorerGuiceAnnotations.add(ExplorerGuiceModule.class); Collection<String> basePackages = getBasePackages(); ClasspathScanner classpathScanner = new ClasspathScanner(basePackages, explorerGuiceAnnotations); List<Module> explorerGuiceModules = new ArrayList<Module>(); String jerseyPkgPath = ""; for (Class<?> explorerGuiceModuleClass : classpathScanner.getClasses()) { try { ExplorerGuiceModule guiceModAnnotation = explorerGuiceModuleClass.getAnnotation(ExplorerGuiceModule.class); if (guiceModAnnotation.jerseyPackagePath() != null && ! guiceModAnnotation.jerseyPackagePath().isEmpty()) { jerseyPkgPath += ";" + guiceModAnnotation.jerseyPackagePath(); } LOG.info("ExplorerGuiceModule init " + explorerGuiceModuleClass.getName()); Module expGuiceModule = (Module) explorerGuiceModuleClass.newInstance(); explorerGuiceModules.add(expGuiceModule); } catch (InstantiationException e) { LOG.error("InstantiationException in building " + explorerGuiceModuleClass.getName()); } catch (IllegalAccessException e) { LOG.error("IllegalAccessException in building " + explorerGuiceModuleClass.getName()); } } LOG.info("Total explorer guice modules added " + explorerGuiceModules.size()); // Add containing servlet module for a pytheas app String appContext = ConfigurationManager.getConfigInstance().getString("com.netflix.pytheas.app.context"); JerseyServletModule jerseyServletModule = buildJerseyServletModule(jerseyPkgPath, appContext); explorerGuiceModules.add(jerseyServletModule); builderToBeUsed.withAdditionalModules(explorerGuiceModules); } @Override protected Collection<String> getBasePackages() { List<String> toReturn = new ArrayList<String>(); String basePackagesStr = ConfigurationManager.getConfigInstance().getString(PropertyNames.SERVER_BOOTSTRAP_BASE_PACKAGES_OVERRIDE); String[] basePackages = basePackagesStr.split(";"); for (String basePackage : basePackages) { toReturn.add(String.valueOf(basePackage)); } return toReturn; } private JerseyServletModule buildJerseyServletModule(final String jerseyPkgPath, final String servletContainerPath) { return new JerseyServletModule() { @Override protected void configureServlets() { bind(GuiceContainer.class).asEagerSingleton(); Map<String, String> params = new HashMap<String, String>(); params.put("com.sun.jersey.config.property.packages", "com.netflix.explorers.resources;" + "com.netflix.explorers.providers;" + jerseyPkgPath); // Route all requests through GuiceContainer serve(servletContainerPath).with(GuiceContainer.class, params); }; }; } }
7,661
0
Create_ds/awsobjectmapper/awsobjectmapper/src/test/java/com/netflix
Create_ds/awsobjectmapper/awsobjectmapper/src/test/java/com/netflix/awsobjectmapper/AmazonObjectMapperTest.java
/** * Copyright 2014 Netflix, 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.netflix.awsobjectmapper; import com.amazonaws.services.ecs.model.VersionInfo; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.reflect.ClassPath; import com.google.common.io.Resources; import org.jeasy.random.EasyRandom; import org.jeasy.random.EasyRandomParameters; import com.amazonaws.services.route53.model.ResourceRecordSet; import java.lang.reflect.Field; import java.util.Set; import java.util.function.Predicate; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class AmazonObjectMapperTest { private boolean hasEmptyConstructor(Class<?> c) { try { c.getConstructor(); // Throws if no match return true; } catch (Exception e) { return false; } } private boolean isModelClass(Class<?> c) { boolean skip = false; // Skip package and exception classes final String simpleName = c.getSimpleName(); skip = simpleName == "package-info" || simpleName.endsWith("Exception"); // Ignore transform classes skip = skip || c.getName().contains(".transform."); // Ignore interfaces skip = skip || c.isInterface(); // Must have an empty constructor skip = skip || !hasEmptyConstructor(c); return !skip; } @Test public void mapRandomAwsObjects() throws Exception { final ObjectMapper mapper = new ObjectMapper(); AmazonObjectMapperConfigurer.configure(mapper); final EasyRandomParameters parameters = new EasyRandomParameters() .ignoreRandomizationErrors(true) .excludeField(excludedFields()) .excludeType(excludedTypes()) .collectionSizeRange(1, 3); final EasyRandom easyRandom = new EasyRandom(parameters); final Set<ClassPath.ClassInfo> classes = ClassPath .from(getClass().getClassLoader()) .getTopLevelClassesRecursive("com.amazonaws"); for (ClassPath.ClassInfo cinfo : classes) { if (cinfo.getName().contains(".model.") && !cinfo.getSimpleName().startsWith("GetConsole") && !cinfo.getName().contains(".s3.model.")) { // TODO: problem with CORSRule final Class<?> c = cinfo.load(); if (isModelClass(c)) { Object obj = easyRandom.nextObject(c); String j1 = mapper.writeValueAsString(obj); Object d1 = mapper.readValue(j1, c); String j2 = mapper.writeValueAsString(d1); Assert.assertEquals(j1, j2); } } } } private Predicate<Field> excludedFields() { return field -> field.getType().equals(com.amazonaws.ResponseMetadata.class) || field.getType().equals(com.amazonaws.http.SdkHttpMetadata.class); } private Predicate<Class<?>> excludedTypes() { return type -> type.getSuperclass().equals(com.amazonaws.AmazonWebServiceRequest.class) || type.equals(com.amazonaws.services.simplesystemsmanagement.model.InventoryAggregator.class); } @Test @SuppressWarnings("deprecation") public void testDeprecatedMapper() throws Exception { final AmazonObjectMapper mapper = new AmazonObjectMapper(); final EasyRandom easyRandom = new EasyRandom(); Object obj = easyRandom.nextObject(VersionInfo.class); String j1 = mapper.writeValueAsString(obj); Object d1 = mapper.readValue(j1, VersionInfo.class); String j2 = mapper.writeValueAsString(d1); Assert.assertEquals(j1, j2); } @Test public void namingStrategy() throws Exception { final ObjectMapper mapper = new ObjectMapper(); AmazonObjectMapperConfigurer.configure(mapper); byte[] json = Resources.toByteArray(Resources.getResource("recordSet.json")); ResourceRecordSet recordSet = mapper.readValue(json, ResourceRecordSet.class); Assert.assertEquals(60L, (long) recordSet.getTTL()); } }
7,662
0
Create_ds/awsobjectmapper/awsobjectmapper/src/main/java/com/netflix
Create_ds/awsobjectmapper/awsobjectmapper/src/main/java/com/netflix/awsobjectmapper/package-info.java
/* * * Copyright 2013 Netflix, 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. * */ /** TODO */ package com.netflix.awsobjectmapper;
7,663
0
Create_ds/sagemaker-python-sdk/tests/data/spark/code/java/hello-java-spark/com/amazonaws/sagemaker/spark
Create_ds/sagemaker-python-sdk/tests/data/spark/code/java/hello-java-spark/com/amazonaws/sagemaker/spark/test/HelloJavaSparkApp.java
package com.amazonaws.sagemaker.spark.test; public class HelloJavaSparkApp { public static void main(final String[] args) { System.out.println("Hello World, this is Java-Spark!"); } }
7,664
0
Create_ds/mantis/mantis-client/src/test
Create_ds/mantis/mantis-client/src/test/java/MantisSSEJobTest.java
/* * Copyright 2019 Netflix, 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. */ import static org.junit.Assert.fail; import io.mantisrx.client.MantisClient; import io.mantisrx.client.MantisSSEJob; import io.mantisrx.client.SinkConnectionsStatus; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observer; import rx.functions.Action1; public class MantisSSEJobTest { private static final Logger logger = LoggerFactory.getLogger(MantisSSEJobTest.class); static Properties zkProps = new Properties(); static { zkProps.put("mantis.zookeeper.connectString", "100.67.80.172:2181,100.67.71.221:2181,100.67.89.26:2181,100.67.71.34:2181,100.67.80.18:2181"); zkProps.put("mantis.zookeeper.leader.announcement.path", "/leader"); zkProps.put("mantis.zookeeper.root", "/mantis/master"); } // @Test public void jobDiscoveryInfoStreamTest() throws InterruptedException { CountDownLatch latch = new CountDownLatch(5); MantisClient mClient = new MantisClient(zkProps); mClient.jobClusterDiscoveryInfoStream("SineFnTest") .map((schedInfo) -> { latch.countDown(); return String.valueOf(schedInfo); }) .doOnError(e -> logger.error("caught error", e)) .subscribe((sc) -> logger.info("got {}", sc)); latch.await(5, TimeUnit.MINUTES); } // @Test public void connectToJobTest() { CountDownLatch latch = new CountDownLatch(5); CountDownLatch connectionStatusReceived = new CountDownLatch(1); MantisSSEJob job = new MantisSSEJob.Builder(zkProps) .name("GroupByIP") .sinkConnectionsStatusObserver(new Observer<SinkConnectionsStatus>() { @Override public void onCompleted() { // TODO Auto-generated method stub } @Override public void onError(Throwable e) { // TODO Auto-generated method stub } @Override public void onNext(SinkConnectionsStatus t) { connectionStatusReceived.countDown(); } }) .onConnectionReset(new Action1<Throwable>() { @Override public void call(Throwable throwable) { System.err.println("Reconnecting due to error: " + throwable.getMessage()); } }) // .sinkParams(params) .buildJobConnector(); job.connectAndGet() .flatMap((t) -> { return t.map((mmsse) -> { return mmsse.getEventAsString(); }); }) .take(5) .doOnNext((d) -> { latch.countDown(); }) .toBlocking().subscribe((data) -> { System.out.println("Got data -> " + data); }); ; try { latch.await(10, TimeUnit.SECONDS); connectionStatusReceived.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { fail(); } } //@Test public void submitAndConnectTest() { CountDownLatch latch = new CountDownLatch(2); CountDownLatch connectionStatusReceived = new CountDownLatch(1); MantisSSEJob job = new MantisSSEJob.Builder(zkProps) .name("mantis-examples-sine-function") .sinkConnectionsStatusObserver(new Observer<SinkConnectionsStatus>() { @Override public void onCompleted() { // TODO Auto-generated method stub } @Override public void onError(Throwable e) { // TODO Auto-generated method stub } @Override public void onNext(SinkConnectionsStatus t) { connectionStatusReceived.countDown(); } }) .onConnectionReset(new Action1<Throwable>() { @Override public void call(Throwable throwable) { System.err.println("Reconnecting due to error: " + throwable.getMessage()); } }) .onCloseKillJob() // .sinkParams(params) .buildJobSubmitter(); job.submitAndGet() .flatMap((t) -> { return t.map((mmsse) -> { return mmsse.getEventAsString(); }); }) .take(2) .doOnNext((d) -> { latch.countDown(); }) .toBlocking().subscribe((data) -> { System.out.println("Got data -> " + data); }); ; try { latch.await(20, TimeUnit.SECONDS); connectionStatusReceived.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { fail(); } } static class NoOpSinkConnectionsStatusObserver implements Observer<SinkConnectionsStatus> { @Override public void onCompleted() { logger.warn("Got Completed on SinkConnectionStatus "); } @Override public void onError(Throwable e) { logger.error("Got Error on SinkConnectionStatus ", e); } @Override public void onNext(SinkConnectionsStatus t) { logger.info("Got Sink Connection Status update " + t); } } }
7,665
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/SinkClient.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.client; import rx.Observable; public interface SinkClient<T> { boolean hasError(); String getError(); Observable<Observable<T>> getResults(); Observable<Observable<T>> getPartitionedResults(int forPartition, int totalPartitions); }
7,666
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/JobSinkLocator.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.client; import io.reactivex.mantis.remote.observable.EndpointChange; import rx.Observable; public interface JobSinkLocator { Observable<EndpointChange> locateSinkForJob(String jobId); Observable<EndpointChange> locatePartitionedSinkForJob(String jobId, int forPartition, int totalPartitions); }
7,667
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/SinkClientImpl.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.client; import com.netflix.spectator.api.BasicTag; import io.mantisrx.common.metrics.Gauge; import io.mantisrx.common.metrics.Metrics; import io.mantisrx.common.metrics.spectator.MetricGroupId; import io.mantisrx.server.master.client.MasterClientWrapper; import io.reactivex.mantis.remote.observable.EndpointChange; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import lombok.ToString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observer; import rx.functions.Action1; import rx.functions.Func1; public class SinkClientImpl<T> implements SinkClient<T> { private static final Logger logger = LoggerFactory.getLogger(SinkClientImpl.class); final String jobId; final SinkConnectionFunc<T> sinkConnectionFunc; final JobSinkLocator jobSinkLocator; final private AtomicBoolean nowClosed = new AtomicBoolean(false); final private SinkConnections<T> sinkConnections = new SinkConnections<>(); private final String sinkGuageName = "SinkConnections"; private final String expectedSinksGaugeName = "ExpectedSinkConnections"; private final String sinkReceivingDataGaugeName = "sinkRecvngData"; private final String clientNotConnectedToAllSourcesGaugeName = "clientNotConnectedToAllSources"; private final Gauge sinkGauge; private final Gauge expectedSinksGauge; private final Gauge sinkReceivingDataGauge; private final Gauge clientNotConnectedToAllSourcesGauge; private final AtomicInteger numSinkWorkers = new AtomicInteger(); private final AtomicInteger numSinkRunningWorkers = new AtomicInteger(); private final Observer<SinkConnectionsStatus> sinkConnectionsStatusObserver; private final long dataRecvTimeoutSecs; private final Metrics metrics; private final boolean disablePingFiltering; SinkClientImpl(String jobId, SinkConnectionFunc<T> sinkConnectionFunc, JobSinkLocator jobSinkLocator, Observable<MasterClientWrapper.JobSinkNumWorkers> numSinkWorkersObservable, Observer<SinkConnectionsStatus> sinkConnectionsStatusObserver, long dataRecvTimeoutSecs) { this(jobId, sinkConnectionFunc, jobSinkLocator, numSinkWorkersObservable, sinkConnectionsStatusObserver, dataRecvTimeoutSecs, false); } SinkClientImpl(String jobId, SinkConnectionFunc<T> sinkConnectionFunc, JobSinkLocator jobSinkLocator, Observable<MasterClientWrapper.JobSinkNumWorkers> numSinkWorkersObservable, Observer<SinkConnectionsStatus> sinkConnectionsStatusObserver, long dataRecvTimeoutSecs, boolean disablePingFiltering) { this.jobId = jobId; this.sinkConnectionFunc = sinkConnectionFunc; this.jobSinkLocator = jobSinkLocator; BasicTag jobIdTag = new BasicTag("jobId", Optional.ofNullable(jobId).orElse("NullJobId")); MetricGroupId metricGroupId = new MetricGroupId(SinkClientImpl.class.getCanonicalName(), jobIdTag); this.metrics = new Metrics.Builder() .id(metricGroupId) .addGauge(sinkGuageName) .addGauge(expectedSinksGaugeName) .addGauge(sinkReceivingDataGaugeName) .addGauge(clientNotConnectedToAllSourcesGaugeName) .build(); sinkGauge = metrics.getGauge(sinkGuageName); expectedSinksGauge = metrics.getGauge(expectedSinksGaugeName); sinkReceivingDataGauge = metrics.getGauge(sinkReceivingDataGaugeName); clientNotConnectedToAllSourcesGauge = metrics.getGauge(clientNotConnectedToAllSourcesGaugeName); numSinkWorkersObservable .doOnNext((jobSinkNumWorkers) -> { numSinkWorkers.set(jobSinkNumWorkers.getNumSinkWorkers()); numSinkRunningWorkers.set(jobSinkNumWorkers.getNumSinkRunningWorkers()); }) .takeWhile((integer) -> !nowClosed.get()) .subscribe(); this.sinkConnectionsStatusObserver = sinkConnectionsStatusObserver; this.dataRecvTimeoutSecs = dataRecvTimeoutSecs; this.disablePingFiltering = disablePingFiltering; } private String toSinkName(String host, int port) { return host + "-" + port; } @Override public boolean hasError() { return false; } @Override public String getError() { return null; } @Override public Observable<Observable<T>> getResults() { return getPartitionedResults(-1, 0); } @Override public Observable<Observable<T>> getPartitionedResults(final int forIndex, final int totalPartitions) { return internalGetResults(forIndex, totalPartitions); // return Observable // .create(new Observable.OnSubscribe<Observable<T>>() { // @Override // public void call(final Subscriber subscriber) { // internalGetResults(forIndex, totalPartitions).subscribe(subscriber); // } // }) // .subscribeOn(Schedulers.io()); } private <T> Observable<Observable<T>> internalGetResults(int forIndex, int totalPartitions) { return jobSinkLocator .locatePartitionedSinkForJob(jobId, forIndex, totalPartitions) .map(new Func1<EndpointChange, Observable<T>>() { @Override public Observable<T> call(EndpointChange endpointChange) { if (nowClosed.get()) return Observable.empty(); if (endpointChange.getType() == EndpointChange.Type.complete) { return handleEndpointClose(endpointChange); } else { return handleEndpointConnect(endpointChange); } } }) .doOnUnsubscribe(() -> { try { logger.warn("Closing connections to sink of job {}", jobId); closeAllConnections(); } catch (Exception e) { logger.warn("Error closing all connections to sink of job {}", jobId, e); } }) .share() // .lift(new Observable.Operator<Observable<T>, Observable<T>>() { // @Override // public Subscriber<? super Observable<T>> call(Subscriber<? super Observable<T>> subscriber) { // subscriber.add(Subscriptions.create(new Action0() { // @Override // public void call() { // try { // logger.warn("Closing connections to sink of job " + jobId); // closeAllConnections(); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // })); // return subscriber; // } // }) // .share() // .lift(new DropOperator<Observable<T>>("client_partition_share")) ; } private <T> Observable<T> handleEndpointConnect(EndpointChange endpoint) { logger.info("Opening connection to sink at " + endpoint.toString()); final String unwrappedHost = MasterClientWrapper.getUnwrappedHost(endpoint.getEndpoint().getHost()); SinkConnection sinkConnection = sinkConnectionFunc.call(unwrappedHost, endpoint.getEndpoint().getPort(), new Action1<Boolean>() { @Override public void call(Boolean flag) { updateSinkConx(flag); } }, new Action1<Boolean>() { @Override public void call(Boolean flag) { updateSinkDataReceivingStatus(flag); } }, dataRecvTimeoutSecs, this.disablePingFiltering ); if (nowClosed.get()) {// check if closed before adding try { sinkConnection.close(); } catch (Exception e) { logger.warn("Error closing sink connection " + sinkConnection.getName() + " - " + e.getMessage(), e); } return Observable.empty(); } sinkConnections.put(toSinkName(unwrappedHost, endpoint.getEndpoint().getPort()), sinkConnection); if (nowClosed.get()) { try { sinkConnection.close(); sinkConnections.remove(toSinkName(unwrappedHost, endpoint.getEndpoint().getPort())); return Observable.empty(); } catch (Exception e) { logger.warn("Error closing sink connection - " + e.getMessage()); } } return ((SinkConnection<T>) sinkConnection).call() .takeWhile(e -> !nowClosed.get()) ; } private void updateSinkDataReceivingStatus(Boolean flag) { if (flag) sinkReceivingDataGauge.increment(); else sinkReceivingDataGauge.decrement(); expectedSinksGauge.set(numSinkWorkers.get()); if (expectedSinksGauge.value() != sinkReceivingDataGauge.value()) { this.clientNotConnectedToAllSourcesGauge.set(1); } else { this.clientNotConnectedToAllSourcesGauge.set(0); } if (sinkConnectionsStatusObserver != null) { synchronized (sinkConnectionsStatusObserver) { sinkConnectionsStatusObserver.onNext(new SinkConnectionsStatus(sinkReceivingDataGauge.value(), sinkGauge.value(), numSinkWorkers.get(), numSinkRunningWorkers.get())); } } } private void updateSinkConx(Boolean flag) { if (flag) sinkGauge.increment(); else sinkGauge.decrement(); expectedSinksGauge.set(numSinkWorkers.get()); if (expectedSinksGauge.value() != sinkReceivingDataGauge.value()) { this.clientNotConnectedToAllSourcesGauge.set(1); } else { this.clientNotConnectedToAllSourcesGauge.set(0); } if (sinkConnectionsStatusObserver != null) { synchronized (sinkConnectionsStatusObserver) { sinkConnectionsStatusObserver.onNext(new SinkConnectionsStatus(sinkReceivingDataGauge.value(), sinkGauge.value(), numSinkWorkers.get(), numSinkRunningWorkers.get())); } } } private <T> Observable<T> handleEndpointClose(EndpointChange endpoint) { logger.info("Closed connection to sink at " + endpoint.toString()); final String unwrappedHost = MasterClientWrapper.getUnwrappedHost(endpoint.getEndpoint().getHost()); final SinkConnection<T> removed = (SinkConnection<T>) sinkConnections.remove(toSinkName(unwrappedHost, endpoint.getEndpoint().getPort())); if (removed != null) { try { removed.close(); } catch (Exception e) { // shouldn't happen logger.error("Unexpected exception on closing sinkConnection: " + e.getMessage(), e); } } else { logger.error("SinkConnections does not contain endpoint to be removed. host: {}, sinkConnections: {}", unwrappedHost, sinkConnections); } return Observable.empty(); } private void closeAllConnections() throws Exception { nowClosed.set(true); sinkConnections.closeOut((SinkConnection<T> tSinkConnection) -> { try { tSinkConnection.close(); } catch (Exception e) { logger.warn("Error closing sink connection " + tSinkConnection.getName() + " - " + e.getMessage(), e); } }); } @ToString class SinkConnections<T> { final private Map<String, SinkConnection<T>> sinkConnections = new HashMap<>(); private boolean isClosed = false; private void put(String key, SinkConnection<T> val) { synchronized (sinkConnections) { if (isClosed) return; sinkConnections.put(key, val); } } private SinkConnection<T> remove(String key) { synchronized (sinkConnections) { return sinkConnections.remove(key); } } private void closeOut(Action1<SinkConnection<T>> onClose) { synchronized (sinkConnections) { isClosed = true; } for (SinkConnection<T> sinkConnection : sinkConnections.values()) { logger.info("Closing " + sinkConnection.getName()); onClose.call(sinkConnection); } } } }
7,668
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/SinkConnectionsStatus.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.client; public class SinkConnectionsStatus { private final long numConnected; private final long total; private final long recevingDataFrom; private final long runningCount; public SinkConnectionsStatus(long recevingDataFrom, long numConnected, long total, long runningCount) { this.recevingDataFrom = recevingDataFrom; this.numConnected = numConnected; this.total = total; this.runningCount = runningCount; } public long getRecevingDataFrom() { return recevingDataFrom; } public long getNumConnected() { return numConnected; } public long getTotal() { return total; } public long getRunningCount() { return runningCount; } }
7,669
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/SinkConnectionFunc.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.client; import rx.functions.Action1; import rx.functions.Func2; public interface SinkConnectionFunc<T> extends Func2<String, Integer, SinkConnection<T>> { default SinkConnection<T> call(String t1, Integer t2, Action1<Boolean> updateConxStatus, Action1<Boolean> updateDataRecvngStatus, long dataRecvTimeoutSecs) { return call(t1, t2, updateConxStatus, updateDataRecvngStatus, dataRecvTimeoutSecs, false); } SinkConnection<T> call(String t1, Integer t2, Action1<Boolean> updateConxStatus, Action1<Boolean> updateDataRecvngStatus, long dataRecvTimeoutSecs, boolean disablePingFiltering); }
7,670
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/MantisClient.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.client; import com.mantisrx.common.utils.Services; import io.mantisrx.runtime.JobSla; import io.mantisrx.runtime.MantisJobState; import io.mantisrx.runtime.descriptor.SchedulingInfo; import io.mantisrx.runtime.parameter.Parameter; import io.mantisrx.server.core.Configurations; import io.mantisrx.server.core.CoreConfiguration; import io.mantisrx.server.core.JobSchedulingInfo; import io.mantisrx.server.master.client.HighAvailabilityServices; import io.mantisrx.server.master.client.HighAvailabilityServicesUtil; import io.mantisrx.server.master.client.MantisMasterGateway; import io.mantisrx.server.master.client.MasterClientWrapper; import io.reactivex.mantis.remote.observable.EndpointChange; import java.util.List; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observer; import rx.subjects.PublishSubject; public class MantisClient { private static final Logger logger = LoggerFactory.getLogger(MantisClient.class); private static final String ENABLE_PINGS_KEY = "mantis.sse.disablePingFiltering"; private final boolean disablePingFiltering; private final MasterClientWrapper clientWrapper; private final JobSinkLocator jobSinkLocator = new JobSinkLocator() { @Override public Observable<EndpointChange> locateSinkForJob(final String jobId) { return locatePartitionedSinkForJob(jobId, -1, 0); } @Override public Observable<EndpointChange> locatePartitionedSinkForJob(final String jobId, final int forPartition, final int totalPartitions) { return clientWrapper.getMasterClientApi() .flatMap((MantisMasterGateway mantisMasterClientApi) -> { return mantisMasterClientApi.getSinkStageNum(jobId) .take(1) // only need to figure out sink stage number once .flatMap((Integer integer) -> { logger.info("Getting sink locations for " + jobId); return clientWrapper.getSinkLocations(jobId, integer, forPartition, totalPartitions); }); }); } }; /** * The following properties are required: * <UL> * <LI> * #default 1000<br> * mantis.zookeeper.connectionTimeMs=1000 * </LI> * <LI> * # default 500<br> * mantis.zookeeper.connection.retrySleepMs=500 * </LI> * <LI> * # default 5<br> * mantis.zookeeper.connection.retryCount=5 * </LI> * <LI> * # default NONE<br> * mantis.zookeeper.connectString= * </LI> * <LI> * #default NONE<br> * mantis.zookeeper.root= * </LI> * <LI> * #default /leader <br> * mantis.zookeeper.leader.announcement.path= * </LI> * </UL> * * @param properties */ public MantisClient(Properties properties) { HighAvailabilityServices haServices = HighAvailabilityServicesUtil.createHAServices( Configurations.frmProperties(properties, CoreConfiguration.class)); Services.startAndWait(haServices); clientWrapper = new MasterClientWrapper(haServices.getMasterClientApi()); this.disablePingFiltering = Boolean.parseBoolean(properties.getProperty(ENABLE_PINGS_KEY)); } public MantisClient(MasterClientWrapper clientWrapper, boolean disablePingFiltering) { this.disablePingFiltering = disablePingFiltering; this.clientWrapper = clientWrapper; } public MantisClient(MasterClientWrapper clientWrapper) { this(clientWrapper, false); } public JobSinkLocator getSinkLocator() { return jobSinkLocator; } /* package */ MasterClientWrapper getClientWrapper() { return clientWrapper; } private MantisMasterGateway blockAndGetMasterApi() { return clientWrapper .getMasterClientApi() .toBlocking() .first(); } public Observable<Boolean> namedJobExists(final String jobName) { return clientWrapper.namedJobExists(jobName); } public <T> Observable<SinkClient<T>> getSinkClientByJobName(final String jobName, final SinkConnectionFunc<T> sinkConnectionFunc, final Observer<SinkConnectionsStatus> sinkConnectionsStatusObserver) { return getSinkClientByJobName(jobName, sinkConnectionFunc, sinkConnectionsStatusObserver, 5); } public <T> Observable<SinkClient<T>> getSinkClientByJobName(final String jobName, final SinkConnectionFunc<T> sinkConnectionFunc, final Observer<SinkConnectionsStatus> sinkConnectionsStatusObserver, final long dataRecvTimeoutSecs) { final AtomicReference<String> lastJobIdRef = new AtomicReference<>(); return clientWrapper.getNamedJobsIds(jobName) .doOnUnsubscribe(() -> lastJobIdRef.set(null)) // .lift(new Observable.Operator<String, String>() { // @Override // public Subscriber<? super String> call(Subscriber<? super String> subscriber) { // subscriber.add(Subscriptions.create(new Action0() { // @Override // public void call() { // lastJobIdRef.set(null); // } // })); // return subscriber; // } // }) .filter((String newJobId) -> { logger.info("Got job cluster's new jobId=" + newJobId); return newJobIdIsGreater(lastJobIdRef.get(), newJobId); }) .map((final String jobId) -> { if (MasterClientWrapper.InvalidNamedJob.equals(jobId)) return getErrorSinkClient(jobId); lastJobIdRef.set(jobId); logger.info("Connecting to job " + jobName + " with new jobId=" + jobId); return getSinkClientByJobId(jobId, sinkConnectionFunc, sinkConnectionsStatusObserver, dataRecvTimeoutSecs); }); } private Boolean newJobIdIsGreater(String oldJobId, String newJobId) { if (oldJobId == null) return true; final int oldIdx = oldJobId.lastIndexOf('-'); if (oldIdx < 0) return true; final int newIdx = newJobId.lastIndexOf('-'); if (newIdx < 0) return true; try { int old = Integer.parseInt(oldJobId.substring(oldIdx + 1)); int newJ = Integer.parseInt(newJobId.substring(newIdx + 1)); return newJ > old; } catch (NumberFormatException | IndexOutOfBoundsException e) { return true; // can't parse numbers, assume it is not the same as old job id } } private <T> SinkClient<T> getErrorSinkClient(final String mesg) { return new SinkClient<T>() { @Override public boolean hasError() { return true; } @Override public String getError() { return mesg; } @Override public Observable<Observable<T>> getResults() { return null; } @Override public Observable<Observable<T>> getPartitionedResults(int forPartition, int totalPartitions) { return null; } }; } public <T> SinkClient<T> getSinkClientByJobId(final String jobId, final SinkConnectionFunc<T> sinkConnectionFunc, Observer<SinkConnectionsStatus> sinkConnectionsStatusObserver) { return getSinkClientByJobId(jobId, sinkConnectionFunc, sinkConnectionsStatusObserver, 5); } public <T> SinkClient<T> getSinkClientByJobId(final String jobId, final SinkConnectionFunc<T> sinkConnectionFunc, Observer<SinkConnectionsStatus> sinkConnectionsStatusObserver, long dataRecvTimeoutSecs) { PublishSubject<MasterClientWrapper.JobSinkNumWorkers> numSinkWrkrsSubject = PublishSubject.create(); clientWrapper.addNumSinkWorkersObserver(numSinkWrkrsSubject); return new SinkClientImpl<T>(jobId, sinkConnectionFunc, getSinkLocator(), numSinkWrkrsSubject .filter((jobSinkNumWorkers) -> jobId.equals(jobSinkNumWorkers.getJobId())), sinkConnectionsStatusObserver, dataRecvTimeoutSecs, this.disablePingFiltering); } public String submitJob(final String name, final String version, final List<Parameter> parameters, final JobSla jobSla, final SchedulingInfo schedulingInfo) throws Exception { return clientWrapper.getMasterClientApi() .flatMap((MantisMasterGateway mantisMasterClientApi) -> { return mantisMasterClientApi.submitJob(name, version, parameters, jobSla, schedulingInfo) .onErrorResumeNext((t) -> { logger.warn(t.getMessage()); return Observable.empty(); }); }) .take(1) .toBlocking() .first() .getJobId(); } public String submitJob(final String name, final String version, final List<Parameter> parameters, final JobSla jobSla, final long subscriptionTimeoutSecs, final SchedulingInfo schedulingInfo) throws Exception { return clientWrapper.getMasterClientApi() .flatMap((MantisMasterGateway mantisMasterClientApi) -> { return mantisMasterClientApi.submitJob(name, version, parameters, jobSla, subscriptionTimeoutSecs, schedulingInfo) .onErrorResumeNext((Throwable t) -> { logger.warn(t.getMessage()); return Observable.empty(); }); } ) .take(1) .toBlocking() .first() .getJobId(); } public String submitJob(final String name, final String version, final List<Parameter> parameters, final JobSla jobSla, final long subscriptionTimeoutSecs, final SchedulingInfo schedulingInfo, final boolean readyForJobMaster) throws Exception { return clientWrapper.getMasterClientApi() .flatMap((MantisMasterGateway mantisMasterClientApi) -> { return mantisMasterClientApi.submitJob(name, version, parameters, jobSla, subscriptionTimeoutSecs, schedulingInfo, readyForJobMaster) .onErrorResumeNext((Throwable t) -> { logger.warn(t.getMessage()); return Observable.empty(); }); }) .take(1) .toBlocking() .first() .getJobId(); } public void killJob(final String jobId) { clientWrapper.getMasterClientApi() .flatMap((MantisMasterGateway mantisMasterClientApi) -> { return mantisMasterClientApi.killJob(jobId) .onErrorResumeNext((Throwable t) -> { logger.warn(t.getMessage()); return Observable.empty(); }); }) .take(1) .toBlocking() .first(); } // public void createNamedJob(final CreateJobClusterRequest request) { // clientWrapper.getMasterClientApi() // .flatMap((MantisMasterClientApi mantisMasterClientApi) -> { // return mantisMasterClientApi.createNamedJob(request) // .onErrorResumeNext((t) -> { // logger.warn(t.getMessage()); // return Observable.empty(); // }); // }) // .take(1) // .toBlocking() // .first(); // } // // public void updateNamedJob(final UpdateJobClusterRequest request) { // clientWrapper.getMasterClientApi() // .flatMap((MantisMasterClientApi mantisMasterClientApi) -> { // return mantisMasterClientApi.updateNamedJob(request) // .onErrorResumeNext((t) -> { // logger.warn(t.getMessage()); // return Observable.empty(); // }); // }) // .take(1) // .toBlocking() // .first(); // } /** * Get json array data for a list of jobs for a given job cluster. * * @param name Name of the job * @param state State of jobs to match; null matches any state * * @return Json array data of the list of jobs, if any. */ public Observable<String> getJobsOfNamedJob(final String name, final MantisJobState.MetaState state) { return clientWrapper.getMasterClientApi() .flatMap((MantisMasterGateway mantisMasterClientApi) -> { return mantisMasterClientApi.getJobsOfNamedJob(name, state); }) .first(); } /** * A stream of changes associated with the given JobId */ public Observable<String> getJobStatusObservable(final String jobId) { return clientWrapper.getMasterClientApi() .flatMap((MantisMasterGateway mantisMasterClientApi) -> { return mantisMasterClientApi.getJobStatusObservable(jobId); }); } /** * A stream of scheduling changes for the given Jobid */ public Observable<JobSchedulingInfo> getSchedulingChanges(final String jobId) { return clientWrapper.getMasterClientApi() .flatMap((masterClientApi) -> masterClientApi.schedulingChanges(jobId)); } /** * A stream of discovery updates for the latest job ID of given Job cluster * * @param jobCluster Job cluster name * * @return Observable<JobSchedulingInfo> stream of JobSchedulingInfo for latest jobID of job cluster */ public Observable<JobSchedulingInfo> jobClusterDiscoveryInfoStream(final String jobCluster) { final AtomicReference<String> lastJobIdRef = new AtomicReference<>(); return clientWrapper.getNamedJobsIds(jobCluster) .doOnUnsubscribe(() -> lastJobIdRef.set(null)) .filter((String newJobId) -> { logger.info("Got job cluster {}'s new jobId : {}", jobCluster, newJobId); return newJobIdIsGreater(lastJobIdRef.get(), newJobId); }) .switchMap((final String jobId) -> { if (MasterClientWrapper.InvalidNamedJob.equals(jobId)) { return Observable.error(new Exception("No such job cluster " + jobCluster)); } lastJobIdRef.set(jobId); logger.info("[{}] switched to streaming discovery info for {}", jobCluster, jobId); return getSchedulingChanges(jobId); }); } }
7,671
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/SseSinkConnectionFunction.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.client; import static com.mantisrx.common.utils.MantisMetricStringConstants.DROP_OPERATOR_INCOMING_METRIC_GROUP; import com.mantisrx.common.utils.NettyUtils; import io.mantisrx.common.MantisServerSentEvent; import io.mantisrx.common.metrics.Counter; import io.mantisrx.common.metrics.Metrics; import io.mantisrx.common.metrics.MetricsRegistry; import io.mantisrx.common.metrics.spectator.MetricGroupId; import io.mantisrx.runtime.parameter.SinkParameters; import io.mantisrx.server.core.ServiceRegistry; import io.mantisrx.server.worker.client.SseWorkerConnection; import io.reactivx.mantis.operators.DropOperator; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.functions.Action1; public class SseSinkConnectionFunction implements SinkConnectionFunc<MantisServerSentEvent> { private static final String DEFAULT_BUFFER_SIZE_STR = "0"; private static final Logger logger = LoggerFactory.getLogger(SseSinkConnectionFunction.class); private static final CopyOnWriteArraySet<MetricGroupId> metricsSet = new CopyOnWriteArraySet<>(); private static final MetricGroupId metricGroupId; private static final Action1<Throwable> defaultConxResetHandler = new Action1<Throwable>() { @Override public void call(Throwable throwable) { logger.warn("Retrying reset connection"); try {Thread.sleep(500);} catch (InterruptedException ie) { logger.debug("Interrupted waiting for retrying connection"); } } }; static { // NJ // Use single netty thread NettyUtils.setNettyThreads(); metricGroupId = new MetricGroupId(DROP_OPERATOR_INCOMING_METRIC_GROUP + "_SseSinkConnectionFunction_withBuffer"); metricsSet.add(metricGroupId); logger.info("SETTING UP METRICS PRINTER THREAD"); new ScheduledThreadPoolExecutor(1).scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { Set<MetricGroupId> metricGroups = new HashSet<>(metricsSet); if (!metricGroups.isEmpty()) { for (MetricGroupId metricGroup : metricGroups) { final Metrics metric = MetricsRegistry.getInstance().getMetric(metricGroup); if (metric != null) { final Counter onNext = metric.getCounter("" + DropOperator.Counters.onNext); final Counter onError = metric.getCounter("" + DropOperator.Counters.onError); final Counter onComplete = metric.getCounter("" + DropOperator.Counters.onComplete); final Counter dropped = metric.getCounter("" + DropOperator.Counters.dropped); logger.info(metricGroup.id() + ": onNext=" + onNext.value() + ", onError=" + onError.value() + ", onComplete=" + onComplete.value() + ", dropped=" + dropped.value() // + ", buffered=" + buffered.value() ); } } } } catch (Exception e) { logger.warn("Unexpected error in metrics printer thread: " + e.getMessage(), e); } } }, 60, 60, TimeUnit.SECONDS); } private final boolean reconnectUponConnectionRest; private final Action1<Throwable> connectionResetHandler; private final SinkParameters sinkParameters; private final int bufferSize; public SseSinkConnectionFunction(boolean reconnectUponConnectionRest, Action1<Throwable> connectionResetHandler) { this(reconnectUponConnectionRest, connectionResetHandler, null); } public SseSinkConnectionFunction(boolean reconnectUponConnectionRest, Action1<Throwable> connectionResetHandler, SinkParameters sinkParameters) { this.reconnectUponConnectionRest = reconnectUponConnectionRest; this.connectionResetHandler = connectionResetHandler == null ? defaultConxResetHandler : connectionResetHandler; this.sinkParameters = sinkParameters; String bufferSizeStr = ServiceRegistry.INSTANCE.getPropertiesService().getStringValue("mantisClient.buffer.size", DEFAULT_BUFFER_SIZE_STR); bufferSize = Integer.parseInt(Optional.ofNullable(bufferSizeStr).orElse(DEFAULT_BUFFER_SIZE_STR)); } @Override public SinkConnection<MantisServerSentEvent> call(String hostname, Integer port) { return call(hostname, port, null, null, 5); } @Override public SinkConnection<MantisServerSentEvent> call(final String hostname, final Integer port, final Action1<Boolean> updateConxStatus, final Action1<Boolean> updateDataRecvngStatus, final long dataRecvTimeoutSecs, final boolean disablePingFiltering) { return new SinkConnection<MantisServerSentEvent>() { private final SseWorkerConnection workerConn = new SseWorkerConnection("Sink", hostname, port, updateConxStatus, updateDataRecvngStatus, connectionResetHandler, dataRecvTimeoutSecs, reconnectUponConnectionRest, metricsSet, bufferSize, sinkParameters, disablePingFiltering,metricGroupId); @Override public String getName() { return workerConn.getName(); } @Override public void close() throws Exception { workerConn.close(); } @Override public Observable<MantisServerSentEvent> call() { return workerConn.call(); } }; } }
7,672
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/MantisSSEJob.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.client; import io.mantisrx.common.MantisServerSentEvent; import io.mantisrx.runtime.JobSla; import io.mantisrx.runtime.MantisJobDurationType; import io.mantisrx.runtime.descriptor.SchedulingInfo; import io.mantisrx.runtime.parameter.Parameter; import io.mantisrx.runtime.parameter.SinkParameters; import io.mantisrx.server.master.client.ConditionalRetry; import io.mantisrx.server.master.client.NoSuchJobException; import io.reactivx.mantis.operators.DropOperator; import java.io.Closeable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observer; import rx.Subscriber; import rx.functions.Action1; import rx.schedulers.Schedulers; public class MantisSSEJob implements Closeable { private static final String ConnectTimeoutSecsPropertyName = "MantisClientConnectTimeoutSecs"; private static final Logger logger = LoggerFactory.getLogger(MantisSSEJob.class); private final Builder builder; private final Mode mode; private Observable<Observable<MantisServerSentEvent>> resultsObservable; private String jobId = null; private int forPartition = -1; private int totalPartitions = 0; private MantisSSEJob(Builder builder, Mode mode) { this.builder = builder; this.mode = mode; if (builder.connectTimeoutSecs > 0) System.setProperty(ConnectTimeoutSecsPropertyName, String.valueOf(builder.connectTimeoutSecs)); } @Override public synchronized void close() { if (mode == Mode.Submit && builder.ephemeral) { if (jobId != null) { builder.mantisClient.killJob(jobId); logger.info("Sent kill to master for job " + jobId); } else logger.warn("Unexpected to not have JobId to kill ephemeral job"); } } public String getJobId() { return jobId; } private Observable<Observable<MantisServerSentEvent>> sinksToObservable(final Observable<SinkClient<MantisServerSentEvent>> sinkClients) { final ConditionalRetry retryObject = new ConditionalRetry(null, "SinkClient_" + builder.name); return sinkClients .switchMap((SinkClient<MantisServerSentEvent> serverSentEventSinkClient) -> { if (serverSentEventSinkClient.hasError()) return Observable.just(Observable.just(new MantisServerSentEvent(serverSentEventSinkClient.getError()))); return serverSentEventSinkClient.getPartitionedResults(forPartition, totalPartitions); }) .doOnError((Throwable throwable) -> { logger.warn("Error getting sink Observable: " + throwable.getMessage()); if (!(throwable instanceof NoSuchJobException)) retryObject.setErrorRef(throwable); // don't retry if not NoSuchJobException }) .retryWhen(retryObject.getRetryLogic()) ; } @Deprecated public synchronized Observable<MantisServerSentEvent> connectAndGetObservable() throws IllegalStateException { return connectAndGet().flatMap(o -> o); } public synchronized Observable<Observable<MantisServerSentEvent>> connectAndGet() throws IllegalStateException { if (mode != Mode.Connect) throw new IllegalStateException("Can't call connect to sink"); if (resultsObservable == null) { logger.info("Getting sink for job name " + builder.name); final Boolean exists = builder.mantisClient.namedJobExists(builder.name) .take(1) .toBlocking() .first(); resultsObservable = exists ? sinksToObservable(builder.mantisClient.getSinkClientByJobName( builder.name, new SseSinkConnectionFunction(true, builder.onConnectionReset, builder.sinkParameters), builder.sinkConnectionsStatusObserver, builder.dataRecvTimeoutSecs) ) .share() //.lift(new DropOperator<Observable<MantisServerSentEvent>>("client_connect_sse_share")) : Observable.just(Observable.just(new MantisServerSentEvent("No such job name " + builder.name))); } return resultsObservable; } @Deprecated public synchronized Observable<MantisServerSentEvent> submitAndGetObservable() throws IllegalStateException { return submitAndGet().flatMap(o -> o); } public synchronized Observable<Observable<MantisServerSentEvent>> submitAndGet() throws IllegalStateException { if (mode != Mode.Submit) throw new IllegalStateException("Can't submit job"); if (resultsObservable != null) return resultsObservable; return Observable .create(new Observable.OnSubscribe<Observable<MantisServerSentEvent>>() { @Override public void call(Subscriber<? super Observable<MantisServerSentEvent>> subscriber) { try { JobSla jobSla = builder.jobSla == null ? new JobSla(0L, 0L, JobSla.StreamSLAType.Lossy, builder.ephemeral ? MantisJobDurationType.Transient : MantisJobDurationType.Perpetual, "") : new JobSla(builder.jobSla.getRuntimeLimitSecs(), builder.jobSla.getMinRuntimeSecs(), builder.jobSla.getSlaType(), builder.ephemeral ? MantisJobDurationType.Transient : MantisJobDurationType.Perpetual, builder.jobSla.getUserProvidedType()); jobId = builder.mantisClient.submitJob(builder.name, builder.jarVersion, builder.parameters, jobSla, builder.schedulingInfo); logger.info("Submitted job name " + builder.name + " and got jobId: " + jobId); resultsObservable = builder.mantisClient .getSinkClientByJobId(jobId, new SseSinkConnectionFunction(true, builder.onConnectionReset), builder.sinkConnectionsStatusObserver, builder.dataRecvTimeoutSecs) .getResults(); resultsObservable.subscribe(subscriber); } catch (Exception e) { subscriber.onError(e); } } }) .doOnError((Throwable throwable) -> { logger.warn(throwable.getMessage()); }) .lift(new DropOperator<>("client_submit_sse_share")) .share() .observeOn(Schedulers.io()) ; } enum Mode {Submit, Connect} public static class Builder { private final MantisClient mantisClient; private final List<Parameter> parameters = new ArrayList<>(); private String name; private String jarVersion; private SinkParameters sinkParameters = new SinkParameters.Builder().build(); private Action1<Throwable> onConnectionReset; private boolean ephemeral = false; private SchedulingInfo schedulingInfo; private JobSla jobSla; private long connectTimeoutSecs = 0L; private Observer<SinkConnectionsStatus> sinkConnectionsStatusObserver = null; private long dataRecvTimeoutSecs = 5; public Builder(Properties properties) { this(new MantisClient(properties)); } public Builder() { Properties properties = new Properties(); properties.setProperty("mantis.zookeeper.connectionTimeMs", "1000"); properties.setProperty("mantis.zookeeper.connection.retrySleepMs", "500"); properties.setProperty("mantis.zookeeper.connection.retryCount", "500"); properties.setProperty("mantis.zookeeper.connectString", System.getenv("mantis.zookeeper.connectString")); properties.setProperty("mantis.zookeeper.root", System.getenv("mantis.zookeeper.root")); properties.setProperty("mantis.zookeeper.leader.announcement.path", System.getenv("mantis.zookeeper.leader.announcement.path")); mantisClient = new MantisClient(properties); } public Builder(MantisClient mantisClient) { this.mantisClient = mantisClient; } public Builder name(String name) { this.name = name; return this; } public Builder jarVersion(String jarVersion) { this.jarVersion = jarVersion; return this; } public Builder parameters(Parameter... params) { this.parameters.addAll(Arrays.asList(params)); return this; } public Builder sinkParams(SinkParameters queryParams) { this.sinkParameters = queryParams; return this; } public Builder onCloseKillJob() { this.ephemeral = true; return this; } public Builder schedulingInfo(SchedulingInfo schedulingInfo) { this.schedulingInfo = schedulingInfo; return this; } public Builder jobSla(JobSla jobSla) { this.jobSla = jobSla; if (jobSla != null) this.ephemeral = jobSla.getDurationType() == MantisJobDurationType.Transient; return this; } public Builder connectTimeoutSecs(long connectTimeoutSecs) { this.connectTimeoutSecs = connectTimeoutSecs; return this; } public Builder onConnectionReset(Action1<Throwable> onConnectionReset) { this.onConnectionReset = onConnectionReset; return this; } public Builder sinkConnectionsStatusObserver(Observer<SinkConnectionsStatus> sinkConnectionsStatusObserver) { this.sinkConnectionsStatusObserver = sinkConnectionsStatusObserver; return this; } public Builder sinkDataRecvTimeoutSecs(long t) { dataRecvTimeoutSecs = t; return this; } public MantisSSEJob buildJobSubmitter() { return new MantisSSEJob(this, Mode.Submit); } public MantisSSEJob buildJobConnector(int forPartition, int totalPartitions) { if (forPartition >= totalPartitions) throw new IllegalArgumentException("forPartition " + forPartition + " must be less than totalPartitions " + totalPartitions); MantisSSEJob job = new MantisSSEJob(this, Mode.Connect); job.forPartition = forPartition; job.totalPartitions = totalPartitions; return job; } public MantisSSEJob buildJobConnector() { return new MantisSSEJob(this, Mode.Connect); } } }
7,673
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/SinkConnection.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.client; import rx.Observable; import rx.functions.Func0; public interface SinkConnection<T> extends Func0<Observable<T>>, AutoCloseable { String getName(); }
7,674
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/StageWorkersCount.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.client; import com.sampullara.cli.Args; import com.sampullara.cli.Argument; import io.mantisrx.server.core.JobSchedulingInfo; import io.mantisrx.server.core.WorkerAssignments; import io.mantisrx.server.master.client.MantisMasterGateway; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import rx.Observable; import rx.Subscriber; import rx.functions.Action0; import rx.functions.Func1; public class StageWorkersCount { @Argument(alias = "p", description = "Specify a configuration file", required = true) private static String propFile = ""; @Argument(alias = "j", description = "Specify job Id", required = true) private static String jobIdString = ""; private final String jobId; private final MantisClient mantisClient; public StageWorkersCount(String jobId, MantisClient mantisClient) { this.jobId = jobId; this.mantisClient = mantisClient; } public static void main(String[] args) { try { Args.parse(StageWorkersCount.class, args); } catch (IllegalArgumentException e) { Args.usage(StageWorkersCount.class); System.exit(1); } Properties properties = new Properties(); System.out.println("propfile=" + propFile); try (InputStream inputStream = new FileInputStream(propFile)) { properties.load(inputStream); } catch (IOException e) { e.printStackTrace(); } StageWorkersCount workersCount = new StageWorkersCount(jobIdString, new MantisClient(properties)); workersCount.getWorkerCounts(1) .subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { System.out.println("Completed"); System.exit(0); } @Override public void onError(Throwable e) { System.err.println("Unexpected error: " + e.getMessage()); e.printStackTrace(); } @Override public void onNext(Integer integer) { System.out.println("#Workers changed to " + integer); } }); try {Thread.sleep(10000000);} catch (InterruptedException ie) {} } Observable<Integer> getWorkerCounts(final int stageNumber) { final AtomicInteger workerCount = new AtomicInteger(0); final AtomicBoolean gotCompletion = new AtomicBoolean(false); return mantisClient .getClientWrapper() .getMasterClientApi() .flatMap(new Func1<MantisMasterGateway, Observable<Integer>>() { @Override public Observable<Integer> call(MantisMasterGateway mantisMasterClientApi) { return mantisMasterClientApi .schedulingChanges(jobId) .map(new Func1<JobSchedulingInfo, Integer>() { @Override public Integer call(JobSchedulingInfo jobSchedulingInfo) { final WorkerAssignments assignments = jobSchedulingInfo.getWorkerAssignments().get(stageNumber); if (assignments == null) return -1; else return assignments.getNumWorkers(); } }) .filter(new Func1<Integer, Boolean>() { @Override public Boolean call(Integer newCount) { if (newCount == workerCount.get()) return false; workerCount.set(newCount); return true; } }) .doOnCompleted(new Action0() { @Override public void call() { gotCompletion.set(true); } }); } }) .takeWhile(new Func1<Integer, Boolean>() { @Override public Boolean call(Integer integer) { return !gotCompletion.get(); } }); } }
7,675
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/examples/SubmitEphemeralJob.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.client.examples; import com.sampullara.cli.Args; import com.sampullara.cli.Argument; import io.mantisrx.client.MantisSSEJob; import io.mantisrx.common.MantisServerSentEvent; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscription; import rx.functions.Action0; import rx.functions.Action1; // Example to show how a short ephemeral job can be submitted and auto killed when done. public class SubmitEphemeralJob { private static final Logger logger = LoggerFactory.getLogger(SubmitEphemeralJob.class); @Argument(alias = "p", description = "Specify a configuration file", required = true) private static String propFile = ""; @Argument(alias = "n", description = "Job name for submission", required = false) private static String jobName; public static void main(String[] args) { try { Args.parse(SubmitEphemeralJob.class, args); } catch (IllegalArgumentException e) { Args.usage(SubmitEphemeralJob.class); System.exit(1); } Properties properties = new Properties(); try (InputStream inputStream = new FileInputStream(propFile)) { properties.load(inputStream); } catch (IOException e) { e.printStackTrace(); } final CountDownLatch latch = new CountDownLatch(1); // AutoCloseable job will terminate job if onCloseKillJob() called when building it Subscription subscription1 = null; // Subscription s2=null; MantisSSEJob job1 = new MantisSSEJob.Builder(properties) .name(jobName) // .parameters(new Parameter("param1", "val1"), new Parameter("param2", "val2")) // .jarVersion("1.2") .onCloseKillJob() .onConnectionReset(new Action1<Throwable>() { @Override public void call(Throwable throwable) { System.err.println("Reconnecting due to error: " + throwable.getMessage()); } }) .buildJobSubmitter(); // MantisSSEJob job2 = new MantisSSEJob.Builder(properties) // .name(jobName) //// .parameters(new Parameter("param1", "val1"), new Parameter("param2", "val2")) //// .jarVersion("1.2") // .onCloseKillJob() // .onConnectionReset(new Action1<Throwable>() { // @Override // public void call(Throwable throwable) { // System.err.println("Reconnecting due to error: " + throwable.getMessage()); // } // }) // .buildJobSubmitter(); try { Observable<Observable<MantisServerSentEvent>> observable = job1.submitAndGet(); subscription1 = observable .doOnNext(new Action1<Observable<MantisServerSentEvent>>() { @Override public void call(Observable<MantisServerSentEvent> o) { o.doOnNext(new Action1<MantisServerSentEvent>() { @Override public void call(MantisServerSentEvent data) { logger.info("Got event: " + data); latch.countDown(); } }).subscribe(); } }) .doOnCompleted(new Action0() { @Override public void call() { System.out.println("Observable completed!!!"); } }) .subscribe(); if (latch.await(50, TimeUnit.SECONDS)) System.out.println("SUCCESS"); else System.out.println("FAILURE"); // final Observable<Observable<MantisServerSentEvent>> o2 = job2.submitAndGet(); // s2 = o2 // .doOnNext(new Action1<Observable<MantisServerSentEvent>>() { // @Override // public void call(Observable<MantisServerSentEvent> o) { // o.doOnNext(new Action1<MantisServerSentEvent>() { // @Override // public void call(MantisServerSentEvent event) { // logger.info(" Got event: " + event); // } // }).subscribe(); // } // }) // .doOnCompleted(new Action0() { // @Override // public void call() { // System.out.println("Observable completed!!!"); // } // }) // .subscribe(); if (latch.await(50, TimeUnit.SECONDS)) System.out.println("SUCCESS"); else System.out.println("FAILURE"); Thread.sleep(30000000); subscription1.unsubscribe(); // unsubscribe to close connection to sink // s2.unsubscribe(); job1.close(); // job2.close(); } catch (Exception e) { e.printStackTrace(); } System.exit(0); } }
7,676
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/examples/GetJobsList.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.client.examples; import com.sampullara.cli.Args; import com.sampullara.cli.Argument; import io.mantisrx.client.MantisClient; import io.mantisrx.runtime.MantisJobState; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class GetJobsList { @Argument(alias = "p", description = "Specify a configuration file", required = true) private static String propFile = ""; @Argument(alias = "n", description = "Job name for getting list", required = true) private static String jobName; public static void main(String[] args) { try { Args.parse(GetJobsList.class, args); } catch (IllegalArgumentException e) { Args.usage(GetJobsList.class); System.exit(1); } System.out.println("propfile=" + propFile); Properties properties = new Properties(); try (InputStream inputStream = new FileInputStream(propFile)) { properties.load(inputStream); } catch (IOException e) { e.printStackTrace(); } final MantisClient mantisClient = new MantisClient(properties); String json = mantisClient .getJobsOfNamedJob(jobName, MantisJobState.MetaState.Active) .toBlocking() .first(); System.out.println("json: " + json); } }
7,677
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/examples/SubmitWithRuntimeLimit.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.client.examples; import com.sampullara.cli.Args; import com.sampullara.cli.Argument; import io.mantisrx.client.MantisSSEJob; import io.mantisrx.common.MantisServerSentEvent; import io.mantisrx.runtime.JobSla; import io.mantisrx.runtime.MantisJobDurationType; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscription; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func1; public class SubmitWithRuntimeLimit { private static final Logger logger = LoggerFactory.getLogger(SubmitWithRuntimeLimit.class); @Argument(alias = "p", description = "Specify a configuration file", required = true) private static String propFile = ""; @Argument(alias = "n", description = "Job name for submission", required = false) private static String jobName; public static void main(String[] args) { try { Args.parse(SubmitWithRuntimeLimit.class, args); } catch (IllegalArgumentException e) { Args.usage(SubmitEphemeralJob.class); System.exit(1); } Properties properties = new Properties(); try (InputStream inputStream = new FileInputStream(propFile)) { properties.load(inputStream); } catch (IOException e) { e.printStackTrace(); } final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean completed = new AtomicBoolean(false); final long runtimeLimitSecs = 30; MantisSSEJob job = new MantisSSEJob.Builder(properties) .name(jobName) .jobSla(new JobSla(runtimeLimitSecs, 0L, JobSla.StreamSLAType.Lossy, MantisJobDurationType.Perpetual, "")) .onConnectionReset(new Action1<Throwable>() { @Override public void call(Throwable throwable) { System.err.println("Reconnecting due to error: " + throwable.getMessage()); } }) .buildJobSubmitter(); final Observable<Observable<MantisServerSentEvent>> observable = job.submitAndGet(); final Subscription subscription = observable .flatMap(new Func1<Observable<MantisServerSentEvent>, Observable<?>>() { @Override public Observable<?> call(Observable<MantisServerSentEvent> eventObservable) { return eventObservable .doOnNext(new Action1<MantisServerSentEvent>() { @Override public void call(MantisServerSentEvent event) { if (completed.get()) System.out.println("FAILURE"); System.out.println("Got: " + event.getEventAsString()); } }); } }) .doOnCompleted(new Action0() { @Override public void call() { latch.countDown(); } }) .subscribe(); try { Thread.sleep((runtimeLimitSecs + 10) * 1000); // add a buffer for job launch time completed.set(true); // set expectation of complete Thread.sleep(20000); // give some time to see if we still get data, which would be a failure } catch (InterruptedException e) { e.printStackTrace(); } subscription.unsubscribe(); System.exit(0); } }
7,678
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/examples/SubmitWithUniqueTag.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.client.examples; import com.sampullara.cli.Args; import com.sampullara.cli.Argument; import io.mantisrx.client.MantisSSEJob; import io.mantisrx.common.MantisServerSentEvent; import io.mantisrx.runtime.JobSla; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscription; import rx.functions.Action1; public class SubmitWithUniqueTag { private static final Logger logger = LoggerFactory.getLogger(SubmitWithUniqueTag.class); @Argument(alias = "p", description = "Specify a configuration file", required = true) private static String propFile = ""; @Argument(alias = "n", description = "Job name for submission", required = false) private static String jobName; public static void main(String[] args) { try { Args.parse(SubmitWithUniqueTag.class, args); } catch (IllegalArgumentException e) { Args.usage(SubmitEphemeralJob.class); System.exit(1); } Properties properties = new Properties(); try (InputStream inputStream = new FileInputStream(propFile)) { properties.load(inputStream); } catch (IOException e) { e.printStackTrace(); } final JobSla jobSla = new JobSla.Builder() .withUniqueJobTagValue("foobar") .build(); MantisSSEJob job = new MantisSSEJob.Builder(properties) .jobSla(jobSla) .name(jobName) .buildJobSubmitter(); final Observable<Observable<MantisServerSentEvent>> o = job.submitAndGet(); final CountDownLatch latch = new CountDownLatch(5); final Subscription subscribe = o .doOnNext(new Action1<Observable<MantisServerSentEvent>>() { @Override public void call(Observable<MantisServerSentEvent> eventObservable) { eventObservable .doOnNext(new Action1<MantisServerSentEvent>() { @Override public void call(MantisServerSentEvent event) { System.out.println("event: " + event.getEventAsString()); latch.countDown(); } }) .subscribe(); } }) .subscribe(); try { if (latch.await(50, TimeUnit.SECONDS)) System.out.println("SUCCESS"); else System.out.println("FAILURE"); subscribe.unsubscribe(); System.exit(0); } catch (InterruptedException e) { e.printStackTrace(); } } }
7,679
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/examples/ConnectToNamedJob.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.client.examples; import com.mantisrx.common.utils.Services; import com.sampullara.cli.Args; import com.sampullara.cli.Argument; import io.mantisrx.client.MantisSSEJob; import io.mantisrx.client.SinkConnectionsStatus; import io.mantisrx.common.MantisServerSentEvent; import io.mantisrx.server.core.Configurations; import io.mantisrx.server.core.CoreConfiguration; import io.mantisrx.server.core.JobSchedulingInfo; import io.mantisrx.server.core.WorkerAssignments; import io.mantisrx.server.core.WorkerHost; import io.mantisrx.server.master.client.HighAvailabilityServices; import io.mantisrx.server.master.client.HighAvailabilityServicesUtil; import io.mantisrx.server.master.client.MantisMasterGateway; import io.mantisrx.server.master.client.MasterClientWrapper; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observer; import rx.Subscription; import rx.functions.Action0; import rx.functions.Action1; public class ConnectToNamedJob { private static final Logger logger = LoggerFactory.getLogger(ConnectToNamedJob.class); private final static AtomicLong prevDroppedCount = new AtomicLong(0L); @Argument(alias = "p", description = "Specify a configuration file", required = true) private static String propFile = ""; @Argument(alias = "n", description = "Job name for submission", required = true) private static String jobName; public static void main2(final String[] args) { List<String> remArgs = Collections.emptyList(); try { remArgs = Args.parse(ConnectToNamedJob.class, args); } catch (IllegalArgumentException e) { Args.usage(SubmitEphemeralJob.class); System.exit(1); } if (remArgs.isEmpty()) { System.err.println("Must provide JobId as argument"); System.exit(1); } final String jobId = remArgs.get(0); Properties properties = new Properties(); System.out.println("propfile=" + propFile); try (InputStream inputStream = new FileInputStream(propFile)) { properties.load(inputStream); } catch (IOException e) { e.printStackTrace(); } HighAvailabilityServices haServices = HighAvailabilityServicesUtil.createHAServices( Configurations.frmProperties(properties, CoreConfiguration.class)); Services.startAndWait(haServices); MasterClientWrapper clientWrapper = new MasterClientWrapper(haServices.getMasterClientApi()); clientWrapper.getMasterClientApi() .doOnNext(new Action1<MantisMasterGateway>() { @Override public void call(MantisMasterGateway clientApi) { logger.info("************** connecting to schedInfo for job " + jobId); clientApi.schedulingChanges(jobId) .doOnNext(new Action1<JobSchedulingInfo>() { @Override public void call(JobSchedulingInfo schedulingInfo) { final WorkerAssignments workerAssignments = schedulingInfo.getWorkerAssignments().get(1); for (Map.Entry<Integer, WorkerHost> entry : workerAssignments.getHosts().entrySet()) { System.out.println("Worker " + entry.getKey() + ": state=" + entry.getValue().getState() + ", host=" + entry.getValue().getHost() + ", port=" + entry.getValue().getPort()); } } }) .subscribe(); ; } }) .subscribe(); // clientWrapper.getMasterClientApi() // .doOnNext(new Action1<MantisMasterClientApi>() { // @Override // public void call(MantisMasterClientApi clientApi) { // logger.info("************* connecting to namedJob info for " + jobId); // clientApi.namedJobInfo(jobId) // .doOnNext(new Action1<NamedJobInfo>() { // @Override // public void call(NamedJobInfo namedJobInfo) { // System.out.println(namedJobInfo.getJobId()); // } // }) // .subscribe(); // } // }) // .subscribe(); try {Thread.sleep(10000000);} catch (InterruptedException ie) {} } public static void main(String[] args) { //SinkParameters params = new SinkParameters.Builder().withParameter("filter", "windows8").build(); final AtomicLong eventCounter = new AtomicLong(0L); System.setProperty("log4j.logger.io", "DEBUG"); try { Args.parse(ConnectToNamedJob.class, args); } catch (IllegalArgumentException e) { Args.usage(SubmitEphemeralJob.class); System.exit(1); } Properties properties = new Properties(); System.out.println("propfile=" + propFile); try (InputStream inputStream = new FileInputStream(propFile)) { properties.load(inputStream); } catch (IOException e) { e.printStackTrace(); } final CountDownLatch latch = new CountDownLatch(1); MantisSSEJob job = null; try { job = new MantisSSEJob.Builder(properties) .name(jobName) .onConnectionReset(new Action1<Throwable>() { @Override public void call(Throwable throwable) { System.err.println("Reconnecting due to error: " + throwable.getMessage()); } }) .sinkConnectionsStatusObserver(new Observer<SinkConnectionsStatus>() { @Override public void onCompleted() { System.out.println("ConnectionStatusObserver completed"); } @Override public void onError(Throwable e) { System.err.println("ConnectionStatusObserver error: " + e.getMessage()); } @Override public void onNext(SinkConnectionsStatus status) { System.out.println("ConnectionStatusObserver: receiving from " + status.getRecevingDataFrom() + ", connected to " + status.getNumConnected() + " of " + status.getTotal()); } }) .sinkDataRecvTimeoutSecs(11) // .sinkParams(params) //.sinkParams(new SinkParameters.Builder().withParameter("subscriptionId", "abc").withParameter("filter", "true").build()) // for zuul source job .buildJobConnector(); } catch (Exception e) { e.printStackTrace(); } //try{Thread.sleep(3000);}catch(InterruptedException ie){} System.out.println("Subscribing now"); Subscription subscription = job.connectAndGet() .doOnNext(new Action1<Observable<MantisServerSentEvent>>() { @Override public void call(Observable<MantisServerSentEvent> o) { o .doOnNext(new Action1<MantisServerSentEvent>() { @Override public void call(MantisServerSentEvent data) { logger.info("Got event: + " + data); latch.countDown(); // if(eventCounter.incrementAndGet()>4) // throw new RuntimeException("Test exception"); } }) .subscribe(); } }) .doOnError(new Action1<Throwable>() { @Override public void call(Throwable throwable) { logger.error(throwable.getMessage()); } }) .doOnCompleted(new Action0() { @Override public void call() { System.out.println("Completed"); System.exit(0); } }) .subscribe(); // Subscription s2 = job.connectAndGetObservable() // .doOnNext(new Action1<ServerSentEvent>() { // @Override // public void call(ServerSentEvent event) { // logger.info(" 2nd: Got event: type=" + event.getEventType() + " data: " + event.getEventData()); // latch.countDown(); // } // }) // .doOnError(new Action1<Throwable>() { // @Override // public void call(Throwable throwable) { // logger.error(throwable.getMessage()); // } // }) // .subscribe(); try { boolean await = latch.await(30, TimeUnit.SECONDS); if (await) System.out.println("PASSED"); else System.err.println("FAILED!"); Thread.sleep(5000000); } catch (InterruptedException e) { e.printStackTrace(); } subscription.unsubscribe(); System.out.println("Unsubscribed"); try {Thread.sleep(80000);} catch (InterruptedException ie) {} System.exit(0); } }
7,680
0
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client
Create_ds/mantis/mantis-client/src/main/java/io/mantisrx/client/examples/SampleClient.java
/* * Copyright 2021 Netflix, 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 io.mantisrx.client.examples; // //import java.io.File; //import java.io.FileInputStream; //import java.io.IOException; //import java.io.InputStream; //import java.util.Properties; //import java.util.concurrent.CountDownLatch; //import java.util.concurrent.atomic.AtomicReference; // //import com.fasterxml.jackson.databind.DeserializationFeature; //import com.fasterxml.jackson.databind.ObjectMapper; //import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; //import com.sampullara.cli.Args; //import com.sampullara.cli.Argument; //import io.mantisrx.client.MantisClient; //import io.mantisrx.client.SinkClient; //import io.mantisrx.client.SseSinkConnectionFunction; //import io.mantisrx.common.MantisServerSentEvent; ////import io.mantisrx.master.api.proto.CreateJobClusterRequest; ////import io.mantisrx.master.api.proto.UpdateJobClusterRequest; ////import io.mantisrx.master.core.proto.JobDefinition; ////import io.mantisrx.master.core.proto.JobOwner; //import io.mantisrx.runtime.JobOwner; //import io.mantisrx.runtime.JobSla; //import io.mantisrx.runtime.MantisJobDurationType; //import io.mantisrx.runtime.descriptor.SchedulingInfo; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; //import rx.Observable; //import rx.Subscription; //import rx.functions.Action0; //import rx.functions.Action1; // // //// Simple throw-away implementation to show one way to use MantisClient //public class SampleClient { // // private static final Logger logger = LoggerFactory.getLogger(SampleClient.class); // private static final ObjectMapper objectMapper = new ObjectMapper(); // @Argument(alias = "p", description = "Specify a configuration file", required = true) // private static String propFile = ""; // @Argument(alias = "j", description = "Specify a job Id", required = false) // private static String jobId; // @Argument(alias = "c", description = "Command to run create/submit/sink", required = true) // private static String cmd; // @Argument(alias = "n", description = "Job name for submission", required = false) // private static String jobName; // @Argument(alias = "u", description = "Job JAR URL for submission", required = false) // private static String jobUrl; // @Argument(alias = "s", description = "Filename containing scheduling information", required = false) // private static String schedulingInfoFile; // @Argument(alias = "d", description = "Job duration type", required = false) // private static String durationTypeString; // private static MantisJobDurationType durationType = MantisJobDurationType.Perpetual; // private static SchedulingInfo schedulingInfo; // // public static void main(String[] args) { // objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // objectMapper.registerModule(new Jdk8Module()); // try { // Args.parse(SampleClient.class, args); // } catch (IllegalArgumentException e) { // Args.usage(SampleClient.class); // System.exit(1); // } // System.out.println("propfile=" + propFile); // Properties properties = new Properties(); // try (InputStream inputStream = new FileInputStream(propFile)) { // properties.load(inputStream); // } catch (IOException e) { // e.printStackTrace(); // } // final MantisClient mantisClient = new MantisClient(properties); // if (durationTypeString != null && !durationTypeString.isEmpty()) // durationType = MantisJobDurationType.valueOf(durationTypeString); // try { // switch (cmd) { // case "create": // if (jobName == null || jobName.isEmpty() || jobUrl == null || jobUrl.isEmpty() || // schedulingInfoFile == null || schedulingInfoFile.isEmpty()) { // System.err.println("Must provide job name, url, and scheduling info filename for Job Cluster creation"); // } else { // schedulingInfo = loadSchedulingInfo(schedulingInfoFile); // doCreate(mantisClient); // } // break; // case "update": // if (jobName == null || jobName.isEmpty() || jobUrl == null || jobUrl.isEmpty() || // schedulingInfoFile == null || schedulingInfoFile.isEmpty()) { // System.err.println("Must provide job name, url, and scheduling info filename for Job Cluster update"); // } else { // schedulingInfo = loadSchedulingInfo(schedulingInfoFile); // doUpdate(mantisClient); // } // break; // case "submit": // if (jobName == null || jobName.isEmpty()) { // System.err.println("Must provide job name for submit"); // } else { // if (schedulingInfoFile != null && !schedulingInfoFile.isEmpty()) // schedulingInfo = loadSchedulingInfo(schedulingInfoFile); // jobId = doSubmit(mantisClient); // //System.out.println("Calling sink connect on the job " + jobId); // //doGetSinkData(mantisClient, jobId); // } // break; // case "sink": // if (jobId == null || jobId.isEmpty()) { // System.err.println("Must provide jobId to connect to its sink"); // } else { // // Thread t1 = new Thread() { // // @Override // // public void run() { // // doGetSinkData(mantisClient, "ea261597-daf7-4635-b07c-0d0d6f73ca3d"); // // } // // }; // Thread t2 = new Thread() { // @Override // public void run() { // doGetSinkData(mantisClient, jobId); // } // }; // //t1.start(); // t2.start(); // } // break; // default: // logger.error("Unknown command " + cmd); // break; // } // } catch (Throwable t) { // t.printStackTrace(); // } // } // // private static SchedulingInfo loadSchedulingInfo(String schedulingInfoFile) throws IOException { // File file = new File(schedulingInfoFile); // if (file.canRead()) { // return objectMapper.readValue(file, SchedulingInfo.class); // } else // throw new IOException("Can't read scheduling info file " + schedulingInfoFile); // } // // private static void doCreate(MantisClient mantisClient) throws Throwable { // JobDefinition jobDefinition = JobDefinition.newBuilder() // .setName(jobName) // .setVersion("0.0.1") // .setJobSla(io.mantisrx.master.core.proto.JobSla.newBuilder() // .setUserProvidedType("") // .setDurationTypeValue(durationType.ordinal()) // .setSlaType(io.mantisrx.master.core.proto.JobSla.StreamSLAType.Lossy) // .setMinRuntimeSecs(0) // .setRuntimeLimitSecs(0)) // .setSchedulingInfo(io.mantisrx.master.core.proto.SchedulingInfo.parseFrom(objectMapper.writeValueAsBytes(schedulingInfo))) // .build(); // JobOwner owner = JobOwner.newBuilder() // .setName("Test") // .setContactEmail("test@netflix.com") // .setDescription("") // .setRepo("http://www.example.com") // .build(); // CreateJobClusterRequest req = CreateJobClusterRequest.newBuilder() // .setJobDefinition(jobDefinition) // .setOwner(owner) // .build(); // mantisClient.createNamedJob(req); // System.out.println(jobName + " created"); // } // // private static void doUpdate(MantisClient mantisClient) throws Throwable { // JobDefinition jobDefinition = JobDefinition.newBuilder() // .setName(jobName) // .setVersion("0.0.1") // .setJobSla(io.mantisrx.master.core.proto.JobSla.newBuilder() // .setUserProvidedType("") // .setDurationTypeValue(durationType.ordinal()) // .setSlaType(io.mantisrx.master.core.proto.JobSla.StreamSLAType.Lossy) // .setMinRuntimeSecs(0) // .setRuntimeLimitSecs(0)) // .setSchedulingInfo(io.mantisrx.master.core.proto.SchedulingInfo.parseFrom(objectMapper.writeValueAsBytes(schedulingInfo))) // .build(); // JobOwner owner = JobOwner.newBuilder() // .setName("Test") // .setContactEmail("test@netflix.com") // .setDescription("") // .setRepo("http://www.example.com") // .build(); // UpdateJobClusterRequest req = UpdateJobClusterRequest.newBuilder() // .setJobDefinition(jobDefinition) // .setOwner(owner) // .build(); // mantisClient.updateNamedJob(req); // System.out.println(jobName + " updated"); // } // // private static String doSubmit(MantisClient mantisClient) throws Throwable { // String id = mantisClient.submitJob(jobName, null, null, new JobSla(0L, 0L, JobSla.StreamSLAType.Lossy, durationType, ""), schedulingInfo); // System.out.println("Job ID: " + id); // return id; // } // // private static void doGetSinkData(MantisClient mantisClient, final String localJobId) { // final CountDownLatch startLatch = new CountDownLatch(1); // final CountDownLatch finishLatch = new CountDownLatch(1); // final SinkClient sinkClient = mantisClient.getSinkClientByJobId(localJobId, // new SseSinkConnectionFunction(true, new Action1<Throwable>() { // @Override // public void call(Throwable throwable) { // System.err.println("Sink connection error: " + throwable.getMessage()); // try {Thread.sleep(500);} catch (InterruptedException ie) { // System.err.println("Interrupted waiting for retrying connection"); // } // } // }), null); // System.out.println("GETTING results observable for job " + localJobId); // Observable<MantisServerSentEvent> resultsObservable = Observable.merge(sinkClient // .getResults()); // System.out.println("SUBSCRIBING to it"); // final AtomicReference<Subscription> ref = new AtomicReference<>(null); // final Thread t = new Thread() { // @Override // public void run() { // try { // startLatch.await(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // try {sleep(300000);} catch (InterruptedException ie) {} // System.out.println("Closing client conx"); // try { // ref.get().unsubscribe(); // finishLatch.countDown(); // } catch (Exception e) { // e.printStackTrace(); // } // } // }; // t.setDaemon(true); // final Subscription s = resultsObservable // .doOnCompleted(new Action0() { // @Override // public void call() { // finishLatch.countDown(); // } // }) // .subscribe(new Action1<MantisServerSentEvent>() { // @Override // public void call(MantisServerSentEvent event) { // if (startLatch.getCount() > 0) { // startLatch.countDown(); // } // System.out.println(localJobId.substring(0, 5) + ": Got SSE (event=" + event.getEventAsString() + "): "); // } // }); // ref.set(s); // t.start(); // System.out.println("SUBSCRIBED to job sink changes"); // try { // finishLatch.await(); // System.err.println("Sink observable completed"); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // //}
7,681
0
Create_ds/mantis/mantis-common-serde/src/main/java/io/mantisrx
Create_ds/mantis/mantis-common-serde/src/main/java/io/mantisrx/common/JsonSerializer.java
/* * Copyright 2022 Netflix, 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 io.mantisrx.common; import io.mantisrx.shaded.com.fasterxml.jackson.core.type.TypeReference; import io.mantisrx.shaded.com.fasterxml.jackson.databind.DeserializationFeature; import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper; import io.mantisrx.shaded.com.fasterxml.jackson.databind.SerializationFeature; import io.mantisrx.shaded.com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; import io.mantisrx.shaded.com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import java.io.IOException; import java.util.Map; public class JsonSerializer { private static final ObjectMapper defaultObjectMapper = new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) .registerModule(new Jdk8Module()); public static final SimpleFilterProvider DEFAULT_FILTER_PROVIDER; static { DEFAULT_FILTER_PROVIDER = new SimpleFilterProvider(); DEFAULT_FILTER_PROVIDER.setFailOnUnknownId(false); } public <T> T fromJSON(String json, Class<T> expectedType) throws IOException { return defaultObjectMapper.readerFor(expectedType).readValue(json); } public <T> T fromJson(byte[] json, Class<T> expectedType) throws IOException { return defaultObjectMapper.readValue(json, expectedType); } public <T> T fromJSON(String json, TypeReference<T> expectedType) throws IOException { return defaultObjectMapper.readerFor(expectedType).readValue(json); } public String toJson(Object object) throws IOException { return defaultObjectMapper.writeValueAsString(object); } public byte[] toJsonBytes(Object object) throws IOException { return defaultObjectMapper.writeValueAsBytes(object); } public Map<String, Object> toMap(String json) throws IOException { return defaultObjectMapper.readValue(json, new TypeReference<Map<String, Object>>() { }); } }
7,682
0
Create_ds/mantis/mantis-examples/mantis-examples-sine-function/src/main/java/io/mantisrx/mantis/examples
Create_ds/mantis/mantis-examples/mantis-examples-sine-function/src/main/java/io/mantisrx/mantis/examples/sinefunction/SineFunctionDslJob.java
/* * Copyright 2022 Netflix, 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 io.mantisrx.mantis.examples.sinefunction; import static io.mantisrx.mantis.examples.sinefunction.SineFunctionJob.INTERVAL_SEC; import static io.mantisrx.mantis.examples.sinefunction.SineFunctionJob.RANDOM_RATE; import static io.mantisrx.mantis.examples.sinefunction.SineFunctionJob.RANGE_MAX; import static io.mantisrx.mantis.examples.sinefunction.SineFunctionJob.RANGE_MIN; import static io.mantisrx.mantis.examples.sinefunction.SineFunctionJob.USE_RANDOM_FLAG; import io.mantisrx.mantis.examples.sinefunction.core.Point; import io.mantisrx.runtime.Config; import io.mantisrx.runtime.Job; import io.mantisrx.runtime.core.MantisStream; import io.mantisrx.runtime.core.WindowSpec; import io.mantisrx.runtime.core.functions.SimpleReduceFunction; import io.mantisrx.runtime.core.sinks.ObservableSinkImpl; import io.mantisrx.runtime.core.sources.ObservableSourceImpl; import io.mantisrx.runtime.executor.LocalJobExecutorNetworked; import io.mantisrx.runtime.parameter.type.BooleanParameter; import io.mantisrx.runtime.parameter.type.DoubleParameter; import io.mantisrx.runtime.parameter.type.IntParameter; import io.mantisrx.runtime.parameter.validator.Validators; import lombok.extern.slf4j.Slf4j; @Slf4j public class SineFunctionDslJob { public static void main(String[] args) { final double amplitude = 5.0; final double frequency = 1; final double phase = 0.0; Config<Point> jobConfig = MantisStream.create(null) .source(new ObservableSourceImpl<>(new SineFunctionJob.TimerSource())) .filter(x -> x % 2 == 0) .map(x -> new Point(x, amplitude * Math.sin((frequency * x) + phase))) .keyBy(x -> x.getX() % 10) .window(WindowSpec.count(2)) .reduce((SimpleReduceFunction<Point>) (acc, i) -> new Point(acc.getX() + i.getX(), i.getY())) .sink(new ObservableSinkImpl<>(SineFunctionJob.sseSink)); Job<Point> pointJob = jobConfig.parameterDefinition( new BooleanParameter() .name(USE_RANDOM_FLAG) .defaultValue(false) .description("If true, produce a random sequence of integers. If false," + " produce a sequence of integers starting at 0 and increasing by 1.") .build() ).parameterDefinition(new DoubleParameter() .name(RANDOM_RATE) .defaultValue(1.0) .description("The chance a random integer is generated, for the given period") .validator(Validators.range(0, 1)) .build() ).parameterDefinition(new IntParameter() .name(INTERVAL_SEC) .defaultValue(1) .description("Period at which to generate a random integer value to send to sine function") .validator(Validators.range(1, 60)) .build() ).parameterDefinition(new IntParameter() .name(RANGE_MIN) .defaultValue(0) .description("Minimun of random integer value") .validator(Validators.range(0, 100)) .build() ).parameterDefinition(new IntParameter() .name(RANGE_MAX) .defaultValue(100) .description("Maximum of random integer value") .validator(Validators.range(1, 100)) .build() ).create(); LocalJobExecutorNetworked.execute(pointJob); } }
7,683
0
Create_ds/mantis/mantis-examples/mantis-examples-sine-function/src/main/java/io/mantisrx/mantis/examples
Create_ds/mantis/mantis-examples/mantis-examples-sine-function/src/main/java/io/mantisrx/mantis/examples/sinefunction/SineFunctionJob.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.mantis.examples.sinefunction; import io.mantisrx.mantis.examples.sinefunction.core.Point; import io.mantisrx.mantis.examples.sinefunction.stages.SinePointGeneratorStage; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.Job; import io.mantisrx.runtime.MantisJob; import io.mantisrx.runtime.MantisJobProvider; import io.mantisrx.runtime.Metadata; import io.mantisrx.runtime.ScalarToScalar; import io.mantisrx.runtime.codec.JacksonCodecs; import io.mantisrx.runtime.executor.LocalJobExecutorNetworked; import io.mantisrx.runtime.parameter.Parameter; import io.mantisrx.runtime.parameter.type.BooleanParameter; import io.mantisrx.runtime.parameter.type.DoubleParameter; import io.mantisrx.runtime.parameter.type.IntParameter; import io.mantisrx.runtime.parameter.validator.Validators; import io.mantisrx.runtime.sink.SelfDocumentingSink; import io.mantisrx.runtime.sink.ServerSentEventsSink; import io.mantisrx.runtime.sink.predicate.Predicate; import io.mantisrx.runtime.source.Index; import io.mantisrx.runtime.source.Source; import java.io.IOException; import java.util.Random; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.Subscription; import rx.functions.Func1; import rx.schedulers.Schedulers; public class SineFunctionJob extends MantisJobProvider<Point> { public static final String INTERVAL_SEC = "intervalSec"; public static final String RANGE_MAX = "max"; public static final String RANGE_MIN = "min"; public static final String AMPLITUDE = "amplitude"; public static final String FREQUENCY = "frequency"; public static final String PHASE = "phase"; public static final String RANDOM_RATE = "randomRate"; public static final String USE_RANDOM_FLAG = "useRandom"; /** * The SSE sink sets up an SSE server that can be connected to using SSE clients(curl etc.) to see * a real-time stream of (x, y) tuples on a sine curve. */ public static final SelfDocumentingSink<Point> sseSink = new ServerSentEventsSink.Builder<Point>() .withEncoder(point -> String.format("{\"x\": %f, \"y\": %f}", point.getX(), point.getY())) .withPredicate(new Predicate<>( "filter=even, returns even x parameters; filter=odd, returns odd x parameters.", parameters -> { Func1<Point, Boolean> filter = point -> { return true; }; if (parameters != null && parameters.containsKey("filter")) { String filterBy = parameters.get("filter").get(0); // create filter function based on parameter value filter = point -> { // filter by evens or odds for x values if ("even".equalsIgnoreCase(filterBy)) { return (point.getX() % 2 == 0); } else if ("odd".equalsIgnoreCase(filterBy)) { return (point.getX() % 2 != 0); } return true; // if not even/odd }; } return filter; } )) .build(); /** * The Stage com.netflix.mantis.examples.config defines how the output of the stage is serialized onto the next stage or sink. */ static ScalarToScalar.Config<Integer, Point> stageConfig() { return new ScalarToScalar.Config<Integer, Point>() .codec(JacksonCodecs.pojo(Point.class)); } /** * Run this in the IDE and look for * {@code AbstractServer:95 main - Rx server started at port: <PORT_NUMBER>} in the console output. * Connect to the port using {@code curl localhost:<PORT_NUMBER>} * to see a stream of (x, y) coordinates on a sine curve. */ public static void main(String[] args) { LocalJobExecutorNetworked.execute(new SineFunctionJob().getJobInstance(), new Parameter("useRandom", "false")); } @Override public Job<Point> getJobInstance() { return MantisJob // Define the data source for this job. .source(new TimerSource()) // Add stages to transform the event stream received from the Source. .stage(new SinePointGeneratorStage(), stageConfig()) // Define a sink to output the transformed stream over SSE or an external system like Cassandra, etc. .sink(sseSink) // Add Job parameters that can be passed in by the user when submitting a job. .parameterDefinition(new BooleanParameter() .name(USE_RANDOM_FLAG) .required() .description("If true, produce a random sequence of integers. If false," + " produce a sequence of integers starting at 0 and increasing by 1.") .build()) .parameterDefinition(new DoubleParameter() .name(RANDOM_RATE) .defaultValue(1.0) .description("The chance a random integer is generated, for the given period") .validator(Validators.range(0, 1)) .build()) .parameterDefinition(new IntParameter() .name(INTERVAL_SEC) .defaultValue(1) .description("Period at which to generate a random integer value to send to sine function") .validator(Validators.range(1, 60)) .build()) .parameterDefinition(new IntParameter() .name(RANGE_MIN) .defaultValue(0) .description("Minimun of random integer value") .validator(Validators.range(0, 100)) .build()) .parameterDefinition(new IntParameter() .name(RANGE_MAX) .defaultValue(100) .description("Maximum of random integer value") .validator(Validators.range(1, 100)) .build()) .parameterDefinition(new DoubleParameter() .name(AMPLITUDE) .defaultValue(10.0) .description("Amplitude for sine function") .validator(Validators.range(1, 100)) .build()) .parameterDefinition(new DoubleParameter() .name(FREQUENCY) .defaultValue(1.0) .description("Frequency for sine function") .validator(Validators.range(1, 100)) .build()) .parameterDefinition(new DoubleParameter() .name(PHASE) .defaultValue(0.0) .description("Phase for sine function") .validator(Validators.range(0, 100)) .build()) .metadata(new Metadata.Builder() .name("Sine function") .description("Produces an infinite stream of points, along the sine function, using the" + " following function definition: f(x) = amplitude * sin(frequency * x + phase)." + " The input to the function is either random between [min, max], or an integer sequence starting " + " at 0. The output is served via HTTP server using SSE protocol.") .build()) .create(); } /** * This source generates a monotonically increasingly value per tick as per INTERVAL_SEC Job parameter. * If USE_RANDOM_FLAG is set, the source generates a random value per tick. */ static class TimerSource implements Source<Integer> { @Override public Observable<Observable<Integer>> call(Context context, Index index) { // If you want to be informed of scaleup/scale down of the source stage of this job you can subscribe // to getTotalNumWorkersObservable like the following. Subscription subscription = index.getTotalNumWorkersObservable().subscribeOn(Schedulers.io()).subscribe((workerCount) -> { System.out.println("Total worker count changed to -> " + workerCount); }); final int period = (int) context.getParameters().get(INTERVAL_SEC); final int max = (int) context.getParameters().get(RANGE_MAX); final int min = (int) context.getParameters().get(RANGE_MIN); final double randomRate = (double) context.getParameters().get(RANDOM_RATE); final boolean useRandom = (boolean) context.getParameters().get(USE_RANDOM_FLAG); final Random randomNumGenerator = new Random(); final Random randomRateVariable = new Random(); return Observable.just( Observable.interval(0, period, TimeUnit.SECONDS) .map(time -> { System.out.println("total worker num: " + index.getTotalNumWorkers()); if (useRandom) { return randomNumGenerator.nextInt((max - min) + 1) + min; } else { return (int) (long) time; } }) .filter(x -> { double value = randomRateVariable.nextDouble(); return (value <= randomRate); }) .doOnUnsubscribe(subscription::unsubscribe) ); } @Override public void close() throws IOException { } } }
7,684
0
Create_ds/mantis/mantis-examples/mantis-examples-sine-function/src/main/java/io/mantisrx/mantis/examples/sinefunction
Create_ds/mantis/mantis-examples/mantis-examples-sine-function/src/main/java/io/mantisrx/mantis/examples/sinefunction/core/Point.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.mantis.examples.sinefunction.core; import io.mantisrx.runtime.codec.JsonType; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; public class Point implements JsonType, Serializable { private double x; private double y; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public Point(@JsonProperty("x") double x, @JsonProperty("y") double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } }
7,685
0
Create_ds/mantis/mantis-examples/mantis-examples-sine-function/src/main/java/io/mantisrx/mantis/examples/sinefunction
Create_ds/mantis/mantis-examples/mantis-examples-sine-function/src/main/java/io/mantisrx/mantis/examples/sinefunction/stages/SinePointGeneratorStage.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.mantis.examples.sinefunction.stages; import io.mantisrx.mantis.examples.sinefunction.SineFunctionJob; import io.mantisrx.mantis.examples.sinefunction.core.Point; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.computation.ScalarComputation; import rx.Observable; /** * This class implements the ScalarComputation type of Mantis Stage and * transforms the value received from the Source into a Point on a sine-function curve * based on AMPLITUDE, FREQUENCY and PHASE job parameters. */ public class SinePointGeneratorStage implements ScalarComputation<Integer, Point> { @Override public Observable<Point> call(Context context, Observable<Integer> o) { final double amplitude = (double) context.getParameters().get(SineFunctionJob.AMPLITUDE); final double frequency = (double) context.getParameters().get(SineFunctionJob.FREQUENCY); final double phase = (double) context.getParameters().get(SineFunctionJob.PHASE); return o .filter(x -> x % 2 == 0) .map(x -> new Point(x, amplitude * Math.sin((frequency * x) + phase))); } }
7,686
0
Create_ds/mantis/mantis-examples/mantis-examples-mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web
Create_ds/mantis/mantis-examples/mantis-examples-mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web/servlet/HelloServlet.java
/* * Copyright 2019 Netflix, 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.netflix.mantis.examples.mantispublishsample.web.servlet; import com.netflix.mantis.examples.mantispublishsample.web.service.MyService; import java.io.IOException; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * A simple servlet that looks for the existence of a name parameter in the request and responds * with a Hello message. */ @Singleton public class HelloServlet extends HttpServlet { @Inject MyService myService; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); if (name == null) name = "Universe"; String result = myService.hello(name); response.getWriter().print(result); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); if (name == null) name = "World"; request.setAttribute("user", name); request.getRequestDispatcher("response.jsp").forward(request, response); } }
7,687
0
Create_ds/mantis/mantis-examples/mantis-examples-mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web
Create_ds/mantis/mantis-examples/mantis-examples-mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web/config/DefaultGuiceServletConfig.java
/* * Copyright 2019 Netflix, 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.netflix.mantis.examples.mantispublishsample.web.config; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.servlet.GuiceServletContextListener; import com.google.inject.servlet.ServletModule; import com.netflix.archaius.guice.ArchaiusModule; import com.netflix.mantis.examples.mantispublishsample.web.filter.CaptureRequestEventFilter; import com.netflix.mantis.examples.mantispublishsample.web.service.MyService; import com.netflix.mantis.examples.mantispublishsample.web.service.MyServiceImpl; import com.netflix.mantis.examples.mantispublishsample.web.servlet.HelloServlet; import com.netflix.spectator.nflx.SpectatorModule; import io.mantisrx.publish.netty.guice.MantisRealtimeEventsPublishModule; /** * Wire up the servlets, filters and other modules. */ public class DefaultGuiceServletConfig extends GuiceServletContextListener { @Override protected Injector getInjector() { return Guice.createInjector( new ArchaiusModule(), new MantisRealtimeEventsPublishModule(), new SpectatorModule(), new ServletModule() { @Override protected void configureServlets() { filter("/*").through(CaptureRequestEventFilter.class); serve("/hello").with(HelloServlet.class); bind(MyService.class).to(MyServiceImpl.class); } } ); } }
7,688
0
Create_ds/mantis/mantis-examples/mantis-examples-mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web
Create_ds/mantis/mantis-examples/mantis-examples-mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web/filter/CaptureRequestEventFilter.java
/* * Copyright 2019 Netflix, 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.netflix.mantis.examples.mantispublishsample.web.filter; import io.mantisrx.publish.api.Event; import io.mantisrx.publish.api.EventPublisher; import io.mantisrx.publish.api.PublishStatus; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import lombok.extern.slf4j.Slf4j; /** * A sample filter that captures Request and Response headers and sends them to * Mantis using the mantis-publish library. */ @Slf4j @Singleton public class CaptureRequestEventFilter implements Filter { private static final String RESPONSE_HEADER_PREFIX = "response.header."; private static final String REQUEST_HEADER_PREFIX = "request.header."; private static final String VALUE_SEPARATOR = ","; @Inject private EventPublisher publisher; @Override public void init(FilterConfig filterConfig) { log.info("Capture Request data filter inited"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) servletRequest; final HttpServletResponse res = (HttpServletResponse)servletResponse; log.debug("In do filter"); final long startMillis = System.currentTimeMillis(); // Add a wrapper around the Response object to capture headers. final ResponseSpy responseSpy = new ResponseSpy(res); // Send request down the filter chain filterChain.doFilter(servletRequest,responseSpy); // request is complete now gather all the request data and send to mantis. processPostFilter(startMillis, req, responseSpy); } /** * Invoked after the request has been completed. Used to gather all the request and response headers * associated with this request and publish to mantis. * @param startMillis The time processing began for this request. * @param req The servlet request object * @param responseSpy The spy servlet response. */ private void processPostFilter(long startMillis, HttpServletRequest req, ResponseSpy responseSpy) { try { Map<String, Object> event = new HashMap<>(); postProcess(req, responseSpy,event); Event rEvent = new Event(event); final long duration = System.currentTimeMillis() - startMillis; rEvent.set("duration", duration); log.info("sending event {} to stream {}", rEvent); CompletionStage<PublishStatus> sendResult = publisher.publish(rEvent); sendResult.whenCompleteAsync((status,throwable) -> { log.info("Filter send event status=> {}", status); }); } catch (Exception e) { log.error("failed to process event", e); } } /** * Captures the request and response headers associated with this request. * @param httpServletRequest * @param responseSpy * @param event */ private void postProcess(HttpServletRequest httpServletRequest, ResponseSpy responseSpy, Map<String,Object> event) { try { int rdm = ThreadLocalRandom.current().nextInt(); if(rdm < 0) { rdm = rdm * (-1); } event.put("request.uuid", rdm); captureRequestData(event, httpServletRequest); captureResponseData(event, responseSpy); } catch (Exception e) { event.put("exception", e.toString()); log.error("Error capturing data in api.RequestEventInfoCollector filter! uri=" + httpServletRequest.getRequestURI(), e); } } /** * Captures response headers. * @param event * @param res */ private void captureResponseData(Map<String, Object> event, ResponseSpy res ) { log.debug("Capturing response data"); // response headers for (String name : res.headers.keySet()) { final StringBuilder valBuilder = new StringBuilder(); boolean firstValue = true; for (String s : res.headers.get(name)) { // only prepends separator for non-first header values if (firstValue) firstValue = false; else { valBuilder.append(VALUE_SEPARATOR); } valBuilder.append(s); } event.put(RESPONSE_HEADER_PREFIX + name, valBuilder.toString()); } // Set Cookies if (!res.cookies.isEmpty()) { Iterator<Cookie> cookies = res.cookies.iterator(); StringBuilder setCookies = new StringBuilder(); while (cookies.hasNext()) { Cookie cookie = cookies.next(); setCookies.append(cookie.getName()).append("=").append(cookie.getValue()); String domain = cookie.getDomain(); if (domain != null) { setCookies.append("; Domain=").append(domain); } int maxAge = cookie.getMaxAge(); if (maxAge >= 0) { setCookies.append("; Max-Age=").append(maxAge); } String path = cookie.getPath(); if (path != null) { setCookies.append("; Path=").append(path); } if (cookie.getSecure()) { setCookies.append("; Secure"); } if (cookie.isHttpOnly()) { setCookies.append("; HttpOnly"); } if (cookies.hasNext()) { setCookies.append(VALUE_SEPARATOR); } } event.put(RESPONSE_HEADER_PREFIX + "set-cookie", setCookies.toString()); } // status of the request int status = res.statusCode; event.put("status", status); } /** * Captures request headers. * @param event * @param req */ private void captureRequestData(Map<String, Object> event, HttpServletRequest req) { // basic request properties String path = req.getRequestURI(); if (path == null) path = "/"; event.put("path", path); event.put("host", req.getHeader("host")); event.put("query", req.getQueryString()); event.put("method", req.getMethod()); event.put("currentTime", System.currentTimeMillis()); // request headers for (final Enumeration<String> names = req.getHeaderNames(); names.hasMoreElements();) { final String name = (String)names.nextElement(); final StringBuilder valBuilder = new StringBuilder(); boolean firstValue = true; for (final Enumeration<String> vals = req.getHeaders(name); vals.hasMoreElements();) { // only prepends separator for non-first header values if (firstValue) firstValue = false; else { valBuilder.append(VALUE_SEPARATOR); } valBuilder.append(vals.nextElement()); } event.put(REQUEST_HEADER_PREFIX + name, valBuilder.toString()); } // request params // HTTP POSTs send a param with a weird encoded name, so we strip them out with this regex if("GET".equals(req.getMethod())) { final Map<String,String[]> params = req.getParameterMap(); for (final Object key : params.keySet()) { final String keyString = key.toString(); final Object val = params.get(key); String valString; if (val instanceof String[]) { final String[] valArray = (String[]) val; if (valArray.length == 1) valString = valArray[0]; else valString = Arrays.asList((String[]) val).toString(); } else { valString = val.toString(); } event.put("param." + key, valString); } } } @Override public void destroy() { } /** * A simple wrapper for {@link HttpServletResponseWrapper} that is used to capture headers * and cookies associated with the response. */ private static final class ResponseSpy extends HttpServletResponseWrapper { int statusCode = 200; final Map<String, List<String>> headers = new ConcurrentHashMap<>(); final List<Cookie> cookies = new ArrayList<>(); private ResponseSpy(HttpServletResponse response) { super(response); } @Override public void setStatus(int sc) { super.setStatus(sc); this.statusCode = sc; } @Override public void addCookie(Cookie cookie) { cookies.add(cookie); super.addCookie(cookie); } @Override public void setHeader(String name, String value) { List<String> values = new ArrayList<>(); values.add(value); headers.put(name, values); super.setHeader(name, value); } @Override public void addHeader(String name, String value) { List<String> values = headers.computeIfAbsent(name, k -> new ArrayList<>()); values.add(value); super.addHeader(name, value); } @Override public void setDateHeader(String name, long date) { List<String> values = new ArrayList<>(); values.add(Long.toString(date)); headers.put(name, values); super.setDateHeader(name, date); } @Override public void setIntHeader(String name, int val) { List<String> values = new ArrayList<>(); values.add(Integer.toString(val)); headers.put(name, values); super.setIntHeader(name, val); } } }
7,689
0
Create_ds/mantis/mantis-examples/mantis-examples-mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web
Create_ds/mantis/mantis-examples/mantis-examples-mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web/service/MyService.java
/* * Copyright 2019 Netflix, 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.netflix.mantis.examples.mantispublishsample.web.service; public interface MyService { String hello(String name); }
7,690
0
Create_ds/mantis/mantis-examples/mantis-examples-mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web
Create_ds/mantis/mantis-examples/mantis-examples-mantis-publish-web-sample/src/main/java/com/netflix/mantis/examples/mantispublishsample/web/service/MyServiceImpl.java
/* * Copyright 2019 Netflix, 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.netflix.mantis.examples.mantispublishsample.web.service; public class MyServiceImpl implements MyService { @Override public String hello(String name) { return "Hello, " + name; } }
7,691
0
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/SyntheticSourceJob.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.sourcejob.synthetic; import io.mantisrx.runtime.Job; import io.mantisrx.runtime.MantisJob; import io.mantisrx.runtime.MantisJobProvider; import io.mantisrx.runtime.executor.LocalJobExecutorNetworked; import io.mantisrx.sourcejob.synthetic.core.TaggedData; import io.mantisrx.sourcejob.synthetic.sink.QueryRequestPostProcessor; import io.mantisrx.sourcejob.synthetic.sink.QueryRequestPreProcessor; import io.mantisrx.sourcejob.synthetic.sink.TaggedDataSourceSink; import io.mantisrx.sourcejob.synthetic.source.SyntheticSource; import io.mantisrx.sourcejob.synthetic.stage.TaggingStage; /** * A sample queryable source job that generates synthetic request events. * Clients connect to this job via the Sink port using an MQL expression. The job then sends only the data * that matches the query to the client. The client can be another Mantis Job or a user manually running a GET request. * * Run this sample by executing the main method of this class. Then look for the SSE port where the output of this job * will be available for streaming. E.g Serving modern HTTP SSE server sink on port: 8299 * Usage: curl "localhost:<sseport>?clientId=<myId>&subscriptionId=<someid>&criterion=<valid mql query> * * E.g <code>curl "localhost:8498?subscriptionId=nj&criterion=select%20country%20from%20stream%20where%20status%3D%3D500&clientId=nj2"</code> * Here the user is submitted an MQL query select country from stream where status==500. */ public class SyntheticSourceJob extends MantisJobProvider<TaggedData> { @Override public Job<TaggedData> getJobInstance() { return MantisJob // synthetic source generates random RequestEvents. .source(new SyntheticSource()) // Tags events with queries that match .stage(new TaggingStage(), TaggingStage.config()) // A custom sink that processes query parameters to register and deregister MQL queries .sink(new TaggedDataSourceSink(new QueryRequestPreProcessor(), new QueryRequestPostProcessor())) // required parameters .create(); } public static void main(String[] args) { LocalJobExecutorNetworked.execute(new SyntheticSourceJob().getJobInstance()); } }
7,692
0
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/core/MQL.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.sourcejob.synthetic.core; import io.mantisrx.mql.jvm.core.Query; import io.mantisrx.mql.shaded.clojure.java.api.Clojure; import io.mantisrx.mql.shaded.clojure.lang.IFn; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.functions.Func1; /** * The MQL class provides a Java/Scala friendly static interface to MQL functionality which is written in Clojure. * This class provides a few pieces of functionality; * - It wraps the Clojure interop so that the user interacts with typed methods via the static interface. * - It provides methods for accessing individual bits of query functionality, allowing interesting uses * such as aggregator-mql which uses these components to implement the query in a horizontally scalable / distributed * fashion on Mantis. * - It functions as an Rx Transformer of MantisServerSentEvent to MQLResult allowing a user to inline all MQL * functionality quickly as such: `myObservable.compose(MQL.parse(myQuery));` */ public class MQL { // // Clojure Interop // private static IFn require = Clojure.var("io.mantisrx.mql.shaded.clojure.core", "require"); static { require.invoke(Clojure.read("io.mantisrx.mql.jvm.interfaces.core")); require.invoke(Clojure.read("io.mantisrx.mql.jvm.interfaces.server")); } private static IFn cljMakeQuery = Clojure.var("io.mantisrx.mql.jvm.interfaces.server", "make-query"); private static IFn cljSuperset = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "queries->superset-projection"); private static IFn parser = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "parser"); private static IFn parses = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "parses?"); private static IFn getParseError = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "get-parse-error"); private static IFn queryToGroupByFn = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->groupby"); private static IFn queryToHavingPred = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->having-pred"); private static IFn queryToOrderBy = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->orderby"); private static IFn queryToLimit = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->limit"); private static IFn queryToExtrapolationFn = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->extrapolator"); private static IFn queryToAggregateFn = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "agg-query->projection"); private static IFn queryToWindow = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "query->window"); private static Logger logger = LoggerFactory.getLogger(MQL.class); private static ConcurrentHashMap<HashSet<Query>, IFn> superSetProjectorCache = new ConcurrentHashMap<>(); private final String query; private final boolean threadingEnabled; private final Optional<String> sourceJobName; public static void init() { logger.info("Initializing MQL runtime."); } // // Constructors and Static Factory Methods // public MQL(String query, boolean threadingEnabled) { if (query == null) { throw new IllegalArgumentException("MQL cannot be used as an operator with a null query."); } this.query = transformLegacyQuery(query); if (!parses(query)) { throw new IllegalArgumentException(getParseError(query)); } this.threadingEnabled = threadingEnabled; this.sourceJobName = Optional.empty(); } public MQL(String query, String sourceJobName) { if (query == null) { throw new IllegalArgumentException("MQL cannot be used as an operator with a null query."); } this.query = transformLegacyQuery(query); if (!parses(query)) { throw new IllegalArgumentException(getParseError(query)); } this.threadingEnabled = false; this.sourceJobName = Optional.ofNullable(sourceJobName); } public static MQL parse(String query) { return new MQL(query, false); } public static MQL parse(String query, boolean threadingEnabled) { return new MQL(query, threadingEnabled); } public static MQL parse(String query, String sourceName) { return new MQL(query, sourceName); } // // Source Job Integration // /** * Constructs an object implementing the Query interface. * This includes functions; * matches (Map<String, Object>>) -> Boolean * Returns true iff the data contained within the map parameter satisfies the query's WHERE clause. * project (Map<String, Object>>) -> Map<String, Object>> * Returns the provided map in accordance with the SELECT clause of the query. * sample (Map<String, Object>>) -> Boolean * Returns true if the data should be sampled, this function is a tautology if no SAMPLE clause is provided. * * @param subscriptionId The ID representing the subscription. * @param query The (valid) MQL query to parse. * * @return An object implementing the Query interface. */ public static Query makeQuery(String subscriptionId, String query) { /* if (!parses(query)) { String error = getParseError(query); logger.error("Failed to parse query [" + query + "]\nError: " + error + "."); throw new IllegalArgumentException(error); } */ return (Query) cljMakeQuery.invoke(subscriptionId, query.trim()); } @SuppressWarnings("unchecked") private static IFn computeSuperSetProjector(HashSet<Query> queries) { ArrayList<String> qs = new ArrayList<>(queries.size()); for (Query query : queries) { qs.add(query.getRawQuery()); } return (IFn) cljSuperset.invoke(new ArrayList(qs)); } /** * Projects a single Map<String, Object> which contains a superset of all fields for the provided queries. * This is useful in use cases such as the mantis-realtime-events library in which we desire to minimize the data * egressed off box. This should minimize JSON serialization time as well as network bandwidth used to transmit * the events. * <p> * NOTE: This function caches the projectors for performance reasons, this has implications for memory usage as each * combination of queries results in a new cached function. In practice this has had little impact for <= 100 * queries. * * @param queries A Collection of Query objects generated using #makeQuery(String subscriptionId, String query). * @param datum A Map representing the input event to be projected. * * @return A Map representing the union (superset) of all fields required for processing all queries passed in. */ @SuppressWarnings("unchecked") public static Map<String, Object> projectSuperSet(Collection<Query> queries, Map<String, Object> datum) { IFn superSetProjector = superSetProjectorCache.computeIfAbsent(new HashSet<Query>(queries), (qs) -> { return computeSuperSetProjector(qs); }); return (Map<String, Object>) superSetProjector.invoke(datum); } // // Partial Query Functionality // public static Func1<Map<String, Object>, Object> getGroupByFn(String query) { IFn func = (IFn) queryToGroupByFn.invoke(query); return func::invoke; } @SuppressWarnings("unchecked") public static Func1<Map<String, Object>, Boolean> getHavingPredicate(String query) { IFn func = (IFn) queryToHavingPred.invoke(query); return (datum) -> (Boolean) func.invoke(datum); } @SuppressWarnings("unchecked") public static Func1<Observable<Map<String, Object>>, Observable<Map<String, Object>>> getAggregateFn(String query) { IFn func = (IFn) queryToAggregateFn.invoke(query); return (obs) -> (Observable<Map<String, Object>>) func.invoke(obs); } @SuppressWarnings("unchecked") public static Func1<Map<String, Object>, Map<String, Object>> getExtrapolationFn(String query) { IFn func = (IFn) queryToExtrapolationFn.invoke(query); return (datum) -> (Map<String, Object>) func.invoke(datum); } @SuppressWarnings("unchecked") public static Func1<Observable<Map<String, Object>>, Observable<Map<String, Object>>> getOrderBy(String query) { IFn func = (IFn) queryToOrderBy.invoke(query); return obs -> (Observable<Map<String, Object>>) func.invoke(obs); } // public static List<Long> getWindow(String query) { // clojure.lang.PersistentVector result = (clojure.lang.PersistentVector)queryToWindow.invoke(query); // Long window = (Long)result.nth(0); // Long shift = (Long)result.nth(1); // return Arrays.asList(window, shift); // } public static Long getLimit(String query) { return (Long) queryToLimit.invoke(query); } // // Helper Functions // /** * A predicate which indicates whether or not the MQL parser considers query to be a valid query. * * @param query A String representing the MQL query. * * @return A boolean indicating whether or not the query successfully parses. */ public static Boolean parses(String query) { return (Boolean) parses.invoke(query); } /** * A convenience function allowing a caller to determine what went wrong if a call to #parses(String query) returns * false. * * @param query A String representing the MQL query. * * @return A String representing the parse error for an MQL query, null if no parse error occurred. */ public static String getParseError(String query) { return (String) getParseError.invoke(query); } /** * A helper which converts bare true/false queries to MQL. * * @param criterion A Mantis Query (old query language) query. * * @return A valid MQL query string assuming the input was valid. */ public static String transformLegacyQuery(String criterion) { return criterion.toLowerCase().equals("true") ? "select * where true" : criterion.toLowerCase().equals("false") ? "select * where false" : criterion; } public static void main(String[] args) { System.out.println(MQL.makeQuery("abc", "select * from stream where true")); } }
7,693
0
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/core/TaggedData.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.sourcejob.synthetic.core; import io.mantisrx.common.codec.Codec; import io.mantisrx.runtime.codec.JsonType; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class TaggedData implements JsonType { private final Set<String> matchedClients = new HashSet<String>(); private Map<String, Object> payLoad; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public TaggedData(@JsonProperty("data") Map<String, Object> data) { this.payLoad = data; } public Set<String> getMatchedClients() { return matchedClients; } public boolean matchesClient(String clientId) { return matchedClients.contains(clientId); } public void addMatchedClient(String clientId) { matchedClients.add(clientId); } public Map<String, Object> getPayload() { return this.payLoad; } public void setPayload(Map<String, Object> newPayload) { this.payLoad = newPayload; } public static Codec<TaggedData> taggedDataCodec() { return new Codec<TaggedData>() { @Override public TaggedData decode(byte[] bytes) { return new TaggedData(new HashMap<>()); } @Override public byte[] encode(final TaggedData value) { return new byte[128]; } }; } }
7,694
0
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/core/MQLQueryManager.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.sourcejob.synthetic.core; import io.mantisrx.mql.jvm.core.Query; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; public class MQLQueryManager { static class LazyHolder { private static final MQLQueryManager INSTANCE = new MQLQueryManager(); } private ConcurrentHashMap<String, Query> queries = new ConcurrentHashMap<>(); public static MQLQueryManager getInstance() { return LazyHolder.INSTANCE; } private MQLQueryManager() { } public void registerQuery(String id, String query) { query = MQL.transformLegacyQuery(query); Query q = MQL.makeQuery(id, query); queries.put(id, q); } public void deregisterQuery(String id) { queries.remove(id); } public Collection<Query> getRegisteredQueries() { return queries.values(); } public void clear() { queries.clear(); } public static void main(String[] args) throws Exception { MQLQueryManager qm = getInstance(); String query = "SELECT * WHERE true SAMPLE {\"strategy\":\"RANDOM\",\"threshold\":1}"; qm.registerQuery("fake2", query); System.out.println(MQL.parses(MQL.transformLegacyQuery(query))); System.out.println(MQL.getParseError(MQL.transformLegacyQuery(query))); System.out.println(qm.getRegisteredQueries()); } }
7,695
0
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/proto/RequestEvent.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.sourcejob.synthetic.proto; import io.mantisrx.common.codec.Codec; import io.mantisrx.shaded.com.fasterxml.jackson.core.JsonProcessingException; import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper; import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import lombok.Builder; import lombok.Data; /** * Represents a Request Event a service may receive. */ @Data @Builder public class RequestEvent { private static final ObjectMapper mapper = new ObjectMapper(); private static final ObjectReader requestEventReader = mapper.readerFor(RequestEvent.class); private final String userId; private final String uri; private final int status; private final String country; private final String deviceType; public Map<String,Object> toMap() { Map<String,Object> data = new HashMap<>(); data.put("userId", userId); data.put("uri", uri); data.put("status", status); data.put("country", country); data.put("deviceType", deviceType); return data; } public String toJsonString() { try { return mapper.writeValueAsString(this); } catch (JsonProcessingException e) { e.printStackTrace(); return null; } } /** * The codec defines how this class should be serialized before transporting across network. * @return */ public static Codec<RequestEvent> requestEventCodec() { return new Codec<RequestEvent>() { @Override public RequestEvent decode(byte[] bytes) { try { return requestEventReader.readValue(bytes); } catch (IOException e) { throw new RuntimeException(e); } } @Override public byte[] encode(final RequestEvent value) { try { return mapper.writeValueAsBytes(value); } catch (Exception e) { throw new RuntimeException(e); } } }; } }
7,696
0
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/source/SyntheticSource.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.sourcejob.synthetic.source; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.parameter.ParameterDefinition; import io.mantisrx.runtime.parameter.type.IntParameter; import io.mantisrx.runtime.parameter.validator.Validators; import io.mantisrx.runtime.source.Index; import io.mantisrx.runtime.source.Source; import io.mantisrx.sourcejob.synthetic.proto.RequestEvent; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import net.andreinc.mockneat.MockNeat; import rx.Observable; /** * Generates random set of RequestEvents at a preconfigured interval. */ @Slf4j public class SyntheticSource implements Source<String> { private static final String DATA_GENERATION_RATE_MSEC_PARAM = "dataGenerationRate"; private MockNeat mockDataGenerator; private int dataGenerateRateMsec = 250; @Override public Observable<Observable<String>> call(Context context, Index index) { return Observable.just(Observable .interval(dataGenerateRateMsec, TimeUnit.MILLISECONDS) .map((tick) -> generateEvent()) .map((event) -> event.toJsonString()) .filter(Objects::nonNull) .doOnNext((event) -> { log.debug("Generated Event {}", event); })); } @Override public void init(Context context, Index index) { mockDataGenerator = MockNeat.threadLocal(); dataGenerateRateMsec = (int)context.getParameters().get(DATA_GENERATION_RATE_MSEC_PARAM,250); } @Override public List<ParameterDefinition<?>> getParameters() { List<ParameterDefinition<?>> params = new ArrayList<>(); params.add(new IntParameter() .name(DATA_GENERATION_RATE_MSEC_PARAM) .description("Rate at which to generate data") .validator(Validators.range(100,1000000)) .defaultValue(250) .build()); return params; } private RequestEvent generateEvent() { String path = mockDataGenerator.probabilites(String.class) .add(0.1, "/login") .add(0.2, "/genre/horror") .add(0.5, "/genre/comedy") .add(0.2, "/mylist") .get(); String deviceType = mockDataGenerator.probabilites(String.class) .add(0.1, "ps4") .add(0.1, "xbox") .add(0.2, "browser") .add(0.3, "ios") .add(0.3, "android") .get(); String userId = mockDataGenerator.strings().size(10).get(); int status = mockDataGenerator.probabilites(Integer.class) .add(0.1,500) .add(0.7,200) .add(0.2,500) .get(); String country = mockDataGenerator.countries().names().get(); return RequestEvent.builder() .status(status) .uri(path) .country(country) .userId(userId) .deviceType(deviceType) .build(); } @Override public void close() throws IOException { } }
7,697
0
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/sink/QueryRequestPostProcessor.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.sourcejob.synthetic.sink; import static com.mantisrx.common.utils.MantisSourceJobConstants.CRITERION_PARAM_NAME; import static com.mantisrx.common.utils.MantisSourceJobConstants.SUBSCRIPTION_ID_PARAM_NAME; import io.mantisrx.runtime.Context; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; import rx.functions.Func2; /** * This is a callback that is invoked after a client connected to the sink of this job disconnects. This is used * to cleanup the queries the client had registered. */ @Slf4j public class QueryRequestPostProcessor implements Func2<Map<String, List<String>>, Context, Void> { public QueryRequestPostProcessor() { } @Override public Void call(Map<String, List<String>> queryParams, Context context) { log.info("RequestPostProcessor:queryParams: " + queryParams); if (queryParams != null) { if (queryParams.containsKey(SUBSCRIPTION_ID_PARAM_NAME) && queryParams.containsKey(CRITERION_PARAM_NAME)) { final String subId = queryParams.get(SUBSCRIPTION_ID_PARAM_NAME).get(0); final String query = queryParams.get(CRITERION_PARAM_NAME).get(0); final String clientId = queryParams.get("clientId").get(0); if (subId != null && query != null) { try { if (clientId != null && !clientId.isEmpty()) { deregisterQuery(clientId + "_" + subId); } else { deregisterQuery(subId); } } catch (Throwable t) { log.error("Error propagating unsubscription notification", t); } } } } return null; } private void deregisterQuery(String subId) { QueryRefCountMap.INSTANCE.removeQuery(subId); } }
7,698
0
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic
Create_ds/mantis/mantis-examples/mantis-examples-synthetic-sourcejob/src/main/java/io/mantisrx/sourcejob/synthetic/sink/TaggedDataSourceSink.java
/* * Copyright 2019 Netflix, 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 io.mantisrx.sourcejob.synthetic.sink; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.PortRequest; import io.mantisrx.runtime.sink.ServerSentEventsSink; import io.mantisrx.runtime.sink.Sink; import io.mantisrx.runtime.sink.predicate.Predicate; import io.mantisrx.shaded.com.fasterxml.jackson.core.JsonProcessingException; import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper; import io.mantisrx.sourcejob.synthetic.core.TaggedData; import java.io.IOException; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; import rx.Observable; import rx.Subscription; import rx.functions.Func2; /** * A custom sink that allows clients to connect to this job with an MQL expression and in turn receive events * matching this expression. */ @Slf4j public class TaggedDataSourceSink implements Sink<TaggedData> { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private final ServerSentEventsSink<TaggedData> sink; private Subscription subscription; static class NoOpProcessor implements Func2<Map<String, List<String>>, Context, Void> { @Override public Void call(Map<String, List<String>> t1, Context t2) { return null; } } public TaggedDataSourceSink() { this(new NoOpProcessor(), new NoOpProcessor()); } public TaggedDataSourceSink(Func2<Map<String, List<String>>, Context, Void> preProcessor, Func2<Map<String, List<String>>, Context, Void> postProcessor) { this.sink = new ServerSentEventsSink.Builder<TaggedData>() .withEncoder((data) -> { try { return OBJECT_MAPPER.writeValueAsString(data.getPayload()); } catch (JsonProcessingException e) { e.printStackTrace(); return "{\"error\":" + e.getMessage() + "}"; } }) .withPredicate(new Predicate<>("description", new TaggedEventFilter())) .withRequestPreprocessor(preProcessor) .withRequestPostprocessor(postProcessor) .build(); } @Override public void call(Context context, PortRequest portRequest, Observable<TaggedData> observable) { observable = observable .filter((t1) -> !t1.getPayload().isEmpty()); observable.subscribe(); sink.call(context, portRequest, observable); } @Override public void close() throws IOException { try { sink.close(); } finally { subscription.unsubscribe(); } } }
7,699