index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/abdera/spring/src/test/java/org/apache/abdera
Create_ds/abdera/spring/src/test/java/org/apache/abdera/spring/TestAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.spring; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.context.ResponseContextException; import org.apache.abdera.protocol.server.impl.AbstractCollectionAdapter; public class TestAdapter extends AbstractCollectionAdapter { @Override public String getAuthor(RequestContext request) throws ResponseContextException { return null; } @Override public String getId(RequestContext request) { // TODO Auto-generated method stub return null; } public String getHref(RequestContext request) { // TODO Auto-generated method stub return null; } public String getTitle(RequestContext request) { // TODO Auto-generated method stub return null; } public ResponseContext deleteEntry(RequestContext request) { // TODO Auto-generated method stub return null; } public ResponseContext getEntry(RequestContext request) { // TODO Auto-generated method stub return null; } public ResponseContext getFeed(RequestContext request) { // TODO Auto-generated method stub return null; } public ResponseContext postEntry(RequestContext request) { // TODO Auto-generated method stub return null; } public ResponseContext putEntry(RequestContext request) { // TODO Auto-generated method stub return null; } }
7,800
0
Create_ds/abdera/spring/src/test/java/org/apache/abdera
Create_ds/abdera/spring/src/test/java/org/apache/abdera/spring/TestSuite.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.spring; import org.junit.internal.TextListener; import org.junit.runner.JUnitCore; public class TestSuite { public static void main(String[] args) { JUnitCore runner = new JUnitCore(); runner.addListener(new TextListener(System.out)); runner.run(ProviderDefinitionParserTest.class); } }
7,801
0
Create_ds/abdera/spring/src/main/java/org/apache/abdera
Create_ds/abdera/spring/src/main/java/org/apache/abdera/spring/WorkspaceDefinitionParser.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.abdera.spring; import org.apache.abdera.protocol.server.impl.SimpleWorkspaceInfo; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.xml.ParserContext; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @SuppressWarnings("unchecked") public class WorkspaceDefinitionParser extends org.apache.abdera.spring.AbstractSingleBeanDefinitionParser { @Override protected void doParse(Element element, ParserContext ctx, BeanDefinitionBuilder bean) { ManagedList collections = new ManagedList(); NodeList nodes = element.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE // && // n.getNodeName().equals("bean")) { // Element childElement = (Element)n; // BeanDefinitionHolder child = ctx.getDelegate().parseBeanDefinitionElement(childElement); // collections.add(child); // } else if (n.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE && // n.getNodeName().equals("ref") ) { Element childElement = (Element)n; Object child = ctx.getDelegate().parsePropertySubElement(childElement, bean.getRawBeanDefinition()); collections.add(child); } } bean.addPropertyValue("collections", collections); NamedNodeMap atts = element.getAttributes(); Node title = atts.getNamedItem("title"); if (title != null) { bean.addPropertyValue("title", title.getNodeValue()); } } @Override protected String getBeanClassName(Element arg0) { String cls = super.getBeanClassName(arg0); if (cls == null) { cls = SimpleWorkspaceInfo.class.getName(); } return cls; } @Override protected boolean shouldGenerateIdAsFallback() { return true; } }
7,802
0
Create_ds/abdera/spring/src/main/java/org/apache/abdera
Create_ds/abdera/spring/src/main/java/org/apache/abdera/spring/NamespaceHandler.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.abdera.spring; import org.springframework.beans.factory.xml.NamespaceHandlerSupport; public class NamespaceHandler extends NamespaceHandlerSupport { public void init() { registerBeanDefinitionParser("workspace", new WorkspaceDefinitionParser()); registerBeanDefinitionParser("provider", new DefaultProviderDefinitionParser()); registerBeanDefinitionParser("regexTargetResolver", new RegexTargetResolverDefinitionParser()); } }
7,803
0
Create_ds/abdera/spring/src/main/java/org/apache/abdera
Create_ds/abdera/spring/src/main/java/org/apache/abdera/spring/AbstractSingleBeanDefinitionParser.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.abdera.spring; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate; import org.springframework.beans.factory.xml.ParserContext; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public abstract class AbstractSingleBeanDefinitionParser extends org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser { public AbstractSingleBeanDefinitionParser() { super(); } @Override protected void doParse(Element element, ParserContext ctx, BeanDefinitionBuilder bean) { NamedNodeMap atts = element.getAttributes(); for (int i = 0; i < atts.getLength(); i++) { Attr node = (Attr)atts.item(i); String val = node.getValue(); String name = node.getLocalName(); if ("abstract".equals(name)) { bean.setAbstract(true); } else if (!"id".equals(name) && !"name".equals(name)) { mapAttribute(bean, element, name, val); } } NodeList children = element.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { String name = n.getLocalName(); mapElement(ctx, bean, (Element)n, name); } } } protected void mapElement(ParserContext ctx, BeanDefinitionBuilder bean, Element element, String name) { } protected void mapAttribute(BeanDefinitionBuilder bean, Element element, String name, String val) { } protected void setFirstChildAsProperty(Element element, ParserContext ctx, BeanDefinitionBuilder bean, String propertyName) { String id = getAndRegisterFirstChild(element, ctx, bean, propertyName); bean.addPropertyReference(propertyName, id); } protected String getAndRegisterFirstChild(Element element, ParserContext ctx, BeanDefinitionBuilder bean, String propertyName) { Element first = getFirstChild(element); if (first == null) { throw new IllegalStateException(propertyName + " property must have child elements!"); } return getAndRegister(ctx, bean, first); } protected String getAndRegister(ParserContext ctx, BeanDefinitionBuilder bean, Element el) { // Seems odd that we have to do the registration, I wonder if there is a better way String id; BeanDefinition child; if (el.getNamespaceURI().equals(BeanDefinitionParserDelegate.BEANS_NAMESPACE_URI)) { String name = el.getLocalName(); if ("ref".equals(name)) { id = el.getAttribute("bean"); if (id == null) { throw new IllegalStateException("<ref> elements must have a \"bean\" attribute!"); } return id; } else if ("bean".equals(name)) { BeanDefinitionHolder bdh = ctx.getDelegate().parseBeanDefinitionElement(el); child = bdh.getBeanDefinition(); id = bdh.getBeanName(); } else { throw new UnsupportedOperationException("Elements with the name " + name + " are not currently " + "supported as sub elements of " + el.getParentNode().getLocalName()); } } else { child = ctx.getDelegate().parseCustomElement(el, bean.getBeanDefinition()); id = child.toString(); } ctx.getRegistry().registerBeanDefinition(id, child); return id; } protected Element getFirstChild(Element element) { Element first = null; NodeList children = element.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { first = (Element)n; } } return first; } }
7,804
0
Create_ds/abdera/spring/src/main/java/org/apache/abdera
Create_ds/abdera/spring/src/main/java/org/apache/abdera/spring/ProviderFactoryBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.spring; import java.lang.reflect.Constructor; import java.util.Collection; import javax.security.auth.Subject; import org.apache.abdera.protocol.Resolver; import org.apache.abdera.protocol.server.Filter; import org.apache.abdera.protocol.server.Target; import org.apache.abdera.protocol.server.WorkspaceInfo; import org.apache.abdera.protocol.server.WorkspaceManager; import org.apache.abdera.protocol.server.impl.DefaultProvider; import org.springframework.beans.factory.FactoryBean; @SuppressWarnings("unchecked") public class ProviderFactoryBean implements FactoryBean { private Class<? extends DefaultProvider> providerClass = DefaultProvider.class; private String base; private WorkspaceManager workspaceManager; private Collection<WorkspaceInfo> workspaces; private Resolver<Target> targetResolver; private Resolver<Subject> subjectResolver; private Filter[] filters; public Object getObject() throws Exception { DefaultProvider p = null; if (base != null) { Constructor<? extends DefaultProvider> constructor = providerClass.getConstructor(String.class); p = constructor.newInstance(base); } else { p = providerClass.newInstance(); } if (workspaceManager != null) { p.setWorkspaceManager(workspaceManager); } if (workspaces != null && workspaces.size() > 0) { p.addWorkspaces(workspaces); } if (targetResolver != null) { p.setTargetResolver(targetResolver); } if (subjectResolver != null) { p.setSubjectResolver(subjectResolver); } if (filters != null && filters.length > 0) { p.addFilter(filters); } return p; } public Class getObjectType() { return providerClass; } public boolean isSingleton() { return true; } public Class getProviderClass() { return providerClass; } public void setProviderClass(Class providerClass) { this.providerClass = providerClass; } public String getBase() { return base; } public void setBase(String base) { this.base = base; } public WorkspaceManager getWorkspaceManager() { return workspaceManager; } public void setWorkspaceManager(WorkspaceManager workspaceManager) { this.workspaceManager = workspaceManager; } public Collection<WorkspaceInfo> getWorkspaces() { return workspaces; } public void setWorkspaces(Collection<WorkspaceInfo> workspaces) { this.workspaces = workspaces; } public Resolver<Target> getTargetResolver() { return targetResolver; } public void setTargetResolver(Resolver<Target> targetResolver) { this.targetResolver = targetResolver; } public Resolver<Subject> getSubjectResolver() { return subjectResolver; } public void setSubjectResolver(Resolver<Subject> subjectResolver) { this.subjectResolver = subjectResolver; } public Filter[] getFilters() { return filters; } public void setFilters(Filter[] filters) { this.filters = filters; } }
7,805
0
Create_ds/abdera/spring/src/main/java/org/apache/abdera
Create_ds/abdera/spring/src/main/java/org/apache/abdera/spring/RegexTargetResolverFactoryBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.spring; import java.util.List; import org.apache.abdera.protocol.server.TargetType; import org.apache.abdera.protocol.server.impl.RegexTargetResolver; import org.springframework.beans.factory.FactoryBean; @SuppressWarnings("unchecked") public class RegexTargetResolverFactoryBean implements FactoryBean { private List<String> services; private List<String> collections; private List<String> entries; private List<String> media; private List<String> categories; public Object getObject() throws Exception { RegexTargetResolver resolver = new RegexTargetResolver(); init(resolver, services, TargetType.TYPE_SERVICE); init(resolver, collections, TargetType.TYPE_COLLECTION); init(resolver, entries, TargetType.TYPE_ENTRY); init(resolver, media, TargetType.TYPE_MEDIA); init(resolver, categories, TargetType.TYPE_CATEGORIES); return resolver; } private void init(RegexTargetResolver resolver, List<String> patterns, TargetType t) { if (patterns == null) return; for (String s : patterns) { resolver.setPattern(s, t); } } public Class getObjectType() { return RegexTargetResolver.class; } public boolean isSingleton() { return true; } public List<String> getCollections() { return collections; } public void setCollections(List<String> collections) { this.collections = collections; } public List<String> getEntries() { return entries; } public void setEntries(List<String> entries) { this.entries = entries; } public List<String> getServices() { return services; } public void setServices(List<String> services) { this.services = services; } public List<String> getCategories() { return categories; } public void setCategories(List<String> categories) { this.categories = categories; } public List<String> getMedia() { return media; } public void setMedia(List<String> media) { this.media = media; } }
7,806
0
Create_ds/abdera/spring/src/main/java/org/apache/abdera
Create_ds/abdera/spring/src/main/java/org/apache/abdera/spring/DefaultProviderDefinitionParser.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.abdera.spring; import java.util.List; import org.apache.abdera.protocol.server.Provider; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.util.StringUtils; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class DefaultProviderDefinitionParser extends org.apache.abdera.spring.AbstractSingleBeanDefinitionParser { @Override protected void mapAttribute(BeanDefinitionBuilder bean, Element element, String name, String val) { if (name.equals("base")) { bean.addPropertyValue(name, val); } else if (name.equals("class")) { bean.addPropertyValue("providerClass", val); } } @Override @SuppressWarnings("unchecked") protected void mapElement(ParserContext ctx, BeanDefinitionBuilder bean, Element element, String name) { if (name.equals("workspaceManager")) { setFirstChildAsProperty(element, ctx, bean, "workspaceManager"); } else if (name.equals("targetResolver")) { setFirstChildAsProperty(element, ctx, bean, "targetResolver"); } else if (name.equals("subjectResolver")) { setFirstChildAsProperty(element, ctx, bean, name); } else if (name.equals("filter")) { MutablePropertyValues values = bean.getBeanDefinition().getPropertyValues(); PropertyValue pv = values.getPropertyValue("filters"); List filters = pv != null ? (List)pv.getValue() : new ManagedList(); NodeList nodes = element.getChildNodes(); Object child = null; if (element.hasAttribute("ref")) { if (!StringUtils.hasText(element.getAttribute("ref"))) { ctx.getReaderContext().error(name + " contains empty 'ref' attribute", element); } child = new RuntimeBeanReference(element.getAttribute("ref")); ((RuntimeBeanReference)child).setSource(ctx.extractSource(element)); } else if (nodes != null) { for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { Element childElement = (Element)n; child = ctx.getDelegate().parsePropertySubElement(childElement, bean.getRawBeanDefinition()); } } } if (child != null) { filters.add(child); } bean.addPropertyValue("filters", filters); } else if (name.equals("workspace")) { String id = getAndRegister(ctx, bean, element); bean.addPropertyReference("workspaces", id); } else if (name.equals("property")) { ctx.getDelegate().parsePropertyElement(element, bean.getRawBeanDefinition()); } } @Override protected String getBeanClassName(Element arg0) { String cls = super.getBeanClassName(arg0); if (cls == null) { cls = ProviderFactoryBean.class.getName(); } return cls; } @Override protected String resolveId(Element element, AbstractBeanDefinition arg1, ParserContext arg2) throws BeanDefinitionStoreException { String id = element.getAttribute("id"); if (id == null || "".equals(id)) { id = Provider.class.getName(); } return id; } }
7,807
0
Create_ds/abdera/spring/src/main/java/org/apache/abdera
Create_ds/abdera/spring/src/main/java/org/apache/abdera/spring/RegexTargetResolverDefinitionParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.spring; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.ParserContext; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class RegexTargetResolverDefinitionParser extends org.apache.abdera.spring.AbstractSingleBeanDefinitionParser { @Override protected void doParse(Element element, ParserContext ctx, BeanDefinitionBuilder bean) { NamedNodeMap atts = element.getAttributes(); for (int i = 0; i < atts.getLength(); i++) { Attr node = (Attr)atts.item(i); String val = node.getValue(); String name = node.getLocalName(); if ("abstract".equals(name)) { bean.setAbstract(true); } else if (!"id".equals(name) && !"name".equals(name)) { mapAttribute(bean, element, name, val); } } List<String> collection = new ArrayList<String>(); List<String> category = new ArrayList<String>(); List<String> entry = new ArrayList<String>(); List<String> service = new ArrayList<String>(); List<String> media = new ArrayList<String>(); NodeList children = element.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { String name = n.getLocalName(); if (name.equals("collection")) { collection.add(getText(n)); } else if (name.equals("category")) { category.add(getText(n)); } else if (name.equals("entry")) { entry.add(getText(n)); } else if (name.equals("media")) { media.add(getText(n)); } else if (name.equals("service")) { service.add(getText(n)); } } } bean.addPropertyValue("categories", category); bean.addPropertyValue("collections", collection); bean.addPropertyValue("entries", entry); bean.addPropertyValue("media", media); bean.addPropertyValue("services", service); } private String getText(Node n) { if (n == null) { return null; } Node n1 = getChild(n, Node.TEXT_NODE); if (n1 == null) { return null; } return n1.getNodeValue().trim(); } public static Node getChild(Node parent, int type) { Node n = parent.getFirstChild(); while (n != null && type != n.getNodeType()) { n = n.getNextSibling(); } if (n == null) { return null; } return n; } @Override protected String getBeanClassName(Element arg0) { String cls = super.getBeanClassName(arg0); if (cls == null) { cls = RegexTargetResolverFactoryBean.class.getName(); } return cls; } @Override protected String resolveId(Element arg0, AbstractBeanDefinition arg1, ParserContext arg2) throws BeanDefinitionStoreException { String id = super.resolveId(arg0, arg1, arg2); if (id == null) { id = RegexTargetResolverFactoryBean.class.getName() + new Object().hashCode(); } return id; } }
7,808
0
Create_ds/abdera/spring/src/main/java/org/apache/abdera
Create_ds/abdera/spring/src/main/java/org/apache/abdera/spring/SpringAbderaServlet.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.spring; import org.apache.abdera.protocol.server.Provider; import org.apache.abdera.protocol.server.servlet.AbderaServlet; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; /** * Loads a Spring ServiceContext from a Spring WebApplicationContext. By default it looks for a bean with the name * "org.apache.abdera.protocol.server.ServiceContext". This can be overridden by supplying the "serviceContextBeanName" * initialization parameter. */ public class SpringAbderaServlet extends AbderaServlet { private static final long serialVersionUID = -7579564455804753809L; protected Provider createProvider() { String providerName = getInitParameter("providerBeanName"); if (providerName == null) { providerName = Provider.class.getName(); } WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); Provider p = (Provider)ctx.getBean(providerName); p.init(getAbdera(), getProperties(getServletConfig())); return p; } }
7,809
0
Create_ds/directory-buildtools/junit-addons/src/test/java/org/apache/directory/junit
Create_ds/directory-buildtools/junit-addons/src/test/java/org/apache/directory/junit/tools/MultiThreadedMultiInvokerThreadsafeTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.junit.tools; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.concurrent.atomic.AtomicLong; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; public class MultiThreadedMultiInvokerThreadsafeTest { private static final int NUM_THREADS = 100; private static final int NUM_INVOCATIONS = 10000; private static final int NUM_METHODS = 10; @Rule public MultiThreadedMultiInvoker i = new MultiThreadedMultiInvoker( NUM_THREADS, NUM_INVOCATIONS ); private static AtomicLong counter; private static long startTime; @BeforeClass public static void initCounter() { counter = new AtomicLong( 0L ); } @BeforeClass public static void initStartTime() { startTime = System.currentTimeMillis(); } @AfterClass public static void checkCounter() { assertEquals( 1L * NUM_THREADS * NUM_INVOCATIONS * NUM_METHODS, counter.get() ); } @AfterClass public static void checkRuntime() { long endTime = System.currentTimeMillis(); long runTime = endTime - startTime; if ( runTime > 10000 ) { fail( "Test shut run in less than 10 seconds." ); } } @Test public void test0() { counter.incrementAndGet(); } @Test public void test1() { counter.incrementAndGet(); } @Test public void test2() { counter.incrementAndGet(); } @Test public void test3() { counter.incrementAndGet(); } @Test public void test4() { counter.incrementAndGet(); } @Test public void test5() { counter.incrementAndGet(); } @Test public void test6() { counter.incrementAndGet(); } @Test public void test7() { counter.incrementAndGet(); } @Test public void test8() { counter.incrementAndGet(); } @Test public void test9() { counter.incrementAndGet(); } }
7,810
0
Create_ds/directory-buildtools/junit-addons/src/test/java/org/apache/directory/junit
Create_ds/directory-buildtools/junit-addons/src/test/java/org/apache/directory/junit/tools/MultiThreadedMultiInvokerNotThreadsafeTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.junit.tools; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; public class MultiThreadedMultiInvokerNotThreadsafeTest { private static final int NUM_THREADS = 1; private static final int NUM_INVOCATIONS = 1000000; private static final int NUM_METHODS = 10; @Rule public MultiThreadedMultiInvoker i = new MultiThreadedMultiInvoker( NUM_THREADS, NUM_INVOCATIONS ); private static long counter; private static long startTime; @BeforeClass public static void initCounter() { counter = 0l; } @BeforeClass public static void initStartTime() { startTime = System.currentTimeMillis(); } @AfterClass public static void checkCounter() { assertEquals( 1L * NUM_THREADS * NUM_INVOCATIONS * NUM_METHODS, counter ); } @AfterClass public static void checkRuntime() { long endTime = System.currentTimeMillis(); long runTime = endTime - startTime; if ( runTime > 10000 ) { fail( "Test shut run in less than 10 seconds." ); } } @Test public void test0() { counter++; } @Test public void test1() { counter++; } @Test public void test2() { counter++; } @Test public void test3() { counter++; } @Test public void test4() { counter++; } @Test public void test5() { counter++; } @Test public void test6() { counter++; } @Test public void test7() { counter++; } @Test public void test8() { counter++; } @Test public void test9() { counter++; } }
7,811
0
Create_ds/directory-buildtools/junit-addons/src/main/java/org/apache/directory/junit
Create_ds/directory-buildtools/junit-addons/src/main/java/org/apache/directory/junit/tools/NoMultiThreadedInvocation.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.junit.tools; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicates that a test shouldn't be invoked by multiple threads. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ @Retention(RetentionPolicy.RUNTIME) @Target( { ElementType.METHOD }) public @interface NoMultiThreadedInvocation { /** * The optional reason why the test shouldn't be invoked by multiple threads. */ String value() default ""; }
7,812
0
Create_ds/directory-buildtools/junit-addons/src/main/java/org/apache/directory/junit
Create_ds/directory-buildtools/junit-addons/src/main/java/org/apache/directory/junit/tools/MultiThreadedMultiInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.junit.tools; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.rules.MethodRule; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; /** * Rule that invokes each test method multiple times using multiple threads. * * Just put the following two lines to your test. * * <pre> * &#064;RuleRule * public MultiThreadedMultiInvoker i = new MultiThreadedMultiInvoker(); * </pre> * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class MultiThreadedMultiInvoker implements MethodRule { public static final boolean THREADSAFE = true; public static final boolean NOT_THREADSAFE = false; private static ExecutorService pool = Executors.newCachedThreadPool(); private int numThreads; private int numInvocationsPerThread; private boolean trace; /** * Instantiates a new multi threaded invoker. * * The number of threads and invocations per thread are derived from * system properties 'threads' and 'invocations'. * * @param threadSafe whether the tested class is thread safe */ public MultiThreadedMultiInvoker( boolean threadSafe ) { this.numThreads = threadSafe ? getSystemIntProperty( "mtmi.threads", 1 ) : 1; this.numInvocationsPerThread = getSystemIntProperty( "mtmi.invocations", 1 ); this.trace = getSystemBoolProperty( "mtmi.trace", false ); } private int getSystemIntProperty( String key, int def ) { String property = System.getProperty( key, "" + def ); int value = Integer.parseInt( property ); return value; } private boolean getSystemBoolProperty( String key, boolean def ) { String property = System.getProperty( key, "" + def ); boolean value = Boolean.parseBoolean( property ); return value; } /** * Instantiates a new multi threaded multi invoker. * * @param numThreads the number of threads * @param numInvocationsPerThread the number of method invocations per thread */ public MultiThreadedMultiInvoker( int numThreads, int numInvocationsPerThread ) { super(); this.numThreads = numThreads; this.numInvocationsPerThread = numInvocationsPerThread; this.trace = false; } /** * Instantiates a new multi threaded multi invoker. * * @param numThreads the number of threads * @param numInvocationsPerThread the number of method invocations per thread * @param trace the trace flag */ public MultiThreadedMultiInvoker( int numThreads, int numInvocationsPerThread, boolean trace ) { super(); this.numThreads = numThreads; this.numInvocationsPerThread = numInvocationsPerThread; this.trace = trace; } /** * {@inheritDoc} */ public Statement apply( final Statement base, final FrameworkMethod method, final Object target ) { return new Statement() { @Override public void evaluate() throws Throwable { int count = numThreads; if ( method.getAnnotation( NoMultiThreadedInvocation.class ) != null ) { count = 1; } final long start = System.currentTimeMillis(); final List<Throwable> throwables = Collections.synchronizedList( new ArrayList<Throwable>() ); final List<Future<Void>> futures = new ArrayList<Future<Void>>(); for ( int threadNum = 0; threadNum < count; threadNum++ ) { Callable<Void> c = new Callable<Void>() { public Void call() throws Exception { try { for ( int invocationNum = 0; invocationNum < numInvocationsPerThread; invocationNum++ ) { if ( trace ) { long t = System.currentTimeMillis() - start; System.out.println( t + " - " + method.getName() + " - " + Thread.currentThread().getName() + " - Invocation " + ( invocationNum + 1 ) + "/" + numInvocationsPerThread ); } base.evaluate(); } } catch ( Throwable t ) { if ( trace ) { t.printStackTrace(); } throwables.add( t ); } return null; } }; Future<Void> future = pool.submit( c ); futures.add( future ); } for ( Future<Void> future : futures ) { future.get(); } if ( !throwables.isEmpty() ) { throw throwables.get( 0 ); } } }; } }
7,813
0
Create_ds/directory-buildtools/junit-addons/src/main/java/com/mycila/junit
Create_ds/directory-buildtools/junit-addons/src/main/java/com/mycila/junit/concurrent/NamedThreadFactory.java
/** * Copyright (C) 2010 Mycila <mathieu.carbou@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mycila.junit.concurrent; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * @author Mathieu Carbou (mathieu.carbou@gmail.com) */ final class NamedThreadFactory implements ThreadFactory { static final AtomicInteger poolNumber = new AtomicInteger(1); final AtomicInteger threadNumber = new AtomicInteger(1); final ThreadGroup group; NamedThreadFactory(String poolName) { group = new ThreadGroup(poolName + "-" + poolNumber.getAndIncrement()); } public Thread newThread(Runnable r) { return new Thread(group, r, group.getName() + "-thread-" + threadNumber.getAndIncrement(), 0); } }
7,814
0
Create_ds/directory-buildtools/junit-addons/src/main/java/com/mycila/junit
Create_ds/directory-buildtools/junit-addons/src/main/java/com/mycila/junit/concurrent/ConcurrentJunitRunner.java
/** * Copyright (C) 2010 Mycila <mathieu.carbou@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mycila.junit.concurrent; import org.junit.Test; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.InitializationError; import org.junit.runners.model.TestClass; /** * @author Mathieu Carbou (mathieu.carbou@gmail.com) */ public final class ConcurrentJunitRunner extends BlockJUnit4ClassRunner { public ConcurrentJunitRunner(final Class<?> klass) throws InitializationError { super(klass); int nThreads = 0; if (klass.isAnnotationPresent(Concurrency.class)) nThreads = Math.max(0, klass.getAnnotation(Concurrency.class).value()); if (nThreads == 0) nThreads = new TestClass(klass).getAnnotatedMethods(Test.class).size(); if (nThreads == 0) nThreads = Runtime.getRuntime().availableProcessors(); setScheduler(new ConcurrentRunnerScheduler( klass.getSimpleName(), Math.min(Runtime.getRuntime().availableProcessors(), nThreads), nThreads)); } }
7,815
0
Create_ds/directory-buildtools/junit-addons/src/main/java/com/mycila/junit
Create_ds/directory-buildtools/junit-addons/src/main/java/com/mycila/junit/concurrent/ConcurrentException.java
/** * Copyright (C) 2010 Mycila <mathieu.carbou@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mycila.junit.concurrent; /** * @author Mathieu Carbou (mathieu.carbou@gmail.com) */ public final class ConcurrentException extends RuntimeException { private ConcurrentException(Throwable cause) { super(cause.getMessage(), cause); } public Throwable unwrap() { Throwable t = getCause(); while (t instanceof ConcurrentException) t = t.getCause(); return t; } public static ConcurrentException wrap(Throwable t) { if (t instanceof ConcurrentException) t = ((ConcurrentException) t).unwrap(); ConcurrentException concurrentException = new ConcurrentException(t); concurrentException.setStackTrace(t.getStackTrace()); return concurrentException; } }
7,816
0
Create_ds/directory-buildtools/junit-addons/src/main/java/com/mycila/junit
Create_ds/directory-buildtools/junit-addons/src/main/java/com/mycila/junit/concurrent/ConcurrentSuite.java
/** * Copyright (C) 2010 Mycila <mathieu.carbou@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mycila.junit.concurrent; import org.junit.internal.builders.AllDefaultPossibilitiesBuilder; import org.junit.runner.Runner; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; import java.util.Arrays; import java.util.List; /** * @author Mathieu Carbou (mathieu.carbou@gmail.com) */ public final class ConcurrentSuite extends Suite { public ConcurrentSuite(Class<?> klass) throws InitializationError { super(klass, new AllDefaultPossibilitiesBuilder(true) { @Override public Runner runnerForClass(Class<?> testClass) throws Throwable { List<RunnerBuilder> builders = Arrays.asList( new RunnerBuilder() { @Override public Runner runnerForClass(Class<?> testClass) throws Throwable { Concurrency annotation = testClass.getAnnotation(Concurrency.class); return annotation != null ? new ConcurrentJunitRunner(testClass) : null; } }, ignoredBuilder(), annotatedBuilder(), suiteMethodBuilder(), junit3Builder(), junit4Builder()); for (RunnerBuilder each : builders) { Runner runner = each.safeRunnerForClass(testClass); if (runner != null) return runner; } return null; } }); int nThreads = 0; if (klass.isAnnotationPresent(Concurrency.class)) nThreads = Math.max(0, klass.getAnnotation(Concurrency.class).value()); if (nThreads == 0) { SuiteClasses suiteClasses = klass.getAnnotation(SuiteClasses.class); nThreads = suiteClasses != null ? suiteClasses.value().length : Runtime.getRuntime().availableProcessors(); } setScheduler(new ConcurrentRunnerScheduler( klass.getSimpleName(), Math.min(Runtime.getRuntime().availableProcessors(), nThreads), nThreads)); } }
7,817
0
Create_ds/directory-buildtools/junit-addons/src/main/java/com/mycila/junit
Create_ds/directory-buildtools/junit-addons/src/main/java/com/mycila/junit/concurrent/Concurrency.java
/** * Copyright (C) 2010 Mycila <mathieu.carbou@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mycila.junit.concurrent; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Set the number of threads. * <br> * If 0 or less, the number of thread will be the number of test methdds ot test classes in the suite. * <br> * If the computation cannot be done, the default thread number will be the number of available cores. * * @author Mathieu Carbou (mathieu.carbou@gmail.com) */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface Concurrency { int value() default 0; }
7,818
0
Create_ds/directory-buildtools/junit-addons/src/main/java/com/mycila/junit
Create_ds/directory-buildtools/junit-addons/src/main/java/com/mycila/junit/concurrent/ConcurrentRunnerScheduler.java
/** * Copyright (C) 2010 Mycila <mathieu.carbou@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mycila.junit.concurrent; import org.junit.runners.model.RunnerScheduler; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * @author Mathieu Carbou (mathieu.carbou@gmail.com) */ final class ConcurrentRunnerScheduler implements RunnerScheduler { private final ExecutorService executorService; private final Queue<Future<Void>> tasks = new LinkedList<Future<Void>>(); private final CompletionService<Void> completionService; public ConcurrentRunnerScheduler(String name, int nThreadsMin, int nThreadsMax) { executorService = new ThreadPoolExecutor( nThreadsMin, nThreadsMax, 10L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new NamedThreadFactory(name), new ThreadPoolExecutor.CallerRunsPolicy()); completionService = new ExecutorCompletionService<Void>(executorService); } public void schedule(Runnable childStatement) { tasks.offer(completionService.submit(childStatement, null)); } public void finished() throws ConcurrentException { try { while (!tasks.isEmpty()) { Future<Void> f = completionService.take(); tasks.remove(f); f.get(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (ExecutionException e) { throw ConcurrentException.wrap(e.getCause()); } finally { while (!tasks.isEmpty()) tasks.poll().cancel(true); executorService.shutdownNow(); } } }
7,819
0
Create_ds/directory-buildtools/junit-addons/src/main/java/com/mycila/junit
Create_ds/directory-buildtools/junit-addons/src/main/java/com/mycila/junit/concurrent/ConcurrentRule.java
/** * Copyright (C) 2010 Mycila <mathieu.carbou@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mycila.junit.concurrent; import org.junit.rules.MethodRule; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import java.util.concurrent.CountDownLatch; /** * @author Mathieu Carbou (mathieu.carbou@gmail.com) */ public final class ConcurrentRule implements MethodRule { public Statement apply(final Statement statement, final FrameworkMethod frameworkMethod, final Object o) { return new Statement() { public void evaluate() throws Throwable { Concurrency concurrency = frameworkMethod.getAnnotation(Concurrency.class); if (concurrency == null) statement.evaluate(); else { int nThreads = Math.max(0, concurrency.value()); if (nThreads == 0) nThreads = Runtime.getRuntime().availableProcessors(); ConcurrentRunnerScheduler scheduler = new ConcurrentRunnerScheduler( o.getClass().getSimpleName() + "." + frameworkMethod.getName(), nThreads, nThreads); final CountDownLatch go = new CountDownLatch(1); Runnable runnable = new Runnable() { public void run() { try { go.await(); statement.evaluate(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable throwable) { throw ConcurrentException.wrap(throwable); } } }; for (int i = 0; i < nThreads; i++) scheduler.schedule(runnable); go.countDown(); try { scheduler.finished(); } catch (ConcurrentException e) { throw e.unwrap(); } } } }; } }
7,820
0
Create_ds/squaredev-graphql-pkce-demo/android/app/src/release/java/com
Create_ds/squaredev-graphql-pkce-demo/android/app/src/release/java/com/squaredevgraphqlpkce/ReactNativeFlipper.java
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * <p>This source code is licensed under the MIT license found in the LICENSE file in the root * directory of this source tree. */ package com.squaredevgraphqlpkce; import android.content.Context; import com.facebook.react.ReactInstanceManager; /** * Class responsible of loading Flipper inside your React Native application. This is the release * flavor of it so it's empty as we don't want to load Flipper. */ public class ReactNativeFlipper { public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { // Do nothing as we don't want to initialize Flipper on Release. } }
7,821
0
Create_ds/squaredev-graphql-pkce-demo/android/app/src/main/java/com
Create_ds/squaredev-graphql-pkce-demo/android/app/src/main/java/com/squaredevgraphqlpkce/MainApplication.java
package com.squaredevgraphqlpkce; import android.app.Application; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint; import com.facebook.react.defaults.DefaultReactNativeHost; import com.facebook.soloader.SoLoader; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new DefaultReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List<ReactPackage> packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } @Override protected boolean isNewArchEnabled() { return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; } @Override protected Boolean isHermesEnabled() { return BuildConfig.IS_HERMES_ENABLED; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { // If you opted-in for the New Architecture, we load the native entry point for this app. DefaultNewArchitectureEntryPoint.load(); } ReactNativeFlipper.initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); } }
7,822
0
Create_ds/squaredev-graphql-pkce-demo/android/app/src/main/java/com
Create_ds/squaredev-graphql-pkce-demo/android/app/src/main/java/com/squaredevgraphqlpkce/MainActivity.java
package com.squaredevgraphqlpkce; import com.facebook.react.ReactActivity; import com.facebook.react.ReactActivityDelegate; import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint; import com.facebook.react.defaults.DefaultReactActivityDelegate; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ @Override protected String getMainComponentName() { return "squaredevGraphqlPkce"; } /** * Returns the instance of the {@link ReactActivityDelegate}. Here we use a util class {@link * DefaultReactActivityDelegate} which allows you to easily enable Fabric and Concurrent React * (aka React 18) with two boolean flags. */ @Override protected ReactActivityDelegate createReactActivityDelegate() { return new DefaultReactActivityDelegate( this, getMainComponentName(), // If you opted-in for the New Architecture, we enable the Fabric Renderer. DefaultNewArchitectureEntryPoint.getFabricEnabled(), // fabricEnabled // If you opted-in for the New Architecture, we enable Concurrent React (i.e. React 18). DefaultNewArchitectureEntryPoint.getConcurrentReactEnabled() // concurrentRootEnabled ); } }
7,823
0
Create_ds/squaredev-graphql-pkce-demo/android/app/src/debug/java/com
Create_ds/squaredev-graphql-pkce-demo/android/app/src/debug/java/com/squaredevgraphqlpkce/ReactNativeFlipper.java
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * <p>This source code is licensed under the MIT license found in the LICENSE file in the root * directory of this source tree. */ package com.squaredevgraphqlpkce; import android.content.Context; import com.facebook.flipper.android.AndroidFlipperClient; import com.facebook.flipper.android.utils.FlipperUtils; import com.facebook.flipper.core.FlipperClient; import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin; import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin; import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin; import com.facebook.flipper.plugins.inspector.DescriptorMapping; import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin; import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor; import com.facebook.flipper.plugins.network.NetworkFlipperPlugin; import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin; import com.facebook.react.ReactInstanceEventListener; import com.facebook.react.ReactInstanceManager; import com.facebook.react.bridge.ReactContext; import com.facebook.react.modules.network.NetworkingModule; import okhttp3.OkHttpClient; /** * Class responsible of loading Flipper inside your React Native application. This is the debug * flavor of it. Here you can add your own plugins and customize the Flipper setup. */ public class ReactNativeFlipper { public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { if (FlipperUtils.shouldEnableFlipper(context)) { final FlipperClient client = AndroidFlipperClient.getInstance(context); client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults())); client.addPlugin(new DatabasesFlipperPlugin(context)); client.addPlugin(new SharedPreferencesFlipperPlugin(context)); client.addPlugin(CrashReporterPlugin.getInstance()); NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin(); NetworkingModule.setCustomClientBuilder( new NetworkingModule.CustomClientBuilder() { @Override public void apply(OkHttpClient.Builder builder) { builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); } }); client.addPlugin(networkFlipperPlugin); client.start(); // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized // Hence we run if after all native modules have been initialized ReactContext reactContext = reactInstanceManager.getCurrentReactContext(); if (reactContext == null) { reactInstanceManager.addReactInstanceEventListener( new ReactInstanceEventListener() { @Override public void onReactContextInitialized(ReactContext reactContext) { reactInstanceManager.removeReactInstanceEventListener(this); reactContext.runOnNativeModulesQueueThread( new Runnable() { @Override public void run() { client.addPlugin(new FrescoFlipperPlugin()); } }); } }); } else { client.addPlugin(new FrescoFlipperPlugin()); } } } }
7,824
0
Create_ds/eureka/eureka-server-governator/src/main/java/com/netflix
Create_ds/eureka/eureka-server-governator/src/main/java/com/netflix/eureka/EurekaContextListener.java
package com.netflix.eureka; import com.netflix.discovery.converters.JsonXStream; import com.netflix.discovery.converters.XmlXStream; import com.netflix.eureka.util.EurekaMonitors; import com.netflix.governator.LifecycleInjector; import com.netflix.governator.guice.servlet.GovernatorServletContextListener; import com.thoughtworks.xstream.XStream; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; /** * @author David Liu */ public class EurekaContextListener extends GovernatorServletContextListener { private EurekaServerContext serverContext; @Override public void contextInitialized(ServletContextEvent servletContextEvent) { super.contextInitialized(servletContextEvent); ServletContext sc = servletContextEvent.getServletContext(); sc.setAttribute(EurekaServerContext.class.getName(), serverContext); // Copy registry from neighboring eureka node int registryCount = serverContext.getRegistry().syncUp(); serverContext.getRegistry().openForTraffic(serverContext.getApplicationInfoManager(), registryCount); // Register all monitoring statistics. EurekaMonitors.registerAllStats(); } public void contextDestroyed(ServletContextEvent servletContextEvent) { EurekaMonitors.shutdown(); ServletContext sc = servletContextEvent.getServletContext(); sc.removeAttribute(EurekaServerContext.class.getName()); super.contextDestroyed(servletContextEvent); } @Override protected LifecycleInjector createInjector() { // For backward compatibility JsonXStream.getInstance().registerConverter(new V1AwareInstanceInfoConverter(), XStream.PRIORITY_VERY_HIGH); XmlXStream.getInstance().registerConverter(new V1AwareInstanceInfoConverter(), XStream.PRIORITY_VERY_HIGH); LifecycleInjector injector = EurekaInjectorCreator.createInjector(); serverContext = injector.getInstance(EurekaServerContext.class); return injector; } }
7,825
0
Create_ds/eureka/eureka-server-governator/src/main/java/com/netflix
Create_ds/eureka/eureka-server-governator/src/main/java/com/netflix/eureka/EurekaInjectorCreator.java
package com.netflix.eureka; import com.netflix.discovery.guice.EurekaModule; import com.netflix.eureka.guice.Ec2EurekaServerModule; import com.netflix.eureka.guice.LocalDevEurekaServerModule; import com.netflix.governator.InjectorBuilder; import com.netflix.governator.LifecycleInjector; import com.netflix.governator.ProvisionDebugModule; import com.sun.jersey.api.core.PackagesResourceConfig; 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.util.HashMap; import java.util.Map; /** * @author David Liu */ public class EurekaInjectorCreator { private static final Logger logger = LoggerFactory.getLogger(EurekaInjectorCreator.class); public static LifecycleInjector createInjector() { try { return InjectorBuilder .fromModules( new EurekaModule(), new Ec2EurekaServerModule(), new ProvisionDebugModule(), new JerseyServletModule() { @Override protected void configureServlets() { filter("/*").through(StatusFilter.class); filter("/*").through(ServerRequestAuthFilter.class); filter("/v2/apps", "/v2/apps/*").through(GzipEncodingEnforcingFilter.class); //filter("/*").through(RateLimitingFilter.class); // enable if needed // REST Map<String, String> params = new HashMap<String, String>(); params.put(PackagesResourceConfig.PROPERTY_PACKAGES, "com.sun.jersey"); params.put(PackagesResourceConfig.PROPERTY_PACKAGES, "com.netflix"); params.put("com.sun.jersey.config.property.WebPageContentRegex", "/(flex|images|js|css|jsp)/.*"); params.put("com.sun.jersey.spi.container.ContainerRequestFilters", "com.sun.jersey.api.container.filter.GZIPContentEncodingFilter"); params.put("com.sun.jersey.spi.container.ContainerResponseFilters", "com.sun.jersey.api.container.filter.GZIPContentEncodingFilter"); filter("/*").through(GuiceContainer.class, params); bind(GuiceContainer.class).asEagerSingleton(); } } ) .createInjector(); } catch (Exception e) { logger.error("Failed to create the injector", e); e.printStackTrace(); throw new RuntimeException(e); } } }
7,826
0
Create_ds/eureka/eureka-server-governator/src/main/java/com/netflix/eureka
Create_ds/eureka/eureka-server-governator/src/main/java/com/netflix/eureka/guice/LocalDevEurekaServerModule.java
package com.netflix.eureka.guice; import com.google.inject.AbstractModule; import com.google.inject.Scopes; import com.netflix.eureka.DefaultEurekaServerConfig; import com.netflix.eureka.DefaultEurekaServerContext; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.EurekaServerContext; import com.netflix.eureka.cluster.PeerEurekaNodes; import com.netflix.eureka.registry.AbstractInstanceRegistry; import com.netflix.eureka.registry.InstanceRegistry; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl; import com.netflix.eureka.resources.DefaultServerCodecs; import com.netflix.eureka.resources.ServerCodecs; /** * @author David Liu */ public class LocalDevEurekaServerModule extends AbstractModule { @Override protected void configure() { // server bindings bind(EurekaServerConfig.class).to(DefaultEurekaServerConfig.class).in(Scopes.SINGLETON); bind(PeerEurekaNodes.class).in(Scopes.SINGLETON); // registry and interfaces bind(PeerAwareInstanceRegistryImpl.class).asEagerSingleton(); bind(InstanceRegistry.class).to(PeerAwareInstanceRegistryImpl.class); bind(AbstractInstanceRegistry.class).to(PeerAwareInstanceRegistryImpl.class); bind(PeerAwareInstanceRegistry.class).to(PeerAwareInstanceRegistryImpl.class); bind(ServerCodecs.class).to(DefaultServerCodecs.class).in(Scopes.SINGLETON); bind(EurekaServerContext.class).to(DefaultEurekaServerContext.class).in(Scopes.SINGLETON); } @Override public boolean equals(Object obj) { return LocalDevEurekaServerModule.class.equals(obj.getClass()); } @Override public int hashCode() { return LocalDevEurekaServerModule.class.hashCode(); } }
7,827
0
Create_ds/eureka/eureka-server-governator/src/main/java/com/netflix/eureka
Create_ds/eureka/eureka-server-governator/src/main/java/com/netflix/eureka/guice/Ec2EurekaServerModule.java
package com.netflix.eureka.guice; import com.google.inject.AbstractModule; import com.google.inject.Scopes; import com.netflix.eureka.DefaultEurekaServerConfig; import com.netflix.eureka.DefaultEurekaServerContext; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.EurekaServerContext; import com.netflix.eureka.aws.AwsBinderDelegate; import com.netflix.eureka.cluster.PeerEurekaNodes; import com.netflix.eureka.registry.AbstractInstanceRegistry; import com.netflix.eureka.registry.AwsInstanceRegistry; import com.netflix.eureka.registry.InstanceRegistry; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import com.netflix.eureka.resources.DefaultServerCodecs; import com.netflix.eureka.resources.ServerCodecs; /** * @author David Liu */ public class Ec2EurekaServerModule extends AbstractModule { @Override protected void configure() { bind(EurekaServerConfig.class).to(DefaultEurekaServerConfig.class).in(Scopes.SINGLETON); bind(PeerEurekaNodes.class).in(Scopes.SINGLETON); bind(AwsBinderDelegate.class).asEagerSingleton(); // registry and interfaces bind(AwsInstanceRegistry.class).asEagerSingleton(); bind(InstanceRegistry.class).to(AwsInstanceRegistry.class); bind(AbstractInstanceRegistry.class).to(AwsInstanceRegistry.class); bind(PeerAwareInstanceRegistry.class).to(AwsInstanceRegistry.class); bind(ServerCodecs.class).to(DefaultServerCodecs.class).in(Scopes.SINGLETON); bind(EurekaServerContext.class).to(DefaultEurekaServerContext.class).in(Scopes.SINGLETON); } @Override public boolean equals(Object obj) { return Ec2EurekaServerModule.class.equals(obj.getClass()); } @Override public int hashCode() { return Ec2EurekaServerModule.class.hashCode(); } }
7,828
0
Create_ds/eureka/eureka-examples/src/main/java/com/netflix
Create_ds/eureka/eureka-examples/src/main/java/com/netflix/eureka/ExampleEurekaService.java
/* * Copyright 2012 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.eureka; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.EurekaClient; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.config.DynamicPropertyFactory; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.EurekaClientConfig; /** * Sample Eureka service that registers with Eureka to receive and process requests. * This example just receives one request and exits once it receives the request after processing it. * */ public class ExampleEurekaService { private static ApplicationInfoManager applicationInfoManager; private static EurekaClient eurekaClient; private static synchronized ApplicationInfoManager initializeApplicationInfoManager(EurekaInstanceConfig instanceConfig) { if (applicationInfoManager == null) { InstanceInfo instanceInfo = new EurekaConfigBasedInstanceInfoProvider(instanceConfig).get(); applicationInfoManager = new ApplicationInfoManager(instanceConfig, instanceInfo); } return applicationInfoManager; } private static synchronized EurekaClient initializeEurekaClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig clientConfig) { if (eurekaClient == null) { eurekaClient = new DiscoveryClient(applicationInfoManager, clientConfig); } return eurekaClient; } public static void main(String[] args) { DynamicPropertyFactory configInstance = com.netflix.config.DynamicPropertyFactory.getInstance(); ApplicationInfoManager applicationInfoManager = initializeApplicationInfoManager(new MyDataCenterInstanceConfig()); EurekaClient eurekaClient = initializeEurekaClient(applicationInfoManager, new DefaultEurekaClientConfig()); ExampleServiceBase exampleServiceBase = new ExampleServiceBase(applicationInfoManager, eurekaClient, configInstance); try { exampleServiceBase.start(); } finally { // the stop calls shutdown on eurekaClient exampleServiceBase.stop(); } } }
7,829
0
Create_ds/eureka/eureka-examples/src/main/java/com/netflix
Create_ds/eureka/eureka-examples/src/main/java/com/netflix/eureka/ExampleServiceBase.java
package com.netflix.eureka; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.InstanceInfo; import com.netflix.config.DynamicPropertyFactory; import com.netflix.discovery.EurekaClient; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Date; /** * An example service (that can be initialized in a variety of ways) that registers with eureka * and listens for REST calls on port 8001. */ @Singleton public class ExampleServiceBase { private final ApplicationInfoManager applicationInfoManager; private final EurekaClient eurekaClient; private final DynamicPropertyFactory configInstance; @Inject public ExampleServiceBase(ApplicationInfoManager applicationInfoManager, EurekaClient eurekaClient, DynamicPropertyFactory configInstance) { this.applicationInfoManager = applicationInfoManager; this.eurekaClient = eurekaClient; this.configInstance = configInstance; } @PostConstruct public void start() { // A good practice is to register as STARTING and only change status to UP // after the service is ready to receive traffic System.out.println("Registering service to eureka with STARTING status"); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.STARTING); System.out.println("Simulating service initialization by sleeping for 2 seconds..."); try { Thread.sleep(2000); } catch (InterruptedException e) { // Nothing } // Now we change our status to UP System.out.println("Done sleeping, now changing status to UP"); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UP); waitForRegistrationWithEureka(eurekaClient); System.out.println("Service started and ready to process requests.."); try { int myServingPort = applicationInfoManager.getInfo().getPort(); // read from my registered info ServerSocket serverSocket = new ServerSocket(myServingPort); final Socket s = serverSocket.accept(); System.out.println("Client got connected... processing request from the client"); processRequest(s); } catch (IOException e) { e.printStackTrace(); } System.out.println("Simulating service doing work by sleeping for " + 5 + " seconds..."); try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { // Nothing } } @PreDestroy public void stop() { if (eurekaClient != null) { System.out.println("Shutting down server. Demo over."); eurekaClient.shutdown(); } } private void waitForRegistrationWithEureka(EurekaClient eurekaClient) { // my vip address to listen on String vipAddress = configInstance.getStringProperty("eureka.vipAddress", "sampleservice.mydomain.net").get(); InstanceInfo nextServerInfo = null; while (nextServerInfo == null) { try { nextServerInfo = eurekaClient.getNextServerFromEureka(vipAddress, false); } catch (Throwable e) { System.out.println("Waiting ... verifying service registration with eureka ..."); try { Thread.sleep(10000); } catch (InterruptedException e1) { e1.printStackTrace(); } } } } private void processRequest(final Socket s) { try { BufferedReader rd = new BufferedReader(new InputStreamReader(s.getInputStream())); String line = rd.readLine(); if (line != null) { System.out.println("Received a request from the example client: " + line); } String response = "BAR " + new Date(); System.out.println("Sending the response to the client: " + response); PrintStream out = new PrintStream(s.getOutputStream()); out.println(response); } catch (Throwable e) { System.err.println("Error processing requests"); } finally { if (s != null) { try { s.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
7,830
0
Create_ds/eureka/eureka-examples/src/main/java/com/netflix
Create_ds/eureka/eureka-examples/src/main/java/com/netflix/eureka/ExampleEurekaGovernatedService.java
package com.netflix.eureka; import com.google.inject.AbstractModule; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.config.DynamicPropertyFactory; import com.netflix.discovery.guice.EurekaModule; import com.netflix.governator.InjectorBuilder; import com.netflix.governator.LifecycleInjector; /** * Sample Eureka service that registers with Eureka to receive and process requests, using EurekaModule. */ public class ExampleEurekaGovernatedService { static class ExampleServiceModule extends AbstractModule { @Override protected void configure() { bind(ExampleServiceBase.class).asEagerSingleton(); } } private static LifecycleInjector init() throws Exception { System.out.println("Creating injector for Example Service"); LifecycleInjector injector = InjectorBuilder .fromModules(new EurekaModule(), new ExampleServiceModule()) .overrideWith(new AbstractModule() { @Override protected void configure() { DynamicPropertyFactory configInstance = com.netflix.config.DynamicPropertyFactory.getInstance(); bind(DynamicPropertyFactory.class).toInstance(configInstance); // the default impl of EurekaInstanceConfig is CloudInstanceConfig, which we only want in an AWS // environment. Here we override that by binding MyDataCenterInstanceConfig to EurekaInstanceConfig. bind(EurekaInstanceConfig.class).to(MyDataCenterInstanceConfig.class); // (DiscoveryClient optional bindings) bind the optional event bus // bind(EventBus.class).to(EventBusImpl.class).in(Scopes.SINGLETON); } }) .createInjector(); System.out.println("Done creating the injector"); return injector; } public static void main(String[] args) throws Exception { LifecycleInjector injector = null; try { injector = init(); injector.awaitTermination(); } catch (Exception e) { System.out.println("Error starting the sample service: " + e); e.printStackTrace(); } finally { if (injector != null) { injector.shutdown(); } } } }
7,831
0
Create_ds/eureka/eureka-examples/src/main/java/com/netflix
Create_ds/eureka/eureka-examples/src/main/java/com/netflix/eureka/ExampleEurekaClient.java
/* * Copyright 2012 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.eureka; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.InetSocketAddress; import java.net.Socket; import java.util.Date; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; /** * Sample Eureka client that discovers the example service using Eureka and sends requests. * * In this example, the program tries to get the example from the EurekaClient, and then * makes a REST call to a supported service endpoint * */ public class ExampleEurekaClient { private static ApplicationInfoManager applicationInfoManager; private static EurekaClient eurekaClient; private static synchronized ApplicationInfoManager initializeApplicationInfoManager(EurekaInstanceConfig instanceConfig) { if (applicationInfoManager == null) { InstanceInfo instanceInfo = new EurekaConfigBasedInstanceInfoProvider(instanceConfig).get(); applicationInfoManager = new ApplicationInfoManager(instanceConfig, instanceInfo); } return applicationInfoManager; } private static synchronized EurekaClient initializeEurekaClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig clientConfig) { if (eurekaClient == null) { eurekaClient = new DiscoveryClient(applicationInfoManager, clientConfig); } return eurekaClient; } public void sendRequestToServiceUsingEureka(EurekaClient eurekaClient) { // initialize the client // this is the vip address for the example service to talk to as defined in conf/sample-eureka-service.properties String vipAddress = "sampleservice.mydomain.net"; InstanceInfo nextServerInfo = null; try { nextServerInfo = eurekaClient.getNextServerFromEureka(vipAddress, false); } catch (Exception e) { System.err.println("Cannot get an instance of example service to talk to from eureka"); System.exit(-1); } System.out.println("Found an instance of example service to talk to from eureka: " + nextServerInfo.getVIPAddress() + ":" + nextServerInfo.getPort()); System.out.println("healthCheckUrl: " + nextServerInfo.getHealthCheckUrl()); System.out.println("override: " + nextServerInfo.getOverriddenStatus()); Socket s = new Socket(); int serverPort = nextServerInfo.getPort(); try { s.connect(new InetSocketAddress(nextServerInfo.getHostName(), serverPort)); } catch (IOException e) { System.err.println("Could not connect to the server :" + nextServerInfo.getHostName() + " at port " + serverPort); } catch (Exception e) { System.err.println("Could not connect to the server :" + nextServerInfo.getHostName() + " at port " + serverPort + "due to Exception " + e); } try { String request = "FOO " + new Date(); System.out.println("Connected to server. Sending a sample request: " + request); PrintStream out = new PrintStream(s.getOutputStream()); out.println(request); System.out.println("Waiting for server response.."); BufferedReader rd = new BufferedReader(new InputStreamReader(s.getInputStream())); String str = rd.readLine(); if (str != null) { System.out.println("Received response from server: " + str); System.out.println("Exiting the client. Demo over.."); } rd.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { ExampleEurekaClient sampleClient = new ExampleEurekaClient(); // create the client ApplicationInfoManager applicationInfoManager = initializeApplicationInfoManager(new MyDataCenterInstanceConfig()); EurekaClient client = initializeEurekaClient(applicationInfoManager, new DefaultEurekaClientConfig()); // use the client sampleClient.sendRequestToServiceUsingEureka(client); // shutdown the client eurekaClient.shutdown(); } }
7,832
0
Create_ds/eureka/eureka-server/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-server/src/test/java/com/netflix/eureka/resources/EurekaClientServerRestIntegrationTest.java
package com.netflix.eureka.resources; import java.io.File; import java.io.FilenameFilter; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.shared.resolver.DefaultEndpoint; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.TransportClientFactory; import com.netflix.discovery.shared.transport.jersey.JerseyEurekaHttpClientFactory; import com.netflix.discovery.util.InstanceInfoGenerator; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.cluster.protocol.ReplicationInstance; import com.netflix.eureka.cluster.protocol.ReplicationInstanceResponse; import com.netflix.eureka.cluster.protocol.ReplicationList; import com.netflix.eureka.cluster.protocol.ReplicationListResponse; import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action; import com.netflix.eureka.transport.JerseyReplicationClient; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.webapp.WebAppContext; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Test REST layer of client/server communication. This test instantiates fully configured Jersey container, * which is essential to verifying content encoding/decoding with different format types (JSON vs XML, compressed vs * uncompressed). * * @author Tomasz Bak */ public class EurekaClientServerRestIntegrationTest { private static final String[] EUREKA1_WAR_DIRS = {"build/libs", "eureka-server/build/libs"}; private static final Pattern WAR_PATTERN = Pattern.compile("eureka-server.*.war"); private static EurekaServerConfig eurekaServerConfig; private static Server server; private static TransportClientFactory httpClientFactory; private static EurekaHttpClient jerseyEurekaClient; private static JerseyReplicationClient jerseyReplicationClient; /** * We do not include ASG data to prevent server from consulting AWS for its status. */ private static final InstanceInfoGenerator infoGenerator = InstanceInfoGenerator.newBuilder(10, 2).withAsg(false).build(); private static final Iterator<InstanceInfo> instanceInfoIt = infoGenerator.serviceIterator(); private static String eurekaServiceUrl; @BeforeClass public static void setUp() throws Exception { injectEurekaConfiguration(); startServer(); createEurekaServerConfig(); httpClientFactory = JerseyEurekaHttpClientFactory.newBuilder() .withClientName("testEurekaClient") .withConnectionTimeout(1000) .withReadTimeout(1000) .withMaxConnectionsPerHost(1) .withMaxTotalConnections(1) .withConnectionIdleTimeout(1000) .build(); jerseyEurekaClient = httpClientFactory.newClient(new DefaultEndpoint(eurekaServiceUrl)); ServerCodecs serverCodecs = new DefaultServerCodecs(eurekaServerConfig); jerseyReplicationClient = JerseyReplicationClient.createReplicationClient( eurekaServerConfig, serverCodecs, eurekaServiceUrl ); } @AfterClass public static void tearDown() throws Exception { removeEurekaConfiguration(); if (jerseyReplicationClient != null) { jerseyReplicationClient.shutdown(); } if (server != null) { server.stop(); } if (httpClientFactory != null) { httpClientFactory.shutdown(); } } @Test public void testRegistration() throws Exception { InstanceInfo instanceInfo = instanceInfoIt.next(); EurekaHttpResponse<Void> httpResponse = jerseyEurekaClient.register(instanceInfo); assertThat(httpResponse.getStatusCode(), is(equalTo(204))); } @Test public void testHeartbeat() throws Exception { // Register first InstanceInfo instanceInfo = instanceInfoIt.next(); jerseyEurekaClient.register(instanceInfo); // Now send heartbeat EurekaHttpResponse<InstanceInfo> heartBeatResponse = jerseyReplicationClient.sendHeartBeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null); assertThat(heartBeatResponse.getStatusCode(), is(equalTo(200))); assertThat(heartBeatResponse.getEntity(), is(nullValue())); } @Test public void testMissedHeartbeat() throws Exception { InstanceInfo instanceInfo = instanceInfoIt.next(); // Now send heartbeat EurekaHttpResponse<InstanceInfo> heartBeatResponse = jerseyReplicationClient.sendHeartBeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null); assertThat(heartBeatResponse.getStatusCode(), is(equalTo(404))); } @Test public void testCancelForEntryThatExists() throws Exception { // Register first InstanceInfo instanceInfo = instanceInfoIt.next(); jerseyEurekaClient.register(instanceInfo); // Now cancel EurekaHttpResponse<Void> httpResponse = jerseyEurekaClient.cancel(instanceInfo.getAppName(), instanceInfo.getId()); assertThat(httpResponse.getStatusCode(), is(equalTo(200))); } @Test public void testCancelForEntryThatDoesNotExist() throws Exception { // Now cancel InstanceInfo instanceInfo = instanceInfoIt.next(); EurekaHttpResponse<Void> httpResponse = jerseyEurekaClient.cancel(instanceInfo.getAppName(), instanceInfo.getId()); assertThat(httpResponse.getStatusCode(), is(equalTo(404))); } @Test public void testStatusOverrideUpdateAndDelete() throws Exception { // Register first InstanceInfo instanceInfo = instanceInfoIt.next(); jerseyEurekaClient.register(instanceInfo); // Now override status EurekaHttpResponse<Void> overrideUpdateResponse = jerseyEurekaClient.statusUpdate(instanceInfo.getAppName(), instanceInfo.getId(), InstanceStatus.DOWN, instanceInfo); assertThat(overrideUpdateResponse.getStatusCode(), is(equalTo(200))); InstanceInfo fetchedInstance = expectInstanceInfoInRegistry(instanceInfo); assertThat(fetchedInstance.getStatus(), is(equalTo(InstanceStatus.DOWN))); // Now remove override EurekaHttpResponse<Void> deleteOverrideResponse = jerseyEurekaClient.deleteStatusOverride(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo); assertThat(deleteOverrideResponse.getStatusCode(), is(equalTo(200))); fetchedInstance = expectInstanceInfoInRegistry(instanceInfo); assertThat(fetchedInstance.getStatus(), is(equalTo(InstanceStatus.UNKNOWN))); } @Test public void testBatch() throws Exception { InstanceInfo instanceInfo = instanceInfoIt.next(); ReplicationInstance replicationInstance = ReplicationInstance.replicationInstance() .withAction(Action.Register) .withAppName(instanceInfo.getAppName()) .withId(instanceInfo.getId()) .withInstanceInfo(instanceInfo) .withLastDirtyTimestamp(System.currentTimeMillis()) .withStatus(instanceInfo.getStatus().name()) .build(); EurekaHttpResponse<ReplicationListResponse> httpResponse = jerseyReplicationClient.submitBatchUpdates(new ReplicationList(replicationInstance)); assertThat(httpResponse.getStatusCode(), is(equalTo(200))); List<ReplicationInstanceResponse> replicationListResponse = httpResponse.getEntity().getResponseList(); assertThat(replicationListResponse.size(), is(equalTo(1))); assertThat(replicationListResponse.get(0).getStatusCode(), is(equalTo(200))); } private static InstanceInfo expectInstanceInfoInRegistry(InstanceInfo instanceInfo) { EurekaHttpResponse<InstanceInfo> queryResponse = jerseyEurekaClient.getInstance(instanceInfo.getAppName(), instanceInfo.getId()); assertThat(queryResponse.getStatusCode(), is(equalTo(200))); assertThat(queryResponse.getEntity(), is(notNullValue())); assertThat(queryResponse.getEntity().getId(), is(equalTo(instanceInfo.getId()))); return queryResponse.getEntity(); } /** * This will be read by server internal discovery client. We need to salience it. */ private static void injectEurekaConfiguration() throws UnknownHostException { String myHostName = InetAddress.getLocalHost().getHostName(); String myServiceUrl = "http://" + myHostName + ":8080/v2/"; System.setProperty("eureka.region", "default"); System.setProperty("eureka.name", "eureka"); System.setProperty("eureka.vipAddress", "eureka.mydomain.net"); System.setProperty("eureka.port", "8080"); System.setProperty("eureka.preferSameZone", "false"); System.setProperty("eureka.shouldUseDns", "false"); System.setProperty("eureka.shouldFetchRegistry", "false"); System.setProperty("eureka.serviceUrl.defaultZone", myServiceUrl); System.setProperty("eureka.serviceUrl.default.defaultZone", myServiceUrl); System.setProperty("eureka.awsAccessId", "fake_aws_access_id"); System.setProperty("eureka.awsSecretKey", "fake_aws_secret_key"); System.setProperty("eureka.numberRegistrySyncRetries", "0"); } private static void removeEurekaConfiguration() { } private static void startServer() throws Exception { File warFile = findWar(); server = new Server(8080); WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/"); webapp.setWar(warFile.getAbsolutePath()); server.setHandler(webapp); server.start(); eurekaServiceUrl = "http://localhost:8080/v2"; } private static File findWar() { File dir = null; for (String candidate : EUREKA1_WAR_DIRS) { File candidateFile = new File(candidate); if (candidateFile.exists()) { dir = candidateFile; break; } } if (dir == null) { throw new IllegalStateException("No directory found at any in any pre-configured location: " + Arrays.toString(EUREKA1_WAR_DIRS)); } File[] warFiles = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return WAR_PATTERN.matcher(name).matches(); } }); if (warFiles.length == 0) { throw new IllegalStateException("War file not found in directory " + dir); } if (warFiles.length > 1) { throw new IllegalStateException("Multiple war files found in directory " + dir + ": " + Arrays.toString(warFiles)); } return warFiles[0]; } private static void createEurekaServerConfig() { eurekaServerConfig = mock(EurekaServerConfig.class); // Cluster management related when(eurekaServerConfig.getPeerEurekaNodesUpdateIntervalMs()).thenReturn(1000); // Replication logic related when(eurekaServerConfig.shouldSyncWhenTimestampDiffers()).thenReturn(true); when(eurekaServerConfig.getMaxTimeForReplication()).thenReturn(1000); when(eurekaServerConfig.getMaxElementsInPeerReplicationPool()).thenReturn(10); when(eurekaServerConfig.getMinThreadsForPeerReplication()).thenReturn(1); when(eurekaServerConfig.getMaxThreadsForPeerReplication()).thenReturn(1); when(eurekaServerConfig.shouldBatchReplication()).thenReturn(true); // Peer node connectivity (used by JerseyReplicationClient) when(eurekaServerConfig.getPeerNodeTotalConnections()).thenReturn(1); when(eurekaServerConfig.getPeerNodeTotalConnectionsPerHost()).thenReturn(1); when(eurekaServerConfig.getPeerNodeConnectionIdleTimeoutSeconds()).thenReturn(1000); } }
7,833
0
Create_ds/eureka/eureka-client-jersey2/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client-jersey2/src/test/java/com/netflix/discovery/guice/Jersey2EurekaModuleTest.java
package com.netflix.discovery.guice; import com.google.inject.AbstractModule; import com.google.inject.Binding; import com.google.inject.Key; import com.google.inject.Scopes; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.providers.MyDataCenterInstanceConfigProvider; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.DiscoveryManager; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.transport.jersey.TransportClientFactories; import com.netflix.discovery.shared.transport.jersey2.Jersey2TransportClientFactories; import com.netflix.governator.InjectorBuilder; import com.netflix.governator.LifecycleInjector; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author David Liu */ public class Jersey2EurekaModuleTest { private LifecycleInjector injector; @Before public void setUp() throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.region", "default"); ConfigurationManager.getConfigInstance().setProperty("eureka.shouldFetchRegistry", "false"); ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "false"); ConfigurationManager.getConfigInstance().setProperty("eureka.serviceUrl.default", "http://localhost:8080/eureka/v2"); injector = InjectorBuilder .fromModule(new Jersey2EurekaModule()) .overrideWith(new AbstractModule() { @Override protected void configure() { // the default impl of EurekaInstanceConfig is CloudInstanceConfig, which we only want in an AWS // environment. Here we override that by binding MyDataCenterInstanceConfig to EurekaInstanceConfig. bind(EurekaInstanceConfig.class).toProvider(MyDataCenterInstanceConfigProvider.class).in(Scopes.SINGLETON); } }) .createInjector(); } @After public void tearDown() { if (injector != null) { injector.shutdown(); } ConfigurationManager.getConfigInstance().clear(); } @SuppressWarnings("deprecation") @Test public void testDI() { InstanceInfo instanceInfo = injector.getInstance(InstanceInfo.class); Assert.assertEquals(ApplicationInfoManager.getInstance().getInfo(), instanceInfo); EurekaClient eurekaClient = injector.getInstance(EurekaClient.class); DiscoveryClient discoveryClient = injector.getInstance(DiscoveryClient.class); Assert.assertEquals(DiscoveryManager.getInstance().getEurekaClient(), eurekaClient); Assert.assertEquals(DiscoveryManager.getInstance().getDiscoveryClient(), discoveryClient); Assert.assertEquals(eurekaClient, discoveryClient); EurekaClientConfig eurekaClientConfig = injector.getInstance(EurekaClientConfig.class); Assert.assertEquals(DiscoveryManager.getInstance().getEurekaClientConfig(), eurekaClientConfig); EurekaInstanceConfig eurekaInstanceConfig = injector.getInstance(EurekaInstanceConfig.class); Assert.assertEquals(DiscoveryManager.getInstance().getEurekaInstanceConfig(), eurekaInstanceConfig); Binding<TransportClientFactories> binding = injector.getExistingBinding(Key.get(TransportClientFactories.class)); Assert.assertNotNull(binding); // has a binding for jersey2 TransportClientFactories transportClientFactories = injector.getInstance(TransportClientFactories.class); Assert.assertTrue(transportClientFactories instanceof Jersey2TransportClientFactories); } }
7,834
0
Create_ds/eureka/eureka-client-jersey2/src/test/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client-jersey2/src/test/java/com/netflix/discovery/shared/transport/jersey2/AbstractJersey2EurekaHttpClientTest.java
/* * Copyright 2015 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.discovery.shared.transport.jersey2; import java.net.URI; import com.netflix.discovery.shared.resolver.DefaultEndpoint; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpClientCompatibilityTestSuite; import com.netflix.discovery.shared.transport.TransportClientFactory; import com.netflix.discovery.shared.transport.jersey2.Jersey2ApplicationClientFactory.Jersey2ApplicationClientFactoryBuilder; import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; import org.junit.After; /** * @author Tomasz Bak */ public class AbstractJersey2EurekaHttpClientTest extends EurekaHttpClientCompatibilityTestSuite { private AbstractJersey2EurekaHttpClient jersey2HttpClient; @Override @After public void tearDown() throws Exception { if (jersey2HttpClient != null) { jersey2HttpClient.shutdown(); } super.tearDown(); } @Override protected EurekaHttpClient getEurekaHttpClient(URI serviceURI) { Jersey2ApplicationClientFactoryBuilder factoryBuilder = Jersey2ApplicationClientFactory.newBuilder(); if (serviceURI.getUserInfo() != null) { factoryBuilder.withFeature(HttpAuthenticationFeature.basicBuilder().build()); } TransportClientFactory clientFactory = factoryBuilder.build(); jersey2HttpClient = (AbstractJersey2EurekaHttpClient) clientFactory.newClient(new DefaultEndpoint(serviceURI.toString())); return jersey2HttpClient; } }
7,835
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/Jersey2DiscoveryClientOptionalArgs.java
package com.netflix.discovery; import javax.ws.rs.client.ClientRequestFilter; /** * Jersey2 implementation of DiscoveryClientOptionalArgs that supports supplying {@link ClientRequestFilter} */ public class Jersey2DiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs<ClientRequestFilter> { }
7,836
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/guice/Jersey2EurekaModule.java
package com.netflix.discovery.guice; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Scopes; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.providers.CloudInstanceConfigProvider; import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider; import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.Jersey2DiscoveryClientOptionalArgs; import com.netflix.discovery.providers.DefaultEurekaClientConfigProvider; import com.netflix.discovery.shared.resolver.EndpointRandomizer; import com.netflix.discovery.shared.resolver.ResolverUtils; import com.netflix.discovery.shared.transport.jersey.TransportClientFactories; import com.netflix.discovery.shared.transport.jersey2.Jersey2TransportClientFactories; /** * @author David Liu */ public final class Jersey2EurekaModule extends AbstractModule { @Override protected void configure() { // need to eagerly initialize bind(ApplicationInfoManager.class).asEagerSingleton(); // // override these in additional modules if necessary with Modules.override() // bind(EurekaInstanceConfig.class).toProvider(CloudInstanceConfigProvider.class).in(Scopes.SINGLETON); bind(EurekaClientConfig.class).toProvider(DefaultEurekaClientConfigProvider.class).in(Scopes.SINGLETON); // this is the self instanceInfo used for registration purposes bind(InstanceInfo.class).toProvider(EurekaConfigBasedInstanceInfoProvider.class).in(Scopes.SINGLETON); bind(EurekaClient.class).to(DiscoveryClient.class).in(Scopes.SINGLETON); bind(EndpointRandomizer.class).toInstance(ResolverUtils::randomize); // jersey2 support bindings bind(AbstractDiscoveryClientOptionalArgs.class).to(Jersey2DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON); } @Provides public TransportClientFactories getTransportClientFactories() { return Jersey2TransportClientFactories.getInstance(); } @Override public boolean equals(Object obj) { return obj != null && getClass().equals(obj.getClass()); } @Override public int hashCode() { return getClass().hashCode(); } }
7,837
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport/jersey2/Jersey2TransportClientFactories.java
package com.netflix.discovery.shared.transport.jersey2; import java.util.Collection; import java.util.Optional; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.ws.rs.client.ClientRequestFilter; import com.netflix.appinfo.EurekaClientIdentity; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.resolver.EurekaEndpoint; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.TransportClientFactory; import com.netflix.discovery.shared.transport.decorator.MetricsCollectingEurekaHttpClient; import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient; import com.netflix.discovery.shared.transport.jersey.TransportClientFactories; public class Jersey2TransportClientFactories implements TransportClientFactories<ClientRequestFilter> { private static final Jersey2TransportClientFactories INSTANCE = new Jersey2TransportClientFactories(); public static Jersey2TransportClientFactories getInstance() { return INSTANCE; } @Override public TransportClientFactory newTransportClientFactory(final EurekaClientConfig clientConfig, final Collection<ClientRequestFilter> additionalFilters, final InstanceInfo myInstanceInfo) { return newTransportClientFactory(clientConfig, additionalFilters, myInstanceInfo, Optional.empty(), Optional.empty()); } @Override public TransportClientFactory newTransportClientFactory(EurekaClientConfig clientConfig, Collection<ClientRequestFilter> additionalFilters, InstanceInfo myInstanceInfo, Optional<SSLContext> sslContext, Optional<HostnameVerifier> hostnameVerifier) { final TransportClientFactory jerseyFactory = Jersey2ApplicationClientFactory.create( clientConfig, additionalFilters, myInstanceInfo, new EurekaClientIdentity(myInstanceInfo.getIPAddr(), "Jersey2DefaultClient"), sslContext, hostnameVerifier ); final TransportClientFactory metricsFactory = MetricsCollectingEurekaHttpClient.createFactory(jerseyFactory); return new TransportClientFactory() { @Override public EurekaHttpClient newClient(EurekaEndpoint serviceUrl) { return metricsFactory.newClient(serviceUrl); } @Override public void shutdown() { metricsFactory.shutdown(); jerseyFactory.shutdown(); } }; } @Override public TransportClientFactory newTransportClientFactory(Collection<ClientRequestFilter> additionalFilters, EurekaJerseyClient providedJerseyClient) { throw new UnsupportedOperationException(); } }
7,838
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport/jersey2/EurekaIdentityHeaderFilter.java
package com.netflix.discovery.shared.transport.jersey2; import java.io.IOException; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; import com.netflix.appinfo.AbstractEurekaIdentity; public class EurekaIdentityHeaderFilter implements ClientRequestFilter { private final AbstractEurekaIdentity authInfo; public EurekaIdentityHeaderFilter(AbstractEurekaIdentity authInfo) { this.authInfo = authInfo; } @Override public void filter(ClientRequestContext requestContext) throws IOException { if (authInfo != null) { requestContext.getHeaders().putSingle(AbstractEurekaIdentity.AUTH_NAME_HEADER_KEY, authInfo.getName()); requestContext.getHeaders().putSingle(AbstractEurekaIdentity.AUTH_VERSION_HEADER_KEY, authInfo.getVersion()); if (authInfo.getId() != null) { requestContext.getHeaders().putSingle(AbstractEurekaIdentity.AUTH_ID_HEADER_KEY, authInfo.getId()); } } } }
7,839
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport/jersey2/Jersey2EurekaIdentityHeaderFilter.java
package com.netflix.discovery.shared.transport.jersey2; import com.netflix.appinfo.AbstractEurekaIdentity; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; import java.io.IOException; public class Jersey2EurekaIdentityHeaderFilter implements ClientRequestFilter { private final AbstractEurekaIdentity authInfo; public Jersey2EurekaIdentityHeaderFilter(AbstractEurekaIdentity authInfo) { this.authInfo = authInfo; } @Override public void filter(ClientRequestContext requestContext) throws IOException { if (authInfo != null) { requestContext.getHeaders().putSingle(AbstractEurekaIdentity.AUTH_NAME_HEADER_KEY, authInfo.getName()); requestContext.getHeaders().putSingle(AbstractEurekaIdentity.AUTH_VERSION_HEADER_KEY, authInfo.getVersion()); if (authInfo.getId() != null) { requestContext.getHeaders().putSingle(AbstractEurekaIdentity.AUTH_ID_HEADER_KEY, authInfo.getId()); } } } }
7,840
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport/jersey2/Jersey2ApplicationClient.java
package com.netflix.discovery.shared.transport.jersey2; import javax.ws.rs.client.Client; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.core.MultivaluedMap; import java.util.List; import java.util.Map; /** * A version of Jersey2 {@link com.netflix.discovery.shared.transport.EurekaHttpClient} to be used by applications. * * @author David Liu */ public class Jersey2ApplicationClient extends AbstractJersey2EurekaHttpClient { private final MultivaluedMap<String, Object> additionalHeaders; public Jersey2ApplicationClient(Client jerseyClient, String serviceUrl, MultivaluedMap<String, Object> additionalHeaders) { super(jerseyClient, serviceUrl); this.additionalHeaders = additionalHeaders; } @Override protected void addExtraHeaders(Builder webResource) { if (additionalHeaders != null) { for (Map.Entry<String, List<Object>> entry: additionalHeaders.entrySet()) { webResource.header(entry.getKey(), entry.getValue()); } } } }
7,841
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport/jersey2/EurekaJersey2ClientImpl.java
package com.netflix.discovery.shared.transport.jersey2; import static com.netflix.discovery.util.DiscoveryBuildInfo.buildVersion; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyStore; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import org.apache.http.client.params.ClientPNames; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.params.CoreProtocolPNames; import org.glassfish.jersey.apache.connector.ApacheClientProperties; import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.discovery.converters.wrappers.CodecWrappers; import com.netflix.discovery.converters.wrappers.DecoderWrapper; import com.netflix.discovery.converters.wrappers.EncoderWrapper; import com.netflix.discovery.provider.DiscoveryJerseyProvider; import com.netflix.servo.monitor.BasicCounter; import com.netflix.servo.monitor.BasicTimer; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.monitor.Monitors; import com.netflix.servo.monitor.Stopwatch; /** * @author Tomasz Bak */ public class EurekaJersey2ClientImpl implements EurekaJersey2Client { private static final Logger s_logger = LoggerFactory.getLogger(EurekaJersey2ClientImpl.class); private static final int HTTP_CONNECTION_CLEANER_INTERVAL_MS = 30 * 1000; private static final String PROTOCOL = "https"; private static final String PROTOCOL_SCHEME = "SSL"; private static final int HTTPS_PORT = 443; private static final String KEYSTORE_TYPE = "JKS"; private final Client apacheHttpClient; private final ConnectionCleanerTask connectionCleanerTask; ClientConfig jerseyClientConfig; private final ScheduledExecutorService eurekaConnCleaner = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { private final AtomicInteger threadNumber = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r, "Eureka-Jersey2Client-Conn-Cleaner" + threadNumber.incrementAndGet()); thread.setDaemon(true); return thread; } }); public EurekaJersey2ClientImpl( int connectionTimeout, int readTimeout, final int connectionIdleTimeout, ClientConfig clientConfig) { try { jerseyClientConfig = clientConfig; jerseyClientConfig.register(DiscoveryJerseyProvider.class); // Disable json autodiscovery, since json (de)serialization is provided by DiscoveryJerseyProvider jerseyClientConfig.property(ClientProperties.JSON_PROCESSING_FEATURE_DISABLE, Boolean.TRUE); jerseyClientConfig.property(ClientProperties.MOXY_JSON_FEATURE_DISABLE, Boolean.TRUE); jerseyClientConfig.connectorProvider(new ApacheConnectorProvider()); jerseyClientConfig.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); jerseyClientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); apacheHttpClient = ClientBuilder.newClient(jerseyClientConfig); connectionCleanerTask = new ConnectionCleanerTask(connectionIdleTimeout); eurekaConnCleaner.scheduleWithFixedDelay( connectionCleanerTask, HTTP_CONNECTION_CLEANER_INTERVAL_MS, HTTP_CONNECTION_CLEANER_INTERVAL_MS, TimeUnit.MILLISECONDS); } catch (Throwable e) { throw new RuntimeException("Cannot create Jersey2 client", e); } } @Override public Client getClient() { return apacheHttpClient; } /** * Clean up resources. */ @Override public void destroyResources() { if (eurekaConnCleaner != null) { // Execute the connection cleaner one final time during shutdown eurekaConnCleaner.execute(connectionCleanerTask); eurekaConnCleaner.shutdown(); } if (apacheHttpClient != null) { apacheHttpClient.close(); } } public static class EurekaJersey2ClientBuilder { private boolean systemSSL; private String clientName; private int maxConnectionsPerHost; private int maxTotalConnections; private String trustStoreFileName; private String trustStorePassword; private String userAgent; private String proxyUserName; private String proxyPassword; private String proxyHost; private String proxyPort; private int connectionTimeout; private int readTimeout; private int connectionIdleTimeout; private EncoderWrapper encoderWrapper; private DecoderWrapper decoderWrapper; public EurekaJersey2ClientBuilder withClientName(String clientName) { this.clientName = clientName; return this; } public EurekaJersey2ClientBuilder withUserAgent(String userAgent) { this.userAgent = userAgent; return this; } public EurekaJersey2ClientBuilder withConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } public EurekaJersey2ClientBuilder withReadTimeout(int readTimeout) { this.readTimeout = readTimeout; return this; } public EurekaJersey2ClientBuilder withConnectionIdleTimeout(int connectionIdleTimeout) { this.connectionIdleTimeout = connectionIdleTimeout; return this; } public EurekaJersey2ClientBuilder withMaxConnectionsPerHost(int maxConnectionsPerHost) { this.maxConnectionsPerHost = maxConnectionsPerHost; return this; } public EurekaJersey2ClientBuilder withMaxTotalConnections(int maxTotalConnections) { this.maxTotalConnections = maxTotalConnections; return this; } public EurekaJersey2ClientBuilder withProxy(String proxyHost, String proxyPort, String user, String password) { this.proxyHost = proxyHost; this.proxyPort = proxyPort; this.proxyUserName = user; this.proxyPassword = password; return this; } public EurekaJersey2ClientBuilder withSystemSSLConfiguration() { this.systemSSL = true; return this; } public EurekaJersey2ClientBuilder withTrustStoreFile(String trustStoreFileName, String trustStorePassword) { this.trustStoreFileName = trustStoreFileName; this.trustStorePassword = trustStorePassword; return this; } public EurekaJersey2ClientBuilder withEncoder(String encoderName) { return this.withEncoderWrapper(CodecWrappers.getEncoder(encoderName)); } public EurekaJersey2ClientBuilder withEncoderWrapper(EncoderWrapper encoderWrapper) { this.encoderWrapper = encoderWrapper; return this; } public EurekaJersey2ClientBuilder withDecoder(String decoderName, String clientDataAccept) { return this.withDecoderWrapper(CodecWrappers.resolveDecoder(decoderName, clientDataAccept)); } public EurekaJersey2ClientBuilder withDecoderWrapper(DecoderWrapper decoderWrapper) { this.decoderWrapper = decoderWrapper; return this; } public EurekaJersey2Client build() { MyDefaultApacheHttpClient4Config config = new MyDefaultApacheHttpClient4Config(); try { return new EurekaJersey2ClientImpl( connectionTimeout, readTimeout, connectionIdleTimeout, config); } catch (Throwable e) { throw new RuntimeException("Cannot create Jersey client ", e); } } class MyDefaultApacheHttpClient4Config extends ClientConfig { MyDefaultApacheHttpClient4Config() { PoolingHttpClientConnectionManager cm; if (systemSSL) { cm = createSystemSslCM(); } else if (trustStoreFileName != null) { cm = createCustomSslCM(); } else { cm = new PoolingHttpClientConnectionManager(); } if (proxyHost != null) { addProxyConfiguration(); } DiscoveryJerseyProvider discoveryJerseyProvider = new DiscoveryJerseyProvider(encoderWrapper, decoderWrapper); // getSingletons().add(discoveryJerseyProvider); register(discoveryJerseyProvider); // Common properties to all clients cm.setDefaultMaxPerRoute(maxConnectionsPerHost); cm.setMaxTotal(maxTotalConnections); property(ApacheClientProperties.CONNECTION_MANAGER, cm); String fullUserAgentName = (userAgent == null ? clientName : userAgent) + "/v" + buildVersion(); property(CoreProtocolPNames.USER_AGENT, fullUserAgentName); // To pin a client to specific server in case redirect happens, we handle redirects directly // (see DiscoveryClient.makeRemoteCall methods). property(ClientProperties.FOLLOW_REDIRECTS, Boolean.FALSE); property(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE); } private void addProxyConfiguration() { if (proxyUserName != null && proxyPassword != null) { property(ClientProperties.PROXY_USERNAME, proxyUserName); property(ClientProperties.PROXY_PASSWORD, proxyPassword); } else { // Due to bug in apache client, user name/password must always be set. // Otherwise proxy configuration is ignored. property(ClientProperties.PROXY_USERNAME, "guest"); property(ClientProperties.PROXY_PASSWORD, "guest"); } property(ClientProperties.PROXY_URI, "http://" + proxyHost + ":" + proxyPort); } private PoolingHttpClientConnectionManager createSystemSslCM() { ConnectionSocketFactory socketFactory = SSLConnectionSocketFactory.getSystemSocketFactory(); Registry registry = RegistryBuilder.<ConnectionSocketFactory>create() .register(PROTOCOL, socketFactory) .build(); return new PoolingHttpClientConnectionManager(registry); } private PoolingHttpClientConnectionManager createCustomSslCM() { FileInputStream fin = null; try { SSLContext sslContext = SSLContext.getInstance(PROTOCOL_SCHEME); KeyStore sslKeyStore = KeyStore.getInstance(KEYSTORE_TYPE); fin = new FileInputStream(trustStoreFileName); sslKeyStore.load(fin, trustStorePassword.toCharArray()); TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init(sslKeyStore); TrustManager[] trustManagers = factory.getTrustManagers(); sslContext.init(null, trustManagers, null); ConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Registry registry = RegistryBuilder.<ConnectionSocketFactory>create() .register(PROTOCOL, socketFactory) .build(); return new PoolingHttpClientConnectionManager(registry); } catch (Exception ex) { throw new IllegalStateException("SSL configuration issue", ex); } finally { if (fin != null) { try { fin.close(); } catch (IOException ignore) { } } } } } } private class ConnectionCleanerTask implements Runnable { private final int connectionIdleTimeout; private final BasicTimer executionTimeStats; private final Counter cleanupFailed; private ConnectionCleanerTask(int connectionIdleTimeout) { this.connectionIdleTimeout = connectionIdleTimeout; MonitorConfig.Builder monitorConfigBuilder = MonitorConfig.builder("Eureka-Connection-Cleaner-Time"); executionTimeStats = new BasicTimer(monitorConfigBuilder.build()); cleanupFailed = new BasicCounter(MonitorConfig.builder("Eureka-Connection-Cleaner-Failure").build()); try { Monitors.registerObject(this); } catch (Exception e) { s_logger.error("Unable to register with servo.", e); } } @Override public void run() { Stopwatch start = executionTimeStats.start(); try { HttpClientConnectionManager cm = (HttpClientConnectionManager) apacheHttpClient .getConfiguration() .getProperty(ApacheClientProperties.CONNECTION_MANAGER); cm.closeIdleConnections(connectionIdleTimeout, TimeUnit.SECONDS); } catch (Throwable e) { s_logger.error("Cannot clean connections", e); cleanupFailed.increment(); } finally { if (null != start) { start.stop(); } } } } }
7,842
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport/jersey2/AbstractJersey2EurekaHttpClient.java
/* * Copyright 2015 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.discovery.shared.transport.jersey2; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.EurekaHttpResponse.EurekaHttpResponseBuilder; import com.netflix.discovery.util.StringUtil; import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; /** * @author Tomasz Bak */ public abstract class AbstractJersey2EurekaHttpClient implements EurekaHttpClient { private static final Logger logger = LoggerFactory.getLogger(AbstractJersey2EurekaHttpClient.class); protected final Client jerseyClient; protected final String serviceUrl; private final String userName; private final String password; public AbstractJersey2EurekaHttpClient(Client jerseyClient, String serviceUrl) { this.jerseyClient = jerseyClient; this.serviceUrl = serviceUrl; // Jersey2 does not read credentials from the URI. We extract it here and enable authentication feature. String localUserName = null; String localPassword = null; try { URI serviceURI = new URI(serviceUrl); if (serviceURI.getUserInfo() != null) { String[] credentials = serviceURI.getUserInfo().split(":"); if (credentials.length == 2) { localUserName = credentials[0]; localPassword = credentials[1]; } } } catch (URISyntaxException ignore) { } this.userName = localUserName; this.password = localPassword; } @Override public EurekaHttpResponse<Void> register(InstanceInfo info) { String urlPath = "apps/" + info.getAppName(); Response response = null; try { Builder resourceBuilder = jerseyClient.target(serviceUrl).path(urlPath).request(); addExtraProperties(resourceBuilder); addExtraHeaders(resourceBuilder); response = resourceBuilder .accept(MediaType.APPLICATION_JSON) .acceptEncoding("gzip") .post(Entity.json(info)); return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP POST {}/{} with instance {}; statusCode={}", serviceUrl, urlPath, info.getId(), response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<Void> cancel(String appName, String id) { String urlPath = "apps/" + appName + '/' + id; Response response = null; try { Builder resourceBuilder = jerseyClient.target(serviceUrl).path(urlPath).request(); addExtraProperties(resourceBuilder); addExtraHeaders(resourceBuilder); response = resourceBuilder.delete(); return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP DELETE {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) { String urlPath = "apps/" + appName + '/' + id; Response response = null; try { WebTarget webResource = jerseyClient.target(serviceUrl) .path(urlPath) .queryParam("status", info.getStatus().toString()) .queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString()); if (overriddenStatus != null) { webResource = webResource.queryParam("overriddenstatus", overriddenStatus.name()); } Builder requestBuilder = webResource.request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE); response = requestBuilder.put(Entity.entity("{}", MediaType.APPLICATION_JSON_TYPE)); // Jersey2 refuses to handle PUT with no body EurekaHttpResponseBuilder<InstanceInfo> eurekaResponseBuilder = anEurekaHttpResponse(response.getStatus(), InstanceInfo.class).headers(headersOf(response)); if (response.hasEntity()) { eurekaResponseBuilder.entity(response.readEntity(InstanceInfo.class)); } return eurekaResponseBuilder.build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP PUT {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<Void> statusUpdate(String appName, String id, InstanceStatus newStatus, InstanceInfo info) { String urlPath = "apps/" + appName + '/' + id + "/status"; Response response = null; try { Builder requestBuilder = jerseyClient.target(serviceUrl) .path(urlPath) .queryParam("value", newStatus.name()) .queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString()) .request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); response = requestBuilder.put(Entity.entity("{}", MediaType.APPLICATION_JSON_TYPE)); // Jersey2 refuses to handle PUT with no body return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP PUT {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<Void> deleteStatusOverride(String appName, String id, InstanceInfo info) { String urlPath = "apps/" + appName + '/' + id + "/status"; Response response = null; try { Builder requestBuilder = jerseyClient.target(serviceUrl) .path(urlPath) .queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString()) .request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); response = requestBuilder.delete(); return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP DELETE {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<Applications> getApplications(String... regions) { return getApplicationsInternal("apps/", regions); } @Override public EurekaHttpResponse<Applications> getDelta(String... regions) { return getApplicationsInternal("apps/delta", regions); } @Override public EurekaHttpResponse<Applications> getVip(String vipAddress, String... regions) { return getApplicationsInternal("vips/" + vipAddress, regions); } @Override public EurekaHttpResponse<Applications> getSecureVip(String secureVipAddress, String... regions) { return getApplicationsInternal("svips/" + secureVipAddress, regions); } @Override public EurekaHttpResponse<Application> getApplication(String appName) { String urlPath = "apps/" + appName; Response response = null; try { Builder requestBuilder = jerseyClient.target(serviceUrl).path(urlPath).request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).get(); Application application = null; if (response.getStatus() == Status.OK.getStatusCode() && response.hasEntity()) { application = response.readEntity(Application.class); } return anEurekaHttpResponse(response.getStatus(), application).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP GET {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } private EurekaHttpResponse<Applications> getApplicationsInternal(String urlPath, String[] regions) { Response response = null; try { WebTarget webTarget = jerseyClient.target(serviceUrl).path(urlPath); if (regions != null && regions.length > 0) { webTarget = webTarget.queryParam("regions", StringUtil.join(regions)); } Builder requestBuilder = webTarget.request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).get(); Applications applications = null; if (response.getStatus() == Status.OK.getStatusCode() && response.hasEntity()) { applications = response.readEntity(Applications.class); } return anEurekaHttpResponse(response.getStatus(), applications).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP GET {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<InstanceInfo> getInstance(String id) { return getInstanceInternal("instances/" + id); } @Override public EurekaHttpResponse<InstanceInfo> getInstance(String appName, String id) { return getInstanceInternal("apps/" + appName + '/' + id); } private EurekaHttpResponse<InstanceInfo> getInstanceInternal(String urlPath) { Response response = null; try { Builder requestBuilder = jerseyClient.target(serviceUrl).path(urlPath).request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).get(); InstanceInfo infoFromPeer = null; if (response.getStatus() == Status.OK.getStatusCode() && response.hasEntity()) { infoFromPeer = response.readEntity(InstanceInfo.class); } return anEurekaHttpResponse(response.getStatus(), infoFromPeer).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP GET {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public void shutdown() { } protected void addExtraProperties(Builder webResource) { if (userName != null) { webResource.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, userName) .property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, password); } } protected abstract void addExtraHeaders(Builder webResource); private static Map<String, String> headersOf(Response response) { MultivaluedMap<String, String> jerseyHeaders = response.getStringHeaders(); if (jerseyHeaders == null || jerseyHeaders.isEmpty()) { return Collections.emptyMap(); } Map<String, String> headers = new HashMap<>(); for (Entry<String, List<String>> entry : jerseyHeaders.entrySet()) { if (!entry.getValue().isEmpty()) { headers.put(entry.getKey(), entry.getValue().get(0)); } } return headers; } }
7,843
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport/jersey2/EurekaJersey2Client.java
package com.netflix.discovery.shared.transport.jersey2; import javax.ws.rs.client.Client; /** * @author David Liu */ public interface EurekaJersey2Client { Client getClient(); /** * Clean up resources. */ void destroyResources(); }
7,844
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport/jersey2/Jersey2ApplicationClientFactory.java
/* * Copyright 2015 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.discovery.shared.transport.jersey2; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; import javax.ws.rs.core.Feature; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyStore; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import com.netflix.appinfo.AbstractEurekaIdentity; import com.netflix.appinfo.EurekaAccept; import com.netflix.appinfo.EurekaClientIdentity; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.provider.DiscoveryJerseyProvider; import com.netflix.discovery.shared.resolver.EurekaEndpoint; import com.netflix.discovery.shared.transport.EurekaClientFactoryBuilder; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.TransportClientFactory; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.JerseyClient; import org.glassfish.jersey.message.GZipEncoder; import static com.netflix.discovery.util.DiscoveryBuildInfo.buildVersion; /** * @author Tomasz Bak */ public class Jersey2ApplicationClientFactory implements TransportClientFactory { public static final String HTTP_X_DISCOVERY_ALLOW_REDIRECT = "X-Discovery-AllowRedirect"; private static final String KEY_STORE_TYPE = "JKS"; private final Client jersey2Client; private final MultivaluedMap<String, Object> additionalHeaders; public Jersey2ApplicationClientFactory(Client jersey2Client, MultivaluedMap<String, Object> additionalHeaders) { this.jersey2Client = jersey2Client; this.additionalHeaders = additionalHeaders; } @Override public EurekaHttpClient newClient(EurekaEndpoint endpoint) { return new Jersey2ApplicationClient(jersey2Client, endpoint.getServiceUrl(), additionalHeaders); } @Override public void shutdown() { jersey2Client.close(); } public static Jersey2ApplicationClientFactory create(EurekaClientConfig clientConfig, Collection<ClientRequestFilter> additionalFilters, InstanceInfo myInstanceInfo, AbstractEurekaIdentity clientIdentity) { return create(clientConfig, additionalFilters, myInstanceInfo, clientIdentity, Optional.empty(), Optional.empty()); } public static Jersey2ApplicationClientFactory create(EurekaClientConfig clientConfig, Collection<ClientRequestFilter> additionalFilters, InstanceInfo myInstanceInfo, AbstractEurekaIdentity clientIdentity, Optional<SSLContext> sslContext, Optional<HostnameVerifier> hostnameVerifier) { Jersey2ApplicationClientFactoryBuilder clientBuilder = newBuilder(); clientBuilder.withAdditionalFilters(additionalFilters); clientBuilder.withMyInstanceInfo(myInstanceInfo); clientBuilder.withUserAgent("Java-EurekaClient"); clientBuilder.withClientConfig(clientConfig); clientBuilder.withClientIdentity(clientIdentity); sslContext.ifPresent(clientBuilder::withSSLContext); hostnameVerifier.ifPresent(clientBuilder::withHostnameVerifier); if ("true".equals(System.getProperty("com.netflix.eureka.shouldSSLConnectionsUseSystemSocketFactory"))) { clientBuilder.withClientName("DiscoveryClient-HTTPClient-System").withSystemSSLConfiguration(); } else if (clientConfig.getProxyHost() != null && clientConfig.getProxyPort() != null) { clientBuilder.withClientName("Proxy-DiscoveryClient-HTTPClient") .withProxy( clientConfig.getProxyHost(), Integer.parseInt(clientConfig.getProxyPort()), clientConfig.getProxyUserName(), clientConfig.getProxyPassword()); } else { clientBuilder.withClientName("DiscoveryClient-HTTPClient"); } return clientBuilder.build(); } public static Jersey2ApplicationClientFactoryBuilder newBuilder() { return new Jersey2ApplicationClientFactoryBuilder(); } public static class Jersey2ApplicationClientFactoryBuilder extends EurekaClientFactoryBuilder<Jersey2ApplicationClientFactory, Jersey2ApplicationClientFactoryBuilder> { private List<Feature> features = new ArrayList<>(); private List<ClientRequestFilter> additionalFilters = new ArrayList<>(); public Jersey2ApplicationClientFactoryBuilder withFeature(Feature feature) { features.add(feature); return this; } Jersey2ApplicationClientFactoryBuilder withAdditionalFilters(Collection<ClientRequestFilter> additionalFilters) { if (additionalFilters != null) { this.additionalFilters.addAll(additionalFilters); } return this; } @Override public Jersey2ApplicationClientFactory build() { ClientBuilder clientBuilder = ClientBuilder.newBuilder(); ClientConfig clientConfig = new ClientConfig(); for (ClientRequestFilter filter : additionalFilters) { clientConfig.register(filter); } for (Feature feature : features) { clientConfig.register(feature); } addProviders(clientConfig); addSSLConfiguration(clientBuilder); addProxyConfiguration(clientConfig); if (hostnameVerifier != null) { clientBuilder.hostnameVerifier(hostnameVerifier); } // Common properties to all clients final String fullUserAgentName = (userAgent == null ? clientName : userAgent) + "/v" + buildVersion(); clientBuilder.register(new ClientRequestFilter() { // Can we do it better, without filter? @Override public void filter(ClientRequestContext requestContext) { requestContext.getHeaders().put(HttpHeaders.USER_AGENT, Collections.<Object>singletonList(fullUserAgentName)); } }); clientConfig.property(ClientProperties.FOLLOW_REDIRECTS, allowRedirect); clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); clientConfig.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); clientBuilder.withConfig(clientConfig); // Add gzip content encoding support clientBuilder.register(new GZipEncoder()); // always enable client identity headers String ip = myInstanceInfo == null ? null : myInstanceInfo.getIPAddr(); final AbstractEurekaIdentity identity = clientIdentity == null ? new EurekaClientIdentity(ip) : clientIdentity; clientBuilder.register(new Jersey2EurekaIdentityHeaderFilter(identity)); JerseyClient jersey2Client = (JerseyClient) clientBuilder.build(); MultivaluedMap<String, Object> additionalHeaders = new MultivaluedHashMap<>(); if (allowRedirect) { additionalHeaders.add(HTTP_X_DISCOVERY_ALLOW_REDIRECT, "true"); } if (EurekaAccept.compact == eurekaAccept) { additionalHeaders.add(EurekaAccept.HTTP_X_EUREKA_ACCEPT, eurekaAccept.name()); } return new Jersey2ApplicationClientFactory(jersey2Client, additionalHeaders); } private void addSSLConfiguration(ClientBuilder clientBuilder) { FileInputStream fin = null; try { if (systemSSL) { clientBuilder.sslContext(SSLContext.getDefault()); } else if (trustStoreFileName != null) { KeyStore trustStore = KeyStore.getInstance(KEY_STORE_TYPE); fin = new FileInputStream(trustStoreFileName); trustStore.load(fin, trustStorePassword.toCharArray()); clientBuilder.trustStore(trustStore); } else if (sslContext != null) { clientBuilder.sslContext(sslContext); } } catch (Exception ex) { throw new IllegalArgumentException("Cannot setup SSL for Jersey2 client", ex); } finally { if (fin != null) { try { fin.close(); } catch (IOException ignore) { } } } } private void addProxyConfiguration(ClientConfig clientConfig) { if (proxyHost != null) { String proxyAddress = proxyHost; if (proxyPort > 0) { proxyAddress += ':' + proxyPort; } clientConfig.property(ClientProperties.PROXY_URI, proxyAddress); if (proxyUserName != null) { if (proxyPassword == null) { throw new IllegalArgumentException("Proxy user name provided but not password"); } clientConfig.property(ClientProperties.PROXY_USERNAME, proxyUserName); clientConfig.property(ClientProperties.PROXY_PASSWORD, proxyPassword); } } } private void addProviders(ClientConfig clientConfig) { DiscoveryJerseyProvider discoveryJerseyProvider = new DiscoveryJerseyProvider(encoderWrapper, decoderWrapper); clientConfig.register(discoveryJerseyProvider); // Disable json autodiscovery, since json (de)serialization is provided by DiscoveryJerseyProvider clientConfig.property(ClientProperties.JSON_PROCESSING_FEATURE_DISABLE, Boolean.TRUE); clientConfig.property(ClientProperties.MOXY_JSON_FEATURE_DISABLE, Boolean.TRUE); } } }
7,845
0
Create_ds/eureka/eureka-core-jersey2/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core-jersey2/src/test/java/com/netflix/eureka/transport/Jersey2ReplicationClientTest.java
package com.netflix.eureka.transport; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response.Status; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.GZIPOutputStream; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.converters.EurekaJacksonCodec; import com.netflix.discovery.shared.transport.ClusterSampleData; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.eureka.DefaultEurekaServerConfig; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.cluster.PeerEurekaNode; import com.netflix.eureka.resources.ASGResource.ASGStatus; import com.netflix.eureka.resources.DefaultServerCodecs; import com.netflix.eureka.resources.ServerCodecs; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockserver.client.server.MockServerClient; import org.mockserver.junit.MockServerRule; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; /** * Ideally we would test client/server REST layer together as an integration test, where server side has mocked * service layer. Right now server side REST has to much logic, so this test would be equal to testing everything. * Here we test only client side REST communication. * * @author Tomasz Bak */ public class Jersey2ReplicationClientTest { @Rule public MockServerRule serverMockRule = new MockServerRule(this); private MockServerClient serverMockClient; private Jersey2ReplicationClient replicationClient; private final EurekaServerConfig config = new DefaultEurekaServerConfig(); private final ServerCodecs serverCodecs = new DefaultServerCodecs(config); private final InstanceInfo instanceInfo = ClusterSampleData.newInstanceInfo(1); @Before public void setUp() throws Exception { replicationClient = Jersey2ReplicationClient.createReplicationClient( config, serverCodecs, "http://localhost:" + serverMockRule.getHttpPort() + "/eureka/v2" ); } @After public void tearDown() { if (serverMockClient != null) { serverMockClient.reset(); } } @Test public void testRegistrationReplication() throws Exception { serverMockClient.when( request() .withMethod("POST") .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true")) .withPath("/eureka/v2/apps/" + instanceInfo.getAppName()) ).respond( response().withStatusCode(200) ); EurekaHttpResponse<Void> response = replicationClient.register(instanceInfo); assertThat(response.getStatusCode(), is(equalTo(200))); } @Test public void testCancelReplication() throws Exception { serverMockClient.when( request() .withMethod("DELETE") .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true")) .withPath("/eureka/v2/apps/" + instanceInfo.getAppName() + '/' + instanceInfo.getId()) ).respond( response().withStatusCode(204) ); EurekaHttpResponse<Void> response = replicationClient.cancel(instanceInfo.getAppName(), instanceInfo.getId()); assertThat(response.getStatusCode(), is(equalTo(204))); } @Test public void testHeartbeatReplicationWithNoResponseBody() throws Exception { serverMockClient.when( request() .withMethod("PUT") .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true")) .withPath("/eureka/v2/apps/" + instanceInfo.getAppName() + '/' + instanceInfo.getId()) ).respond( response().withStatusCode(200) ); EurekaHttpResponse<InstanceInfo> response = replicationClient.sendHeartBeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, InstanceStatus.DOWN); assertThat(response.getStatusCode(), is(equalTo(200))); assertThat(response.getEntity(), is(nullValue())); } @Test public void testHeartbeatReplicationWithResponseBody() throws Exception { InstanceInfo remoteInfo = new InstanceInfo(this.instanceInfo); remoteInfo.setStatus(InstanceStatus.DOWN); byte[] responseBody = toGzippedJson(remoteInfo); serverMockClient.when( request() .withMethod("PUT") .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true")) .withPath("/eureka/v2/apps/" + this.instanceInfo.getAppName() + '/' + this.instanceInfo.getId()) ).respond( response() .withStatusCode(Status.CONFLICT.getStatusCode()) .withHeader(header("Content-Type", MediaType.APPLICATION_JSON)) .withHeader(header("Content-Encoding", "gzip")) .withBody(responseBody) ); EurekaHttpResponse<InstanceInfo> response = replicationClient.sendHeartBeat(this.instanceInfo.getAppName(), this.instanceInfo.getId(), this.instanceInfo, null); assertThat(response.getStatusCode(), is(equalTo(Status.CONFLICT.getStatusCode()))); assertThat(response.getEntity(), is(notNullValue())); } @Test public void testAsgStatusUpdateReplication() throws Exception { serverMockClient.when( request() .withMethod("PUT") .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true")) .withPath("/eureka/v2/asg/" + instanceInfo.getASGName() + "/status") ).respond( response().withStatusCode(200) ); EurekaHttpResponse<Void> response = replicationClient.statusUpdate(instanceInfo.getASGName(), ASGStatus.ENABLED); assertThat(response.getStatusCode(), is(equalTo(200))); } @Test public void testStatusUpdateReplication() throws Exception { serverMockClient.when( request() .withMethod("PUT") .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true")) .withPath("/eureka/v2/apps/" + instanceInfo.getAppName() + '/' + instanceInfo.getId() + "/status") ).respond( response().withStatusCode(200) ); EurekaHttpResponse<Void> response = replicationClient.statusUpdate(instanceInfo.getAppName(), instanceInfo.getId(), InstanceStatus.DOWN, instanceInfo); assertThat(response.getStatusCode(), is(equalTo(200))); } @Test public void testDeleteStatusOverrideReplication() throws Exception { serverMockClient.when( request() .withMethod("DELETE") .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true")) .withPath("/eureka/v2/apps/" + instanceInfo.getAppName() + '/' + instanceInfo.getId() + "/status") ).respond( response().withStatusCode(204) ); EurekaHttpResponse<Void> response = replicationClient.deleteStatusOverride(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo); assertThat(response.getStatusCode(), is(equalTo(204))); } private static byte[] toGzippedJson(InstanceInfo remoteInfo) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(bos); EurekaJacksonCodec.getInstance().writeTo(remoteInfo, gos); gos.flush(); return bos.toByteArray(); } }
7,846
0
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka/Jersey2EurekaBootStrap.java
package com.netflix.eureka; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.eureka.cluster.Jersey2PeerEurekaNodes; import com.netflix.eureka.cluster.PeerEurekaNodes; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import com.netflix.eureka.resources.ServerCodecs; /** * Jersey2 eureka server bootstrapper * @author Matt Nelson */ public class Jersey2EurekaBootStrap extends EurekaBootStrap { public Jersey2EurekaBootStrap(DiscoveryClient discoveryClient) { super(discoveryClient); } @Override protected PeerEurekaNodes getPeerEurekaNodes(PeerAwareInstanceRegistry registry, EurekaServerConfig eurekaServerConfig, EurekaClientConfig eurekaClientConfig, ServerCodecs serverCodecs, ApplicationInfoManager applicationInfoManager) { PeerEurekaNodes peerEurekaNodes = new Jersey2PeerEurekaNodes( registry, eurekaServerConfig, eurekaClientConfig, serverCodecs, applicationInfoManager ); return peerEurekaNodes; } }
7,847
0
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka/cluster/Jersey2PeerEurekaNodes.java
package com.netflix.eureka.cluster; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.discovery.EurekaClientConfig; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import com.netflix.eureka.resources.ServerCodecs; import com.netflix.eureka.transport.Jersey2ReplicationClient; /** * Jersey2 implementation of PeerEurekaNodes that uses the Jersey2 replication client * @author Matt Nelson */ public class Jersey2PeerEurekaNodes extends PeerEurekaNodes { public Jersey2PeerEurekaNodes(PeerAwareInstanceRegistry registry, EurekaServerConfig serverConfig, EurekaClientConfig clientConfig, ServerCodecs serverCodecs, ApplicationInfoManager applicationInfoManager) { super(registry, serverConfig, clientConfig, serverCodecs, applicationInfoManager); } @Override protected PeerEurekaNode createPeerEurekaNode(String peerEurekaNodeUrl) { HttpReplicationClient replicationClient = Jersey2ReplicationClient.createReplicationClient(serverConfig, serverCodecs, peerEurekaNodeUrl); String targetHost = hostFromUrl(peerEurekaNodeUrl); if (targetHost == null) { targetHost = "host"; } return new PeerEurekaNode(registry, targetHost, peerEurekaNodeUrl, replicationClient, serverConfig); } }
7,848
0
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka/transport/Jersey2DynamicGZIPContentEncodingFilter.java
package com.netflix.eureka.transport; import com.netflix.eureka.EurekaServerConfig; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; import javax.ws.rs.client.ClientResponseContext; import javax.ws.rs.client.ClientResponseFilter; import javax.ws.rs.core.HttpHeaders; import java.io.IOException; public class Jersey2DynamicGZIPContentEncodingFilter implements ClientRequestFilter, ClientResponseFilter { private final EurekaServerConfig config; public Jersey2DynamicGZIPContentEncodingFilter(EurekaServerConfig config) { this.config = config; } @Override public void filter(ClientRequestContext requestContext) throws IOException { if (!requestContext.getHeaders().containsKey(HttpHeaders.ACCEPT_ENCODING)) { requestContext.getHeaders().add(HttpHeaders.ACCEPT_ENCODING, "gzip"); } if (hasEntity(requestContext) && isCompressionEnabled()) { Object contentEncoding = requestContext.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING); if (!"gzip".equals(contentEncoding)) { requestContext.getHeaders().add(HttpHeaders.CONTENT_ENCODING, "gzip"); } } } @Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { Object contentEncoding = responseContext.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING); if ("gzip".equals(contentEncoding)) { responseContext.getHeaders().remove(HttpHeaders.CONTENT_ENCODING); } } private boolean hasEntity(ClientRequestContext requestContext) { return false; } private boolean isCompressionEnabled() { return config.shouldEnableReplicatedRequestCompression(); } }
7,849
0
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka/transport/Jersey2ReplicationClient.java
package com.netflix.eureka.transport; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.net.UnknownHostException; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.jersey2.AbstractJersey2EurekaHttpClient; import com.netflix.discovery.shared.transport.jersey2.EurekaIdentityHeaderFilter; import com.netflix.discovery.shared.transport.jersey2.EurekaJersey2Client; import com.netflix.discovery.shared.transport.jersey2.EurekaJersey2ClientImpl; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.EurekaServerIdentity; import com.netflix.eureka.cluster.HttpReplicationClient; import com.netflix.eureka.cluster.PeerEurekaNode; import com.netflix.eureka.cluster.protocol.ReplicationList; import com.netflix.eureka.cluster.protocol.ReplicationListResponse; import com.netflix.eureka.resources.ASGResource.ASGStatus; import com.netflix.eureka.resources.ServerCodecs; /** * @author Tomasz Bak */ public class Jersey2ReplicationClient extends AbstractJersey2EurekaHttpClient implements HttpReplicationClient { private static final Logger logger = LoggerFactory.getLogger(Jersey2ReplicationClient.class); private final EurekaJersey2Client eurekaJersey2Client; public Jersey2ReplicationClient(EurekaJersey2Client eurekaJersey2Client, String serviceUrl) { super(eurekaJersey2Client.getClient(), serviceUrl); this.eurekaJersey2Client = eurekaJersey2Client; } @Override protected void addExtraHeaders(Builder webResource) { webResource.header(PeerEurekaNode.HEADER_REPLICATION, "true"); } /** * Compared to regular heartbeat, in the replication channel the server may return a more up to date * instance copy. */ @Override public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) { String urlPath = "apps/" + appName + '/' + id; Response response = null; try { WebTarget webResource = jerseyClient.target(serviceUrl) .path(urlPath) .queryParam("status", info.getStatus().toString()) .queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString()); if (overriddenStatus != null) { webResource = webResource.queryParam("overriddenstatus", overriddenStatus.name()); } Builder requestBuilder = webResource.request(); addExtraHeaders(requestBuilder); response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).put(Entity.entity("{}", MediaType.APPLICATION_JSON_TYPE)); // Jersey2 refuses to handle PUT with no body InstanceInfo infoFromPeer = null; if (response.getStatus() == Status.CONFLICT.getStatusCode() && response.hasEntity()) { infoFromPeer = response.readEntity(InstanceInfo.class); } return anEurekaHttpResponse(response.getStatus(), infoFromPeer).type(MediaType.APPLICATION_JSON_TYPE).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("[heartbeat] Jersey HTTP PUT {}; statusCode={}", urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<Void> statusUpdate(String asgName, ASGStatus newStatus) { Response response = null; try { String urlPath = "asg/" + asgName + "/status"; response = jerseyClient.target(serviceUrl) .path(urlPath) .queryParam("value", newStatus.name()) .request() .header(PeerEurekaNode.HEADER_REPLICATION, "true") .put(Entity.text("")); return EurekaHttpResponse.status(response.getStatus()); } finally { if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<ReplicationListResponse> submitBatchUpdates(ReplicationList replicationList) { Response response = null; try { response = jerseyClient.target(serviceUrl) .path(PeerEurekaNode.BATCH_URL_PATH) .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(replicationList)); if (!isSuccess(response.getStatus())) { return anEurekaHttpResponse(response.getStatus(), ReplicationListResponse.class).build(); } ReplicationListResponse batchResponse = response.readEntity(ReplicationListResponse.class); return anEurekaHttpResponse(response.getStatus(), batchResponse).type(MediaType.APPLICATION_JSON_TYPE).build(); } finally { if (response != null) { response.close(); } } } @Override public void shutdown() { super.shutdown(); eurekaJersey2Client.destroyResources(); } public static Jersey2ReplicationClient createReplicationClient(EurekaServerConfig config, ServerCodecs serverCodecs, String serviceUrl) { String name = Jersey2ReplicationClient.class.getSimpleName() + ": " + serviceUrl + "apps/: "; EurekaJersey2Client jerseyClient; try { String hostname; try { hostname = new URL(serviceUrl).getHost(); } catch (MalformedURLException e) { hostname = serviceUrl; } String jerseyClientName = "Discovery-PeerNodeClient-" + hostname; EurekaJersey2ClientImpl.EurekaJersey2ClientBuilder clientBuilder = new EurekaJersey2ClientImpl.EurekaJersey2ClientBuilder() .withClientName(jerseyClientName) .withUserAgent("Java-EurekaClient-Replication") .withEncoderWrapper(serverCodecs.getFullJsonCodec()) .withDecoderWrapper(serverCodecs.getFullJsonCodec()) .withConnectionTimeout(config.getPeerNodeConnectTimeoutMs()) .withReadTimeout(config.getPeerNodeReadTimeoutMs()) .withMaxConnectionsPerHost(config.getPeerNodeTotalConnectionsPerHost()) .withMaxTotalConnections(config.getPeerNodeTotalConnections()) .withConnectionIdleTimeout(config.getPeerNodeConnectionIdleTimeoutSeconds()); if (serviceUrl.startsWith("https://") && "true".equals(System.getProperty("com.netflix.eureka.shouldSSLConnectionsUseSystemSocketFactory"))) { clientBuilder.withSystemSSLConfiguration(); } jerseyClient = clientBuilder.build(); } catch (Throwable e) { throw new RuntimeException("Cannot Create new Replica Node :" + name, e); } String ip = null; try { ip = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { logger.warn("Cannot find localhost ip", e); } Client jerseyApacheClient = jerseyClient.getClient(); jerseyApacheClient.register(new Jersey2DynamicGZIPContentEncodingFilter(config)); EurekaServerIdentity identity = new EurekaServerIdentity(ip); jerseyApacheClient.register(new EurekaIdentityHeaderFilter(identity)); return new Jersey2ReplicationClient(jerseyClient, serviceUrl); } private static boolean isSuccess(int statusCode) { return statusCode >= 200 && statusCode < 300; } }
7,850
0
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka/resources/EurekaServerContextBinder.java
package com.netflix.eureka.resources; import org.glassfish.hk2.api.Factory; import org.glassfish.hk2.utilities.binding.AbstractBinder; import com.netflix.eureka.EurekaServerContext; import com.netflix.eureka.EurekaServerContextHolder; /** * Jersey2 binder for the EurekaServerContext. Replaces the GuiceFilter in the server WAR web.xml * @author Matt Nelson */ public class EurekaServerContextBinder extends AbstractBinder { public class EurekaServerContextFactory implements Factory<EurekaServerContext> { @Override public EurekaServerContext provide() { return EurekaServerContextHolder.getInstance().getServerContext(); } @Override public void dispose(EurekaServerContext t) { } } /** * {@inheritDoc} */ @Override protected void configure() { bindFactory(new EurekaServerContextFactory()).to(EurekaServerContext.class); } }
7,851
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/EurekaEventListenerTest.java
package com.netflix.discovery; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import static com.netflix.discovery.util.EurekaEntityFunctions.toApplications; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; import java.io.IOException; import javax.ws.rs.core.MediaType; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.junit.resource.DiscoveryClientResource; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.SimpleEurekaHttpServer; public class EurekaEventListenerTest { private static final EurekaHttpClient requestHandler = mock(EurekaHttpClient.class); private static SimpleEurekaHttpServer eurekaHttpServer; @Rule public DiscoveryClientResource discoveryClientResource = DiscoveryClientResource.newBuilder() .withRegistration(true) .withRegistryFetch(true) .connectWith(eurekaHttpServer) .build(); /** * Share server stub by all tests. */ @BeforeClass public static void setUpClass() throws IOException { eurekaHttpServer = new SimpleEurekaHttpServer(requestHandler); } @AfterClass public static void tearDownClass() throws Exception { if (eurekaHttpServer != null) { eurekaHttpServer.shutdown(); } } @Before public void setUp() throws Exception { reset(requestHandler); when(requestHandler.register(any(InstanceInfo.class))).thenReturn(EurekaHttpResponse.status(204)); when(requestHandler.cancel(anyString(), anyString())).thenReturn(EurekaHttpResponse.status(200)); when(requestHandler.getDelta()).thenReturn( anEurekaHttpResponse(200, new Applications()).type(MediaType.APPLICATION_JSON_TYPE).build() ); } static class CapturingEurekaEventListener implements EurekaEventListener { private volatile EurekaEvent event; @Override public void onEvent(EurekaEvent event) { this.event = event; } } @Test public void testCacheRefreshEvent() throws Exception { CapturingEurekaEventListener listener = new CapturingEurekaEventListener(); Applications initialApps = toApplications(discoveryClientResource.getMyInstanceInfo()); when(requestHandler.getApplications()).thenReturn( anEurekaHttpResponse(200, initialApps).type(MediaType.APPLICATION_JSON_TYPE).build() ); DiscoveryClient client = (DiscoveryClient) discoveryClientResource.getClient(); client.registerEventListener(listener); client.refreshRegistry(); assertNotNull(listener.event); assertThat(listener.event, is(instanceOf(CacheRefreshedEvent.class))); } }
7,852
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/BaseDiscoveryClientTester.java
package com.netflix.discovery; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.LeaseInfo; import com.netflix.discovery.junit.resource.DiscoveryClientResource; import com.netflix.discovery.shared.Application; import org.junit.Rule; import javax.annotation.Nullable; import java.util.Arrays; import java.util.List; /** * @author Nitesh Kant */ public abstract class BaseDiscoveryClientTester { public static final String REMOTE_REGION = "myregion"; public static final String REMOTE_ZONE = "myzone"; public static final int CLIENT_REFRESH_RATE = 10; public static final String ALL_REGIONS_VIP1_ADDR = "myvip1"; public static final String REMOTE_REGION_APP1_INSTANCE1_HOSTNAME = "blah1-1"; public static final String REMOTE_REGION_APP1_INSTANCE2_HOSTNAME = "blah1-2"; public static final String LOCAL_REGION_APP1_NAME = "MYAPP1_LOC"; public static final String LOCAL_REGION_APP1_INSTANCE1_HOSTNAME = "blahloc1-1"; public static final String LOCAL_REGION_APP1_INSTANCE2_HOSTNAME = "blahloc1-2"; public static final String REMOTE_REGION_APP1_NAME = "MYAPP1"; public static final String ALL_REGIONS_VIP2_ADDR = "myvip2"; public static final String REMOTE_REGION_APP2_INSTANCE1_HOSTNAME = "blah2-1"; public static final String REMOTE_REGION_APP2_INSTANCE2_HOSTNAME = "blah2-2"; public static final String LOCAL_REGION_APP2_NAME = "MYAPP2_LOC"; public static final String LOCAL_REGION_APP2_INSTANCE1_HOSTNAME = "blahloc2-1"; public static final String LOCAL_REGION_APP2_INSTANCE2_HOSTNAME = "blahloc2-2"; public static final String REMOTE_REGION_APP2_NAME = "MYAPP2"; public static final String ALL_REGIONS_VIP3_ADDR = "myvip3"; public static final String LOCAL_REGION_APP3_NAME = "MYAPP3_LOC"; public static final String LOCAL_REGION_APP3_INSTANCE1_HOSTNAME = "blahloc3-1"; @Rule public MockRemoteEurekaServer mockLocalEurekaServer = new MockRemoteEurekaServer(); protected EurekaClient client; protected void setupProperties() { DiscoveryClientResource.setupDiscoveryClientConfig(mockLocalEurekaServer.getPort(), MockRemoteEurekaServer.EUREKA_API_BASE_PATH); } protected void setupDiscoveryClient() { client = getSetupDiscoveryClient(); } protected EurekaClient getSetupDiscoveryClient() { return getSetupDiscoveryClient(30); } protected EurekaClient getSetupDiscoveryClient(int renewalIntervalInSecs) { InstanceInfo instanceInfo = newInstanceInfoBuilder(renewalIntervalInSecs).build(); return DiscoveryClientResource.setupDiscoveryClient(instanceInfo); } protected InstanceInfo.Builder newInstanceInfoBuilder(int renewalIntervalInSecs) { return DiscoveryClientResource.newInstanceInfoBuilder(renewalIntervalInSecs); } protected void shutdownDiscoveryClient() { if (client != null) { client.shutdown(); } } protected void addLocalAppDelta() { Application myappDelta = new Application(LOCAL_REGION_APP3_NAME); InstanceInfo instanceInfo = createInstance(LOCAL_REGION_APP3_NAME, ALL_REGIONS_VIP3_ADDR, LOCAL_REGION_APP3_INSTANCE1_HOSTNAME, null); instanceInfo.setActionType(InstanceInfo.ActionType.ADDED); myappDelta.addInstance(instanceInfo); mockLocalEurekaServer.addLocalRegionAppsDelta(LOCAL_REGION_APP3_NAME, myappDelta); } protected void populateLocalRegistryAtStartup() { for (Application app : createLocalApps()) { mockLocalEurekaServer.addLocalRegionApps(app.getName(), app); } for (Application appDelta : createLocalAppsDelta()) { mockLocalEurekaServer.addLocalRegionAppsDelta(appDelta.getName(), appDelta); } } protected void populateRemoteRegistryAtStartup() { for (Application app : createRemoteApps()) { mockLocalEurekaServer.addRemoteRegionApps(app.getName(), app); } for (Application appDelta : createRemoteAppsDelta()) { mockLocalEurekaServer.addRemoteRegionAppsDelta(appDelta.getName(), appDelta); } } protected static List<Application> createRemoteApps() { Application myapp1 = new Application(REMOTE_REGION_APP1_NAME); InstanceInfo instanceInfo1 = createInstance(REMOTE_REGION_APP1_NAME, ALL_REGIONS_VIP1_ADDR, REMOTE_REGION_APP1_INSTANCE1_HOSTNAME, REMOTE_ZONE); myapp1.addInstance(instanceInfo1); Application myapp2 = new Application(REMOTE_REGION_APP2_NAME); InstanceInfo instanceInfo2 = createInstance(REMOTE_REGION_APP2_NAME, ALL_REGIONS_VIP2_ADDR, REMOTE_REGION_APP2_INSTANCE1_HOSTNAME, REMOTE_ZONE); myapp2.addInstance(instanceInfo2); return Arrays.asList(myapp1, myapp2); } protected static List<Application> createRemoteAppsDelta() { Application myapp1 = new Application(REMOTE_REGION_APP1_NAME); InstanceInfo instanceInfo1 = createInstance(REMOTE_REGION_APP1_NAME, ALL_REGIONS_VIP1_ADDR, REMOTE_REGION_APP1_INSTANCE2_HOSTNAME, REMOTE_ZONE); instanceInfo1.setActionType(InstanceInfo.ActionType.ADDED); myapp1.addInstance(instanceInfo1); Application myapp2 = new Application(REMOTE_REGION_APP2_NAME); InstanceInfo instanceInfo2 = createInstance(REMOTE_REGION_APP2_NAME, ALL_REGIONS_VIP2_ADDR, REMOTE_REGION_APP2_INSTANCE2_HOSTNAME, REMOTE_ZONE); instanceInfo2.setActionType(InstanceInfo.ActionType.ADDED); myapp2.addInstance(instanceInfo2); return Arrays.asList(myapp1, myapp2); } protected static List<Application> createLocalApps() { Application myapp1 = new Application(LOCAL_REGION_APP1_NAME); InstanceInfo instanceInfo1 = createInstance(LOCAL_REGION_APP1_NAME, ALL_REGIONS_VIP1_ADDR, LOCAL_REGION_APP1_INSTANCE1_HOSTNAME, null); myapp1.addInstance(instanceInfo1); Application myapp2 = new Application(LOCAL_REGION_APP2_NAME); InstanceInfo instanceInfo2 = createInstance(LOCAL_REGION_APP2_NAME, ALL_REGIONS_VIP2_ADDR, LOCAL_REGION_APP2_INSTANCE1_HOSTNAME, null); myapp2.addInstance(instanceInfo2); return Arrays.asList(myapp1, myapp2); } protected static List<Application> createLocalAppsDelta() { Application myapp1 = new Application(LOCAL_REGION_APP1_NAME); InstanceInfo instanceInfo1 = createInstance(LOCAL_REGION_APP1_NAME, ALL_REGIONS_VIP1_ADDR, LOCAL_REGION_APP1_INSTANCE2_HOSTNAME, null); instanceInfo1.setActionType(InstanceInfo.ActionType.ADDED); myapp1.addInstance(instanceInfo1); Application myapp2 = new Application(LOCAL_REGION_APP2_NAME); InstanceInfo instanceInfo2 = createInstance(LOCAL_REGION_APP2_NAME, ALL_REGIONS_VIP2_ADDR, LOCAL_REGION_APP2_INSTANCE2_HOSTNAME, null); instanceInfo2.setActionType(InstanceInfo.ActionType.ADDED); myapp2.addInstance(instanceInfo2); return Arrays.asList(myapp1, myapp2); } protected static InstanceInfo createInstance(String appName, String vipAddress, String instanceHostName, String zone) { InstanceInfo.Builder instanceBuilder = InstanceInfo.Builder.newBuilder(); instanceBuilder.setAppName(appName); instanceBuilder.setVIPAddress(vipAddress); instanceBuilder.setHostName(instanceHostName); instanceBuilder.setIPAddr("10.10.101.1"); AmazonInfo amazonInfo = getAmazonInfo(zone, instanceHostName); instanceBuilder.setDataCenterInfo(amazonInfo); instanceBuilder.setMetadata(amazonInfo.getMetadata()); instanceBuilder.setLeaseInfo(LeaseInfo.Builder.newBuilder().build()); return instanceBuilder.build(); } protected static AmazonInfo getAmazonInfo(@Nullable String availabilityZone, String instanceHostName) { AmazonInfo.Builder azBuilder = AmazonInfo.Builder.newBuilder(); azBuilder.addMetadata(AmazonInfo.MetaDataKey.availabilityZone, null == availabilityZone ? "us-east-1a" : availabilityZone); azBuilder.addMetadata(AmazonInfo.MetaDataKey.instanceId, instanceHostName); azBuilder.addMetadata(AmazonInfo.MetaDataKey.amiId, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.instanceType, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.localIpv4, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.publicIpv4, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.publicHostname, instanceHostName); return azBuilder.build(); } }
7,853
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/MockRemoteEurekaServer.java
package com.netflix.discovery; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.netflix.appinfo.AbstractEurekaIdentity; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.EurekaClientIdentity; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.XmlXStream; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import org.junit.Assert; import org.junit.rules.ExternalResource; import org.mortbay.jetty.Request; import org.mortbay.jetty.Server; import org.mortbay.jetty.handler.AbstractHandler; /** * @author Nitesh Kant */ public class MockRemoteEurekaServer extends ExternalResource { public static final String EUREKA_API_BASE_PATH = "/eureka/v2/"; private static Pattern HOSTNAME_PATTERN = Pattern.compile("\"hostName\"\\s?:\\s?\\\"([A-Za-z0-9\\.-]*)\\\""); private static Pattern STATUS_PATTERN = Pattern.compile("\"status\"\\s?:\\s?\\\"([A-Z_]*)\\\""); private int port; private final Map<String, Application> applicationMap = new HashMap<String, Application>(); private final Map<String, Application> remoteRegionApps = new HashMap<String, Application>(); private final Map<String, Application> remoteRegionAppsDelta = new HashMap<String, Application>(); private final Map<String, Application> applicationDeltaMap = new HashMap<String, Application>(); private Server server; private final AtomicBoolean sentDelta = new AtomicBoolean(); private final AtomicBoolean sentRegistry = new AtomicBoolean(); public final BlockingQueue<String> registrationStatusesQueue = new LinkedBlockingQueue<>(); public final List<String> registrationStatuses = new ArrayList<>(); public final AtomicLong registerCount = new AtomicLong(0); public final AtomicLong heartbeatCount = new AtomicLong(0); public final AtomicLong getFullRegistryCount = new AtomicLong(0); public final AtomicLong getSingleVipCount = new AtomicLong(0); public final AtomicLong getDeltaCount = new AtomicLong(0); @Override protected void before() throws Throwable { start(); } @Override protected void after() { try { stop(); } catch (Exception e) { Assert.fail(e.getMessage()); } } public void start() throws Exception { server = new Server(port); server.setHandler(new AppsResourceHandler()); server.start(); port = server.getConnectors()[0].getLocalPort(); } public int getPort() { return port; } public void stop() throws Exception { server.stop(); server = null; port = 0; registrationStatusesQueue.clear(); registrationStatuses.clear(); applicationMap.clear(); remoteRegionApps.clear(); remoteRegionAppsDelta.clear(); applicationDeltaMap.clear(); } public boolean isSentDelta() { return sentDelta.get(); } public boolean isSentRegistry() { return sentRegistry.get(); } public void addRemoteRegionApps(String appName, Application app) { remoteRegionApps.put(appName, app); } public void addRemoteRegionAppsDelta(String appName, Application app) { remoteRegionAppsDelta.put(appName, app); } public void addLocalRegionApps(String appName, Application app) { applicationMap.put(appName, app); } public void addLocalRegionAppsDelta(String appName, Application app) { applicationDeltaMap.put(appName, app); } public void waitForDeltaToBeRetrieved(int refreshRate) throws InterruptedException { int count = 0; while (count++ < 3 && !isSentDelta()) { System.out.println("Sleeping for " + refreshRate + " seconds to let the remote registry fetch delta. Attempt: " + count); Thread.sleep(3 * refreshRate * 1000); System.out.println("Done sleeping for 10 seconds to let the remote registry fetch delta. Delta fetched: " + isSentDelta()); } System.out.println("Sleeping for extra " + refreshRate + " seconds for the client to update delta in memory."); } // // A base default resource handler for the mock server // private class AppsResourceHandler extends AbstractHandler { @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { String authName = request.getHeader(AbstractEurekaIdentity.AUTH_NAME_HEADER_KEY); String authVersion = request.getHeader(AbstractEurekaIdentity.AUTH_VERSION_HEADER_KEY); String authId = request.getHeader(AbstractEurekaIdentity.AUTH_ID_HEADER_KEY); Assert.assertEquals(EurekaClientIdentity.DEFAULT_CLIENT_NAME, authName); Assert.assertNotNull(authVersion); Assert.assertNotNull(authId); String pathInfo = request.getPathInfo(); System.out.println("Eureka port: " + port + ". " + System.currentTimeMillis() + ". Eureka resource mock, received request on path: " + pathInfo + ". HTTP method: |" + request.getMethod() + '|' + ", query string: " + request.getQueryString()); boolean handled = false; if (null != pathInfo && pathInfo.startsWith("")) { pathInfo = pathInfo.substring(EUREKA_API_BASE_PATH.length()); boolean includeRemote = isRemoteRequest(request); if (pathInfo.startsWith("apps/delta")) { getDeltaCount.getAndIncrement(); Applications apps = new Applications(); apps.setVersion(100L); if (sentDelta.compareAndSet(false, true)) { addDeltaApps(includeRemote, apps); } else { System.out.println("Eureka port: " + port + ". " + System.currentTimeMillis() + ". Not including delta as it has already been sent."); } apps.setAppsHashCode(getDeltaAppsHashCode(includeRemote)); sendOkResponseWithContent((Request) request, response, apps); handled = true; } else if (pathInfo.equals("apps/")) { getFullRegistryCount.getAndIncrement(); Applications apps = new Applications(); apps.setVersion(100L); for (Application application : applicationMap.values()) { apps.addApplication(application); } if (includeRemote) { for (Application application : remoteRegionApps.values()) { apps.addApplication(application); } } if (sentDelta.get()) { addDeltaApps(includeRemote, apps); } else { System.out.println("Eureka port: " + port + ". " + System.currentTimeMillis() + ". Not including delta apps in /apps response, as delta has not been sent."); } apps.setAppsHashCode(apps.getReconcileHashCode()); sendOkResponseWithContent((Request) request, response, apps); sentRegistry.set(true); handled = true; } else if (pathInfo.startsWith("vips/")) { getSingleVipCount.getAndIncrement(); String vipAddress = pathInfo.substring("vips/".length()); Applications apps = new Applications(); apps.setVersion(-1l); for (Application application : applicationMap.values()) { Application retApp = new Application(application.getName()); for (InstanceInfo instance : application.getInstances()) { if (vipAddress.equals(instance.getVIPAddress())) { retApp.addInstance(instance); } } if (retApp.getInstances().size() > 0) { apps.addApplication(retApp); } } apps.setAppsHashCode(apps.getReconcileHashCode()); sendOkResponseWithContent((Request) request, response, apps); handled = true; } else if (pathInfo.startsWith("apps")) { // assume this is the renewal heartbeat if (request.getMethod().equals("PUT")) { // this is the renewal heartbeat heartbeatCount.getAndIncrement(); } else if (request.getMethod().equals("POST")) { // this is a register request registerCount.getAndIncrement(); String statusStr = null; String hostname = null; String line; BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { Matcher hostNameMatcher = HOSTNAME_PATTERN.matcher(line); if (hostname == null && hostNameMatcher.find()) { hostname = hostNameMatcher.group(1); // don't break here as we want to read the full buffer for a clean connection close } Matcher statusMatcher = STATUS_PATTERN.matcher(line); if (statusStr == null && statusMatcher.find()) { statusStr = statusMatcher.group(1); // don't break here as we want to read the full buffer for a clean connection close } } System.out.println("Matched status to: " + statusStr); registrationStatusesQueue.add(statusStr); registrationStatuses.add(statusStr); String appName = pathInfo.substring(5); if (!applicationMap.containsKey(appName)) { Application app = new Application(appName); InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName(appName) .setIPAddr("1.1.1.1") .setHostName(hostname) .setStatus(InstanceInfo.InstanceStatus.toEnum(statusStr)) .setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }) .build(); app.addInstance(instanceInfo); applicationMap.put(appName, app); } } Applications apps = new Applications(); apps.setAppsHashCode(""); sendOkResponseWithContent((Request) request, response, apps); handled = true; } else { System.out.println("Not handling request: " + pathInfo); } } if (!handled) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Request path: " + pathInfo + " not supported by eureka resource mock."); } } protected void addDeltaApps(boolean includeRemote, Applications apps) { for (Application application : applicationDeltaMap.values()) { apps.addApplication(application); } if (includeRemote) { for (Application application : remoteRegionAppsDelta.values()) { apps.addApplication(application); } } } protected String getDeltaAppsHashCode(boolean includeRemote) { Applications allApps = new Applications(); for (Application application : applicationMap.values()) { allApps.addApplication(application); } if (includeRemote) { for (Application application : remoteRegionApps.values()) { allApps.addApplication(application); } } addDeltaApps(includeRemote, allApps); return allApps.getReconcileHashCode(); } protected boolean isRemoteRequest(HttpServletRequest request) { String queryString = request.getQueryString(); if (queryString == null) { return false; } return queryString.contains("regions="); } protected void sendOkResponseWithContent(Request request, HttpServletResponse response, Applications apps) throws IOException { String content = XmlXStream.getInstance().toXML(apps); response.setContentType("application/xml"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(content); response.getWriter().flush(); request.setHandled(true); System.out.println("Eureka port: " + port + ". " + System.currentTimeMillis() + ". Eureka resource mock, sent response for request path: " + request.getPathInfo() + ", apps count: " + apps.getRegisteredApplications().size()); } protected void sleep(int seconds) { try { Thread.sleep(seconds); } catch (InterruptedException e) { System.out.println("Interrupted: " + e); } } } }
7,854
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientCloseJerseyThreadTest.java
package com.netflix.discovery; import java.util.Set; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; public class DiscoveryClientCloseJerseyThreadTest extends AbstractDiscoveryClientTester { private static final String JERSEY_THREAD_NAME = "Eureka-JerseyClient-Conn-Cleaner"; private static final String APACHE_THREAD_NAME = "Apache-HttpClient-Conn-Cleaner"; @Test public void testThreadCount() throws InterruptedException { assertThat(containsClientThread(), equalTo(true)); client.shutdown(); // Give up control for cleaner thread to die Thread.sleep(5); assertThat(containsClientThread(), equalTo(false)); } private boolean containsClientThread() { Set<Thread> threads = Thread.getAllStackTraces().keySet(); for (Thread t : threads) { if (t.getName().contains(JERSEY_THREAD_NAME) || t.getName().contains(APACHE_THREAD_NAME)) { return true; } } return false; } }
7,855
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/InstanceInfoReplicatorTest.java
package com.netflix.discovery; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.HealthCheckHandler; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.LeaseInfo; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.UUID; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author David Liu */ public class InstanceInfoReplicatorTest { private final int burstSize = 2; private final int refreshRateSeconds = 2; private DiscoveryClient discoveryClient; private InstanceInfoReplicator replicator; @Before public void setUp() throws Exception { discoveryClient = mock(DiscoveryClient.class); InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder() .setIPAddr("10.10.101.00") .setHostName("Hosttt") .setAppName("EurekaTestApp-" + UUID.randomUUID()) .setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }) .setLeaseInfo(LeaseInfo.Builder.newBuilder().setRenewalIntervalInSecs(30).build()); InstanceInfo instanceInfo = builder.build(); instanceInfo.setStatus(InstanceInfo.InstanceStatus.DOWN); this.replicator = new InstanceInfoReplicator(discoveryClient, instanceInfo, refreshRateSeconds, burstSize); } @After public void tearDown() throws Exception { replicator.stop(); } @Test public void testOnDemandUpdate() throws Throwable { assertTrue(replicator.onDemandUpdate()); Thread.sleep(10); // give some time for execution assertTrue(replicator.onDemandUpdate()); Thread.sleep(1000 * refreshRateSeconds / 2); assertTrue(replicator.onDemandUpdate()); Thread.sleep(10); verify(discoveryClient, times(3)).refreshInstanceInfo(); verify(discoveryClient, times(1)).register(); } @Test public void testOnDemandUpdateRateLimiting() throws Throwable { assertTrue(replicator.onDemandUpdate()); Thread.sleep(10); // give some time for execution assertTrue(replicator.onDemandUpdate()); Thread.sleep(10); // give some time for execution assertFalse(replicator.onDemandUpdate()); Thread.sleep(1000); verify(discoveryClient, times(2)).refreshInstanceInfo(); verify(discoveryClient, times(1)).register(); } @Test public void testOnDemandUpdateResetAutomaticRefresh() throws Throwable { replicator.start(0); Thread.sleep(1000 * refreshRateSeconds / 2); assertTrue(replicator.onDemandUpdate()); Thread.sleep(1000 * refreshRateSeconds + 50); verify(discoveryClient, times(3)).refreshInstanceInfo(); // 1 initial refresh, 1 onDemand, 1 auto verify(discoveryClient, times(1)).register(); // all but 1 is no-op } @Test public void testOnDemandUpdateResetAutomaticRefreshWithInitialDelay() throws Throwable { replicator.start(1000 * refreshRateSeconds); assertTrue(replicator.onDemandUpdate()); Thread.sleep(1000 * refreshRateSeconds + 100); verify(discoveryClient, times(2)).refreshInstanceInfo(); // 1 onDemand, 1 auto verify(discoveryClient, times(1)).register(); // all but 1 is no-op } }
7,856
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/MockBackupRegistry.java
package com.netflix.discovery; import java.util.HashMap; import java.util.Map; import com.google.inject.Singleton; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; /** * @author Nitesh Kant */ @Singleton public class MockBackupRegistry implements BackupRegistry { private Map<String, Applications> remoteRegionVsApps = new HashMap<String, Applications>(); private Applications localRegionApps; @Override public Applications fetchRegistry() { if (null == localRegionApps) { return new Applications(); } return localRegionApps; } @Override public Applications fetchRegistry(String[] includeRemoteRegions) { Applications toReturn = new Applications(); for (Application application : localRegionApps.getRegisteredApplications()) { toReturn.addApplication(application); } for (String region : includeRemoteRegions) { Applications applications = remoteRegionVsApps.get(region); if (null != applications) { for (Application application : applications.getRegisteredApplications()) { toReturn.addApplication(application); } } } return toReturn; } public Applications getLocalRegionApps() { return localRegionApps; } public Map<String, Applications> getRemoteRegionVsApps() { return remoteRegionVsApps; } public void setRemoteRegionVsApps(Map<String, Applications> remoteRegionVsApps) { this.remoteRegionVsApps = remoteRegionVsApps; } public void setLocalRegionApps(Applications localRegionApps) { this.localRegionApps = localRegionApps; } }
7,857
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientRegisterUpdateTest.java
package com.netflix.discovery; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.LeaseInfo; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; /** * @author David Liu */ public class DiscoveryClientRegisterUpdateTest { private TestApplicationInfoManager applicationInfoManager; private MockRemoteEurekaServer mockLocalEurekaServer; private TestClient client; @Before public void setUp() throws Exception { mockLocalEurekaServer = new MockRemoteEurekaServer(); mockLocalEurekaServer.start(); ConfigurationManager.getConfigInstance().setProperty("eureka.name", "EurekaTestApp-" + UUID.randomUUID()); ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "true"); ConfigurationManager.getConfigInstance().setProperty("eureka.appinfo.replicate.interval", 4); ConfigurationManager.getConfigInstance().setProperty("eureka.shouldFetchRegistry", "false"); ConfigurationManager.getConfigInstance().setProperty("eureka.serviceUrl.default", "http://localhost:" + mockLocalEurekaServer.getPort() + MockRemoteEurekaServer.EUREKA_API_BASE_PATH); InstanceInfo seed = InstanceInfoGenerator.takeOne(); LeaseInfo leaseSeed = seed.getLeaseInfo(); LeaseInfo leaseInfo = LeaseInfo.Builder.newBuilder() .setDurationInSecs(leaseSeed.getDurationInSecs()) .setEvictionTimestamp(leaseSeed.getEvictionTimestamp()) .setRegistrationTimestamp(leaseSeed.getRegistrationTimestamp()) .setServiceUpTimestamp(leaseSeed.getServiceUpTimestamp()) .setRenewalTimestamp(leaseSeed.getRenewalTimestamp()) .setRenewalIntervalInSecs(4) // make this more frequent for testing .build(); InstanceInfo instanceInfo = new InstanceInfo.Builder(seed) .setStatus(InstanceInfo.InstanceStatus.STARTING) .setLeaseInfo(leaseInfo) .build(); applicationInfoManager = new TestApplicationInfoManager(instanceInfo); client = Mockito.spy(new TestClient(applicationInfoManager, new DefaultEurekaClientConfig())); // force the initial registration to eagerly run InstanceInfoReplicator instanceInfoReplicator = ((DiscoveryClient) client).getInstanceInfoReplicator(); instanceInfoReplicator.run(); // give some execution time for the initial registration to process expectStatus(InstanceInfo.InstanceStatus.STARTING, 4000, TimeUnit.MILLISECONDS); mockLocalEurekaServer.registrationStatuses.clear(); // and then clear the validation list mockLocalEurekaServer.registerCount.set(0l); } @After public void tearDown() throws Exception { client.shutdown(); mockLocalEurekaServer.stop(); ConfigurationManager.getConfigInstance().clear(); } @Test public void registerUpdateLifecycleTest() throws Exception { applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UP); // give some execution time expectStatus(InstanceInfo.InstanceStatus.UP, 5, TimeUnit.SECONDS); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UNKNOWN); // give some execution time expectStatus(InstanceInfo.InstanceStatus.UNKNOWN, 5, TimeUnit.SECONDS); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.DOWN); // give some execution time expectStatus(InstanceInfo.InstanceStatus.DOWN, 5, TimeUnit.SECONDS); Assert.assertTrue(mockLocalEurekaServer.registerCount.get() >= 3); // at least 3 } /** * This test is similar to the normal lifecycle test, but don't sleep between calls of setInstanceStatus */ @Test public void registerUpdateQuickLifecycleTest() throws Exception { applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UP); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UNKNOWN); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.DOWN); expectStatus(InstanceInfo.InstanceStatus.DOWN, 5, TimeUnit.SECONDS); // this call will be rate limited, but will be transmitted by the automatic update after 10s applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UP); expectStatus(InstanceInfo.InstanceStatus.UP, 5, TimeUnit.SECONDS); Assert.assertTrue(mockLocalEurekaServer.registerCount.get() >= 2); // at least 2 } @Test public void registerUpdateShutdownTest() throws Exception { Assert.assertEquals(1, applicationInfoManager.getStatusChangeListeners().size()); client.shutdown(); Assert.assertEquals(0, applicationInfoManager.getStatusChangeListeners().size()); Mockito.verify(client, Mockito.times(1)).unregister(); } @Test public void testRegistrationDisabled() throws Exception { client.shutdown(); // shutdown the default @Before client first ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "false"); client = new TestClient(applicationInfoManager, new DefaultEurekaClientConfig()); Assert.assertEquals(0, applicationInfoManager.getStatusChangeListeners().size()); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.DOWN); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UP); Thread.sleep(400); client.shutdown(); Assert.assertEquals(0, applicationInfoManager.getStatusChangeListeners().size()); } @Test public void testDoNotUnregisterOnShutdown() throws Exception { client.shutdown(); // shutdown the default @Before client first ConfigurationManager.getConfigInstance().setProperty("eureka.shouldUnregisterOnShutdown", "false"); client = Mockito.spy(new TestClient(applicationInfoManager, new DefaultEurekaClientConfig())); client.shutdown(); Mockito.verify(client, Mockito.never()).unregister(); } public class TestApplicationInfoManager extends ApplicationInfoManager { TestApplicationInfoManager(InstanceInfo instanceInfo) { super(new MyDataCenterInstanceConfig(), instanceInfo, null); } Map<String, StatusChangeListener> getStatusChangeListeners() { return this.listeners; } } private void expectStatus(InstanceInfo.InstanceStatus expected, long timeout, TimeUnit timeUnit) throws InterruptedException { String status = mockLocalEurekaServer.registrationStatusesQueue.poll(timeout, timeUnit); Assert.assertEquals(expected.name(), status); } private static <T> T getLast(List<T> list) { return list.get(list.size() - 1); } private static class TestClient extends DiscoveryClient { public TestClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config) { super(applicationInfoManager, config); } @Override public void unregister() { super.unregister(); } } }
7,858
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientStatsTest.java
package com.netflix.discovery; import org.junit.Assert; import org.junit.Test; /** * Tests for DiscoveryClient stats reported when initial registry fetch succeeds. */ public class DiscoveryClientStatsTest extends AbstractDiscoveryClientTester { @Test public void testNonEmptyInitLocalRegistrySize() throws Exception { Assert.assertTrue(client instanceof DiscoveryClient); DiscoveryClient clientImpl = (DiscoveryClient) client; Assert.assertEquals(createLocalApps().size(), clientImpl.getStats().initLocalRegistrySize()); } @Test public void testInitSucceeded() throws Exception { Assert.assertTrue(client instanceof DiscoveryClient); DiscoveryClient clientImpl = (DiscoveryClient) client; Assert.assertTrue(clientImpl.getStats().initSucceeded()); } }
7,859
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/Jersey1DiscoveryClientOptionalArgsTest.java
package com.netflix.discovery; import javax.inject.Provider; import com.netflix.discovery.shared.transport.jersey.Jersey1DiscoveryClientOptionalArgs; import org.junit.Before; import org.junit.Test; import com.netflix.appinfo.HealthCheckCallback; import com.netflix.appinfo.HealthCheckHandler; /** * @author Matt Nelson */ public class Jersey1DiscoveryClientOptionalArgsTest { private Jersey1DiscoveryClientOptionalArgs args; @Before public void before() { args = new Jersey1DiscoveryClientOptionalArgs(); } @Test public void testHealthCheckCallbackGuiceProvider() { args.setHealthCheckCallbackProvider(new GuiceProvider<HealthCheckCallback>()); } @Test public void testHealthCheckCallbackJavaxProvider() { args.setHealthCheckCallbackProvider(new JavaxProvider<HealthCheckCallback>()); } @Test public void testHealthCheckHandlerGuiceProvider() { args.setHealthCheckHandlerProvider(new GuiceProvider<HealthCheckHandler>()); } @Test public void testHealthCheckHandlerJavaxProvider() { args.setHealthCheckHandlerProvider(new JavaxProvider<HealthCheckHandler>()); } private class JavaxProvider<T> implements Provider<T> { @Override public T get() { return null; } } private class GuiceProvider<T> implements com.google.inject.Provider<T> { @Override public T get() { return null; } } }
7,860
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/EurekaClientLifecycleTest.java
package com.netflix.discovery; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.util.Collections; import java.util.List; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.ProvisionException; import com.google.inject.Scopes; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.PropertiesInstanceConfig; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.resolver.EndpointRandomizer; import com.netflix.discovery.shared.resolver.ResolverUtils; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.SimpleEurekaHttpServer; import com.netflix.discovery.shared.transport.jersey.Jersey1DiscoveryClientOptionalArgs; import com.netflix.discovery.util.InstanceInfoGenerator; import com.netflix.governator.guice.LifecycleInjector; import com.netflix.governator.lifecycle.LifecycleManager; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import static com.netflix.discovery.util.EurekaEntityFunctions.countInstances; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class EurekaClientLifecycleTest { private static final String MY_APPLICATION_NAME = "MYAPPLICATION"; private static final String MY_INSTANCE_ID = "myInstanceId"; private static final Applications APPLICATIONS = InstanceInfoGenerator.newBuilder(1, 1).build().toApplications(); private static final Applications APPLICATIONS_DELTA = new Applications(APPLICATIONS.getAppsHashCode(), 1L, Collections.<Application>emptyList()); public static final int TIMEOUT_MS = 2 * 1000; public static final EurekaHttpClient requestHandler = mock(EurekaHttpClient.class); public static SimpleEurekaHttpServer eurekaHttpServer; @BeforeClass public static void setupClass() throws IOException { eurekaHttpServer = new SimpleEurekaHttpServer(requestHandler); when(requestHandler.register(any(InstanceInfo.class))).thenReturn(EurekaHttpResponse.status(204)); when(requestHandler.cancel(MY_APPLICATION_NAME, MY_INSTANCE_ID)).thenReturn(EurekaHttpResponse.status(200)); when(requestHandler.sendHeartBeat(MY_APPLICATION_NAME, MY_INSTANCE_ID, null, null)).thenReturn( anEurekaHttpResponse(200, InstanceInfo.class).build() ); when(requestHandler.getApplications()).thenReturn( anEurekaHttpResponse(200, APPLICATIONS).type(MediaType.APPLICATION_JSON_TYPE).build() ); when(requestHandler.getDelta()).thenReturn( anEurekaHttpResponse(200, APPLICATIONS_DELTA).type(MediaType.APPLICATION_JSON_TYPE).build() ); } @AfterClass public static void tearDownClass() { if (eurekaHttpServer != null) { eurekaHttpServer.shutdown(); } } @Test public void testEurekaClientLifecycle() throws Exception { Injector injector = LifecycleInjector.builder() .withModules( new AbstractModule() { @Override protected void configure() { bind(EurekaInstanceConfig.class).to(LocalEurekaInstanceConfig.class); bind(EurekaClientConfig.class).to(LocalEurekaClientConfig.class); bind(AbstractDiscoveryClientOptionalArgs.class).to(Jersey1DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON); bind(EndpointRandomizer.class).toInstance(ResolverUtils::randomize); } } ) .build().createInjector(); LifecycleManager lifecycleManager = injector.getInstance(LifecycleManager.class); lifecycleManager.start(); EurekaClient client = injector.getInstance(EurekaClient.class); // Check registration verify(requestHandler, timeout(TIMEOUT_MS).atLeast(1)).register(any(InstanceInfo.class)); // Check registry fetch verify(requestHandler, timeout(TIMEOUT_MS).times(1)).getApplications(); verify(requestHandler, timeout(TIMEOUT_MS).atLeast(1)).getDelta(); assertThat(countInstances(client.getApplications()), is(equalTo(1))); // Shutdown container, and check that unregister happens lifecycleManager.close(); verify(requestHandler, times(1)).cancel(MY_APPLICATION_NAME, MY_INSTANCE_ID); } @Test public void testBackupRegistryInjection() throws Exception { final BackupRegistry backupRegistry = mock(BackupRegistry.class); when(backupRegistry.fetchRegistry()).thenReturn(APPLICATIONS); Injector injector = LifecycleInjector.builder() .withModules( new AbstractModule() { @Override protected void configure() { bind(EurekaInstanceConfig.class).to(LocalEurekaInstanceConfig.class); bind(EurekaClientConfig.class).to(BadServerEurekaClientConfig1.class); bind(BackupRegistry.class).toInstance(backupRegistry); bind(AbstractDiscoveryClientOptionalArgs.class).to(Jersey1DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON); bind(EndpointRandomizer.class).toInstance(ResolverUtils::randomize); } } ) .build().createInjector(); LifecycleManager lifecycleManager = injector.getInstance(LifecycleManager.class); lifecycleManager.start(); EurekaClient client = injector.getInstance(EurekaClient.class); verify(backupRegistry, atLeast(1)).fetchRegistry(); assertThat(countInstances(client.getApplications()), is(equalTo(1))); } @Test(expected = ProvisionException.class) public void testEnforcingRegistrationOnInitFastFail() { Injector injector = LifecycleInjector.builder() .withModules( new AbstractModule() { @Override protected void configure() { bind(EurekaInstanceConfig.class).to(LocalEurekaInstanceConfig.class); bind(EurekaClientConfig.class).to(BadServerEurekaClientConfig2.class); bind(AbstractDiscoveryClientOptionalArgs.class).to(Jersey1DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON); bind(EndpointRandomizer.class).toInstance(ResolverUtils::randomize); } } ) .build().createInjector(); LifecycleManager lifecycleManager = injector.getInstance(LifecycleManager.class); try { lifecycleManager.start(); } catch (Exception e) { throw new RuntimeException(e); } // this will throw a Guice ProvisionException for the constructor failure EurekaClient client = injector.getInstance(EurekaClient.class); } private static class LocalEurekaInstanceConfig extends PropertiesInstanceConfig { @Override public String getInstanceId() { return MY_INSTANCE_ID; } @Override public String getAppname() { return MY_APPLICATION_NAME; } @Override public int getLeaseRenewalIntervalInSeconds() { return 1; } } private static class LocalEurekaClientConfig extends DefaultEurekaClientConfig { @Override public List<String> getEurekaServerServiceUrls(String myZone) { return singletonList(eurekaHttpServer.getServiceURI().toString()); } @Override public int getInitialInstanceInfoReplicationIntervalSeconds() { return 0; } @Override public int getInstanceInfoReplicationIntervalSeconds() { return 1; } @Override public int getRegistryFetchIntervalSeconds() { return 1; } } private static class BadServerEurekaClientConfig1 extends LocalEurekaClientConfig { @Override public List<String> getEurekaServerServiceUrls(String myZone) { return singletonList("http://localhost:1/v2/"); // Fail fast on bad port number } @Override public boolean shouldRegisterWithEureka() { return false; } } private static class BadServerEurekaClientConfig2 extends LocalEurekaClientConfig { @Override public List<String> getEurekaServerServiceUrls(String myZone) { return singletonList("http://localhost:1/v2/"); // Fail fast on bad port number } @Override public boolean shouldFetchRegistry() { return false; } @Override public boolean shouldEnforceRegistrationAtInit() { return true; } } }
7,861
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/EurekaClientLifecycleServerFailureTest.java
package com.netflix.discovery; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.ProvisionException; import com.google.inject.Scopes; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.PropertiesInstanceConfig; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.resolver.EndpointRandomizer; import com.netflix.discovery.shared.resolver.ResolverUtils; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.SimpleEurekaHttpServer; import com.netflix.discovery.shared.transport.jersey.Jersey1DiscoveryClientOptionalArgs; import com.netflix.discovery.util.InstanceInfoGenerator; import com.netflix.governator.guice.LifecycleInjector; import com.netflix.governator.lifecycle.LifecycleManager; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.util.Collections; import java.util.List; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import static java.util.Collections.singletonList; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Tests the `shouldEnforceFetchRegistryAtInit` configuration property, which throws an exception during `DiscoveryClient` * construction if set to `true` and both the primary and backup registry fail to return a successful response. */ public class EurekaClientLifecycleServerFailureTest { private static final String MY_APPLICATION_NAME = "MYAPPLICATION"; private static final String MY_INSTANCE_ID = "myInstanceId"; private static final Applications APPLICATIONS = InstanceInfoGenerator.newBuilder(1, 1).build().toApplications(); private static final Applications APPLICATIONS_DELTA = new Applications(APPLICATIONS.getAppsHashCode(), 1L, Collections.emptyList()); public static final EurekaHttpClient requestHandler = mock(EurekaHttpClient.class); public static SimpleEurekaHttpServer eurekaHttpServer; @BeforeClass public static void setupClass() throws IOException { eurekaHttpServer = new SimpleEurekaHttpServer(requestHandler); when(requestHandler.getApplications()).thenReturn( anEurekaHttpResponse(500, APPLICATIONS).type(MediaType.APPLICATION_JSON_TYPE).build() ); when(requestHandler.getDelta()).thenReturn( anEurekaHttpResponse(500, APPLICATIONS_DELTA).type(MediaType.APPLICATION_JSON_TYPE).build() ); } @AfterClass public static void tearDownClass() { if (eurekaHttpServer != null) { eurekaHttpServer.shutdown(); } } private static class LocalEurekaInstanceConfig extends PropertiesInstanceConfig { @Override public String getInstanceId() { return MY_INSTANCE_ID; } @Override public String getAppname() { return MY_APPLICATION_NAME; } @Override public int getLeaseRenewalIntervalInSeconds() { return 1; } } /** * EurekaClientConfig configured to enforce fetch registry at init */ private static class LocalEurekaClientConfig1 extends DefaultEurekaClientConfig { @Override public List<String> getEurekaServerServiceUrls(String myZone) { return singletonList(eurekaHttpServer.getServiceURI().toString()); } @Override public boolean shouldEnforceFetchRegistryAtInit() { return true; } } /** * EurekaClientConfig configured to enforce fetch registry at init but not to fetch registry */ private static class LocalEurekaClientConfig2 extends DefaultEurekaClientConfig { @Override public List<String> getEurekaServerServiceUrls(String myZone) { return singletonList(eurekaHttpServer.getServiceURI().toString()); } @Override public boolean shouldEnforceFetchRegistryAtInit() { return true; } @Override public boolean shouldFetchRegistry() { return false; } } /** * n.b. without a configured backup registry, the default backup registry is set to `NotImplementedRegistryImpl`, * which returns `null` for its list of applications and thus results in a failure to return a successful response * for registry data when used. */ @Test(expected = ProvisionException.class) public void testEnforceFetchRegistryAtInitPrimaryAndBackupFailure() { Injector injector = LifecycleInjector.builder() .withModules( new AbstractModule() { @Override protected void configure() { bind(EurekaInstanceConfig.class).to(LocalEurekaInstanceConfig.class); bind(EurekaClientConfig.class).to(LocalEurekaClientConfig1.class); bind(AbstractDiscoveryClientOptionalArgs.class).to(Jersey1DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON); bind(EndpointRandomizer.class).toInstance(ResolverUtils::randomize); } } ) .build().createInjector(); LifecycleManager lifecycleManager = injector.getInstance(LifecycleManager.class); try { lifecycleManager.start(); } catch (Exception e) { throw new RuntimeException(e); } // this will throw a Guice ProvisionException for the constructor failure injector.getInstance(EurekaClient.class); } @Test public void testEnforceFetchRegistryAtInitPrimaryFailureAndBackupSuccess() { Injector injector = LifecycleInjector.builder() .withModules( new AbstractModule() { @Override protected void configure() { bind(EurekaInstanceConfig.class).to(LocalEurekaInstanceConfig.class); bind(EurekaClientConfig.class).to(LocalEurekaClientConfig1.class); bind(AbstractDiscoveryClientOptionalArgs.class).to(Jersey1DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON); bind(EndpointRandomizer.class).toInstance(ResolverUtils::randomize); bind(BackupRegistry.class).toInstance(new MockBackupRegistry()); // returns empty list on registry fetch } } ) .build().createInjector(); LifecycleManager lifecycleManager = injector.getInstance(LifecycleManager.class); try { lifecycleManager.start(); } catch (Exception e) { throw new RuntimeException(e); } // this will not throw a Guice ProvisionException for the constructor failure EurekaClient client = injector.getInstance(EurekaClient.class); Assert.assertNotNull(client); } @Test public void testEnforceFetchRegistryAtInitPrimaryFailureNoop() { Injector injector = LifecycleInjector.builder() .withModules( new AbstractModule() { @Override protected void configure() { bind(EurekaInstanceConfig.class).to(LocalEurekaInstanceConfig.class); bind(EurekaClientConfig.class).to(LocalEurekaClientConfig2.class); bind(AbstractDiscoveryClientOptionalArgs.class).to(Jersey1DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON); bind(EndpointRandomizer.class).toInstance(ResolverUtils::randomize); } } ) .build().createInjector(); LifecycleManager lifecycleManager = injector.getInstance(LifecycleManager.class); try { lifecycleManager.start(); } catch (Exception e) { throw new RuntimeException(e); } // this will not throw a Guice ProvisionException for the constructor failure EurekaClient client = injector.getInstance(EurekaClient.class); Assert.assertNotNull(client); } }
7,862
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/BackUpRegistryTest.java
package com.netflix.discovery; import javax.annotation.Nullable; import java.util.List; import java.util.UUID; import com.google.inject.util.Providers; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.resolver.ResolverUtils; import org.junit.After; import org.junit.Assert; import org.junit.Test; /** * @author Nitesh Kant */ public class BackUpRegistryTest { public static final String ALL_REGIONS_VIP_ADDR = "myvip"; public static final String REMOTE_REGION_INSTANCE_1_HOSTNAME = "blah"; public static final String REMOTE_REGION_INSTANCE_2_HOSTNAME = "blah2"; public static final String LOCAL_REGION_APP_NAME = "MYAPP_LOC"; public static final String LOCAL_REGION_INSTANCE_1_HOSTNAME = "blahloc"; public static final String LOCAL_REGION_INSTANCE_2_HOSTNAME = "blahloc2"; public static final String REMOTE_REGION_APP_NAME = "MYAPP"; public static final String REMOTE_REGION = "myregion"; public static final String REMOTE_ZONE = "myzone"; public static final int CLIENT_REFRESH_RATE = 10; public static final int NOT_AVAILABLE_EUREKA_PORT = 756473; private EurekaClient client; private MockBackupRegistry backupRegistry; public void setUp(boolean enableRemote) throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.client.refresh.interval", CLIENT_REFRESH_RATE); ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "false"); if (enableRemote) { ConfigurationManager.getConfigInstance().setProperty("eureka.fetchRemoteRegionsRegistry", REMOTE_REGION); } ConfigurationManager.getConfigInstance().setProperty("eureka.myregion.availabilityZones", REMOTE_ZONE); ConfigurationManager.getConfigInstance().setProperty("eureka.backupregistry", MockBackupRegistry.class.getName()); ConfigurationManager.getConfigInstance().setProperty("eureka.serviceUrl.default", "http://localhost:" + NOT_AVAILABLE_EUREKA_PORT /*Should always be unavailable*/ + MockRemoteEurekaServer.EUREKA_API_BASE_PATH); InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(); builder.setIPAddr("10.10.101.00"); builder.setHostName("Hosttt"); builder.setAppName("EurekaTestApp-" + UUID.randomUUID()); builder.setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }); ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig(), builder.build()); backupRegistry = new MockBackupRegistry(); setupBackupMock(); client = new DiscoveryClient( applicationInfoManager, new DefaultEurekaClientConfig(), null, Providers.of((BackupRegistry)backupRegistry), ResolverUtils::randomize ); } @After public void tearDown() throws Exception { client.shutdown(); ConfigurationManager.getConfigInstance().clear(); } @Test public void testLocalOnly() throws Exception { setUp(false); Applications applications = client.getApplications(); List<Application> registeredApplications = applications.getRegisteredApplications(); System.out.println("***" + registeredApplications); Assert.assertNotNull("Local region apps not found.", registeredApplications); Assert.assertEquals("Local apps size not as expected.", 1, registeredApplications.size()); Assert.assertEquals("Local region apps not present.", LOCAL_REGION_APP_NAME, registeredApplications.get(0).getName()); } @Test public void testRemoteEnabledButLocalOnlyQueried() throws Exception { setUp(true); Applications applications = client.getApplications(); List<Application> registeredApplications = applications.getRegisteredApplications(); Assert.assertNotNull("Local region apps not found.", registeredApplications); Assert.assertEquals("Local apps size not as expected.", 2, registeredApplications.size()); // Remote region comes with no instances. Application localRegionApp = null; Application remoteRegionApp = null; for (Application registeredApplication : registeredApplications) { if (registeredApplication.getName().equals(LOCAL_REGION_APP_NAME)) { localRegionApp = registeredApplication; } else if (registeredApplication.getName().equals(REMOTE_REGION_APP_NAME)) { remoteRegionApp = registeredApplication; } } Assert.assertNotNull("Local region apps not present.", localRegionApp); Assert.assertTrue("Remote region instances returned for local query.", null == remoteRegionApp || remoteRegionApp.getInstances().isEmpty()); } @Test public void testRemoteEnabledAndQueried() throws Exception { setUp(true); Applications applications = client.getApplicationsForARegion(REMOTE_REGION); List<Application> registeredApplications = applications.getRegisteredApplications(); Assert.assertNotNull("Remote region apps not found.", registeredApplications); Assert.assertEquals("Remote apps size not as expected.", 1, registeredApplications.size()); Assert.assertEquals("Remote region apps not present.", REMOTE_REGION_APP_NAME, registeredApplications.get(0).getName()); } @Test public void testAppsHashCode() throws Exception { setUp(true); Applications applications = client.getApplications(); Assert.assertEquals("UP_1_", applications.getAppsHashCode()); } private void setupBackupMock() { Application localApp = createLocalApps(); Applications localApps = new Applications(); localApps.addApplication(localApp); backupRegistry.setLocalRegionApps(localApps); Application remoteApp = createRemoteApps(); Applications remoteApps = new Applications(); remoteApps.addApplication(remoteApp); backupRegistry.getRemoteRegionVsApps().put(REMOTE_REGION, remoteApps); } private Application createLocalApps() { Application myapp = new Application(LOCAL_REGION_APP_NAME); InstanceInfo instanceInfo = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME); myapp.addInstance(instanceInfo); return myapp; } private Application createRemoteApps() { Application myapp = new Application(REMOTE_REGION_APP_NAME); InstanceInfo instanceInfo = createRemoteInstance(REMOTE_REGION_INSTANCE_1_HOSTNAME); myapp.addInstance(instanceInfo); return myapp; } private InstanceInfo createRemoteInstance(String instanceHostName) { InstanceInfo.Builder instanceBuilder = InstanceInfo.Builder.newBuilder(); instanceBuilder.setAppName(REMOTE_REGION_APP_NAME); instanceBuilder.setVIPAddress(ALL_REGIONS_VIP_ADDR); instanceBuilder.setHostName(instanceHostName); instanceBuilder.setIPAddr("10.10.101.1"); AmazonInfo amazonInfo = getAmazonInfo(REMOTE_ZONE, instanceHostName); instanceBuilder.setDataCenterInfo(amazonInfo); instanceBuilder.setMetadata(amazonInfo.getMetadata()); return instanceBuilder.build(); } private InstanceInfo createLocalInstance(String instanceHostName) { InstanceInfo.Builder instanceBuilder = InstanceInfo.Builder.newBuilder(); instanceBuilder.setAppName(LOCAL_REGION_APP_NAME); instanceBuilder.setVIPAddress(ALL_REGIONS_VIP_ADDR); instanceBuilder.setHostName(instanceHostName); instanceBuilder.setIPAddr("10.10.101.1"); AmazonInfo amazonInfo = getAmazonInfo(null, instanceHostName); instanceBuilder.setDataCenterInfo(amazonInfo); instanceBuilder.setMetadata(amazonInfo.getMetadata()); return instanceBuilder.build(); } private AmazonInfo getAmazonInfo(@Nullable String availabilityZone, String instanceHostName) { AmazonInfo.Builder azBuilder = AmazonInfo.Builder.newBuilder(); azBuilder.addMetadata(AmazonInfo.MetaDataKey.availabilityZone, (null == availabilityZone) ? "us-east-1a" : availabilityZone); azBuilder.addMetadata(AmazonInfo.MetaDataKey.instanceId, instanceHostName); azBuilder.addMetadata(AmazonInfo.MetaDataKey.amiId, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.instanceType, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.localIpv4, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.publicIpv4, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.publicHostname, instanceHostName); return azBuilder.build(); } }
7,863
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientRedirectTest.java
package com.netflix.discovery; import javax.ws.rs.core.MediaType; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.EntityBodyConverter; import com.netflix.discovery.junit.resource.DiscoveryClientResource; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.EurekaEntityFunctions; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.mockserver.client.server.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.matchers.Times; import org.mockserver.model.Header; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.verify.VerificationTimes.atLeast; import static org.mockserver.verify.VerificationTimes.exactly; /** * @author Tomasz Bak */ public class DiscoveryClientRedirectTest { static class MockClientHolder { MockServerClient client; } private final InstanceInfo myInstanceInfo = InstanceInfoGenerator.takeOne(); @Rule public MockServerRule redirectServerMockRule = new MockServerRule(this); private MockServerClient redirectServerMockClient; private MockClientHolder targetServerMockClient = new MockClientHolder(); @Rule public MockServerRule targetServerMockRule = new MockServerRule(targetServerMockClient); @Rule public DiscoveryClientResource registryFetchClientRule = DiscoveryClientResource.newBuilder() .withRegistration(false) .withRegistryFetch(true) .withPortResolver(new Callable<Integer>() { @Override public Integer call() throws Exception { return redirectServerMockRule.getHttpPort(); } }) .withInstanceInfo(myInstanceInfo) .build(); @Rule public DiscoveryClientResource registeringClientRule = DiscoveryClientResource.newBuilder() .withRegistration(true) .withRegistryFetch(false) .withPortResolver(new Callable<Integer>() { @Override public Integer call() throws Exception { return redirectServerMockRule.getHttpPort(); } }) .withInstanceInfo(myInstanceInfo) .build(); private String targetServerBaseUri; private final InstanceInfoGenerator dataGenerator = InstanceInfoGenerator.newBuilder(2, 1).withMetaData(true).build(); @Before public void setUp() throws Exception { targetServerBaseUri = "http://localhost:" + targetServerMockRule.getHttpPort(); } @After public void tearDown() { if (redirectServerMockClient != null) { redirectServerMockClient.reset(); } if (targetServerMockClient.client != null) { targetServerMockClient.client.reset(); } } @Test public void testClientQueryFollowsRedirectsAndPinsToTargetServer() throws Exception { Applications fullFetchApps = dataGenerator.takeDelta(1); String fullFetchJson = toJson(fullFetchApps); Applications deltaFetchApps = dataGenerator.takeDelta(1); String deltaFetchJson = toJson(deltaFetchApps); redirectServerMockClient.when( request() .withMethod("GET") .withPath("/eureka/v2/apps/") ).respond( response() .withStatusCode(302) .withHeader(new Header("Location", targetServerBaseUri + "/eureka/v2/apps/")) ); targetServerMockClient.client.when( request() .withMethod("GET") .withPath("/eureka/v2/apps/") ).respond( response() .withStatusCode(200) .withHeader(new Header("Content-Type", "application/json")) .withBody(fullFetchJson) ); targetServerMockClient.client.when( request() .withMethod("GET") .withPath("/eureka/v2/apps/delta") ).respond( response() .withStatusCode(200) .withHeader(new Header("Content-Type", "application/json")) .withBody(deltaFetchJson) ); final EurekaClient client = registryFetchClientRule.getClient(); await(new Callable<Boolean>() { @Override public Boolean call() throws Exception { List<Application> applicationList = client.getApplications().getRegisteredApplications(); return !applicationList.isEmpty() && applicationList.get(0).getInstances().size() == 2; } }, 1, TimeUnit.MINUTES); redirectServerMockClient.verify(request().withMethod("GET").withPath("/eureka/v2/apps/"), exactly(1)); redirectServerMockClient.verify(request().withMethod("GET").withPath("/eureka/v2/apps/delta"), exactly(0)); targetServerMockClient.client.verify(request().withMethod("GET").withPath("/eureka/v2/apps/"), exactly(1)); targetServerMockClient.client.verify(request().withMethod("GET").withPath("/eureka/v2/apps/delta"), atLeast(1)); } // There is an issue with using mock-server for this test case. For now it is verified manually that it works. @Ignore @Test public void testClientRegistrationFollowsRedirectsAndPinsToTargetServer() throws Exception { } @Test public void testClientFallsBackToOriginalServerOnError() throws Exception { Applications fullFetchApps1 = dataGenerator.takeDelta(1); String fullFetchJson1 = toJson(fullFetchApps1); Applications fullFetchApps2 = EurekaEntityFunctions.mergeApplications(fullFetchApps1, dataGenerator.takeDelta(1)); String fullFetchJson2 = toJson(fullFetchApps2); redirectServerMockClient.when( request() .withMethod("GET") .withPath("/eureka/v2/apps/") ).respond( response() .withStatusCode(302) .withHeader(new Header("Location", targetServerBaseUri + "/eureka/v2/apps/")) ); targetServerMockClient.client.when( request() .withMethod("GET") .withPath("/eureka/v2/apps/"), Times.exactly(1) ).respond( response() .withStatusCode(200) .withHeader(new Header("Content-Type", "application/json")) .withBody(fullFetchJson1) ); targetServerMockClient.client.when( request() .withMethod("GET") .withPath("/eureka/v2/apps/delta"), Times.exactly(1) ).respond( response() .withStatusCode(500) ); redirectServerMockClient.when( request() .withMethod("GET") .withPath("/eureka/v2/apps/delta") ).respond( response() .withStatusCode(200) .withHeader(new Header("Content-Type", "application/json")) .withBody(fullFetchJson2) ); final EurekaClient client = registryFetchClientRule.getClient(); await(new Callable<Boolean>() { @Override public Boolean call() throws Exception { List<Application> applicationList = client.getApplications().getRegisteredApplications(); return !applicationList.isEmpty() && applicationList.get(0).getInstances().size() == 2; } }, 1, TimeUnit.MINUTES); redirectServerMockClient.verify(request().withMethod("GET").withPath("/eureka/v2/apps/"), exactly(1)); redirectServerMockClient.verify(request().withMethod("GET").withPath("/eureka/v2/apps/delta"), exactly(1)); targetServerMockClient.client.verify(request().withMethod("GET").withPath("/eureka/v2/apps/"), exactly(1)); targetServerMockClient.client.verify(request().withMethod("GET").withPath("/eureka/v2/apps/delta"), exactly(1)); } private static String toJson(Applications applications) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); new EntityBodyConverter().write(applications, os, MediaType.APPLICATION_JSON_TYPE); os.close(); return os.toString(); } private static void await(Callable<Boolean> condition, long time, TimeUnit timeUnit) throws Exception { long timeout = System.currentTimeMillis() + timeUnit.toMillis(time); while (!condition.call()) { if (System.currentTimeMillis() >= timeout) { throw new TimeoutException(); } Thread.sleep(100); } } }
7,864
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientRegistryTest.java
package com.netflix.discovery; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.junit.resource.DiscoveryClientResource; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.SimpleEurekaHttpServer; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import static com.netflix.discovery.util.EurekaEntityFunctions.copyApplications; import static com.netflix.discovery.util.EurekaEntityFunctions.countInstances; import static com.netflix.discovery.util.EurekaEntityFunctions.mergeApplications; import static com.netflix.discovery.util.EurekaEntityFunctions.takeFirst; import static com.netflix.discovery.util.EurekaEntityFunctions.toApplications; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Nitesh Kant */ public class DiscoveryClientRegistryTest { private static final String TEST_LOCAL_REGION = "us-east-1"; private static final String TEST_REMOTE_REGION = "us-west-2"; private static final String TEST_REMOTE_ZONE = "us-west-2c"; private static final EurekaHttpClient requestHandler = mock(EurekaHttpClient.class); private static SimpleEurekaHttpServer eurekaHttpServer; @Rule public DiscoveryClientResource discoveryClientResource = DiscoveryClientResource.newBuilder() .withRegistration(false) .withRegistryFetch(true) .withRemoteRegions(TEST_REMOTE_REGION) .connectWith(eurekaHttpServer) .build(); /** * Share server stub by all tests. */ @BeforeClass public static void setUpClass() throws IOException { eurekaHttpServer = new SimpleEurekaHttpServer(requestHandler); } @AfterClass public static void tearDownClass() throws Exception { if (eurekaHttpServer != null) { eurekaHttpServer.shutdown(); } } @Before public void setUp() throws Exception { reset(requestHandler); when(requestHandler.cancel(anyString(), anyString())).thenReturn(EurekaHttpResponse.status(200)); when(requestHandler.getDelta()).thenReturn( anEurekaHttpResponse(200, new Applications()).type(MediaType.APPLICATION_JSON_TYPE).build() ); } @Test public void testGetByVipInLocalRegion() throws Exception { Applications applications = InstanceInfoGenerator.newBuilder(4, "app1", "app2").build().toApplications(); InstanceInfo instance = applications.getRegisteredApplications("app1").getInstances().get(0); when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, applications).type(MediaType.APPLICATION_JSON_TYPE).build() ); List<InstanceInfo> result = discoveryClientResource.getClient().getInstancesByVipAddress(instance.getVIPAddress(), false); assertThat(result.size(), is(equalTo(2))); assertThat(result.get(0).getVIPAddress(), is(equalTo(instance.getVIPAddress()))); } @Test public void testGetAllKnownRegions() throws Exception { prepareRemoteRegionRegistry(); EurekaClient client = discoveryClientResource.getClient(); Set<String> allKnownRegions = client.getAllKnownRegions(); assertThat(allKnownRegions.size(), is(equalTo(2))); assertThat(allKnownRegions, hasItem(TEST_REMOTE_REGION)); } @Test public void testAllAppsForRegions() throws Exception { prepareRemoteRegionRegistry(); EurekaClient client = discoveryClientResource.getClient(); Applications appsForRemoteRegion = client.getApplicationsForARegion(TEST_REMOTE_REGION); assertThat(countInstances(appsForRemoteRegion), is(equalTo(4))); Applications appsForLocalRegion = client.getApplicationsForARegion(TEST_LOCAL_REGION); assertThat(countInstances(appsForLocalRegion), is(equalTo(4))); } @Test public void testCacheRefreshSingleAppForLocalRegion() throws Exception { InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(2, "testApp").build(); Applications initialApps = instanceGen.takeDelta(1); String vipAddress = initialApps.getRegisteredApplications().get(0).getInstances().get(0).getVIPAddress(); DiscoveryClientResource vipClientResource = discoveryClientResource.fork().withVipFetch(vipAddress).build(); // Take first portion when(requestHandler.getVip(vipAddress, TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, initialApps).type(MediaType.APPLICATION_JSON_TYPE).build() ); EurekaClient vipClient = vipClientResource.getClient(); assertThat(countInstances(vipClient.getApplications()), is(equalTo(1))); // Now second one when(requestHandler.getVip(vipAddress, TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, instanceGen.toApplications()).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(vipClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); assertThat(countInstances(vipClient.getApplications()), is(equalTo(2))); } @Test public void testEurekaClientPeriodicHeartbeat() throws Exception { DiscoveryClientResource registeringClientResource = discoveryClientResource.fork().withRegistration(true).withRegistryFetch(false).build(); InstanceInfo instance = registeringClientResource.getMyInstanceInfo(); when(requestHandler.register(any(InstanceInfo.class))).thenReturn(EurekaHttpResponse.status(204)); when(requestHandler.sendHeartBeat(instance.getAppName(), instance.getId(), null, null)).thenReturn(anEurekaHttpResponse(200, InstanceInfo.class).build()); registeringClientResource.getClient(); // Initialize verify(requestHandler, timeout(5 * 1000).atLeast(2)).sendHeartBeat(instance.getAppName(), instance.getId(), null, null); } @Test public void testEurekaClientPeriodicCacheRefresh() throws Exception { InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(3, 1).build(); Applications initialApps = instanceGen.takeDelta(1); // Full fetch when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, initialApps).type(MediaType.APPLICATION_JSON_TYPE).build() ); EurekaClient client = discoveryClientResource.getClient(); assertThat(countInstances(client.getApplications()), is(equalTo(1))); // Delta 1 when(requestHandler.getDelta(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, instanceGen.takeDelta(1)).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); // Delta 2 when(requestHandler.getDelta(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, instanceGen.takeDelta(1)).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); assertThat(countInstances(client.getApplications()), is(equalTo(3))); } @Test public void testGetInvalidVIP() throws Exception { Applications applications = InstanceInfoGenerator.newBuilder(1, "testApp").build().toApplications(); when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, applications).type(MediaType.APPLICATION_JSON_TYPE).build() ); EurekaClient client = discoveryClientResource.getClient(); assertThat(countInstances(client.getApplications()), is(equalTo(1))); List<InstanceInfo> instancesByVipAddress = client.getInstancesByVipAddress("XYZ", false); assertThat(instancesByVipAddress.isEmpty(), is(true)); } @Test public void testGetInvalidVIPForRemoteRegion() throws Exception { prepareRemoteRegionRegistry(); EurekaClient client = discoveryClientResource.getClient(); List<InstanceInfo> instancesByVipAddress = client.getInstancesByVipAddress("XYZ", false, TEST_REMOTE_REGION); assertThat(instancesByVipAddress.isEmpty(), is(true)); } @Test public void testGetByVipInRemoteRegion() throws Exception { prepareRemoteRegionRegistry(); EurekaClient client = discoveryClientResource.getClient(); String vipAddress = takeFirst(client.getApplicationsForARegion(TEST_REMOTE_REGION)).getVIPAddress(); List<InstanceInfo> instancesByVipAddress = client.getInstancesByVipAddress(vipAddress, false, TEST_REMOTE_REGION); assertThat(instancesByVipAddress.size(), is(equalTo(2))); InstanceInfo instance = instancesByVipAddress.iterator().next(); assertThat(instance.getVIPAddress(), is(equalTo(vipAddress))); } @Test public void testAppsHashCodeAfterRefresh() throws Exception { InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(2, "testApp").build(); // Full fetch with one item InstanceInfo first = instanceGen.first(); Applications initial = toApplications(first); when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, initial).type(MediaType.APPLICATION_JSON_TYPE).build() ); EurekaClient client = discoveryClientResource.getClient(); assertThat(client.getApplications().getAppsHashCode(), is(equalTo("UP_1_"))); // Delta with one add InstanceInfo second = new InstanceInfo.Builder(instanceGen.take(1)).setStatus(InstanceStatus.DOWN).build(); Applications delta = toApplications(second); delta.setAppsHashCode("DOWN_1_UP_1_"); when(requestHandler.getDelta(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, delta).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); assertThat(client.getApplications().getAppsHashCode(), is(equalTo("DOWN_1_UP_1_"))); } @Test public void testApplyDeltaWithBadInstanceInfoDataCenterInfoAsNull() throws Exception { InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(2, "testApp").build(); // Full fetch with one item InstanceInfo first = instanceGen.first(); Applications initial = toApplications(first); when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, initial).type(MediaType.APPLICATION_JSON_TYPE).build() ); EurekaClient client = discoveryClientResource.getClient(); assertThat(client.getApplications().getAppsHashCode(), is(equalTo("UP_1_"))); // Delta with one add InstanceInfo second = new InstanceInfo.Builder(instanceGen.take(1)).setInstanceId("foo1").setStatus(InstanceStatus.DOWN).setDataCenterInfo(null).build(); InstanceInfo third = new InstanceInfo.Builder(instanceGen.take(1)).setInstanceId("foo2").setStatus(InstanceStatus.UP).setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return null; } }).build(); Applications delta = toApplications(second, third); delta.setAppsHashCode("DOWN_1_UP_2_"); when(requestHandler.getDelta(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, delta).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); assertThat(client.getApplications().getAppsHashCode(), is(equalTo("DOWN_1_UP_2_"))); } @Test public void testEurekaClientPeriodicCacheRefreshForDelete() throws Exception { InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(3, 1).build(); Applications initialApps = instanceGen.takeDelta(2); Applications deltaForDelete = instanceGen.takeDeltaForDelete(true, 1); when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, initialApps).type(MediaType.APPLICATION_JSON_TYPE).build() ); EurekaClient client = discoveryClientResource.getClient(); assertThat(countInstances(client.getApplications()), is(equalTo(2))); when(requestHandler.getDelta(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, deltaForDelete).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); assertThat(client.getApplications().getRegisteredApplications().size(), is(equalTo(1))); assertThat(countInstances(client.getApplications()), is(equalTo(1))); } @Test public void testEurekaClientPeriodicCacheRefreshForDeleteAndNoApplication() throws Exception { InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(3, 1).build(); Applications initialApps = instanceGen.takeDelta(1); Applications deltaForDelete = instanceGen.takeDeltaForDelete(true, 1); when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, initialApps).type(MediaType.APPLICATION_JSON_TYPE).build() ); EurekaClient client = discoveryClientResource.getClient(); assertThat(countInstances(client.getApplications()), is(equalTo(1))); when(requestHandler.getDelta(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, deltaForDelete).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); assertEquals(client.getApplications().getRegisteredApplications(), new ArrayList<>()); } /** * There is a bug, because of which remote registry data structures are not initialized during full registry fetch, only during delta. */ private void prepareRemoteRegionRegistry() throws Exception { Applications localApplications = InstanceInfoGenerator.newBuilder(4, "app1", "app2").build().toApplications(); Applications remoteApplications = InstanceInfoGenerator.newBuilder(4, "remote1", "remote2").withZone(TEST_REMOTE_ZONE).build().toApplications(); Applications allApplications = mergeApplications(localApplications, remoteApplications); // Load remote data in delta, to go around exiting bug in DiscoveryClient Applications delta = copyApplications(remoteApplications); delta.setAppsHashCode(allApplications.getAppsHashCode()); when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, localApplications).type(MediaType.APPLICATION_JSON_TYPE).build() ); when(requestHandler.getDelta(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, delta).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); } }
7,865
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/AbstractDiscoveryClientTester.java
package com.netflix.discovery; import com.netflix.discovery.junit.resource.DiscoveryClientResource; import org.junit.After; import org.junit.Before; /** * @author Nitesh Kant */ public abstract class AbstractDiscoveryClientTester extends BaseDiscoveryClientTester { @Before public void setUp() throws Exception { setupProperties(); populateLocalRegistryAtStartup(); populateRemoteRegistryAtStartup(); setupDiscoveryClient(); } @After public void tearDown() throws Exception { shutdownDiscoveryClient(); DiscoveryClientResource.clearDiscoveryClientConfig(); } }
7,866
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/InstanceRegionCheckerTest.java
package com.netflix.discovery; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.config.ConfigurationManager; import org.junit.Assert; import org.junit.Test; /** * @author Nitesh Kant */ public class InstanceRegionCheckerTest { @Test public void testDefaults() throws Exception { PropertyBasedAzToRegionMapper azToRegionMapper = new PropertyBasedAzToRegionMapper( new DefaultEurekaClientConfig()); InstanceRegionChecker checker = new InstanceRegionChecker(azToRegionMapper, "us-east-1"); azToRegionMapper.setRegionsToFetch(new String[]{"us-east-1"}); AmazonInfo dcInfo = AmazonInfo.Builder.newBuilder().addMetadata(AmazonInfo.MetaDataKey.availabilityZone, "us-east-1c").build(); InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("app").setDataCenterInfo(dcInfo).build(); String instanceRegion = checker.getInstanceRegion(instanceInfo); Assert.assertEquals("Invalid instance region.", "us-east-1", instanceRegion); } @Test public void testDefaultOverride() throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.us-east-1.availabilityZones", "abc,def"); PropertyBasedAzToRegionMapper azToRegionMapper = new PropertyBasedAzToRegionMapper(new DefaultEurekaClientConfig()); InstanceRegionChecker checker = new InstanceRegionChecker(azToRegionMapper, "us-east-1"); azToRegionMapper.setRegionsToFetch(new String[]{"us-east-1"}); AmazonInfo dcInfo = AmazonInfo.Builder.newBuilder().addMetadata(AmazonInfo.MetaDataKey.availabilityZone, "def").build(); InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("app").setDataCenterInfo( dcInfo).build(); String instanceRegion = checker.getInstanceRegion(instanceInfo); Assert.assertEquals("Invalid instance region.", "us-east-1", instanceRegion); } @Test public void testInstanceWithNoAZ() throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.us-east-1.availabilityZones", "abc,def"); PropertyBasedAzToRegionMapper azToRegionMapper = new PropertyBasedAzToRegionMapper(new DefaultEurekaClientConfig()); InstanceRegionChecker checker = new InstanceRegionChecker(azToRegionMapper, "us-east-1"); azToRegionMapper.setRegionsToFetch(new String[]{"us-east-1"}); AmazonInfo dcInfo = AmazonInfo.Builder.newBuilder().addMetadata(AmazonInfo.MetaDataKey.availabilityZone, "").build(); InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("app").setDataCenterInfo( dcInfo).build(); String instanceRegion = checker.getInstanceRegion(instanceInfo); Assert.assertNull("Invalid instance region.", instanceRegion); } @Test public void testNotMappedAZ() throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.us-east-1.availabilityZones", "abc,def"); PropertyBasedAzToRegionMapper azToRegionMapper = new PropertyBasedAzToRegionMapper(new DefaultEurekaClientConfig()); InstanceRegionChecker checker = new InstanceRegionChecker(azToRegionMapper, "us-east-1"); azToRegionMapper.setRegionsToFetch(new String[]{"us-east-1"}); AmazonInfo dcInfo = AmazonInfo.Builder.newBuilder().addMetadata(AmazonInfo.MetaDataKey.availabilityZone, "us-east-1x").build(); InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("abc").setDataCenterInfo(dcInfo).build(); String instanceRegion = checker.getInstanceRegion(instanceInfo); Assert.assertEquals("Invalid instance region.", "us-east-1", instanceRegion); } @Test public void testNotMappedAZNotFollowingFormat() throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.us-east-1.availabilityZones", "abc,def"); PropertyBasedAzToRegionMapper azToRegionMapper = new PropertyBasedAzToRegionMapper(new DefaultEurekaClientConfig()); InstanceRegionChecker checker = new InstanceRegionChecker(azToRegionMapper, "us-east-1"); azToRegionMapper.setRegionsToFetch(new String[]{"us-east-1"}); AmazonInfo dcInfo = AmazonInfo.Builder.newBuilder().addMetadata(AmazonInfo.MetaDataKey.availabilityZone, "us-east-x").build(); InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("abc").setDataCenterInfo(dcInfo).build(); String instanceRegion = checker.getInstanceRegion(instanceInfo); Assert.assertNull("Invalid instance region.", instanceRegion); } }
7,867
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientDisableRegistryTest.java
package com.netflix.discovery; import java.util.UUID; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.config.ConfigurationManager; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author Nitesh Kant */ public class DiscoveryClientDisableRegistryTest { private EurekaClient client; private MockRemoteEurekaServer mockLocalEurekaServer; @Before public void setUp() throws Exception { mockLocalEurekaServer = new MockRemoteEurekaServer(); mockLocalEurekaServer.start(); ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "false"); ConfigurationManager.getConfigInstance().setProperty("eureka.shouldFetchRegistry", "false"); ConfigurationManager.getConfigInstance().setProperty("eureka.serviceUrl.default", "http://localhost:" + mockLocalEurekaServer.getPort() + MockRemoteEurekaServer.EUREKA_API_BASE_PATH); InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(); builder.setIPAddr("10.10.101.00"); builder.setHostName("Hosttt"); builder.setAppName("EurekaTestApp-" + UUID.randomUUID()); builder.setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }); ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig(), builder.build()); client = new DiscoveryClient(applicationInfoManager, new DefaultEurekaClientConfig()); } @Test public void testDisableFetchRegistry() throws Exception { Assert.assertFalse("Registry fetch disabled but eureka server recieved a registry fetch.", mockLocalEurekaServer.isSentRegistry()); } }
7,868
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/TimedSupervisorTaskTest.java
package com.netflix.discovery; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TimedSupervisorTaskTest { private static final int EXP_BACK_OFF_BOUND = 10; private ScheduledExecutorService scheduler; private ListeningExecutorService helperExecutor; private ThreadPoolExecutor executor; private AtomicLong testTaskStartCounter; private AtomicLong testTaskSuccessfulCounter; private AtomicLong testTaskInterruptedCounter; private AtomicLong maxConcurrentTestTasks; private AtomicLong testTaskCounter; @Before public void setUp() { scheduler = Executors.newScheduledThreadPool(4, new ThreadFactoryBuilder() .setNameFormat("DiscoveryClient-%d") .setDaemon(true) .build()); helperExecutor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10)); executor = new ThreadPoolExecutor( 1, // corePoolSize 3, // maxPoolSize 0, // keepAliveTime TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); // use direct handoff testTaskStartCounter = new AtomicLong(0); testTaskSuccessfulCounter = new AtomicLong(0); testTaskInterruptedCounter = new AtomicLong(0); maxConcurrentTestTasks = new AtomicLong(0); testTaskCounter = new AtomicLong(0); } @After public void tearDown() { if (executor != null) { executor.shutdownNow(); } if (helperExecutor != null) { helperExecutor.shutdownNow(); } if (scheduler != null) { scheduler.shutdownNow(); } } @Test public void testSupervisorTaskDefaultSingleTestTaskHappyCase() throws Exception { // testTask should never timeout TestTask testTask = new TestTask(1, false); TimedSupervisorTask supervisorTask = new TimedSupervisorTask("test", scheduler, executor, 5, TimeUnit.SECONDS, EXP_BACK_OFF_BOUND, testTask); helperExecutor.submit(supervisorTask).get(); Assert.assertEquals(1, maxConcurrentTestTasks.get()); Assert.assertEquals(0, testTaskCounter.get()); Assert.assertEquals(1, testTaskStartCounter.get()); Assert.assertEquals(1, testTaskSuccessfulCounter.get()); Assert.assertEquals(0, testTaskInterruptedCounter.get()); } @Test public void testSupervisorTaskCancelsTimedOutTask() throws Exception { // testTask will always timeout TestTask testTask = new TestTask(5, false); TimedSupervisorTask supervisorTask = new TimedSupervisorTask("test", scheduler, executor, 1, TimeUnit.SECONDS, EXP_BACK_OFF_BOUND, testTask); helperExecutor.submit(supervisorTask).get(); Thread.sleep(500); // wait a little bit for the subtask interrupt handler Assert.assertEquals(1, maxConcurrentTestTasks.get()); Assert.assertEquals(1, testTaskCounter.get()); Assert.assertEquals(1, testTaskStartCounter.get()); Assert.assertEquals(0, testTaskSuccessfulCounter.get()); Assert.assertEquals(1, testTaskInterruptedCounter.get()); } @Test public void testSupervisorRejectNewTasksIfThreadPoolIsFullForIncompleteTasks() throws Exception { // testTask should always timeout TestTask testTask = new TestTask(4, true); TimedSupervisorTask supervisorTask = new TimedSupervisorTask("test", scheduler, executor, 1, TimeUnit.MILLISECONDS, EXP_BACK_OFF_BOUND, testTask); scheduler.schedule(supervisorTask, 0, TimeUnit.SECONDS); Thread.sleep(500); // wait a little bit for the subtask interrupt handlers Assert.assertEquals(3, maxConcurrentTestTasks.get()); Assert.assertEquals(3, testTaskCounter.get()); Assert.assertEquals(3, testTaskStartCounter.get()); Assert.assertEquals(0, testTaskSuccessfulCounter.get()); Assert.assertEquals(0, testTaskInterruptedCounter.get()); } @Test public void testSupervisorTaskAsPeriodicScheduledJobHappyCase() throws Exception { // testTask should never timeout TestTask testTask = new TestTask(1, false); TimedSupervisorTask supervisorTask = new TimedSupervisorTask("test", scheduler, executor, 4, TimeUnit.SECONDS, EXP_BACK_OFF_BOUND, testTask); scheduler.schedule(supervisorTask, 0, TimeUnit.SECONDS); Thread.sleep(5000); // let the scheduler run for long enough for some results Assert.assertEquals(1, maxConcurrentTestTasks.get()); Assert.assertEquals(0, testTaskCounter.get()); Assert.assertEquals(0, testTaskInterruptedCounter.get()); } @Test public void testSupervisorTaskAsPeriodicScheduledJobTestTaskTimingOut() throws Exception { // testTask should always timeout TestTask testTask = new TestTask(5, false); TimedSupervisorTask supervisorTask = new TimedSupervisorTask("test", scheduler, executor, 2, TimeUnit.SECONDS, EXP_BACK_OFF_BOUND, testTask); scheduler.schedule(supervisorTask, 0, TimeUnit.SECONDS); Thread.sleep(5000); // let the scheduler run for long enough for some results Assert.assertEquals(1, maxConcurrentTestTasks.get()); Assert.assertTrue(0 != testTaskCounter.get()); // tasks are been cancelled Assert.assertEquals(0, testTaskSuccessfulCounter.get()); } private class TestTask implements Runnable { private final int runTimeSecs; private final boolean blockInterrupt; public TestTask(int runTimeSecs, boolean blockInterrupt) { this.runTimeSecs = runTimeSecs; this.blockInterrupt = blockInterrupt; } public void run() { testTaskStartCounter.incrementAndGet(); try { testTaskCounter.incrementAndGet(); synchronized (maxConcurrentTestTasks) { int activeCount = executor.getActiveCount(); if (maxConcurrentTestTasks.get() < activeCount) { maxConcurrentTestTasks.set(activeCount); } } long endTime = System.currentTimeMillis() + runTimeSecs * 1000; while (endTime >= System.currentTimeMillis()) { try { Thread.sleep(runTimeSecs * 1000); } catch (InterruptedException e) { if (!blockInterrupt) { throw e; } } } testTaskCounter.decrementAndGet(); testTaskSuccessfulCounter.incrementAndGet(); } catch (InterruptedException e) { testTaskInterruptedCounter.incrementAndGet(); } } } }
7,869
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientEventBusTest.java
package com.netflix.discovery; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.junit.resource.DiscoveryClientResource; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.SimpleEurekaHttpServer; import com.netflix.discovery.util.InstanceInfoGenerator; import com.netflix.eventbus.spi.EventBus; import com.netflix.eventbus.spi.Subscribe; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import static com.netflix.discovery.util.EurekaEntityFunctions.toApplications; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; /** * @author David Liu */ public class DiscoveryClientEventBusTest { private static final EurekaHttpClient requestHandler = mock(EurekaHttpClient.class); private static SimpleEurekaHttpServer eurekaHttpServer; @Rule public DiscoveryClientResource discoveryClientResource = DiscoveryClientResource.newBuilder() .withRegistration(false) // we don't need the registration thread for status change .withRegistryFetch(true) .connectWith(eurekaHttpServer) .build(); /** * Share server stub by all tests. */ @BeforeClass public static void setUpClass() throws IOException { eurekaHttpServer = new SimpleEurekaHttpServer(requestHandler); } @AfterClass public static void tearDownClass() throws Exception { if (eurekaHttpServer != null) { eurekaHttpServer.shutdown(); } } @Before public void setUp() throws Exception { reset(requestHandler); when(requestHandler.register(any(InstanceInfo.class))).thenReturn(EurekaHttpResponse.status(204)); when(requestHandler.cancel(anyString(), anyString())).thenReturn(EurekaHttpResponse.status(200)); when(requestHandler.getDelta()).thenReturn( anEurekaHttpResponse(200, new Applications()).type(MediaType.APPLICATION_JSON_TYPE).build() ); } @Test public void testStatusChangeEvent() throws Exception { final CountDownLatch eventLatch = new CountDownLatch(1); final List<StatusChangeEvent> receivedEvents = new ArrayList<>(); EventBus eventBus = discoveryClientResource.getEventBus(); eventBus.registerSubscriber(new Object() { @Subscribe public void consume(StatusChangeEvent event) { receivedEvents.add(event); eventLatch.countDown(); } }); Applications initialApps = toApplications(discoveryClientResource.getMyInstanceInfo()); when(requestHandler.getApplications()).thenReturn( anEurekaHttpResponse(200, initialApps).type(MediaType.APPLICATION_JSON_TYPE).build() ); discoveryClientResource.getClient(); // Activates the client assertThat(eventLatch.await(10, TimeUnit.SECONDS), is(true)); assertThat(receivedEvents.size(), is(equalTo(1))); assertThat(receivedEvents.get(0), is(notNullValue())); } @Test public void testCacheRefreshEvent() throws Exception { InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(2, "testApp").build(); // Initial full fetch Applications initialApps = instanceGen.takeDelta(1); when(requestHandler.getApplications()).thenReturn( anEurekaHttpResponse(200, initialApps).type(MediaType.APPLICATION_JSON_TYPE).build() ); discoveryClientResource.getClient(); // Activates the client // Delta update Applications delta = instanceGen.takeDelta(1); when(requestHandler.getDelta()).thenReturn( anEurekaHttpResponse(200, delta).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(10, TimeUnit.SECONDS), is(true)); } }
7,870
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientHealthTest.java
package com.netflix.discovery; import com.netflix.appinfo.HealthCheckCallback; import com.netflix.appinfo.HealthCheckHandler; import com.netflix.appinfo.InstanceInfo; import com.netflix.config.ConfigurationManager; import org.junit.Assert; import org.junit.Test; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.range; /** * @author Nitesh Kant */ public class DiscoveryClientHealthTest extends AbstractDiscoveryClientTester { @Override protected void setupProperties() { super.setupProperties(); ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "true"); // as the tests in this class triggers the instanceInfoReplicator explicitly, set the below config // so that it does not run as a background task ConfigurationManager.getConfigInstance().setProperty("eureka.appinfo.initial.replicate.time", Integer.MAX_VALUE); ConfigurationManager.getConfigInstance().setProperty("eureka.appinfo.replicate.interval", Integer.MAX_VALUE); } @Override protected InstanceInfo.Builder newInstanceInfoBuilder(int renewalIntervalInSecs) { InstanceInfo.Builder builder = super.newInstanceInfoBuilder(renewalIntervalInSecs); builder.setStatus(InstanceInfo.InstanceStatus.STARTING); return builder; } @Test public void testCallback() throws Exception { MyHealthCheckCallback myCallback = new MyHealthCheckCallback(true); Assert.assertTrue(client instanceof DiscoveryClient); DiscoveryClient clientImpl = (DiscoveryClient) client; InstanceInfoReplicator instanceInfoReplicator = clientImpl.getInstanceInfoReplicator(); instanceInfoReplicator.run(); Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.STARTING, clientImpl.getInstanceInfo().getStatus()); Assert.assertFalse("Healthcheck callback invoked when status is STARTING.", myCallback.isInvoked()); client.registerHealthCheckCallback(myCallback); clientImpl.getInstanceInfo().setStatus(InstanceInfo.InstanceStatus.OUT_OF_SERVICE); Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.OUT_OF_SERVICE, clientImpl.getInstanceInfo().getStatus()); myCallback.reset(); instanceInfoReplicator.run(); Assert.assertFalse("Healthcheck callback invoked when status is OOS.", myCallback.isInvoked()); clientImpl.getInstanceInfo().setStatus(InstanceInfo.InstanceStatus.DOWN); Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.DOWN, clientImpl.getInstanceInfo().getStatus()); myCallback.reset(); instanceInfoReplicator.run(); Assert.assertTrue("Healthcheck callback not invoked.", myCallback.isInvoked()); Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.UP, clientImpl.getInstanceInfo().getStatus()); } @Test public void testHandler() throws Exception { MyHealthCheckHandler myHealthCheckHandler = new MyHealthCheckHandler(InstanceInfo.InstanceStatus.UP); Assert.assertTrue(client instanceof DiscoveryClient); DiscoveryClient clientImpl = (DiscoveryClient) client; InstanceInfoReplicator instanceInfoReplicator = clientImpl.getInstanceInfoReplicator(); Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.STARTING, clientImpl.getInstanceInfo().getStatus()); client.registerHealthCheck(myHealthCheckHandler); instanceInfoReplicator.run(); Assert.assertTrue("Healthcheck callback not invoked when status is STARTING.", myHealthCheckHandler.isInvoked()); Assert.assertEquals("Instance info status not as expected post healthcheck.", InstanceInfo.InstanceStatus.UP, clientImpl.getInstanceInfo().getStatus()); clientImpl.getInstanceInfo().setStatus(InstanceInfo.InstanceStatus.OUT_OF_SERVICE); Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.OUT_OF_SERVICE, clientImpl.getInstanceInfo().getStatus()); myHealthCheckHandler.reset(); instanceInfoReplicator.run(); Assert.assertTrue("Healthcheck callback not invoked when status is OUT_OF_SERVICE.", myHealthCheckHandler.isInvoked()); Assert.assertEquals("Instance info status not as expected post healthcheck.", InstanceInfo.InstanceStatus.UP, clientImpl.getInstanceInfo().getStatus()); clientImpl.getInstanceInfo().setStatus(InstanceInfo.InstanceStatus.DOWN); Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.DOWN, clientImpl.getInstanceInfo().getStatus()); myHealthCheckHandler.reset(); instanceInfoReplicator.run(); Assert.assertTrue("Healthcheck callback not invoked when status is DOWN.", myHealthCheckHandler.isInvoked()); Assert.assertEquals("Instance info status not as expected post healthcheck.", InstanceInfo.InstanceStatus.UP, clientImpl.getInstanceInfo().getStatus()); clientImpl.getInstanceInfo().setStatus(InstanceInfo.InstanceStatus.UP); myHealthCheckHandler.reset(); myHealthCheckHandler.shouldException = true; instanceInfoReplicator.run(); Assert.assertTrue("Healthcheck callback not invoked when status is UP.", myHealthCheckHandler.isInvoked()); Assert.assertEquals("Instance info status not as expected post healthcheck.", InstanceInfo.InstanceStatus.DOWN, clientImpl.getInstanceInfo().getStatus()); } @Test public void shouldRegisterHealthCheckHandlerInConcurrentEnvironment() throws Exception { HealthCheckHandler myHealthCheckHandler = new MyHealthCheckHandler(InstanceInfo.InstanceStatus.UP); int testsCount = 20; int threadsCount = testsCount * 2; CountDownLatch starterLatch = new CountDownLatch(threadsCount); CountDownLatch finishLatch = new CountDownLatch(threadsCount); List<DiscoveryClient> discoveryClients = range(0, testsCount) .mapToObj(i -> (DiscoveryClient) getSetupDiscoveryClient()) .collect(toList()); Stream<Thread> registerCustomHandlerThreads = discoveryClients.stream().map(client -> new SimultaneousStarter(starterLatch, finishLatch, () -> client.registerHealthCheck(myHealthCheckHandler))); Stream<Thread> lazyInitOfDefaultHandlerThreads = discoveryClients.stream().map(client -> new SimultaneousStarter(starterLatch, finishLatch, client::getHealthCheckHandler)); List<Thread> threads = Stream.concat(registerCustomHandlerThreads, lazyInitOfDefaultHandlerThreads) .collect(toList()); Collections.shuffle(threads); threads.forEach(Thread::start); try { finishLatch.await(); discoveryClients.forEach(client -> Assert.assertSame("Healthcheck handler should be custom.", myHealthCheckHandler, client.getHealthCheckHandler())); } finally { //cleanup resources discoveryClients.forEach(DiscoveryClient::shutdown); } } public static class SimultaneousStarter extends Thread { private final CountDownLatch starterLatch; private final CountDownLatch finishLatch; private final Runnable runnable; public SimultaneousStarter(CountDownLatch starterLatch, CountDownLatch finishLatch, Runnable runnable) { this.starterLatch = starterLatch; this.finishLatch = finishLatch; this.runnable = runnable; } @Override public void run() { starterLatch.countDown(); try { starterLatch.await(); runnable.run(); finishLatch.countDown(); } catch (InterruptedException e) { throw new RuntimeException("Something went wrong..."); } } } private static class MyHealthCheckCallback implements HealthCheckCallback { private final boolean health; private volatile boolean invoked; private MyHealthCheckCallback(boolean health) { this.health = health; } @Override public boolean isHealthy() { invoked = true; return health; } public boolean isInvoked() { return invoked; } public void reset() { invoked = false; } } private static class MyHealthCheckHandler implements HealthCheckHandler { private final InstanceInfo.InstanceStatus health; private volatile boolean invoked; volatile boolean shouldException; private MyHealthCheckHandler(InstanceInfo.InstanceStatus health) { this.health = health; } public boolean isInvoked() { return invoked; } public void reset() { shouldException = false; invoked = false; } @Override public InstanceInfo.InstanceStatus getStatus(InstanceInfo.InstanceStatus currentStatus) { invoked = true; if (shouldException) { throw new RuntimeException("test induced exception"); } return health; } } }
7,871
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientStatsInitFailedTest.java
package com.netflix.discovery; import com.netflix.discovery.junit.resource.DiscoveryClientResource; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Tests for DiscoveryClient stats reported when initial registry fetch fails. */ public class DiscoveryClientStatsInitFailedTest extends BaseDiscoveryClientTester { @Before public void setUp() throws Exception { setupProperties(); populateRemoteRegistryAtStartup(); setupDiscoveryClient(); } @After public void tearDown() throws Exception { shutdownDiscoveryClient(); DiscoveryClientResource.clearDiscoveryClientConfig(); } @Test public void testEmptyInitLocalRegistrySize() throws Exception { Assert.assertTrue(client instanceof DiscoveryClient); DiscoveryClient clientImpl = (DiscoveryClient) client; Assert.assertEquals(0, clientImpl.getStats().initLocalRegistrySize()); } @Test public void testInitFailed() throws Exception { Assert.assertTrue(client instanceof DiscoveryClient); DiscoveryClient clientImpl = (DiscoveryClient) client; Assert.assertFalse(clientImpl.getStats().initSucceeded()); } }
7,872
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/util/EurekaEntityFunctionsTest.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.discovery.util; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; public class EurekaEntityFunctionsTest { private Application createSingleInstanceApp( String appId, String instanceId, InstanceInfo.ActionType actionType) { InstanceInfo instanceInfo = Mockito.mock(InstanceInfo.class); Mockito.when(instanceInfo.getId()).thenReturn(instanceId); Mockito.when(instanceInfo.getAppName()).thenReturn(instanceId); Mockito.when(instanceInfo.getStatus()) .thenReturn(InstanceInfo.InstanceStatus.UP); Mockito.when(instanceInfo.getActionType()).thenReturn(actionType); Application application = new Application(appId); application.addInstance(instanceInfo); return application; } private Applications createApplications(Application... applications) { return new Applications("appsHashCode", 1559658285l, new ArrayList<>(Arrays.asList(applications))); } @Test public void testSelectApplicationNamesIfNotNullReturnNameString() { Applications applications = createApplications(new Application("foo"), new Application("bar"), new Application("baz")); HashSet<String> strings = new HashSet<>(Arrays.asList("baz", "bar", "foo")); Assert.assertEquals(strings, EurekaEntityFunctions.selectApplicationNames(applications)); } @Test public void testSelectInstancesMappedByIdIfNotNullReturnMapOfInstances() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); HashMap<String, InstanceInfo> hashMap = new HashMap<>(); hashMap.put("foo", application.getByInstanceId("foo")); Assert.assertEquals(hashMap, EurekaEntityFunctions.selectInstancesMappedById(application)); } @Test public void testSelectInstanceIfInstanceExistsReturnSelectedInstance() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Applications applications = createApplications(application); Assert.assertNull(EurekaEntityFunctions .selectInstance(new Applications(), "foo")); Assert.assertNull(EurekaEntityFunctions .selectInstance(new Applications(), "foo", "foo")); Assert.assertEquals(application.getByInstanceId("foo"), EurekaEntityFunctions.selectInstance(applications, "foo")); Assert.assertEquals(application.getByInstanceId("foo"), EurekaEntityFunctions.selectInstance(applications, "foo", "foo")); } @Test public void testTakeFirstIfNotNullReturnFirstInstance() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Applications applications = createApplications(application); applications.addApplication(application); Assert.assertNull(EurekaEntityFunctions.takeFirst(new Applications())); Assert.assertEquals(application.getByInstanceId("foo"), EurekaEntityFunctions.takeFirst(applications)); } @Test public void testSelectAllIfNotNullReturnAllInstances() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Applications applications = createApplications(application); applications.addApplication(application); Assert.assertEquals(new ArrayList<>(Arrays.asList( application.getByInstanceId("foo"), application.getByInstanceId("foo"))), EurekaEntityFunctions.selectAll(applications)); } @Test public void testToApplicationMapIfNotNullReturnMapOfApplication() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Assert.assertEquals(1, EurekaEntityFunctions.toApplicationMap( new ArrayList<>(Arrays.asList( application.getByInstanceId("foo")))).size()); } @Test public void testToApplicationsIfNotNullReturnApplicationsFromMapOfApplication() { HashMap<String, Application> hashMap = new HashMap<>(); hashMap.put("foo", new Application("foo")); hashMap.put("bar", new Application("bar")); hashMap.put("baz", new Application("baz")); Applications applications = createApplications(new Application("foo"), new Application("bar"), new Application("baz")); Assert.assertEquals(applications.size(), EurekaEntityFunctions.toApplications(hashMap).size()); } @Test public void testToApplicationsIfNotNullReturnApplicationsFromInstances() { InstanceInfo instanceInfo1 = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED).getByInstanceId("foo"); InstanceInfo instanceInfo2 = createSingleInstanceApp("bar", "bar", InstanceInfo.ActionType.ADDED).getByInstanceId("bar"); InstanceInfo instanceInfo3 = createSingleInstanceApp("baz", "baz", InstanceInfo.ActionType.ADDED).getByInstanceId("baz"); Assert.assertEquals(3, EurekaEntityFunctions.toApplications( instanceInfo1, instanceInfo2, instanceInfo3).size()); } @Test public void testCopyApplicationsIfNotNullReturnApplications() { Application application1 = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Application application2 = createSingleInstanceApp("bar", "bar", InstanceInfo.ActionType.ADDED); Applications applications = createApplications(); applications.addApplication(application1); applications.addApplication(application2); Assert.assertEquals(2, EurekaEntityFunctions.copyApplications(applications).size()); } @Test public void testCopyApplicationIfNotNullReturnApplication() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Assert.assertEquals(1, EurekaEntityFunctions.copyApplication(application).size()); } @Test public void testCopyInstancesIfNotNullReturnCollectionOfInstanceInfo() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Assert.assertEquals(1, EurekaEntityFunctions.copyInstances( new ArrayList<>(Arrays.asList( application.getByInstanceId("foo"))), InstanceInfo.ActionType.ADDED).size()); } @Test public void testMergeApplicationsIfNotNullAndHasAppNameReturnApplications() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Applications applications = createApplications(application); Assert.assertEquals(1, EurekaEntityFunctions.mergeApplications( applications, applications).size()); } @Test public void testMergeApplicationsIfNotNullAndDoesNotHaveAppNameReturnApplications() { Application application1 = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Applications applications1 = createApplications(application1); Application application2 = createSingleInstanceApp("bar", "bar", InstanceInfo.ActionType.ADDED); Applications applications2 = createApplications(application2); Assert.assertEquals(2, EurekaEntityFunctions.mergeApplications( applications1, applications2).size()); } @Test public void testMergeApplicationIfActionTypeAddedReturnApplication() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Assert.assertEquals(application.getInstances(), EurekaEntityFunctions.mergeApplication( application, application).getInstances()); } @Test public void testMergeApplicationIfActionTypeModifiedReturnApplication() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.MODIFIED); Assert.assertEquals(application.getInstances(), EurekaEntityFunctions.mergeApplication( application, application).getInstances()); } @Test public void testMergeApplicationIfActionTypeDeletedReturnApplication() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.DELETED); Assert.assertNotEquals(application.getInstances(), EurekaEntityFunctions.mergeApplication( application, application).getInstances()); } @Test public void testUpdateMetaIfNotNullReturnApplications() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Applications applications = createApplications(application); Assert.assertEquals(1l, (long) EurekaEntityFunctions.updateMeta(applications) .getVersion()); } @Test public void testCountInstancesIfApplicationsHasInstancesReturnSize() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Applications applications = createApplications(application); Assert.assertEquals(1, EurekaEntityFunctions.countInstances(applications)); } @Test public void testComparatorByAppNameAndIdIfNotNullReturnInt() { InstanceInfo instanceInfo1 = Mockito.mock(InstanceInfo.class); InstanceInfo instanceInfo2 = Mockito.mock(InstanceInfo.class); InstanceInfo instanceInfo3 = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED).getByInstanceId("foo"); InstanceInfo instanceInfo4 = createSingleInstanceApp("bar", "bar", InstanceInfo.ActionType.ADDED).getByInstanceId("bar"); Assert.assertTrue(EurekaEntityFunctions.comparatorByAppNameAndId() .compare(instanceInfo1, instanceInfo2) > 0); Assert.assertTrue(EurekaEntityFunctions.comparatorByAppNameAndId() .compare(instanceInfo3, instanceInfo2) > 0); Assert.assertTrue(EurekaEntityFunctions.comparatorByAppNameAndId() .compare(instanceInfo1, instanceInfo3) < 0); Assert.assertTrue(EurekaEntityFunctions.comparatorByAppNameAndId() .compare(instanceInfo3, instanceInfo4) > 0); Assert.assertTrue(EurekaEntityFunctions.comparatorByAppNameAndId() .compare(instanceInfo3, instanceInfo3) == 0); } }
7,873
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/util/EurekaUtilsTest.java
package com.netflix.discovery.util; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import org.junit.Assert; import org.junit.Test; /** * @author David Liu */ public class EurekaUtilsTest { @Test public void testIsInEc2() { InstanceInfo instanceInfo1 = new InstanceInfo.Builder(InstanceInfoGenerator.takeOne()) .setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }) .build(); Assert.assertFalse(EurekaUtils.isInEc2(instanceInfo1)); InstanceInfo instanceInfo2 = InstanceInfoGenerator.takeOne(); Assert.assertTrue(EurekaUtils.isInEc2(instanceInfo2)); } @Test public void testIsInVpc() { InstanceInfo instanceInfo1 = new InstanceInfo.Builder(InstanceInfoGenerator.takeOne()) .setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }) .build(); Assert.assertFalse(EurekaUtils.isInVpc(instanceInfo1)); InstanceInfo instanceInfo2 = InstanceInfoGenerator.takeOne(); Assert.assertFalse(EurekaUtils.isInVpc(instanceInfo2)); InstanceInfo instanceInfo3 = InstanceInfoGenerator.takeOne(); ((AmazonInfo) instanceInfo3.getDataCenterInfo()).getMetadata() .put(AmazonInfo.MetaDataKey.vpcId.getName(), "vpc-123456"); Assert.assertTrue(EurekaUtils.isInVpc(instanceInfo3)); } }
7,874
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/util/RateLimiterTest.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.discovery.util; import org.junit.Test; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author Tomasz Bak */ public class RateLimiterTest { private static final long START = 1000000; private static final int BURST_SIZE = 2; private static final int AVERAGE_RATE = 10; @Test public void testEvenLoad() { RateLimiter secondLimiter = new RateLimiter(TimeUnit.SECONDS); long secondStep = 1000 / AVERAGE_RATE; testEvenLoad(secondLimiter, START, BURST_SIZE, AVERAGE_RATE, secondStep); RateLimiter minuteLimiter = new RateLimiter(TimeUnit.MINUTES); long minuteStep = 60 * 1000 / AVERAGE_RATE; testEvenLoad(minuteLimiter, START, BURST_SIZE, AVERAGE_RATE, minuteStep); } private void testEvenLoad(RateLimiter rateLimiter, long start, int burstSize, int averageRate, long step) { long end = start + averageRate * step; for (long currentTime = start; currentTime < end; currentTime += step) { assertTrue(rateLimiter.acquire(burstSize, averageRate, currentTime)); } } @Test public void testBursts() { RateLimiter secondLimiter = new RateLimiter(TimeUnit.SECONDS); long secondStep = 1000 / AVERAGE_RATE; testBursts(secondLimiter, START, BURST_SIZE, AVERAGE_RATE, secondStep); RateLimiter minuteLimiter = new RateLimiter(TimeUnit.MINUTES); long minuteStep = 60 * 1000 / AVERAGE_RATE; testBursts(minuteLimiter, START, BURST_SIZE, AVERAGE_RATE, minuteStep); } private void testBursts(RateLimiter rateLimiter, long start, int burstSize, int averageRate, long step) { // Generate burst, and go above the limit assertTrue(rateLimiter.acquire(burstSize, averageRate, start)); assertTrue(rateLimiter.acquire(burstSize, averageRate, start)); assertFalse(rateLimiter.acquire(burstSize, averageRate, start)); // Now advance by 1.5 STEP assertTrue(rateLimiter.acquire(burstSize, averageRate, start + step + step / 2)); assertFalse(rateLimiter.acquire(burstSize, averageRate, start + step + step / 2)); assertTrue(rateLimiter.acquire(burstSize, averageRate, start + 2 * step)); } }
7,875
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/util/DiscoveryBuildInfoTest.java
package com.netflix.discovery.util; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * @author Tomasz Bak */ public class DiscoveryBuildInfoTest { @Test public void testRequestedManifestIsLocatedAndLoaded() throws Exception { DiscoveryBuildInfo buildInfo = new DiscoveryBuildInfo(ObjectMapper.class); assertThat(buildInfo.getBuildVersion().contains("version_unknown"), is(false)); } }
7,876
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/util/DeserializerStringCacheTest.java
package com.netflix.discovery.util; import java.io.IOException; import java.util.Arrays; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.netflix.discovery.util.DeserializerStringCache.CacheScope; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DeserializerStringCacheTest { @Test public void testUppercaseConversionWithLowercasePreset() throws IOException { DeserializationContext deserializationContext = mock(DeserializationContext.class); DeserializerStringCache deserializerStringCache = DeserializerStringCache.from(deserializationContext); String lowerCaseValue = deserializerStringCache.apply("value", CacheScope.APPLICATION_SCOPE); assertThat(lowerCaseValue, is("value")); JsonParser jsonParser = mock(JsonParser.class); when(jsonParser.getTextCharacters()).thenReturn(new char[] {'v', 'a', 'l', 'u', 'e'}); when(jsonParser.getTextLength()).thenReturn(5); String upperCaseValue = deserializerStringCache.apply(jsonParser, CacheScope.APPLICATION_SCOPE, () -> "VALUE"); assertThat(upperCaseValue, is("VALUE")); } @Test public void testUppercaseConversionWithLongString() throws IOException { DeserializationContext deserializationContext = mock(DeserializationContext.class); DeserializerStringCache deserializerStringCache = DeserializerStringCache.from(deserializationContext); char[] lowercaseValue = new char[1024]; Arrays.fill(lowercaseValue, 'a'); JsonParser jsonParser = mock(JsonParser.class); when(jsonParser.getText()).thenReturn(new String(lowercaseValue)); when(jsonParser.getTextCharacters()).thenReturn(lowercaseValue); when(jsonParser.getTextOffset()).thenReturn(0); when(jsonParser.getTextLength()).thenReturn(lowercaseValue.length); String upperCaseValue = deserializerStringCache.apply(jsonParser, CacheScope.APPLICATION_SCOPE, () -> { try { return jsonParser.getText().toUpperCase(); } catch(IOException ioe) { // not likely from mock above throw new IllegalStateException("mock threw unexpected exception", ioe); } }); char[] expectedValueChars = new char[1024]; Arrays.fill(expectedValueChars, 'A'); String expectedValue = new String(expectedValueChars); assertThat(upperCaseValue, is(expectedValue)); } }
7,877
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/providers/DefaultEurekaClientConfigProviderTest.java
/* * Copyright 2015 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.discovery.providers; import java.util.List; import com.google.inject.Injector; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.CommonConstants; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.EurekaNamespace; import com.netflix.governator.guice.BootstrapBinder; import com.netflix.governator.guice.BootstrapModule; import com.netflix.governator.guice.LifecycleInjector; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * @author Tomasz Bak */ public class DefaultEurekaClientConfigProviderTest { private static final String SERVICE_URI = "http://my.eureka.server:8080/"; @Test public void testNameSpaceInjection() throws Exception { ConfigurationManager.getConfigInstance().setProperty("testnamespace.serviceUrl.default", SERVICE_URI); Injector injector = LifecycleInjector.builder() .withBootstrapModule(new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.bind(String.class).annotatedWith(EurekaNamespace.class).toInstance("testnamespace."); } }) .build() .createInjector(); DefaultEurekaClientConfig clientConfig = injector.getInstance(DefaultEurekaClientConfig.class); List<String> serviceUrls = clientConfig.getEurekaServerServiceUrls("default"); assertThat(serviceUrls.get(0), is(equalTo(SERVICE_URI))); } @Test public void testURLSeparator() throws Exception { testURLSeparator(","); testURLSeparator(" ,"); testURLSeparator(", "); testURLSeparator(" , "); testURLSeparator(" , "); } private void testURLSeparator(String separator) { ConfigurationManager.getConfigInstance().setProperty(CommonConstants.DEFAULT_CONFIG_NAMESPACE + ".serviceUrl.default", SERVICE_URI + separator + SERVICE_URI); DefaultEurekaClientConfig clientConfig = new DefaultEurekaClientConfig(); List<String> serviceUrls = clientConfig.getEurekaServerServiceUrls("default"); assertThat(serviceUrls.get(0), is(equalTo(SERVICE_URI))); assertThat(serviceUrls.get(1), is(equalTo(SERVICE_URI))); } }
7,878
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/guice/EurekaModuleTest.java
package com.netflix.discovery.guice; import com.google.inject.AbstractModule; import com.google.inject.Binding; import com.google.inject.Key; import com.google.inject.Scopes; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.providers.MyDataCenterInstanceConfigProvider; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.DiscoveryManager; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.transport.jersey.TransportClientFactories; import com.netflix.governator.InjectorBuilder; import com.netflix.governator.LifecycleInjector; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author David Liu */ public class EurekaModuleTest { private LifecycleInjector injector; @Before public void setUp() throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.region", "default"); ConfigurationManager.getConfigInstance().setProperty("eureka.shouldFetchRegistry", "false"); ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "false"); ConfigurationManager.getConfigInstance().setProperty("eureka.serviceUrl.default", "http://localhost:8080/eureka/v2"); injector = InjectorBuilder .fromModule(new EurekaModule()) .overrideWith(new AbstractModule() { @Override protected void configure() { // the default impl of EurekaInstanceConfig is CloudInstanceConfig, which we only want in an AWS // environment. Here we override that by binding MyDataCenterInstanceConfig to EurekaInstanceConfig. bind(EurekaInstanceConfig.class).toProvider(MyDataCenterInstanceConfigProvider.class).in(Scopes.SINGLETON); } }) .createInjector(); } @After public void tearDown() { if (injector != null) { injector.shutdown(); } ConfigurationManager.getConfigInstance().clear(); } @SuppressWarnings("deprecation") @Test public void testDI() { InstanceInfo instanceInfo = injector.getInstance(InstanceInfo.class); Assert.assertEquals(ApplicationInfoManager.getInstance().getInfo(), instanceInfo); EurekaClient eurekaClient = injector.getInstance(EurekaClient.class); DiscoveryClient discoveryClient = injector.getInstance(DiscoveryClient.class); Assert.assertEquals(DiscoveryManager.getInstance().getEurekaClient(), eurekaClient); Assert.assertEquals(DiscoveryManager.getInstance().getDiscoveryClient(), discoveryClient); Assert.assertEquals(eurekaClient, discoveryClient); EurekaClientConfig eurekaClientConfig = injector.getInstance(EurekaClientConfig.class); Assert.assertEquals(DiscoveryManager.getInstance().getEurekaClientConfig(), eurekaClientConfig); EurekaInstanceConfig eurekaInstanceConfig = injector.getInstance(EurekaInstanceConfig.class); Assert.assertEquals(DiscoveryManager.getInstance().getEurekaInstanceConfig(), eurekaInstanceConfig); Binding<TransportClientFactories> binding = injector.getExistingBinding(Key.get(TransportClientFactories.class)); Assert.assertNull(binding); // no bindings so defaulting to default of jersey1 } }
7,879
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/provider/DiscoveryJerseyProviderTest.java
/* * Copyright 2016 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.discovery.provider; import javax.ws.rs.core.MediaType; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.wrappers.CodecWrappers; import com.netflix.discovery.util.InstanceInfoGenerator; import org.apache.commons.io.output.ByteArrayOutputStream; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** */ public class DiscoveryJerseyProviderTest { private static final InstanceInfo INSTANCE = InstanceInfoGenerator.takeOne(); private final DiscoveryJerseyProvider jerseyProvider = new DiscoveryJerseyProvider( CodecWrappers.getEncoder(CodecWrappers.JacksonJson.class), CodecWrappers.getDecoder(CodecWrappers.JacksonJson.class) ); @Test public void testJsonEncodingDecoding() throws Exception { testEncodingDecoding(MediaType.APPLICATION_JSON_TYPE); } @Test public void testXmlEncodingDecoding() throws Exception { testEncodingDecoding(MediaType.APPLICATION_XML_TYPE); } @Test public void testDecodingWithUtf8CharsetExplicitlySet() throws Exception { Map<String, String> params = new HashMap<>(); params.put("charset", "UTF-8"); testEncodingDecoding(new MediaType("application", "json", params)); } private void testEncodingDecoding(MediaType mediaType) throws IOException { // Write assertThat(jerseyProvider.isWriteable(InstanceInfo.class, InstanceInfo.class, null, mediaType), is(true)); ByteArrayOutputStream out = new ByteArrayOutputStream(); jerseyProvider.writeTo(INSTANCE, InstanceInfo.class, InstanceInfo.class, null, mediaType, null, out); // Read assertThat(jerseyProvider.isReadable(InstanceInfo.class, InstanceInfo.class, null, mediaType), is(true)); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); InstanceInfo decodedInstance = (InstanceInfo) jerseyProvider.readFrom(InstanceInfo.class, InstanceInfo.class, null, mediaType, null, in); assertThat(decodedInstance, is(equalTo(INSTANCE))); } @Test public void testNonUtf8CharsetIsNotAccepted() throws Exception { Map<String, String> params = new HashMap<>(); params.put("charset", "ISO-8859"); MediaType mediaTypeWithNonSupportedCharset = new MediaType("application", "json", params); assertThat(jerseyProvider.isReadable(InstanceInfo.class, InstanceInfo.class, null, mediaTypeWithNonSupportedCharset), is(false)); } }
7,880
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/XmlXStreamTest.java
package com.netflix.discovery.converters; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.EurekaEntityComparators; import com.netflix.discovery.util.InstanceInfoGenerator; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.security.ForbiddenClassException; import org.junit.Test; /** * @author Tomasz Bak */ public class XmlXStreamTest { @Test public void testEncodingDecodingWithoutMetaData() throws Exception { Applications applications = InstanceInfoGenerator.newBuilder(10, 2).withMetaData(false).build().toApplications(); XStream xstream = XmlXStream.getInstance(); String xmlDocument = xstream.toXML(applications); Applications decodedApplications = (Applications) xstream.fromXML(xmlDocument); assertThat(EurekaEntityComparators.equal(decodedApplications, applications), is(true)); } @Test public void testEncodingDecodingWithMetaData() throws Exception { Applications applications = InstanceInfoGenerator.newBuilder(10, 2).withMetaData(true).build().toApplications(); XStream xstream = XmlXStream.getInstance(); String xmlDocument = xstream.toXML(applications); Applications decodedApplications = (Applications) xstream.fromXML(xmlDocument); assertThat(EurekaEntityComparators.equal(decodedApplications, applications), is(true)); } /** * Tests: http://x-stream.github.io/CVE-2017-7957.html */ @Test(expected=ForbiddenClassException.class, timeout=5000) public void testVoidElementUnmarshalling() throws Exception { XStream xstream = XmlXStream.getInstance(); xstream.fromXML("<void/>"); } /** * Tests: http://x-stream.github.io/CVE-2017-7957.html */ @Test(expected=ForbiddenClassException.class, timeout=5000) public void testVoidAttributeUnmarshalling() throws Exception { XStream xstream = XmlXStream.getInstance(); xstream.fromXML("<string class='void'>Hello, world!</string>"); } }
7,881
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/StringCacheTest.java
package com.netflix.discovery.converters; import com.netflix.discovery.util.StringCache; import org.junit.Test; import static org.junit.Assert.assertTrue; /** * @author Tomasz Bak */ public class StringCacheTest { public static final int CACHE_SIZE = 100000; @Test public void testVerifyStringsAreGarbageCollectedIfNotReferenced() throws Exception { StringCache cache = new StringCache(); for (int i = 0; i < CACHE_SIZE; i++) { cache.cachedValueOf("id#" + i); } gc(); // Testing GC behavior is unpredictable, so we set here low target level // The tests run on desktop show that all strings are removed actually. assertTrue(cache.size() < CACHE_SIZE * 0.1); } public static void gc() { System.gc(); System.runFinalization(); try { Thread.sleep(1000); } catch (InterruptedException e) { // IGNORE } } }
7,882
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/EurekaJacksonCodecIntegrationTest.java
package com.netflix.discovery.converters; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.StandardCopyOption; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.Test; import com.netflix.discovery.shared.Applications; /** * this integration test parses the response of a Eureka discovery server, * specified by url via system property 'discovery.url'. It's useful for memory * utilization and performance tests, but since it's environment specific, the * tests below are @Ignore'd. * */ @org.junit.Ignore public class EurekaJacksonCodecIntegrationTest { private static final int UNREASONABLE_TIMEOUT_MS = 500; private final EurekaJacksonCodec codec = new EurekaJacksonCodec("", ""); /** * parse discovery response in a long-running loop with a delay * * @throws Exception */ @Test public void testRealDecode() throws Exception { Applications applications; File localDiscovery = new File("/var/folders/6j/qy6n1npj11x5j2j_9ng2wzmw0000gp/T/discovery-data-6054758555577530004.json"); //downloadRegistration(System.getProperty("discovery.url")); long testStart = System.currentTimeMillis(); for (int i = 0; i < 60; i++) { try (InputStream is = new FileInputStream(localDiscovery)) { long start = System.currentTimeMillis(); applications = codec.readValue(Applications.class, is); System.out.println("found some applications: " + applications.getRegisteredApplications().size() + " et: " + (System.currentTimeMillis() - start)); } } System.out.println("test time: " + " et: " + (System.currentTimeMillis() - testStart)); } @Test public void testCuriosity() { char[] arr1 = "test".toCharArray(); char[] arr2 = new char[] {'t', 'e', 's', 't'}; System.out.println("array equals" + arr1.equals(arr2)); } /** * parse discovery response with an unreasonable timeout, so that the * parsing job is cancelled * * @throws Exception */ @Test public void testDecodeTimeout() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(5); File localDiscovery = downloadRegistration(System.getProperty("discovery.url")); Callable<Applications> task = () -> { try (InputStream is = new FileInputStream(localDiscovery)) { return codec.readValue(Applications.class, is); } }; final int cancelAllButNthTask = 3; for (int i = 0; i < 30; i++) { Future<Applications> appsFuture = executor.submit(task); if (i % cancelAllButNthTask < cancelAllButNthTask - 1) { Thread.sleep(UNREASONABLE_TIMEOUT_MS); System.out.println("cancelling..." + " i: " + i + " - " + (i % 3)); appsFuture.cancel(true); } try { Applications apps = appsFuture.get(); System.out.println("found some applications: " + apps.toString() + ":" + apps.getRegisteredApplications().size() + " i: " + i + " - " + (i % 3)); } catch (Exception e) { System.out.println(e + " cause: " + " i: " + i + " - " + (i % 3)); } } } /** * low-tech http downloader */ private static File downloadRegistration(String discoveryUrl) throws IOException { if (discoveryUrl == null) { throw new IllegalArgumentException("null value not allowed for parameter discoveryUrl"); } File localFile = File.createTempFile("discovery-data-", ".json"); URL url = new URL(discoveryUrl); System.out.println("downloading registration data from " + url + " to " + localFile); HttpURLConnection hurlConn = (HttpURLConnection) url.openConnection(); hurlConn.setDoOutput(true); hurlConn.setRequestProperty("accept", "application/json"); hurlConn.connect(); try (InputStream is = hurlConn.getInputStream()) { java.nio.file.Files.copy(is, localFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } return localFile; } }
7,883
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/CodecLoadTester.java
package com.netflix.discovery.converters; import javax.ws.rs.core.MediaType; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.jackson.AbstractEurekaJacksonCodec; import com.netflix.discovery.converters.jackson.EurekaJsonJacksonCodec; import com.netflix.discovery.converters.jackson.EurekaXmlJacksonCodec; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.InstanceInfoGenerator; /** * @author Tomasz Bak */ public class CodecLoadTester { private final List<InstanceInfo> instanceInfoList = new ArrayList<>(); private final List<Application> applicationList = new ArrayList<>(); private final Applications applications; private final EntityBodyConverter xstreamCodec = new EntityBodyConverter(); private final EurekaJacksonCodec legacyJacksonCodec = new EurekaJacksonCodec(); private final EurekaJsonJacksonCodec jsonCodecNG = new EurekaJsonJacksonCodec(); private final EurekaJsonJacksonCodec jsonCodecNgCompact = new EurekaJsonJacksonCodec(KeyFormatter.defaultKeyFormatter(), true); private final EurekaXmlJacksonCodec xmlCodecNG = new EurekaXmlJacksonCodec(); private final EurekaXmlJacksonCodec xmlCodecNgCompact = new EurekaXmlJacksonCodec(KeyFormatter.defaultKeyFormatter(), true); static class FirstHolder { Applications value; } static class SecondHolder { Applications value; } private FirstHolder firstHolder = new FirstHolder(); private SecondHolder secondHolder = new SecondHolder(); public CodecLoadTester(int instanceCount, int appCount) { Iterator<InstanceInfo> instanceIt = InstanceInfoGenerator.newBuilder(instanceCount, appCount) .withMetaData(true).build().serviceIterator(); applications = new Applications(); int appIdx = 0; while (instanceIt.hasNext()) { InstanceInfo next = instanceIt.next(); instanceInfoList.add(next); if (applicationList.size() <= appIdx) { applicationList.add(new Application(next.getAppName())); } applicationList.get(appIdx).addInstance(next); appIdx = (appIdx + 1) % appCount; } for (Application app : applicationList) { applications.addApplication(app); } applications.setAppsHashCode(applications.getReconcileHashCode()); firstHolder.value = applications; } public CodecLoadTester(String[] args) throws Exception { if (args.length != 1) { System.err.println("ERROR: too many command line arguments; file name expected only"); throw new IllegalArgumentException(); } String fileName = args[0]; Applications applications; try { System.out.println("Attempting to load " + fileName + " in XML format..."); applications = loadWithCodec(fileName, MediaType.APPLICATION_XML_TYPE); } catch (Exception e) { System.out.println("Attempting to load " + fileName + " in JSON format..."); applications = loadWithCodec(fileName, MediaType.APPLICATION_JSON_TYPE); } this.applications = applications; long totalInstances = 0; for (Application a : applications.getRegisteredApplications()) { totalInstances += a.getInstances().size(); } System.out.printf("Loaded %d applications with %d instances\n", applications.getRegisteredApplications().size(), totalInstances); firstHolder.value = applications; } private Applications loadWithCodec(String fileName, MediaType mediaType) throws IOException { FileInputStream fis = new FileInputStream(fileName); BufferedInputStream bis = new BufferedInputStream(fis); return (Applications) xstreamCodec.read(bis, Applications.class, mediaType); } public void runApplicationsLoadTest(int loops, Func0<Applications> action) { long size = 0; for (int i = 0; i < loops; i++) { size += action.call(applications); } System.out.println("Average applications object size=" + formatSize(size / loops)); } public void runApplicationLoadTest(int loops, Func0<Application> action) { for (int i = 0; i < loops; i++) { action.call(applicationList.get(i % applicationList.size())); } } public void runInstanceInfoLoadTest(int loops, Func0<InstanceInfo> action) { for (int i = 0; i < loops; i++) { action.call(instanceInfoList.get(i % instanceInfoList.size())); } } public void runInstanceInfoIntervalTest(int batch, int intervalMs, long durationSec, Func0 action) { long startTime = System.currentTimeMillis(); long endTime = startTime + durationSec * 1000; long now; do { now = System.currentTimeMillis(); runInstanceInfoLoadTest(batch, action); long waiting = intervalMs - (System.currentTimeMillis() - now); System.out.println("Waiting " + waiting + "ms"); if (waiting > 0) { try { Thread.sleep(waiting); } catch (InterruptedException e) { // IGNORE } } } while (now < endTime); } public void runApplicationIntervalTest(int batch, int intervalMs, long durationSec, Func0 action) { long startTime = System.currentTimeMillis(); long endTime = startTime + durationSec * 1000; long now; do { now = System.currentTimeMillis(); runApplicationLoadTest(batch, action); long waiting = intervalMs - (System.currentTimeMillis() - now); System.out.println("Waiting " + waiting + "ms"); if (waiting > 0) { try { Thread.sleep(waiting); } catch (InterruptedException e) { // IGNORE } } } while (now < endTime); } private static String formatSize(long size) { if (size < 1000) { return String.format("%d [bytes]", size); } if (size < 1024 * 1024) { return String.format("%.2f [KB]", size / 1024f); } return String.format("%.2f [MB]", size / (1024f * 1024f)); } interface Func0<T> { int call(T data); } Func0 legacyJacksonAction = new Func0<Object>() { @Override public int call(Object object) { ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); try { legacyJacksonCodec.writeTo(object, captureStream); byte[] bytes = captureStream.toByteArray(); InputStream source = new ByteArrayInputStream(bytes); legacyJacksonCodec.readValue(object.getClass(), source); return bytes.length; } catch (IOException e) { throw new RuntimeException("unexpected", e); } } }; Func0 xstreamJsonAction = new Func0<Object>() { @Override public int call(Object object) { ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); try { xstreamCodec.write(object, captureStream, MediaType.APPLICATION_JSON_TYPE); byte[] bytes = captureStream.toByteArray(); InputStream source = new ByteArrayInputStream(bytes); xstreamCodec.read(source, InstanceInfo.class, MediaType.APPLICATION_JSON_TYPE); return bytes.length; } catch (IOException e) { throw new RuntimeException("unexpected", e); } } }; Func0 xstreamXmlAction = new Func0<Object>() { @Override public int call(Object object) { ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); try { xstreamCodec.write(object, captureStream, MediaType.APPLICATION_XML_TYPE); byte[] bytes = captureStream.toByteArray(); InputStream source = new ByteArrayInputStream(bytes); xstreamCodec.read(source, InstanceInfo.class, MediaType.APPLICATION_XML_TYPE); return bytes.length; } catch (IOException e) { throw new RuntimeException("unexpected", e); } } }; Func0 createJacksonNgAction(final MediaType mediaType, final boolean compact) { return new Func0<Object>() { @Override public int call(Object object) { AbstractEurekaJacksonCodec codec; if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) { codec = compact ? jsonCodecNgCompact : jsonCodecNG; } else { codec = compact ? xmlCodecNgCompact : xmlCodecNG; } ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); try { codec.writeTo(object, captureStream); byte[] bytes = captureStream.toByteArray(); InputStream source = new ByteArrayInputStream(bytes); Applications readValue = codec.getObjectMapper(object.getClass()).readValue(source, Applications.class); secondHolder.value = readValue; return bytes.length; } catch (IOException e) { throw new RuntimeException("unexpected", e); } } }; } public void runFullSpeed() { int loop = 5; System.gc(); long start = System.currentTimeMillis(); // runInstanceInfoLoadTest(loop, legacyJacksonAction); // runInstanceInfoLoadTest(loop, xstreamAction); // runApplicationLoadTest(loop, legacyJacksonAction); // runApplicationLoadTest(loop, xstreamAction); // ---------------------------------------------------------------- // Applications // runApplicationsLoadTest(loop, xstreamJsonAction); // runApplicationsLoadTest(loop, xstreamXmlAction); // runApplicationsLoadTest(loop, legacyJacksonAction); runApplicationsLoadTest(loop, createJacksonNgAction(MediaType.APPLICATION_JSON_TYPE, false)); long executionTime = System.currentTimeMillis() - start; System.out.printf("Execution time: %d[ms]\n", executionTime); } public void runIntervals() { int batch = 1500; int intervalMs = 1000; long durationSec = 600; // runInstanceInfoIntervalTest(batch, intervalMs, durationSec, legacyJacksonAction); runInstanceInfoIntervalTest(batch, intervalMs, durationSec, xstreamJsonAction); // runApplicationIntervalTest(batch, intervalMs, durationSec, legacyJacksonAction); // runApplicationIntervalTest(batch, intervalMs, durationSec, xstreamAction); } public static void main(String[] args) throws Exception { CodecLoadTester loadTester; if (args.length == 0) { loadTester = new CodecLoadTester(2000, 40); } else { loadTester = new CodecLoadTester(args); } loadTester.runFullSpeed(); Thread.sleep(100000); } }
7,884
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/EnumLookupTest.java
package com.netflix.discovery.converters; import org.junit.Assert; import org.junit.Test; public class EnumLookupTest { enum TestEnum { VAL_ONE("one"), VAL_TWO("two"), VAL_THREE("three"); private final String name; private TestEnum(String name) { this.name = name; } } @Test public void testLookup() { EnumLookup<TestEnum> lookup = new EnumLookup<>(TestEnum.class, v->v.name.toCharArray()); char[] buffer = "zeroonetwothreefour".toCharArray(); Assert.assertSame(TestEnum.VAL_ONE, lookup.find(buffer, 4, 3)); Assert.assertSame(TestEnum.VAL_TWO, lookup.find(buffer, 7, 3)); Assert.assertSame(TestEnum.VAL_THREE, lookup.find(buffer, 10, 5)); } }
7,885
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/EurekaJacksonCodecTest.java
package com.netflix.discovery.converters; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.nio.charset.Charset; import java.util.Iterator; import javax.ws.rs.core.MediaType; import org.junit.Test; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.ActionType; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.EurekaEntityComparators; import com.netflix.discovery.util.InstanceInfoGenerator; /** * @author Tomasz Bak */ public class EurekaJacksonCodecTest { public static final InstanceInfo INSTANCE_INFO_1_A1; public static final InstanceInfo INSTANCE_INFO_2_A1; public static final InstanceInfo INSTANCE_INFO_1_A2; public static final InstanceInfo INSTANCE_INFO_2_A2; public static final Application APPLICATION_1; public static final Application APPLICATION_2; public static final Applications APPLICATIONS; static { Iterator<InstanceInfo> infoIterator = InstanceInfoGenerator.newBuilder(4, 2).withMetaData(true).build().serviceIterator(); INSTANCE_INFO_1_A1 = infoIterator.next(); INSTANCE_INFO_1_A1.setActionType(ActionType.ADDED); INSTANCE_INFO_1_A2 = infoIterator.next(); INSTANCE_INFO_1_A2.setActionType(ActionType.ADDED); INSTANCE_INFO_2_A1 = infoIterator.next(); INSTANCE_INFO_1_A2.setActionType(ActionType.ADDED); INSTANCE_INFO_2_A2 = infoIterator.next(); INSTANCE_INFO_2_A2.setActionType(ActionType.ADDED); APPLICATION_1 = new Application(INSTANCE_INFO_1_A1.getAppName()); APPLICATION_1.addInstance(INSTANCE_INFO_1_A1); APPLICATION_1.addInstance(INSTANCE_INFO_2_A1); APPLICATION_2 = new Application(INSTANCE_INFO_1_A2.getAppName()); APPLICATION_2.addInstance(INSTANCE_INFO_1_A2); APPLICATION_2.addInstance(INSTANCE_INFO_2_A2); APPLICATIONS = new Applications(); APPLICATIONS.addApplication(APPLICATION_1); APPLICATIONS.addApplication(APPLICATION_2); } private final EurekaJacksonCodec codec = new EurekaJacksonCodec(); @Test public void testInstanceInfoJacksonEncodeDecode() throws Exception { // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(INSTANCE_INFO_1_A1, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); InstanceInfo decoded = codec.readValue(InstanceInfo.class, source); assertTrue(EurekaEntityComparators.equal(decoded, INSTANCE_INFO_1_A1)); } @Test public void testInstanceInfoJacksonEncodeDecodeWithoutMetaData() throws Exception { InstanceInfo noMetaDataInfo = InstanceInfoGenerator.newBuilder(1, 1).withMetaData(false).build().serviceIterator().next(); // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(noMetaDataInfo, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); InstanceInfo decoded = codec.readValue(InstanceInfo.class, source); assertTrue(EurekaEntityComparators.equal(decoded, noMetaDataInfo)); } @Test public void testInstanceInfoXStreamEncodeJacksonDecode() throws Exception { InstanceInfo original = INSTANCE_INFO_1_A1; // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); new EntityBodyConverter().write(original, captureStream, MediaType.APPLICATION_JSON_TYPE); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); InstanceInfo decoded = codec.readValue(InstanceInfo.class, source); assertTrue(EurekaEntityComparators.equal(decoded, original)); } @Test public void testInstanceInfoJacksonEncodeXStreamDecode() throws Exception { // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(INSTANCE_INFO_1_A1, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); InstanceInfo decoded = (InstanceInfo) new EntityBodyConverter().read(source, InstanceInfo.class, MediaType.APPLICATION_JSON_TYPE); assertTrue(EurekaEntityComparators.equal(decoded, INSTANCE_INFO_1_A1)); } @Test public void testApplicationJacksonEncodeDecode() throws Exception { // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(APPLICATION_1, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); Application decoded = codec.readValue(Application.class, source); assertTrue(EurekaEntityComparators.equal(decoded, APPLICATION_1)); } @Test public void testApplicationXStreamEncodeJacksonDecode() throws Exception { Application original = APPLICATION_1; // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); new EntityBodyConverter().write(original, captureStream, MediaType.APPLICATION_JSON_TYPE); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); Application decoded = codec.readValue(Application.class, source); assertTrue(EurekaEntityComparators.equal(decoded, original)); } @Test public void testApplicationJacksonEncodeXStreamDecode() throws Exception { // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(APPLICATION_1, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); Application decoded = (Application) new EntityBodyConverter().read(source, Application.class, MediaType.APPLICATION_JSON_TYPE); assertTrue(EurekaEntityComparators.equal(decoded, APPLICATION_1)); } @Test public void testApplicationsJacksonEncodeDecode() throws Exception { // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(APPLICATIONS, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); Applications decoded = codec.readValue(Applications.class, source); assertTrue(EurekaEntityComparators.equal(decoded, APPLICATIONS)); } @Test public void testApplicationsXStreamEncodeJacksonDecode() throws Exception { Applications original = APPLICATIONS; // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); new EntityBodyConverter().write(original, captureStream, MediaType.APPLICATION_JSON_TYPE); byte[] encoded = captureStream.toByteArray(); String encodedString = new String(encoded); // Decode InputStream source = new ByteArrayInputStream(encoded); Applications decoded = codec.readValue(Applications.class, source); assertTrue(EurekaEntityComparators.equal(decoded, original)); } @Test public void testApplicationsJacksonEncodeXStreamDecode() throws Exception { // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(APPLICATIONS, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); Applications decoded = (Applications) new EntityBodyConverter().read(source, Applications.class, MediaType.APPLICATION_JSON_TYPE); assertTrue(EurekaEntityComparators.equal(decoded, APPLICATIONS)); } @Test public void testJacksonWriteToString() throws Exception { String jsonValue = codec.writeToString(INSTANCE_INFO_1_A1); InstanceInfo decoded = codec.readValue(InstanceInfo.class, new ByteArrayInputStream(jsonValue.getBytes(Charset.defaultCharset()))); assertTrue(EurekaEntityComparators.equal(decoded, INSTANCE_INFO_1_A1)); } @Test public void testJacksonWrite() throws Exception { // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(INSTANCE_INFO_1_A1, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode value InputStream source = new ByteArrayInputStream(encoded); InstanceInfo decoded = codec.readValue(InstanceInfo.class, source); assertTrue(EurekaEntityComparators.equal(decoded, INSTANCE_INFO_1_A1)); } }
7,886
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/EurekaCodecCompatibilityTest.java
package com.netflix.discovery.converters; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.MyDataCenterInfo; import com.netflix.discovery.converters.wrappers.CodecWrapper; import com.netflix.discovery.converters.wrappers.CodecWrappers; import com.netflix.discovery.converters.wrappers.DecoderWrapper; import com.netflix.discovery.converters.wrappers.EncoderWrapper; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.EurekaEntityComparators; import com.netflix.discovery.util.InstanceInfoGenerator; import com.netflix.eureka.cluster.protocol.ReplicationInstance; import com.netflix.eureka.cluster.protocol.ReplicationInstanceResponse; import com.netflix.eureka.cluster.protocol.ReplicationList; import com.netflix.eureka.cluster.protocol.ReplicationListResponse; import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * @author Tomasz Bak */ public class EurekaCodecCompatibilityTest { private static final List<CodecWrapper> availableJsonWrappers = new ArrayList<>(); private static final List<CodecWrapper> availableXmlWrappers = new ArrayList<>(); static { availableJsonWrappers.add(new CodecWrappers.XStreamJson()); availableJsonWrappers.add(new CodecWrappers.LegacyJacksonJson()); availableJsonWrappers.add(new CodecWrappers.JacksonJson()); availableXmlWrappers.add(new CodecWrappers.JacksonXml()); availableXmlWrappers.add(new CodecWrappers.XStreamXml()); } private final InstanceInfoGenerator infoGenerator = InstanceInfoGenerator.newBuilder(4, 2).withMetaData(true).build(); private final Iterator<InstanceInfo> infoIterator = infoGenerator.serviceIterator(); interface Action2 { void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException; } /** * @deprecated see to do note in {@link com.netflix.appinfo.LeaseInfo} and delete once legacy is removed */ @Deprecated @Test public void testInstanceInfoEncodeDecodeLegacyJacksonToJackson() throws Exception { final InstanceInfo instanceInfo = infoIterator.next(); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); // convert the field from the json string to what the legacy json would encode as encodedString = encodedString.replaceFirst("lastRenewalTimestamp", "renewalTimestamp"); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue, new EurekaEntityComparators.RawIdEqualFunc()), is(true)); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue), is(true)); } }; verifyForPair( codingAction, InstanceInfo.class, new CodecWrappers.LegacyJacksonJson(), new CodecWrappers.JacksonJson() ); } @Test public void testInstanceInfoEncodeDecodeJsonWithEmptyMetadataMap() throws Exception { final InstanceInfo base = infoIterator.next(); final InstanceInfo instanceInfo = new InstanceInfo.Builder(base) .setMetadata(Collections.EMPTY_MAP) .build(); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue), is(true)); } }; verifyAllPairs(codingAction, Application.class, availableJsonWrappers); verifyAllPairs(codingAction, Application.class, availableXmlWrappers); } /** * During deserialization process in compact mode not all fields might be filtered out. If JVM memory * is an issue, compact version of the encoder should be used on the server side. */ @Test public void testInstanceInfoFullEncodeMiniDecodeJackson() throws Exception { final InstanceInfo instanceInfo = infoIterator.next(); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equalMini(instanceInfo, decodedValue), is(true)); } }; verifyForPair( codingAction, InstanceInfo.class, new CodecWrappers.JacksonJson(), new CodecWrappers.JacksonJsonMini() ); } @Test public void testInstanceInfoFullEncodeMiniDecodeJacksonWithMyOwnDataCenterInfo() throws Exception { final InstanceInfo base = infoIterator.next(); final InstanceInfo instanceInfo = new InstanceInfo.Builder(base) .setDataCenterInfo(new MyDataCenterInfo(DataCenterInfo.Name.MyOwn)) .build(); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equalMini(instanceInfo, decodedValue), is(true)); } }; verifyForPair( codingAction, InstanceInfo.class, new CodecWrappers.JacksonJson(), new CodecWrappers.JacksonJsonMini() ); } @Test public void testInstanceInfoMiniEncodeMiniDecodeJackson() throws Exception { final InstanceInfo instanceInfo = infoIterator.next(); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equalMini(instanceInfo, decodedValue), is(true)); } }; verifyForPair( codingAction, InstanceInfo.class, new CodecWrappers.JacksonJsonMini(), new CodecWrappers.JacksonJsonMini() ); } @Test public void testInstanceInfoEncodeDecode() throws Exception { final InstanceInfo instanceInfo = infoIterator.next(); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue), is(true)); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue, new EurekaEntityComparators.RawIdEqualFunc()), is(true)); } }; verifyAllPairs(codingAction, InstanceInfo.class, availableJsonWrappers); verifyAllPairs(codingAction, InstanceInfo.class, availableXmlWrappers); } // https://github.com/Netflix/eureka/issues/1051 // test going from camel case to lower case @Test public void testInstanceInfoEncodeDecodeCompatibilityDueToOverriddenStatusRenamingV1() throws Exception { final InstanceInfo instanceInfo = infoIterator.next(); new InstanceInfo.Builder(instanceInfo).setOverriddenStatus(InstanceInfo.InstanceStatus.OUT_OF_SERVICE); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); // sed to older naming to test encodedString = encodedString.replace("overriddenStatus", "overriddenstatus"); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue), is(true)); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue, new EurekaEntityComparators.RawIdEqualFunc()), is(true)); } }; verifyAllPairs(codingAction, Application.class, availableJsonWrappers); verifyAllPairs(codingAction, Application.class, availableXmlWrappers); } // same as the above, but go from lower case to camel case @Test public void testInstanceInfoEncodeDecodeCompatibilityDueToOverriddenStatusRenamingV2() throws Exception { final InstanceInfo instanceInfo = infoIterator.next(); new InstanceInfo.Builder(instanceInfo).setOverriddenStatus(InstanceInfo.InstanceStatus.OUT_OF_SERVICE); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); // sed to older naming to test encodedString = encodedString.replace("overriddenstatus", "overriddenStatus"); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue), is(true)); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue, new EurekaEntityComparators.RawIdEqualFunc()), is(true)); } }; verifyAllPairs(codingAction, Application.class, availableJsonWrappers); verifyAllPairs(codingAction, Application.class, availableXmlWrappers); } @Test public void testApplicationEncodeDecode() throws Exception { final Application application = new Application("testApp"); application.addInstance(infoIterator.next()); application.addInstance(infoIterator.next()); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(application); Application decodedValue = decodingCodec.decode(encodedString, Application.class); assertThat(EurekaEntityComparators.equal(application, decodedValue), is(true)); } }; verifyAllPairs(codingAction, Application.class, availableJsonWrappers); verifyAllPairs(codingAction, Application.class, availableXmlWrappers); } @Test public void testApplicationsEncodeDecode() throws Exception { final Applications applications = infoGenerator.takeDelta(2); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(applications); Applications decodedValue = decodingCodec.decode(encodedString, Applications.class); assertThat(EurekaEntityComparators.equal(applications, decodedValue), is(true)); } }; verifyAllPairs(codingAction, Applications.class, availableJsonWrappers); verifyAllPairs(codingAction, Applications.class, availableXmlWrappers); } /** * For backward compatibility with LegacyJacksonJson codec single item arrays shall not be unwrapped. */ @Test public void testApplicationsJsonEncodeDecodeWithSingleAppItem() throws Exception { final Applications applications = infoGenerator.takeDelta(1); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(applications); assertThat(encodedString.contains("\"application\":[{"), is(true)); Applications decodedValue = decodingCodec.decode(encodedString, Applications.class); assertThat(EurekaEntityComparators.equal(applications, decodedValue), is(true)); } }; List<CodecWrapper> jsonCodes = Arrays.asList( new CodecWrappers.LegacyJacksonJson(), new CodecWrappers.JacksonJson() ); verifyAllPairs(codingAction, Applications.class, jsonCodes); } @Test public void testBatchRequestEncoding() throws Exception { InstanceInfo instance = InstanceInfoGenerator.takeOne(); List<ReplicationInstance> replicationInstances = new ArrayList<>(); replicationInstances.add(new ReplicationInstance( instance.getAppName(), instance.getId(), System.currentTimeMillis(), null, instance.getStatus().name(), instance, Action.Register )); final ReplicationList replicationList = new ReplicationList(replicationInstances); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(replicationList); ReplicationList decodedValue = decodingCodec.decode(encodedString, ReplicationList.class); assertThat(decodedValue.getReplicationList().size(), is(equalTo(1))); } }; // In replication channel we use JSON only List<CodecWrapper> jsonCodes = Arrays.asList( new CodecWrappers.JacksonJson(), new CodecWrappers.LegacyJacksonJson() ); verifyAllPairs(codingAction, ReplicationList.class, jsonCodes); } @Test public void testBatchResponseEncoding() throws Exception { List<ReplicationInstanceResponse> responseList = new ArrayList<>(); responseList.add(new ReplicationInstanceResponse(200, InstanceInfoGenerator.takeOne())); final ReplicationListResponse replicationListResponse = new ReplicationListResponse(responseList); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(replicationListResponse); ReplicationListResponse decodedValue = decodingCodec.decode(encodedString, ReplicationListResponse.class); assertThat(decodedValue.getResponseList().size(), is(equalTo(1))); } }; // In replication channel we use JSON only List<CodecWrapper> jsonCodes = Arrays.asList( new CodecWrappers.JacksonJson(), new CodecWrappers.LegacyJacksonJson() ); verifyAllPairs(codingAction, ReplicationListResponse.class, jsonCodes); } public void verifyAllPairs(Action2 codingAction, Class<?> typeToEncode, List<CodecWrapper> codecHolders) throws Exception { for (EncoderWrapper encodingCodec : codecHolders) { for (DecoderWrapper decodingCodec : codecHolders) { String pair = "{" + encodingCodec.codecName() + ',' + decodingCodec.codecName() + '}'; System.out.println("Encoding " + typeToEncode.getSimpleName() + " using " + pair); try { codingAction.call(encodingCodec, decodingCodec); } catch (Exception ex) { throw new Exception("Encoding failure for codec pair " + pair, ex); } } } } public void verifyForPair(Action2 codingAction, Class<?> typeToEncode, EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws Exception { String pair = "{" + encodingCodec.codecName() + ',' + decodingCodec.codecName() + '}'; System.out.println("Encoding " + typeToEncode.getSimpleName() + " using " + pair); try { codingAction.call(encodingCodec, decodingCodec); } catch (Exception ex) { throw new Exception("Encoding failure for codec pair " + pair, ex); } } }
7,887
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/EurekaJsonAndXmlJacksonCodecTest.java
package com.netflix.discovery.converters; import java.util.Iterator; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.AmazonInfo.MetaDataKey; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.DataCenterInfo.Name; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.LeaseInfo; import com.netflix.discovery.converters.jackson.AbstractEurekaJacksonCodec; import com.netflix.discovery.converters.jackson.EurekaJsonJacksonCodec; import com.netflix.discovery.converters.jackson.EurekaXmlJacksonCodec; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.EurekaEntityComparators; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; /** * @author Tomasz Bak */ public class EurekaJsonAndXmlJacksonCodecTest { private final InstanceInfoGenerator infoGenerator = InstanceInfoGenerator.newBuilder(4, 2).withMetaData(true).build(); private final Iterator<InstanceInfo> infoIterator = infoGenerator.serviceIterator(); @Test public void testAmazonInfoEncodeDecodeWithJson() throws Exception { doAmazonInfoEncodeDecodeTest(new EurekaJsonJacksonCodec()); } @Test public void testAmazonInfoEncodeDecodeWithXml() throws Exception { doAmazonInfoEncodeDecodeTest(new EurekaXmlJacksonCodec()); } private void doAmazonInfoEncodeDecodeTest(AbstractEurekaJacksonCodec codec) throws Exception { AmazonInfo amazonInfo = (AmazonInfo) infoIterator.next().getDataCenterInfo(); String encodedString = codec.getObjectMapper(DataCenterInfo.class).writeValueAsString(amazonInfo); DataCenterInfo decodedValue = codec.getObjectMapper(DataCenterInfo.class).readValue(encodedString, DataCenterInfo.class); assertThat(EurekaEntityComparators.equal(amazonInfo, decodedValue), is(true)); } @Test public void testAmazonInfoCompactEncodeDecodeWithJson() throws Exception { doAmazonInfoCompactEncodeDecodeTest(new EurekaJsonJacksonCodec(KeyFormatter.defaultKeyFormatter(), true)); } @Test public void testAmazonInfoCompactEncodeDecodeWithXml() throws Exception { doAmazonInfoCompactEncodeDecodeTest(new EurekaXmlJacksonCodec(KeyFormatter.defaultKeyFormatter(), true)); } private void doAmazonInfoCompactEncodeDecodeTest(AbstractEurekaJacksonCodec codec) throws Exception { AmazonInfo amazonInfo = (AmazonInfo) infoIterator.next().getDataCenterInfo(); String encodedString = codec.getObjectMapper(DataCenterInfo.class).writeValueAsString(amazonInfo); AmazonInfo decodedValue = (AmazonInfo) codec.getObjectMapper(DataCenterInfo.class).readValue(encodedString, DataCenterInfo.class); assertThat(decodedValue.get(MetaDataKey.publicHostname), is(equalTo(amazonInfo.get(MetaDataKey.publicHostname)))); } @Test public void testMyDataCenterInfoEncodeDecodeWithJson() throws Exception { doMyDataCenterInfoEncodeDecodeTest(new EurekaJsonJacksonCodec()); } @Test public void testMyDataCenterInfoEncodeDecodeWithXml() throws Exception { doMyDataCenterInfoEncodeDecodeTest(new EurekaXmlJacksonCodec()); } private void doMyDataCenterInfoEncodeDecodeTest(AbstractEurekaJacksonCodec codec) throws Exception { DataCenterInfo myDataCenterInfo = new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }; String encodedString = codec.getObjectMapper(DataCenterInfo.class).writeValueAsString(myDataCenterInfo); DataCenterInfo decodedValue = codec.getObjectMapper(DataCenterInfo.class).readValue(encodedString, DataCenterInfo.class); assertThat(decodedValue.getName(), is(equalTo(Name.MyOwn))); } @Test public void testLeaseInfoEncodeDecodeWithJson() throws Exception { doLeaseInfoEncodeDecode(new EurekaJsonJacksonCodec()); } @Test public void testLeaseInfoEncodeDecodeWithXml() throws Exception { doLeaseInfoEncodeDecode(new EurekaXmlJacksonCodec()); } private void doLeaseInfoEncodeDecode(AbstractEurekaJacksonCodec codec) throws Exception { LeaseInfo leaseInfo = infoIterator.next().getLeaseInfo(); String encodedString = codec.getObjectMapper(LeaseInfo.class).writeValueAsString(leaseInfo); LeaseInfo decodedValue = codec.getObjectMapper(LeaseInfo.class).readValue(encodedString, LeaseInfo.class); assertThat(EurekaEntityComparators.equal(leaseInfo, decodedValue), is(true)); } @Test public void testInstanceInfoEncodeDecodeWithJson() throws Exception { doInstanceInfoEncodeDecode(new EurekaJsonJacksonCodec()); } @Test public void testInstanceInfoEncodeDecodeWithXml() throws Exception { doInstanceInfoEncodeDecode(new EurekaXmlJacksonCodec()); } private void doInstanceInfoEncodeDecode(AbstractEurekaJacksonCodec codec) throws Exception { InstanceInfo instanceInfo = infoIterator.next(); String encodedString = codec.getObjectMapper(InstanceInfo.class).writeValueAsString(instanceInfo); InstanceInfo decodedValue = codec.getObjectMapper(InstanceInfo.class).readValue(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue), is(true)); } @Test public void testInstanceInfoCompactEncodeDecodeWithJson() throws Exception { doInstanceInfoCompactEncodeDecode(new EurekaJsonJacksonCodec(KeyFormatter.defaultKeyFormatter(), true), true); } @Test public void testInstanceInfoCompactEncodeDecodeWithXml() throws Exception { doInstanceInfoCompactEncodeDecode(new EurekaXmlJacksonCodec(KeyFormatter.defaultKeyFormatter(), true), false); } private void doInstanceInfoCompactEncodeDecode(AbstractEurekaJacksonCodec codec, boolean isJson) throws Exception { InstanceInfo instanceInfo = infoIterator.next(); String encodedString = codec.getObjectMapper(InstanceInfo.class).writeValueAsString(instanceInfo); if (isJson) { JsonNode metadataNode = new ObjectMapper().readTree(encodedString).get("instance").get("metadata"); assertThat(metadataNode, is(nullValue())); } InstanceInfo decodedValue = codec.getObjectMapper(InstanceInfo.class).readValue(encodedString, InstanceInfo.class); assertThat(decodedValue.getId(), is(equalTo(instanceInfo.getId()))); assertThat(decodedValue.getMetadata().isEmpty(), is(true)); } @Test public void testInstanceInfoIgnoredFieldsAreFilteredOutDuringDeserializationProcessWithJson() throws Exception { doInstanceInfoIgnoredFieldsAreFilteredOutDuringDeserializationProcess( new EurekaJsonJacksonCodec(), new EurekaJsonJacksonCodec(KeyFormatter.defaultKeyFormatter(), true) ); } @Test public void testInstanceInfoIgnoredFieldsAreFilteredOutDuringDeserializationProcessWithXml() throws Exception { doInstanceInfoIgnoredFieldsAreFilteredOutDuringDeserializationProcess( new EurekaXmlJacksonCodec(), new EurekaXmlJacksonCodec(KeyFormatter.defaultKeyFormatter(), true) ); } public void doInstanceInfoIgnoredFieldsAreFilteredOutDuringDeserializationProcess(AbstractEurekaJacksonCodec fullCodec, AbstractEurekaJacksonCodec compactCodec) throws Exception { InstanceInfo instanceInfo = infoIterator.next(); // We use regular codec here to have all fields serialized String encodedString = fullCodec.getObjectMapper(InstanceInfo.class).writeValueAsString(instanceInfo); InstanceInfo decodedValue = compactCodec.getObjectMapper(InstanceInfo.class).readValue(encodedString, InstanceInfo.class); assertThat(decodedValue.getId(), is(equalTo(instanceInfo.getId()))); assertThat(decodedValue.getAppName(), is(equalTo(instanceInfo.getAppName()))); assertThat(decodedValue.getIPAddr(), is(equalTo(instanceInfo.getIPAddr()))); assertThat(decodedValue.getVIPAddress(), is(equalTo(instanceInfo.getVIPAddress()))); assertThat(decodedValue.getSecureVipAddress(), is(equalTo(instanceInfo.getSecureVipAddress()))); assertThat(decodedValue.getHostName(), is(equalTo(instanceInfo.getHostName()))); assertThat(decodedValue.getStatus(), is(equalTo(instanceInfo.getStatus()))); assertThat(decodedValue.getActionType(), is(equalTo(instanceInfo.getActionType()))); assertThat(decodedValue.getASGName(), is(equalTo(instanceInfo.getASGName()))); assertThat(decodedValue.getLastUpdatedTimestamp(), is(equalTo(instanceInfo.getLastUpdatedTimestamp()))); AmazonInfo sourceAmazonInfo = (AmazonInfo) instanceInfo.getDataCenterInfo(); AmazonInfo decodedAmazonInfo = (AmazonInfo) decodedValue.getDataCenterInfo(); assertThat(decodedAmazonInfo.get(MetaDataKey.accountId), is(equalTo(sourceAmazonInfo.get(MetaDataKey.accountId)))); } @Test public void testInstanceInfoWithNoMetaEncodeDecodeWithJson() throws Exception { doInstanceInfoWithNoMetaEncodeDecode(new EurekaJsonJacksonCodec(), true); } @Test public void testInstanceInfoWithNoMetaEncodeDecodeWithXml() throws Exception { doInstanceInfoWithNoMetaEncodeDecode(new EurekaXmlJacksonCodec(), false); } private void doInstanceInfoWithNoMetaEncodeDecode(AbstractEurekaJacksonCodec codec, boolean json) throws Exception { InstanceInfo noMetaDataInfo = new InstanceInfo.Builder(infoIterator.next()).setMetadata(null).build(); String encodedString = codec.getObjectMapper(InstanceInfo.class).writeValueAsString(noMetaDataInfo); // Backward compatibility with old codec if (json) { assertThat(encodedString.contains("\"@class\":\"java.util.Collections$EmptyMap\""), is(true)); } InstanceInfo decodedValue = codec.getObjectMapper(InstanceInfo.class).readValue(encodedString, InstanceInfo.class); assertThat(decodedValue.getId(), is(equalTo(noMetaDataInfo.getId()))); assertThat(decodedValue.getMetadata().isEmpty(), is(true)); } @Test public void testApplicationEncodeDecodeWithJson() throws Exception { doApplicationEncodeDecode(new EurekaJsonJacksonCodec()); } @Test public void testApplicationEncodeDecodeWithXml() throws Exception { doApplicationEncodeDecode(new EurekaXmlJacksonCodec()); } private void doApplicationEncodeDecode(AbstractEurekaJacksonCodec codec) throws Exception { Application application = new Application("testApp"); application.addInstance(infoIterator.next()); application.addInstance(infoIterator.next()); String encodedString = codec.getObjectMapper(Application.class).writeValueAsString(application); Application decodedValue = codec.getObjectMapper(Application.class).readValue(encodedString, Application.class); assertThat(EurekaEntityComparators.equal(application, decodedValue), is(true)); } @Test public void testApplicationsEncodeDecodeWithJson() throws Exception { doApplicationsEncodeDecode(new EurekaJsonJacksonCodec()); } @Test public void testApplicationsEncodeDecodeWithXml() throws Exception { doApplicationsEncodeDecode(new EurekaXmlJacksonCodec()); } private void doApplicationsEncodeDecode(AbstractEurekaJacksonCodec codec) throws Exception { Applications applications = infoGenerator.takeDelta(2); String encodedString = codec.getObjectMapper(Applications.class).writeValueAsString(applications); Applications decodedValue = codec.getObjectMapper(Applications.class).readValue(encodedString, Applications.class); assertThat(EurekaEntityComparators.equal(applications, decodedValue), is(true)); } }
7,888
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/JsonXStreamTest.java
package com.netflix.discovery.converters; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import com.thoughtworks.xstream.security.ForbiddenClassException; import org.junit.Test; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.EurekaEntityComparators; import com.netflix.discovery.util.InstanceInfoGenerator; import com.thoughtworks.xstream.XStream; /** * @author Borja Lafuente */ public class JsonXStreamTest { @Test public void testEncodingDecodingWithoutMetaData() throws Exception { Applications applications = InstanceInfoGenerator.newBuilder(10, 2).withMetaData(false).build().toApplications(); XStream xstream = JsonXStream.getInstance(); String jsonDocument = xstream.toXML(applications); Applications decodedApplications = (Applications) xstream.fromXML(jsonDocument); assertThat(EurekaEntityComparators.equal(decodedApplications, applications), is(true)); } @Test public void testEncodingDecodingWithMetaData() throws Exception { Applications applications = InstanceInfoGenerator.newBuilder(10, 2).withMetaData(true).build().toApplications(); XStream xstream = JsonXStream.getInstance(); String jsonDocument = xstream.toXML(applications); Applications decodedApplications = (Applications) xstream.fromXML(jsonDocument); assertThat(EurekaEntityComparators.equal(decodedApplications, applications), is(true)); } /** * Tests: http://x-stream.github.io/CVE-2017-7957.html */ @Test(expected=ForbiddenClassException.class, timeout=5000) public void testVoidElementUnmarshalling() throws Exception { XStream xstream = JsonXStream.getInstance(); xstream.fromXML("{'void':null}"); } }
7,889
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/wrappers/CodecWrappersTest.java
package com.netflix.discovery.converters.wrappers; import junit.framework.Assert; import org.junit.Test; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * @author David Liu */ public class CodecWrappersTest { private static String testWrapperName = "FOO_WRAPPER"; @Test public void testRegisterNewWrapper() { Assert.assertNull(CodecWrappers.getEncoder(testWrapperName)); Assert.assertNull(CodecWrappers.getDecoder(testWrapperName)); CodecWrappers.registerWrapper(new TestWrapper()); Assert.assertNotNull(CodecWrappers.getEncoder(testWrapperName)); Assert.assertNotNull(CodecWrappers.getDecoder(testWrapperName)); } private final class TestWrapper implements CodecWrapper { @Override public <T> T decode(String textValue, Class<T> type) throws IOException { return null; } @Override public <T> T decode(InputStream inputStream, Class<T> type) throws IOException { return null; } @Override public <T> String encode(T object) throws IOException { return null; } @Override public <T> void encode(T object, OutputStream outputStream) throws IOException { } @Override public String codecName() { return testWrapperName; } @Override public boolean support(MediaType mediaType) { return false; } } }
7,890
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/jackson/builder/StringInterningAmazonInfoBuilderTest.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.discovery.converters.jackson.builder; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.exc.InvalidTypeIdException; import com.fasterxml.jackson.databind.module.SimpleModule; import com.netflix.appinfo.AmazonInfo; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.util.HashMap; public class StringInterningAmazonInfoBuilderTest { private ObjectMapper newMapper() { SimpleModule module = new SimpleModule() .addDeserializer(AmazonInfo.class, new StringInterningAmazonInfoBuilder()); return new ObjectMapper().registerModule(module); } /** * Convert to AmazonInfo with a simple map instead of a compact map. The compact map * doesn't have a custom toString and makes it hard to understand diffs in assertions. */ private AmazonInfo nonCompact(AmazonInfo info) { return new AmazonInfo(info.getName().name(), new HashMap<>(info.getMetadata())); } @Test(expected = InvalidTypeIdException.class) public void payloadThatIsEmpty() throws IOException { newMapper().readValue("{}", AmazonInfo.class); } @Test public void payloadWithJustClass() throws IOException { String json = "{" + "\"@class\": \"com.netflix.appinfo.AmazonInfo\"" + "}"; AmazonInfo info = newMapper().readValue(json, AmazonInfo.class); Assert.assertEquals(new AmazonInfo(), info); } @Test public void payloadWithClassAndMetadata() throws IOException { String json = "{" + " \"@class\": \"com.netflix.appinfo.AmazonInfo\"," + " \"metadata\": {" + " \"instance-id\": \"i-12345\"" + " }" + "}"; AmazonInfo info = newMapper().readValue(json, AmazonInfo.class); AmazonInfo expected = AmazonInfo.Builder.newBuilder() .addMetadata(AmazonInfo.MetaDataKey.instanceId, "i-12345") .build(); Assert.assertEquals(expected, nonCompact(info)); } @Test public void payloadWithClassAfterMetadata() throws IOException { String json = "{" + " \"metadata\": {" + " \"instance-id\": \"i-12345\"" + " }," + " \"@class\": \"com.netflix.appinfo.AmazonInfo\"" + "}"; AmazonInfo info = newMapper().readValue(json, AmazonInfo.class); AmazonInfo expected = AmazonInfo.Builder.newBuilder() .addMetadata(AmazonInfo.MetaDataKey.instanceId, "i-12345") .build(); Assert.assertEquals(expected, nonCompact(info)); } @Test public void payloadWithNameBeforeMetadata() throws IOException { String json = "{" + " \"@class\": \"com.netflix.appinfo.AmazonInfo\"," + " \"name\": \"Amazon\"," + " \"metadata\": {" + " \"instance-id\": \"i-12345\"" + " }" + "}"; AmazonInfo info = newMapper().readValue(json, AmazonInfo.class); AmazonInfo expected = AmazonInfo.Builder.newBuilder() .addMetadata(AmazonInfo.MetaDataKey.instanceId, "i-12345") .build(); Assert.assertEquals(expected, nonCompact(info)); } @Test public void payloadWithNameAfterMetadata() throws IOException { String json = "{" + " \"@class\": \"com.netflix.appinfo.AmazonInfo\"," + " \"metadata\": {" + " \"instance-id\": \"i-12345\"" + " }," + " \"name\": \"Amazon\"" + "}"; AmazonInfo info = newMapper().readValue(json, AmazonInfo.class); AmazonInfo expected = AmazonInfo.Builder.newBuilder() .addMetadata(AmazonInfo.MetaDataKey.instanceId, "i-12345") .build(); Assert.assertEquals(expected, nonCompact(info)); } @Test public void payloadWithOtherStuffBeforeAndAfterMetadata() throws IOException { String json = "{" + " \"@class\": \"com.netflix.appinfo.AmazonInfo\"," + " \"foo\": \"bar\"," + " \"metadata\": {" + " \"instance-id\": \"i-12345\"" + " }," + " \"bar\": \"baz\"," + " \"name\": \"Amazon\"" + "}"; AmazonInfo info = newMapper().readValue(json, AmazonInfo.class); AmazonInfo expected = AmazonInfo.Builder.newBuilder() .addMetadata(AmazonInfo.MetaDataKey.instanceId, "i-12345") .build(); Assert.assertEquals(expected, nonCompact(info)); } }
7,891
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/ApplicationsTest.java
package com.netflix.discovery.shared; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.lang.reflect.Constructor; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import com.google.common.collect.Iterables; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.AmazonInfo.MetaDataKey; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.AzToRegionMapper; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.InstanceRegionChecker; import com.netflix.discovery.InstanceRegionCheckerTest; import com.netflix.discovery.PropertyBasedAzToRegionMapper; public class ApplicationsTest { @Test public void testVersionAndAppHash() { Applications apps = new Applications(); assertEquals(-1L, (long)apps.getVersion()); assertNull(apps.getAppsHashCode()); apps.setVersion(101L); apps.setAppsHashCode("UP_5_DOWN_6_"); assertEquals(101L, (long)apps.getVersion()); assertEquals("UP_5_DOWN_6_", apps.getAppsHashCode()); } /** * Test that instancesMap in Application and shuffleVirtualHostNameMap in * Applications are correctly updated when the last instance is removed from * an application and shuffleInstances has been run. */ @Test public void shuffleVirtualHostNameMapLastInstanceTest() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("test") .setVIPAddress("test.testname:1").setDataCenterInfo(myDCI).setHostName("test.hostname").build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications(); applications.addApplication(application); applications.shuffleInstances(true); List<InstanceInfo> testApp = applications.getInstancesByVirtualHostName("test.testname:1"); assertEquals(Iterables.getOnlyElement(testApp), application.getByInstanceId("test.hostname")); application.removeInstance(instanceInfo); assertEquals(0, applications.size()); applications.shuffleInstances(true); testApp = applications.getInstancesByVirtualHostName("test.testname:1"); assertTrue(testApp.isEmpty()); assertNull(application.getByInstanceId("test.hostname")); } /** * Test that instancesMap in Application and shuffleVirtualHostNameMap in * Applications are correctly updated when the last instance is removed from * an application and shuffleInstances has been run. */ @Test public void shuffleSecureVirtualHostNameMapLastInstanceTest() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("test") .setVIPAddress("test.testname:1").setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(myDCI).setHostName("test.hostname").build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications(); assertEquals(0, applications.size()); applications.addApplication(application); assertEquals(1, applications.size()); applications.shuffleInstances(true); List<InstanceInfo> testApp = applications.getInstancesByVirtualHostName("test.testname:1"); assertEquals(Iterables.getOnlyElement(testApp), application.getByInstanceId("test.hostname")); application.removeInstance(instanceInfo); assertNull(application.getByInstanceId("test.hostname")); assertEquals(0, applications.size()); applications.shuffleInstances(true); testApp = applications.getInstancesBySecureVirtualHostName("securetest.testname:7102"); assertTrue(testApp.isEmpty()); assertNull(application.getByInstanceId("test.hostname")); } /** * Test that instancesMap in Application and shuffleVirtualHostNameMap in * Applications are correctly updated when the last instance is removed from * an application and shuffleInstances has been run. */ @Test public void shuffleRemoteRegistryTest() throws Exception { AmazonInfo ai1 = AmazonInfo.Builder.newBuilder() .addMetadata(MetaDataKey.availabilityZone, "us-east-1a") .build(); InstanceInfo instanceInfo1 = InstanceInfo.Builder.newBuilder().setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(ai1) .setAppName("TestApp") .setHostName("test.east.hostname") .build(); AmazonInfo ai2 = AmazonInfo.Builder.newBuilder() .addMetadata(MetaDataKey.availabilityZone, "us-west-2a") .build(); InstanceInfo instanceInfo2 = InstanceInfo.Builder.newBuilder().setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(ai2) .setAppName("TestApp") .setHostName("test.west.hostname") .build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo1); application.addInstance(instanceInfo2); Applications applications = new Applications(); assertEquals(0, applications.size()); applications.addApplication(application); assertEquals(2, applications.size()); EurekaClientConfig clientConfig = Mockito.mock(EurekaClientConfig.class); Mockito.when(clientConfig.getAvailabilityZones("us-east-1")).thenReturn(new String[] {"us-east-1a", "us-east-1b", "us-east-1c", "us-east-1d", "us-east-1e", "us-east-1f"}); Mockito.when(clientConfig.getAvailabilityZones("us-west-2")).thenReturn(new String[] {"us-west-2a", "us-west-2b", "us-west-2c"}); Mockito.when(clientConfig.getRegion()).thenReturn("us-east-1"); Constructor<?> ctor = InstanceRegionChecker.class.getDeclaredConstructor(AzToRegionMapper.class, String.class); ctor.setAccessible(true); PropertyBasedAzToRegionMapper azToRegionMapper = new PropertyBasedAzToRegionMapper(clientConfig); azToRegionMapper.setRegionsToFetch(new String[] {"us-east-1", "us-west-2"}); InstanceRegionChecker instanceRegionChecker = (InstanceRegionChecker)ctor.newInstance(azToRegionMapper, "us-west-2"); Map<String, Applications> remoteRegionsRegistry = new HashMap<>(); remoteRegionsRegistry.put("us-east-1", new Applications()); applications.shuffleAndIndexInstances(remoteRegionsRegistry, clientConfig, instanceRegionChecker); assertNotNull(remoteRegionsRegistry.get("us-east-1").getRegisteredApplications("TestApp").getByInstanceId("test.east.hostname")); assertNull(applications.getRegisteredApplications("TestApp").getByInstanceId("test.east.hostname")); assertNull(remoteRegionsRegistry.get("us-east-1").getRegisteredApplications("TestApp").getByInstanceId("test.west.hostname")); assertNotNull(applications.getRegisteredApplications("TestApp").getByInstanceId("test.west.hostname")); } @Test public void testInfoDetailApplications(){ DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setInstanceId("test.id") .setAppName("test") .setHostName("test.hostname") .setStatus(InstanceStatus.UP) .setIPAddr("test.testip:1") .setPort(8080) .setSecurePort(443) .setDataCenterInfo(myDCI) .build(); Application application = new Application("Test App"); application.addInstance(instanceInfo); Applications applications = new Applications(); applications.addApplication(application); List<InstanceInfo> instanceInfos = application.getInstances(); Assert.assertEquals(1, instanceInfos.size()); Assert.assertTrue(instanceInfos.contains(instanceInfo)); List<Application> appsList = applications.getRegisteredApplications(); Assert.assertEquals(1, appsList.size()); Assert.assertTrue(appsList.contains(application)); Assert.assertEquals(application, applications.getRegisteredApplications(application.getName())); } @Test public void testRegisteredApplications() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(myDCI) .setHostName("test.hostname") .build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications(); applications.addApplication(application); List<Application> appsList = applications.getRegisteredApplications(); Assert.assertEquals(1, appsList.size()); Assert.assertTrue(appsList.contains(application)); Assert.assertEquals(application, applications.getRegisteredApplications(application.getName())); } @Test public void testRegisteredApplicationsConstructor() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(myDCI) .setHostName("test.hostname") .build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications("UP_1_", -1L, Arrays.asList(application)); List<Application> appsList = applications.getRegisteredApplications(); Assert.assertEquals(1, appsList.size()); Assert.assertTrue(appsList.contains(application)); Assert.assertEquals(application, applications.getRegisteredApplications(application.getName())); } @Test public void testApplicationsHashAndVersion() { Applications applications = new Applications("appsHashCode", 1L, Collections.emptyList()); assertEquals(1L, (long)applications.getVersion()); assertEquals("appsHashCode", applications.getAppsHashCode()); } @Test public void testPopulateInstanceCount() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(myDCI) .setHostName("test.hostname") .setStatus(InstanceStatus.UP) .build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications(); applications.addApplication(application); TreeMap<String, AtomicInteger> instanceCountMap = new TreeMap<>(); applications.populateInstanceCountMap(instanceCountMap); assertEquals(1, instanceCountMap.size()); assertNotNull(instanceCountMap.get(InstanceStatus.UP.name())); assertEquals(1, instanceCountMap.get(InstanceStatus.UP.name()).get()); } @Test public void testGetNextIndex() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(myDCI) .setHostName("test.hostname") .setStatus(InstanceStatus.UP) .build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications(); applications.addApplication(application); assertNotNull(applications.getNextIndex("test.testname:1", false)); assertEquals(0L, applications.getNextIndex("test.testname:1", false).get()); assertNotNull(applications.getNextIndex("securetest.testname:7102", true)); assertEquals(0L, applications.getNextIndex("securetest.testname:7102", true).get()); assertNotSame(applications.getNextIndex("test.testname:1", false), applications.getNextIndex("securetest.testname:7102", true)); } @Test public void testReconcileHashcode() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(myDCI) .setHostName("test.hostname") .setStatus(InstanceStatus.UP) .build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications(); String hashCode = applications.getReconcileHashCode(); assertTrue(hashCode.isEmpty()); applications.addApplication(application); hashCode = applications.getReconcileHashCode(); assertFalse(hashCode.isEmpty()); assertEquals("UP_1_", hashCode); } @Test public void testInstanceFiltering() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(myDCI) .setHostName("test.hostname") .setStatus(InstanceStatus.DOWN) .build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications(); applications.addApplication(application); applications.shuffleInstances(true); assertNotNull(applications.getRegisteredApplications("TestApp").getByInstanceId("test.hostname")); assertTrue(applications.getInstancesBySecureVirtualHostName("securetest.testname:7102").isEmpty()); assertTrue(applications.getInstancesBySecureVirtualHostName("test.testname:1").isEmpty()); } }
7,892
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport/EurekaHttpClientsTest.java
/* * Copyright 2015 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.discovery.shared.transport; import javax.ws.rs.core.HttpHeaders; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.resolver.ClosableResolver; import com.netflix.discovery.shared.resolver.ClusterResolver; import com.netflix.discovery.shared.resolver.DefaultEndpoint; import com.netflix.discovery.shared.resolver.EndpointRandomizer; import com.netflix.discovery.shared.resolver.EurekaEndpoint; import com.netflix.discovery.shared.resolver.ResolverUtils; import com.netflix.discovery.shared.resolver.StaticClusterResolver; import com.netflix.discovery.shared.resolver.aws.ApplicationsResolver; import com.netflix.discovery.shared.resolver.aws.AwsEndpoint; import com.netflix.discovery.shared.resolver.aws.EurekaHttpResolver; import com.netflix.discovery.shared.resolver.aws.TestEurekaHttpResolver; import com.netflix.discovery.shared.transport.jersey.Jersey1TransportClientFactories; import com.netflix.discovery.util.EurekaEntityComparators; import com.netflix.discovery.util.InstanceInfoGenerator; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientRequest; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.filter.ClientFilter; import org.junit.After; import org.junit.Before; import org.junit.Test; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Tomasz Bak */ public class EurekaHttpClientsTest { private static final InstanceInfo MY_INSTANCE = InstanceInfoGenerator.newBuilder(1, "myApp").build().first(); private final EurekaInstanceConfig instanceConfig = mock(EurekaInstanceConfig.class); private final ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(instanceConfig, MY_INSTANCE); private final EurekaHttpClient writeRequestHandler = mock(EurekaHttpClient.class); private final EurekaHttpClient readRequestHandler = mock(EurekaHttpClient.class); private EurekaClientConfig clientConfig; private EurekaTransportConfig transportConfig; private SimpleEurekaHttpServer writeServer; private SimpleEurekaHttpServer readServer; private ClusterResolver<EurekaEndpoint> clusterResolver; private EndpointRandomizer randomizer; private EurekaHttpClientFactory clientFactory; private String readServerURI; private final InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(2, 1).build(); @Before public void setUp() throws IOException { clientConfig = mock(EurekaClientConfig.class); transportConfig = mock(EurekaTransportConfig.class); randomizer = ResolverUtils::randomize; when(clientConfig.getEurekaServerTotalConnectionsPerHost()).thenReturn(10); when(clientConfig.getEurekaServerTotalConnections()).thenReturn(10); when(transportConfig.getSessionedClientReconnectIntervalSeconds()).thenReturn(10); writeServer = new SimpleEurekaHttpServer(writeRequestHandler); clusterResolver = new StaticClusterResolver<EurekaEndpoint>("regionA", new DefaultEndpoint("localhost", writeServer.getServerPort(), false, "/v2/")); readServer = new SimpleEurekaHttpServer(readRequestHandler); readServerURI = "http://localhost:" + readServer.getServerPort(); clientFactory = EurekaHttpClients.canonicalClientFactory( "test", transportConfig, clusterResolver, new Jersey1TransportClientFactories().newTransportClientFactory( clientConfig, Collections.<ClientFilter>emptyList(), applicationInfoManager.getInfo() )); } @After public void tearDown() throws Exception { if (writeServer != null) { writeServer.shutdown(); } if (readServer != null) { readServer.shutdown(); } if (clientFactory != null) { clientFactory.shutdown(); } } @Test public void testCanonicalClient() throws Exception { Applications apps = instanceGen.toApplications(); when(writeRequestHandler.getApplications()).thenReturn( anEurekaHttpResponse(302, Applications.class).headers("Location", readServerURI + "/v2/apps").build() ); when(readRequestHandler.getApplications()).thenReturn( anEurekaHttpResponse(200, apps).headers(HttpHeaders.CONTENT_TYPE, "application/json").build() ); EurekaHttpClient eurekaHttpClient = clientFactory.newClient(); EurekaHttpResponse<Applications> result = eurekaHttpClient.getApplications(); assertThat(result.getStatusCode(), is(equalTo(200))); assertThat(EurekaEntityComparators.equal(result.getEntity(), apps), is(true)); } @Test public void testCompositeBootstrapResolver() throws Exception { Applications applications = InstanceInfoGenerator.newBuilder(5, "eurekaWrite", "someOther").build().toApplications(); Applications applications2 = InstanceInfoGenerator.newBuilder(2, "eurekaWrite", "someOther").build().toApplications(); String vipAddress = applications.getRegisteredApplications("eurekaWrite").getInstances().get(0).getVIPAddress(); // setup client config to use fixed root ips for testing when(clientConfig.shouldUseDnsForFetchingServiceUrls()).thenReturn(false); when(clientConfig.getEurekaServerServiceUrls(anyString())).thenReturn(Arrays.asList("http://foo:0")); // can use anything here when(clientConfig.getRegion()).thenReturn("us-east-1"); when(transportConfig.getWriteClusterVip()).thenReturn(vipAddress); when(transportConfig.getAsyncExecutorThreadPoolSize()).thenReturn(4); when(transportConfig.getAsyncResolverRefreshIntervalMs()).thenReturn(400); when(transportConfig.getAsyncResolverWarmUpTimeoutMs()).thenReturn(400); ApplicationsResolver.ApplicationsSource applicationsSource = mock(ApplicationsResolver.ApplicationsSource.class); when(applicationsSource.getApplications(anyInt(), eq(TimeUnit.SECONDS))) .thenReturn(null) // first time .thenReturn(applications) // second time .thenReturn(null); // subsequent times EurekaHttpClient mockHttpClient = mock(EurekaHttpClient.class); when(mockHttpClient.getVip(eq(vipAddress))) .thenReturn(anEurekaHttpResponse(200, applications).build()) .thenReturn(anEurekaHttpResponse(200, applications2).build()); // contains diff number of servers TransportClientFactory transportClientFactory = mock(TransportClientFactory.class); when(transportClientFactory.newClient(any(EurekaEndpoint.class))).thenReturn(mockHttpClient); ClosableResolver<AwsEndpoint> resolver = null; try { resolver = EurekaHttpClients.compositeBootstrapResolver( clientConfig, transportConfig, transportClientFactory, applicationInfoManager.getInfo(), applicationsSource, randomizer ); List endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(applications.getInstancesByVirtualHostName(vipAddress).size())); // wait for the second cycle that hits the app source verify(applicationsSource, timeout(3000).times(2)).getApplications(anyInt(), eq(TimeUnit.SECONDS)); endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(applications.getInstancesByVirtualHostName(vipAddress).size())); // wait for the third cycle that triggers the mock http client (which is the third resolver cycle) // for the third cycle we have mocked the application resolver to return null data so should fall back // to calling the remote resolver again (which should return applications2) verify(mockHttpClient, timeout(3000).times(3)).getVip(anyString()); endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(applications2.getInstancesByVirtualHostName(vipAddress).size())); } finally { if (resolver != null) { resolver.shutdown(); } } } @Test public void testCanonicalResolver() throws Exception { when(clientConfig.getEurekaServerURLContext()).thenReturn("context"); when(clientConfig.getRegion()).thenReturn("region"); when(transportConfig.getAsyncExecutorThreadPoolSize()).thenReturn(3); when(transportConfig.getAsyncResolverRefreshIntervalMs()).thenReturn(400); when(transportConfig.getAsyncResolverWarmUpTimeoutMs()).thenReturn(400); Applications applications = InstanceInfoGenerator.newBuilder(5, "eurekaRead", "someOther").build().toApplications(); String vipAddress = applications.getRegisteredApplications("eurekaRead").getInstances().get(0).getVIPAddress(); ApplicationsResolver.ApplicationsSource applicationsSource = mock(ApplicationsResolver.ApplicationsSource.class); when(applicationsSource.getApplications(anyInt(), eq(TimeUnit.SECONDS))) .thenReturn(null) // first time .thenReturn(applications); // subsequent times EurekaHttpClientFactory remoteResolverClientFactory = mock(EurekaHttpClientFactory.class); EurekaHttpClient httpClient = mock(EurekaHttpClient.class); when(remoteResolverClientFactory.newClient()).thenReturn(httpClient); when(httpClient.getVip(vipAddress)).thenReturn(EurekaHttpResponse.anEurekaHttpResponse(200, applications).build()); EurekaHttpResolver remoteResolver = spy(new TestEurekaHttpResolver(clientConfig, transportConfig, remoteResolverClientFactory, vipAddress)); when(transportConfig.getReadClusterVip()).thenReturn(vipAddress); ApplicationsResolver localResolver = spy(new ApplicationsResolver( clientConfig, transportConfig, applicationsSource, transportConfig.getReadClusterVip())); ClosableResolver resolver = null; try { resolver = EurekaHttpClients.compositeQueryResolver( remoteResolver, localResolver, clientConfig, transportConfig, applicationInfoManager.getInfo(), randomizer ); List endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(applications.getInstancesByVirtualHostName(vipAddress).size())); verify(remoteResolver, times(1)).getClusterEndpoints(); verify(localResolver, times(1)).getClusterEndpoints(); // wait for the second cycle that hits the app source verify(applicationsSource, timeout(3000).times(2)).getApplications(anyInt(), eq(TimeUnit.SECONDS)); endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(applications.getInstancesByVirtualHostName(vipAddress).size())); verify(remoteResolver, times(1)).getClusterEndpoints(); verify(localResolver, times(2)).getClusterEndpoints(); } finally { if (resolver != null) { resolver.shutdown(); } } } @Test public void testAddingAdditionalFilters() throws Exception { TestFilter testFilter = new TestFilter(); Collection<ClientFilter> additionalFilters = Arrays.<ClientFilter>asList(testFilter); TransportClientFactory transportClientFactory = new Jersey1TransportClientFactories().newTransportClientFactory( clientConfig, additionalFilters, MY_INSTANCE ); EurekaHttpClient client = transportClientFactory.newClient(clusterResolver.getClusterEndpoints().get(0)); client.getApplication("foo"); assertThat(testFilter.await(30, TimeUnit.SECONDS), is(true)); } private static class TestFilter extends ClientFilter { private final CountDownLatch latch = new CountDownLatch(1); @Override public ClientResponse handle(ClientRequest cr) throws ClientHandlerException { latch.countDown(); return mock(ClientResponse.class); } public boolean await(long timeout, TimeUnit unit) throws Exception { return latch.await(timeout, unit); } } }
7,893
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport/jersey/JerseyApplicationClientTest.java
/* * Copyright 2015 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.discovery.shared.transport.jersey; import java.net.URI; import com.google.common.base.Preconditions; import com.netflix.discovery.shared.resolver.DefaultEndpoint; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpClientCompatibilityTestSuite; import com.netflix.discovery.shared.transport.TransportClientFactory; import org.junit.After; public class JerseyApplicationClientTest extends EurekaHttpClientCompatibilityTestSuite { private JerseyApplicationClient jerseyHttpClient; @Override @After public void tearDown() throws Exception { if (jerseyHttpClient != null) { jerseyHttpClient.shutdown(); } super.tearDown(); } @Override protected EurekaHttpClient getEurekaHttpClient(URI serviceURI) { Preconditions.checkState(jerseyHttpClient == null, "EurekaHttpClient has been already created"); TransportClientFactory clientFactory = JerseyEurekaHttpClientFactory.newBuilder() .withClientName("compatibilityTestClient") .build(); jerseyHttpClient = (JerseyApplicationClient) clientFactory.newClient(new DefaultEndpoint(serviceURI.toString())); return jerseyHttpClient; } }
7,894
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport/jersey/UnexpectedContentTypeTest.java
package com.netflix.discovery.shared.transport.jersey; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.shared.resolver.DefaultEndpoint; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.TransportClientFactory; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.util.UUID; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author rbolles on 12/19/19. */ public class UnexpectedContentTypeTest { protected static final String CLIENT_APP_NAME = "unexpectedContentTypeTest"; private JerseyApplicationClient jerseyHttpClient; @Rule public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort().dynamicHttpsPort()); // No-args constructor defaults to port 8080 @Before public void setUp() throws Exception { TransportClientFactory clientFactory = JerseyEurekaHttpClientFactory.newBuilder() .withClientName(CLIENT_APP_NAME) .build(); String uri = String.format("http://localhost:%s/v2/", wireMockRule.port()); jerseyHttpClient = (JerseyApplicationClient) clientFactory.newClient(new DefaultEndpoint(uri)); } @Test public void testSendHeartBeatReceivesUnexpectedHtmlResponse() { long lastDirtyTimestamp = System.currentTimeMillis(); String uuid = UUID.randomUUID().toString(); stubFor(put(urlPathEqualTo("/v2/apps/" + CLIENT_APP_NAME + "/" + uuid)) .withQueryParam("status", equalTo("UP")) .withQueryParam("lastDirtyTimestamp", equalTo(lastDirtyTimestamp + "")) .willReturn(aResponse() .withStatus(502) .withHeader("Content-Type", "text/HTML") .withBody("<html><body>Something went wrong in Apacache</body></html>"))); InstanceInfo instanceInfo = mock(InstanceInfo.class); when(instanceInfo.getStatus()).thenReturn(InstanceInfo.InstanceStatus.UP); when(instanceInfo.getLastDirtyTimestamp()).thenReturn(lastDirtyTimestamp); EurekaHttpResponse<InstanceInfo> response = jerseyHttpClient.sendHeartBeat(CLIENT_APP_NAME, uuid, instanceInfo, null); verify(putRequestedFor(urlPathEqualTo("/v2/apps/" + CLIENT_APP_NAME + "/" + uuid)) .withQueryParam("status", equalTo("UP")) .withQueryParam("lastDirtyTimestamp", equalTo(lastDirtyTimestamp + "")) ); assertThat(response.getStatusCode()).as("status code").isEqualTo(502); assertThat(response.getEntity()).as("instance info").isNull(); } @After public void tearDown() throws Exception { if (jerseyHttpClient != null) { jerseyHttpClient.shutdown(); } } }
7,895
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport/decorator/RetryableEurekaHttpClientTest.java
/* * Copyright 2015 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.discovery.shared.transport.decorator; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import com.netflix.discovery.shared.resolver.ClusterResolver; import com.netflix.discovery.shared.resolver.EurekaEndpoint; import com.netflix.discovery.shared.resolver.aws.SampleCluster; import com.netflix.discovery.shared.resolver.aws.AwsEndpoint; import com.netflix.discovery.shared.transport.DefaultEurekaTransportConfig; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.EurekaTransportConfig; import com.netflix.discovery.shared.transport.TransportClientFactory; import com.netflix.discovery.shared.transport.TransportException; import com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.RequestExecutor; import com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.RequestType; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Tomasz Bak */ public class RetryableEurekaHttpClientTest { private static final int NUMBER_OF_RETRIES = 2; private static final int CLUSTER_SIZE = 3; public static final RequestType TEST_REQUEST_TYPE = RequestType.Register; private static final List<AwsEndpoint> CLUSTER_ENDPOINTS = SampleCluster.UsEast1a.builder().withServerPool(CLUSTER_SIZE).build(); private final EurekaTransportConfig transportConfig = mock(EurekaTransportConfig.class); private final ClusterResolver clusterResolver = mock(ClusterResolver.class); private final TransportClientFactory clientFactory = mock(TransportClientFactory.class); private final ServerStatusEvaluator serverStatusEvaluator = ServerStatusEvaluators.legacyEvaluator(); private final RequestExecutor<Void> requestExecutor = mock(RequestExecutor.class); private RetryableEurekaHttpClient retryableClient; private List<EurekaHttpClient> clusterDelegates; @Before public void setUp() throws Exception { when(transportConfig.getRetryableClientQuarantineRefreshPercentage()).thenReturn(0.66); retryableClient = new RetryableEurekaHttpClient( "test", transportConfig, clusterResolver, clientFactory, serverStatusEvaluator, NUMBER_OF_RETRIES); clusterDelegates = new ArrayList<>(CLUSTER_SIZE); for (int i = 0; i < CLUSTER_SIZE; i++) { clusterDelegates.add(mock(EurekaHttpClient.class)); } when(clusterResolver.getClusterEndpoints()).thenReturn(CLUSTER_ENDPOINTS); } @Test public void testRequestsReuseSameConnectionIfThereIsNoError() throws Exception { when(clientFactory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(clusterDelegates.get(0)); when(requestExecutor.execute(clusterDelegates.get(0))).thenReturn(EurekaHttpResponse.status(200)); // First request creates delegate, second reuses it for (int i = 0; i < 3; i++) { EurekaHttpResponse<Void> httpResponse = retryableClient.execute(requestExecutor); assertThat(httpResponse.getStatusCode(), is(equalTo(200))); } verify(clientFactory, times(1)).newClient(Matchers.<EurekaEndpoint>anyVararg()); verify(requestExecutor, times(3)).execute(clusterDelegates.get(0)); } @Test public void testRequestIsRetriedOnConnectionError() throws Exception { when(clientFactory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(clusterDelegates.get(0), clusterDelegates.get(1)); when(requestExecutor.execute(clusterDelegates.get(0))).thenThrow(new TransportException("simulated network error")); when(requestExecutor.execute(clusterDelegates.get(1))).thenReturn(EurekaHttpResponse.status(200)); EurekaHttpResponse<Void> httpResponse = retryableClient.execute(requestExecutor); assertThat(httpResponse.getStatusCode(), is(equalTo(200))); verify(clientFactory, times(2)).newClient(Matchers.<EurekaEndpoint>anyVararg()); verify(requestExecutor, times(1)).execute(clusterDelegates.get(0)); verify(requestExecutor, times(1)).execute(clusterDelegates.get(1)); } @Test(expected = TransportException.class) public void testErrorResponseIsReturnedIfRetryLimitIsReached() throws Exception { simulateTransportError(0, NUMBER_OF_RETRIES + 1); retryableClient.execute(requestExecutor); } @Test public void testQuarantineListIsResetWhenNoMoreServerAreAvailable() throws Exception { // First two call fail simulateTransportError(0, CLUSTER_SIZE); for (int i = 0; i < 2; i++) { executeWithTransportErrorExpectation(); } // Second call, should reset cluster quarantine list, and hit health node 0 when(clientFactory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(clusterDelegates.get(0)); reset(requestExecutor); when(requestExecutor.execute(clusterDelegates.get(0))).thenReturn(EurekaHttpResponse.status(200)); retryableClient.execute(requestExecutor); } @Test public void test5xxStatusCodeResultsInRequestRetry() throws Exception { when(clientFactory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(clusterDelegates.get(0), clusterDelegates.get(1)); when(requestExecutor.execute(clusterDelegates.get(0))).thenReturn(EurekaHttpResponse.status(500)); when(requestExecutor.execute(clusterDelegates.get(1))).thenReturn(EurekaHttpResponse.status(200)); EurekaHttpResponse<Void> httpResponse = retryableClient.execute(requestExecutor); assertThat(httpResponse.getStatusCode(), is(equalTo(200))); verify(requestExecutor, times(1)).execute(clusterDelegates.get(0)); verify(requestExecutor, times(1)).execute(clusterDelegates.get(1)); } @Test(timeout = 10000) public void testConcurrentRequestsLeaveLastSuccessfulDelegate() throws Exception { when(clientFactory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(clusterDelegates.get(0), clusterDelegates.get(1)); BlockingRequestExecutor executor0 = new BlockingRequestExecutor(); BlockingRequestExecutor executor1 = new BlockingRequestExecutor(); Thread thread0 = new Thread(new RequestExecutorRunner(executor0)); Thread thread1 = new Thread(new RequestExecutorRunner(executor1)); // Run parallel requests thread0.start(); executor0.awaitReady(); thread1.start(); executor1.awaitReady(); // Complete request, first thread first, second afterwards executor0.complete(); thread0.join(); executor1.complete(); thread1.join(); // Verify subsequent request done on delegate1 when(requestExecutor.execute(clusterDelegates.get(1))).thenReturn(EurekaHttpResponse.status(200)); EurekaHttpResponse<Void> httpResponse = retryableClient.execute(requestExecutor); assertThat(httpResponse.getStatusCode(), is(equalTo(200))); verify(clientFactory, times(2)).newClient(Matchers.<EurekaEndpoint>anyVararg()); verify(requestExecutor, times(0)).execute(clusterDelegates.get(0)); verify(requestExecutor, times(1)).execute(clusterDelegates.get(1)); } private void simulateTransportError(int delegateFrom, int count) { for (int i = 0; i < count; i++) { int delegateId = delegateFrom + i; when(clientFactory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(clusterDelegates.get(delegateId)); when(requestExecutor.execute(clusterDelegates.get(delegateId))).thenThrow(new TransportException("simulated network error")); } } private void executeWithTransportErrorExpectation() { try { retryableClient.execute(requestExecutor); fail("TransportException expected"); } catch (TransportException ignore) { } } class RequestExecutorRunner implements Runnable { private final RequestExecutor<Void> requestExecutor; RequestExecutorRunner(RequestExecutor<Void> requestExecutor) { this.requestExecutor = requestExecutor; } @Override public void run() { retryableClient.execute(requestExecutor); } } static class BlockingRequestExecutor implements RequestExecutor<Void> { private final CountDownLatch readyLatch = new CountDownLatch(1); private final CountDownLatch completeLatch = new CountDownLatch(1); @Override public EurekaHttpResponse<Void> execute(EurekaHttpClient delegate) { readyLatch.countDown(); try { completeLatch.await(); } catch (InterruptedException e) { throw new IllegalStateException("never released"); } return EurekaHttpResponse.status(200); } @Override public RequestType getRequestType() { return TEST_REQUEST_TYPE; } void awaitReady() { try { readyLatch.await(); } catch (InterruptedException e) { throw new IllegalStateException("never released"); } } void complete() { completeLatch.countDown(); } } }
7,896
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport/decorator/RedirectingEurekaHttpClientTest.java
/* * Copyright 2015 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.discovery.shared.transport.decorator; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.dns.DnsService; import com.netflix.discovery.shared.resolver.EurekaEndpoint; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.TransportClientFactory; import com.netflix.discovery.shared.transport.TransportException; import org.junit.Test; import org.mockito.Matchers; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Tomasz Bak */ public class RedirectingEurekaHttpClientTest { private static final String SERVICE_URL = "http://mydiscovery.test"; private final TransportClientFactory factory = mock(TransportClientFactory.class); private final EurekaHttpClient sourceClient = mock(EurekaHttpClient.class); private final EurekaHttpClient redirectedClient = mock(EurekaHttpClient.class); private final DnsService dnsService = mock(DnsService.class); public void setupRedirect() { when(factory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(sourceClient, redirectedClient); when(sourceClient.getApplications()).thenReturn( anEurekaHttpResponse(302, Applications.class) .headers(HttpHeaders.LOCATION, "http://another.discovery.test/eureka/v2/apps") .build() ); when(dnsService.resolveIp("another.discovery.test")).thenReturn("192.168.0.1"); when(redirectedClient.getApplications()).thenReturn( anEurekaHttpResponse(200, new Applications()).type(MediaType.APPLICATION_JSON_TYPE).build() ); } @Test public void testNonRedirectedRequestsAreServedByFirstClient() throws Exception { when(factory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(sourceClient); when(sourceClient.getApplications()).thenReturn( anEurekaHttpResponse(200, new Applications()).type(MediaType.APPLICATION_JSON_TYPE).build() ); RedirectingEurekaHttpClient httpClient = new RedirectingEurekaHttpClient(SERVICE_URL, factory, dnsService); httpClient.getApplications(); verify(factory, times(1)).newClient(Matchers.<EurekaEndpoint>anyVararg()); verify(sourceClient, times(1)).getApplications(); } @Test public void testRedirectsAreFollowedAndClientIsPinnedToTheLastServer() throws Exception { setupRedirect(); RedirectingEurekaHttpClient httpClient = new RedirectingEurekaHttpClient(SERVICE_URL, factory, dnsService); // First call pins client to resolved IP httpClient.getApplications(); verify(factory, times(2)).newClient(Matchers.<EurekaEndpoint>anyVararg()); verify(sourceClient, times(1)).getApplications(); verify(dnsService, times(1)).resolveIp("another.discovery.test"); verify(redirectedClient, times(1)).getApplications(); // Second call goes straight to the same address httpClient.getApplications(); verify(factory, times(2)).newClient(Matchers.<EurekaEndpoint>anyVararg()); verify(sourceClient, times(1)).getApplications(); verify(dnsService, times(1)).resolveIp("another.discovery.test"); verify(redirectedClient, times(2)).getApplications(); } @Test public void testOnConnectionErrorPinnedClientIsDestroyed() throws Exception { setupRedirect(); RedirectingEurekaHttpClient httpClient = new RedirectingEurekaHttpClient(SERVICE_URL, factory, dnsService); // First call pins client to resolved IP httpClient.getApplications(); verify(redirectedClient, times(1)).getApplications(); // Trigger connection error when(redirectedClient.getApplications()).thenThrow(new TransportException("simulated network error")); try { httpClient.getApplications(); fail("Expected transport error"); } catch (Exception ignored) { } // Subsequent connection shall create new httpClient reset(factory, sourceClient, dnsService, redirectedClient); setupRedirect(); httpClient.getApplications(); verify(factory, times(2)).newClient(Matchers.<EurekaEndpoint>anyVararg()); verify(sourceClient, times(1)).getApplications(); verify(dnsService, times(1)).resolveIp("another.discovery.test"); verify(redirectedClient, times(1)).getApplications(); } }
7,897
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport/decorator/SessionedEurekaHttpClientTest.java
/* * Copyright 2015 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.discovery.shared.transport.decorator; import java.util.concurrent.atomic.AtomicReference; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpClientFactory; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Tomasz Bak */ public class SessionedEurekaHttpClientTest { private final EurekaHttpClient firstClient = mock(EurekaHttpClient.class); private final EurekaHttpClient secondClient = mock(EurekaHttpClient.class); private final EurekaHttpClientFactory factory = mock(EurekaHttpClientFactory.class); @Test public void testReconnectIsEnforcedAtConfiguredInterval() throws Exception { final AtomicReference<EurekaHttpClient> clientRef = new AtomicReference<>(firstClient); when(factory.newClient()).thenAnswer(new Answer<EurekaHttpClient>() { @Override public EurekaHttpClient answer(InvocationOnMock invocation) throws Throwable { return clientRef.get(); } }); SessionedEurekaHttpClient httpClient = null; try { httpClient = new SessionedEurekaHttpClient("test", factory, 1); httpClient.getApplications(); verify(firstClient, times(1)).getApplications(); clientRef.set(secondClient); Thread.sleep(2); httpClient.getApplications(); verify(secondClient, times(1)).getApplications(); } finally { if (httpClient != null) { httpClient.shutdown(); } } } }
7,898
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/StaticClusterResolverTest.java
/* * Copyright 2015 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.discovery.shared.resolver; import java.net.URL; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * @author Tomasz Bak */ public class StaticClusterResolverTest { @Test public void testClusterResolverFromURL() throws Exception { verifyEqual( StaticClusterResolver.fromURL("regionA", new URL("http://eureka.test:8080/eureka/v2/apps")), new DefaultEndpoint("eureka.test", 8080, false, "/eureka/v2/apps") ); verifyEqual( StaticClusterResolver.fromURL("regionA", new URL("https://eureka.test:8081/eureka/v2/apps")), new DefaultEndpoint("eureka.test", 8081, true, "/eureka/v2/apps") ); verifyEqual( StaticClusterResolver.fromURL("regionA", new URL("http://eureka.test/eureka/v2/apps")), new DefaultEndpoint("eureka.test", 80, false, "/eureka/v2/apps") ); verifyEqual( StaticClusterResolver.fromURL("regionA", new URL("https://eureka.test/eureka/v2/apps")), new DefaultEndpoint("eureka.test", 443, true, "/eureka/v2/apps") ); } private static void verifyEqual(ClusterResolver<EurekaEndpoint> actual, EurekaEndpoint expected) { assertThat(actual.getClusterEndpoints().get(0), is(equalTo(expected))); } }
7,899