index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/MergePathToGCRootsRoute.java
/******************************************************************************** * Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.heapdump; import com.google.gson.Gson; import io.vertx.core.Promise; import io.vertx.ext.web.RoutingContext; import org.eclipse.jifa.common.request.PagingRequest; import org.eclipse.jifa.common.vo.PageView; import org.eclipse.jifa.worker.route.HttpMethod; import org.eclipse.jifa.worker.route.ParamKey; import org.eclipse.jifa.worker.route.RouteMeta; import static org.eclipse.jifa.hda.api.Model.GCRootPath; class MergePathToGCRootsRoute extends HeapBaseRoute { @RouteMeta(path = "/mergePathToGCRoots/roots/byClassId") void rootsByClassId(Promise<PageView<GCRootPath.MergePathToGCRootsTreeNode>> promise, @ParamKey("file") String file, @ParamKey("classId") int classId, @ParamKey("grouping") GCRootPath.Grouping grouping, PagingRequest pagingRequest) { promise.complete(analyzerOf(file) .getRootsOfMergePathToGCRootsByClassId(classId, grouping, pagingRequest.getPage(), pagingRequest.getPageSize())); } @RouteMeta(path = "/mergePathToGCRoots/children/byClassId") void childrenByClassId(Promise<PageView<GCRootPath.MergePathToGCRootsTreeNode>> promise, @ParamKey("file") String file, @ParamKey("grouping") GCRootPath.Grouping grouping, PagingRequest pagingRequest, @ParamKey("classId") int classId, @ParamKey("objectIdPathInGCPathTree") int[] objectIdPathInGCPathTree) { promise.complete(analyzerOf(file) .getChildrenOfMergePathToGCRootsByClassId(classId, objectIdPathInGCPathTree, grouping, pagingRequest.getPage(), pagingRequest.getPageSize())); } @RouteMeta(path = "/mergePathToGCRoots/roots/byObjectIds", method = HttpMethod.POST) void rootsByObjectId(Promise<PageView<GCRootPath.MergePathToGCRootsTreeNode>> promise, @ParamKey("file") String file, @ParamKey("grouping") GCRootPath.Grouping grouping, RoutingContext context, PagingRequest pagingRequest) { int[] objectIds = new Gson().fromJson(context.getBodyAsString(), int[].class); promise.complete(analyzerOf(file) .getRootsOfMergePathToGCRootsByObjectIds(objectIds, grouping, pagingRequest.getPage(), pagingRequest.getPageSize())); } @RouteMeta(path = "/mergePathToGCRoots/children/byObjectIds", method = HttpMethod.POST) void childrenByObjectId(Promise<PageView<GCRootPath.MergePathToGCRootsTreeNode>> promise, @ParamKey("file") String file, @ParamKey("grouping") GCRootPath.Grouping grouping, PagingRequest pagingRequest, RoutingContext context, @ParamKey("objectIdPathInGCPathTree") int[] objectIdPathInGCPathTree) { int[] objectIds = new Gson().fromJson(context.getBodyAsString(), int[].class); promise.complete(analyzerOf(file) .getChildrenOfMergePathToGCRootsByObjectIds(objectIds, objectIdPathInGCPathTree, grouping, pagingRequest.getPage(), pagingRequest.getPageSize())); } }
6,900
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/SystemPropertyRoute.java
/******************************************************************************** * Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.heapdump; import io.vertx.core.Promise; import org.eclipse.jifa.worker.route.ParamKey; import org.eclipse.jifa.worker.route.RouteMeta; import java.util.Map; class SystemPropertyRoute extends HeapBaseRoute { @RouteMeta(path = "/systemProperties") void systemProperty(Promise<Map<String, String>> promise, @ParamKey("file") String file) { promise.complete(analyzerOf(file).getSystemProperties()); } }
6,901
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/ObjectListRoute.java
/******************************************************************************** * Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.heapdump; import io.vertx.core.Promise; import org.eclipse.jifa.common.request.PagingRequest; import org.eclipse.jifa.common.vo.PageView; import org.eclipse.jifa.hda.api.Model; import org.eclipse.jifa.worker.route.ParamKey; import org.eclipse.jifa.worker.route.RouteMeta; import static org.eclipse.jifa.common.util.Assertion.ASSERT; class ObjectListRoute extends HeapBaseRoute { @RouteMeta(path = "/outbounds") void outbounds(Promise<PageView<Model.JavaObject>> promise, @ParamKey("file") String file, PagingRequest pagingRequest, @ParamKey("objectId") int objectId) { ASSERT.isTrue(objectId >= 0, "Object id must be greater than or equal to 0"); promise.complete(analyzerOf(file).getOutboundOfObject(objectId, pagingRequest.getPage(), pagingRequest.getPageSize())); } @RouteMeta(path = "/inbounds") void inbounds(Promise<PageView<Model.JavaObject>> promise, @ParamKey("file") String file, PagingRequest pagingRequest, @ParamKey("objectId") int objectId) { ASSERT.isTrue(objectId >= 0, "Object id must be greater than or equal to 0"); promise.complete(analyzerOf(file).getInboundOfObject(objectId, pagingRequest.getPage(), pagingRequest.getPageSize())); } }
6,902
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/OQLRoute.java
/******************************************************************************** * Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.heapdump; import io.vertx.core.Promise; import org.eclipse.jifa.common.request.PagingRequest; import org.eclipse.jifa.hda.api.Model; import org.eclipse.jifa.worker.route.ParamKey; import org.eclipse.jifa.worker.route.RouteMeta; class OQLRoute extends HeapBaseRoute { @RouteMeta(path = "/oql") void oql(Promise<Model.OQLResult> promise, @ParamKey("file") String file, @ParamKey("oql") String oql, @ParamKey(value = "sortBy", mandatory = false) String sortBy, @ParamKey(value = "ascendingOrder", mandatory = false) boolean ascendingOrder, PagingRequest pagingRequest) { promise.complete(analyzerOf(file).getOQLResult(oql, sortBy, ascendingOrder, pagingRequest.getPage(), pagingRequest.getPageSize())); } }
6,903
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/OverviewRoute.java
/******************************************************************************** * Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.heapdump; import io.vertx.core.Promise; import org.eclipse.jifa.hda.api.Model; import org.eclipse.jifa.worker.route.ParamKey; import org.eclipse.jifa.worker.route.RouteMeta; import java.util.List; class OverviewRoute extends HeapBaseRoute { @RouteMeta(path = "/details") void details(Promise<Model.Overview.Details> promise, @ParamKey("file") String file) { promise.complete(analyzerOf(file).getDetails()); } @RouteMeta(path = "/biggestObjects") void biggestObjects(Promise<List<Model.Overview.BigObject>> promise, @ParamKey("file") String file) { promise.complete(analyzerOf(file).getBigObjects()); } }
6,904
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/DuplicatedClassesRoute.java
/******************************************************************************** * Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.heapdump; import io.vertx.core.Promise; import org.eclipse.jifa.common.request.PagingRequest; import org.eclipse.jifa.common.vo.PageView; import org.eclipse.jifa.common.vo.support.SearchType; import org.eclipse.jifa.worker.route.ParamKey; import org.eclipse.jifa.worker.route.RouteMeta; import static org.eclipse.jifa.hda.api.Model.DuplicatedClass; class DuplicatedClassesRoute extends HeapBaseRoute { @RouteMeta(path = "/duplicatedClasses/classes") void classRecords(Promise<PageView<DuplicatedClass.ClassItem>> promise, @ParamKey("file") String file, @ParamKey(value = "searchText", mandatory = false) String searchText, @ParamKey(value = "searchType", mandatory = false) SearchType searchType, PagingRequest pagingRequest) { promise.complete(analyzerOf(file).getDuplicatedClasses(searchText, searchType, pagingRequest.getPage(), pagingRequest.getPageSize())); } @RouteMeta(path = "/duplicatedClasses/classLoaders") void classLoaderRecords(Promise<PageView<DuplicatedClass.ClassLoaderItem>> promise, @ParamKey("file") String file, @ParamKey("index") int index, PagingRequest pagingRequest) { promise.complete(analyzerOf(file).getClassloadersOfDuplicatedClass(index, pagingRequest.getPage(), pagingRequest.getPageSize())); } }
6,905
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/ClassLoaderRoute.java
/******************************************************************************** * Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.heapdump; import io.vertx.core.Promise; import org.eclipse.jifa.common.request.PagingRequest; import org.eclipse.jifa.common.vo.PageView; import org.eclipse.jifa.hda.api.Model; import org.eclipse.jifa.worker.route.ParamKey; import org.eclipse.jifa.worker.route.RouteMeta; class ClassLoaderRoute extends HeapBaseRoute { @RouteMeta(path = "/classLoaderExplorer/summary") void summary(Promise<Model.ClassLoader.Summary> promise, @ParamKey("file") String file) { promise.complete(analyzerOf(file).getSummaryOfClassLoaders()); } @RouteMeta(path = "/classLoaderExplorer/classLoader") void classLoaders(Promise<PageView<Model.ClassLoader.Item>> promise, @ParamKey("file") String file, PagingRequest pagingRequest) { promise.complete(analyzerOf(file).getClassLoaders(pagingRequest.getPage(), pagingRequest.getPageSize())); } @RouteMeta(path = "/classLoaderExplorer/children") void children(Promise<PageView<Model.ClassLoader.Item>> promise, @ParamKey("file") String file, @ParamKey("classLoaderId") int classLoaderId, PagingRequest pagingRequest) { promise.complete(analyzerOf(file).getChildrenOfClassLoader(classLoaderId, pagingRequest.getPage(), pagingRequest.getPageSize())); } }
6,906
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/UnreachableObjectsRoute.java
/******************************************************************************** * Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.heapdump; import io.vertx.core.Promise; import org.eclipse.jifa.common.request.PagingRequest; import org.eclipse.jifa.common.vo.PageView; import org.eclipse.jifa.hda.api.Model; import org.eclipse.jifa.worker.route.ParamKey; import org.eclipse.jifa.worker.route.RouteMeta; class UnreachableObjectsRoute extends HeapBaseRoute { @RouteMeta(path = "/unreachableObjects/summary") void summary(Promise<Model.UnreachableObject.Summary> promise, @ParamKey("file") String file) { promise.complete(analyzerOf(file).getSummaryOfUnreachableObjects()); } @RouteMeta(path = "/unreachableObjects/records") void records(Promise<PageView<Model.UnreachableObject.Item>> promise, @ParamKey("file") String file, PagingRequest pagingRequest) { promise.complete(analyzerOf(file).getUnreachableObjects(pagingRequest.getPage(), pagingRequest.getPageSize())); } }
6,907
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/GCRootRoute.java
/******************************************************************************** * Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.heapdump; import io.vertx.core.Promise; import org.eclipse.jifa.common.request.PagingRequest; import org.eclipse.jifa.common.vo.PageView; import org.eclipse.jifa.hda.api.Model; import org.eclipse.jifa.worker.route.ParamKey; import org.eclipse.jifa.worker.route.RouteMeta; import java.util.List; import static org.eclipse.jifa.hda.api.Model.GCRoot; class GCRootRoute extends HeapBaseRoute { @RouteMeta(path = "/GCRoots") void roots(Promise<List<GCRoot.Item>> promise, @ParamKey("file") String file) { promise.complete(analyzerOf(file).getGCRoots()); } @RouteMeta(path = "/GCRoots/classes") void classes(Promise<PageView<GCRoot.Item>> promise, @ParamKey("file") String file, @ParamKey("rootTypeIndex") int rootTypeIndex, PagingRequest pagingRequest) { promise.complete(analyzerOf(file).getClassesOfGCRoot(rootTypeIndex, pagingRequest.getPage(), pagingRequest.getPageSize())); } @RouteMeta(path = "/GCRoots/class/objects") void objects(Promise<PageView<Model.JavaObject>> promise, @ParamKey("file") String file, @ParamKey("rootTypeIndex") int rootTypeIndex, @ParamKey("classIndex") int classIndex, PagingRequest pagingRequest) { promise.complete(analyzerOf(file).getObjectsOfGCRoot(rootTypeIndex, classIndex, pagingRequest.getPage(), pagingRequest.getPageSize())); } }
6,908
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/HistogramRoute.java
/******************************************************************************** * Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.heapdump; import io.vertx.core.Promise; import org.eclipse.jifa.common.request.PagingRequest; import org.eclipse.jifa.common.vo.PageView; import org.eclipse.jifa.common.vo.support.SearchType; import org.eclipse.jifa.hda.api.Model; import org.eclipse.jifa.worker.route.ParamKey; import org.eclipse.jifa.worker.route.RouteMeta; class HistogramRoute extends HeapBaseRoute { @RouteMeta(path = "/histogram") void histogram(Promise<PageView<Model.Histogram.Item>> promise, @ParamKey("file") String file, @ParamKey("groupingBy") Model.Histogram.Grouping groupingBy, @ParamKey(value = "ids", mandatory = false) int[] ids, @ParamKey(value = "sortBy", mandatory = false) String sortBy, @ParamKey(value = "ascendingOrder", mandatory = false) boolean ascendingOrder, @ParamKey(value = "searchText", mandatory = false) String searchText, @ParamKey(value = "searchType", mandatory = false) SearchType searchType, PagingRequest pagingRequest) { promise.complete(analyzerOf(file).getHistogram(groupingBy, ids, sortBy, ascendingOrder, searchText, searchType, pagingRequest.getPage(), pagingRequest.getPageSize())); } @RouteMeta(path = "/histogram/children") void children(Promise<PageView<Model.Histogram.Item>> promise, @ParamKey("file") String file, @ParamKey("groupingBy") Model.Histogram.Grouping groupingBy, @ParamKey(value = "ids", mandatory = false) int[] ids, @ParamKey(value = "sortBy", mandatory = false) String sortBy, @ParamKey(value = "ascendingOrder", mandatory = false) boolean ascendingOrder, @ParamKey("parentObjectId") int parentObjectId, PagingRequest pagingRequest) { promise.complete(analyzerOf(file).getChildrenOfHistogram(groupingBy, ids, sortBy, ascendingOrder, parentObjectId, pagingRequest.getPage(), pagingRequest.getPageSize())); } @RouteMeta(path = "/histogram/objects") void objects(Promise<PageView<Model.JavaObject>> promise, @ParamKey("file") String file, @ParamKey("classId") int classId, PagingRequest pagingRequest) { promise.complete(analyzerOf(file).getHistogramObjects(classId, pagingRequest.getPage(), pagingRequest.getPageSize())); } }
6,909
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/ThreadRoute.java
/******************************************************************************** * Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.heapdump; import io.vertx.core.Promise; import org.eclipse.jifa.common.request.PagingRequest; import org.eclipse.jifa.common.vo.PageView; import org.eclipse.jifa.common.vo.support.SearchType; import org.eclipse.jifa.hda.api.Model; import org.eclipse.jifa.worker.route.ParamKey; import org.eclipse.jifa.worker.route.RouteMeta; import java.util.List; class ThreadRoute extends HeapBaseRoute { @RouteMeta(path = "/threadsSummary") void threadsSummary(Promise<Model.Thread.Summary> promise, @ParamKey("file") String file, @ParamKey(value = "searchText", mandatory = false) String searchText, @ParamKey(value = "searchType", mandatory = false) SearchType searchType) { promise.complete(analyzerOf(file).getSummaryOfThreads(searchText, searchType)); } @RouteMeta(path = "/threads") void threads(Promise<PageView<Model.Thread.Item>> promise, @ParamKey("file") String file, @ParamKey(value = "sortBy", mandatory = false) String sortBy, @ParamKey(value = "ascendingOrder", mandatory = false) boolean ascendingOrder, @ParamKey(value = "searchText", mandatory = false) String searchText, @ParamKey(value = "searchType", mandatory = false) SearchType searchType, PagingRequest paging) { promise.complete(analyzerOf(file).getThreads(sortBy, ascendingOrder, searchText, searchType, paging.getPage(), paging.getPageSize())); } @RouteMeta(path = "/stackTrace") void stackTrace(Promise<List<Model.Thread.StackFrame>> promise, @ParamKey("file") String file, @ParamKey("objectId") int objectId) { promise.complete(analyzerOf(file).getStackTrace(objectId)); } @RouteMeta(path = "/locals") void locals(Promise<List<Model.Thread.LocalVariable>> promise, @ParamKey("file") String file, @ParamKey("objectId") int objectId, @ParamKey("depth") int depth, @ParamKey("firstNonNativeFrame") boolean firstNonNativeFrame) { promise.complete(analyzerOf(file).getLocalVariables(objectId, depth, firstNonNativeFrame)); } }
6,910
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/ObjectRoute.java
/******************************************************************************** * Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.heapdump; import io.vertx.core.Promise; import org.eclipse.jifa.hda.api.Model; import org.eclipse.jifa.worker.route.ParamKey; import org.eclipse.jifa.worker.route.RouteMeta; import static org.eclipse.jifa.common.util.Assertion.ASSERT; class ObjectRoute extends HeapBaseRoute { @RouteMeta(path = "/object") void info(Promise<Model.JavaObject> promise, @ParamKey("file") String file, @ParamKey("objectId") int objectId) { ASSERT.isTrue(objectId >= 0, "Object id must be greater than or equal to 0"); promise.complete(analyzerOf(file).getObjectInfo(objectId)); } }
6,911
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/DominatorTreeRoute.java
/******************************************************************************** * Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.heapdump; import io.vertx.core.Promise; import org.eclipse.jifa.common.request.PagingRequest; import org.eclipse.jifa.common.vo.PageView; import org.eclipse.jifa.common.vo.support.SearchType; import org.eclipse.jifa.worker.route.ParamKey; import org.eclipse.jifa.worker.route.RouteMeta; import static org.eclipse.jifa.hda.api.Model.DominatorTree; class DominatorTreeRoute extends HeapBaseRoute { @RouteMeta(path = "/dominatorTree/roots") void roots(Promise<PageView<? extends DominatorTree.Item>> promise, @ParamKey("file") String file, @ParamKey("grouping") DominatorTree.Grouping grouping, @ParamKey(value = "sortBy", mandatory = false) String sortBy, @ParamKey(value = "ascendingOrder", mandatory = false) boolean ascendingOrder, @ParamKey(value = "searchText", mandatory = false) String searchText, @ParamKey(value = "searchType", mandatory = false) SearchType searchType, PagingRequest pagingRequest) { promise.complete(analyzerOf(file).getRootsOfDominatorTree(grouping, sortBy, ascendingOrder, searchText, searchType, pagingRequest.getPage(), pagingRequest.getPageSize())); } @RouteMeta(path = "/dominatorTree/children") void children(Promise<PageView<? extends DominatorTree.Item>> promise, @ParamKey("file") String file, @ParamKey("grouping") DominatorTree.Grouping grouping, @ParamKey(value = "sortBy", mandatory = false) String sortBy, @ParamKey(value = "ascendingOrder", mandatory = false) boolean ascendingOrder, PagingRequest pagingRequest, @ParamKey("parentObjectId") int parentObjectId, @ParamKey(value = "idPathInResultTree", mandatory = false) int[] idPathInResultTree) { promise.complete(analyzerOf(file).getChildrenOfDominatorTree(grouping, sortBy, ascendingOrder, parentObjectId, idPathInResultTree, pagingRequest.getPage(), pagingRequest.getPageSize())); } }
6,912
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/LeakRoute.java
/******************************************************************************** * Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.heapdump; import io.vertx.core.Promise; import org.eclipse.jifa.hda.api.Model; import org.eclipse.jifa.worker.route.ParamKey; import org.eclipse.jifa.worker.route.RouteMeta; class LeakRoute extends HeapBaseRoute { @RouteMeta(path = "/leak/report") void report(Promise<Model.LeakReport> promise, @ParamKey("file") String file) { promise.complete(analyzerOf(file).getLeakReport()); } }
6,913
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/gclog/GCLogBaseRoute.java
/******************************************************************************** * Copyright (c) 2022 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.gclog; import org.eclipse.jifa.worker.route.BaseRoute; import org.eclipse.jifa.worker.route.MappingPrefix; import java.util.ArrayList; import java.util.List; @MappingPrefix("/gc-log/:file") public class GCLogBaseRoute extends BaseRoute { private static List<Class<? extends GCLogBaseRoute>> ROUTES = new ArrayList<>(); static { ROUTES.add(GCLogRoute.class); } public static List<Class<? extends GCLogBaseRoute>> routes() { return ROUTES; } }
6,914
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/gclog/GCLogRoute.java
/******************************************************************************** * Copyright (c) 2022 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.route.gclog; import org.eclipse.jifa.gclog.diagnoser.AnalysisConfig; import org.eclipse.jifa.gclog.diagnoser.GlobalDiagnoser; import org.eclipse.jifa.gclog.vo.GCEventVO; import org.eclipse.jifa.gclog.model.modeInfo.GCLogMetadata; import org.eclipse.jifa.gclog.model.GCModel; import io.vertx.core.Promise; import org.eclipse.jifa.common.request.PagingRequest; import org.eclipse.jifa.common.vo.PageView; import org.eclipse.jifa.gclog.model.modeInfo.VmOptions; import org.eclipse.jifa.gclog.vo.*; import org.eclipse.jifa.worker.route.HttpMethod; import org.eclipse.jifa.worker.route.ParamKey; import org.eclipse.jifa.worker.route.RouteMeta; import org.eclipse.jifa.worker.support.Analyzer; import java.util.List; import java.util.Map; public class GCLogRoute extends org.eclipse.jifa.worker.route.gclog.GCLogBaseRoute { @RouteMeta(path = "/metadata") void metadata(Promise<GCLogMetadata> promise, @ParamKey("file") String file) { final GCModel model = Analyzer.getOrOpenGCLogModel(file); promise.complete(model.getGcModelMetadata()); } @RouteMeta(path = "/objectStatistics") void objectStats(Promise<ObjectStatistics> promise, @ParamKey("file") String file, @ParamKey("start") double start, @ParamKey("end") double end) { final GCModel model = Analyzer.getOrOpenGCLogModel(file); promise.complete(model.getObjectStatistics(new TimeRange(start, end))); } @RouteMeta(path = "/memoryStatistics") void memoryStats(Promise<MemoryStatistics> promise, @ParamKey("file") String file, @ParamKey("start") double start, @ParamKey("end") double end) { final GCModel model = Analyzer.getOrOpenGCLogModel(file); promise.complete(model.getMemoryStatistics(new TimeRange(start, end))); } @RouteMeta(path = "/pauseDistribution") void pauseStats(Promise<Map<String, int[]>> promise, @ParamKey("file") String file, @ParamKey("start") double start, @ParamKey("end") double end, @ParamKey("partitions") int[] partitions) { final GCModel model = Analyzer.getOrOpenGCLogModel(file); promise.complete(model.getPauseDistribution(new TimeRange(start, end), partitions)); } @RouteMeta(path = "/pauseStatistics") void pauseStats(Promise<PauseStatistics> promise, @ParamKey("file") String file, @ParamKey("start") double start, @ParamKey("end") double end) { final GCModel model = Analyzer.getOrOpenGCLogModel(file); promise.complete(model.getPauseStatistics(new TimeRange(start, end))); } @RouteMeta(path = "/phaseStatistics") void phaseStats(Promise<PhaseStatistics> promise, @ParamKey("file") String file, @ParamKey("start") double start, @ParamKey("end") double end) { final GCModel model = Analyzer.getOrOpenGCLogModel(file); promise.complete(model.getPhaseStatistics(new TimeRange(start, end))); } @RouteMeta(path = "/gcDetails") void detail(Promise<PageView<GCEventVO>> promise, @ParamKey("file") String file, @ParamKey(value = "eventType", mandatory = false) String eventType, @ParamKey(value = "gcCause", mandatory = false) String gcCause, @ParamKey(value = "logTimeLow", mandatory = false) Double logTimeLow, @ParamKey(value = "logTimeHigh", mandatory = false) Double logTimeHigh, @ParamKey(value = "pauseTimeLow", mandatory = false) Double pauseTimeLow, // time range of config is ignored for the time being @ParamKey("config") AnalysisConfig config, PagingRequest pagingRequest) { final GCModel model = Analyzer.getOrOpenGCLogModel(file); GCModel.GCDetailFilter filter = new GCModel.GCDetailFilter(eventType, gcCause, logTimeLow, logTimeHigh, pauseTimeLow); promise.complete(model.getGCDetails(pagingRequest, filter, config)); } @RouteMeta(path = "/vmOptions", method = HttpMethod.GET) void getVMOptions(Promise<VmOptions.VmOptionResult> promise, @ParamKey("file") String file) { final GCModel model = Analyzer.getOrOpenGCLogModel(file); VmOptions options = model.getVmOptions(); promise.complete(options == null ? null : options.getVmOptionResult()); } @RouteMeta(path = "/timeGraphData", method = HttpMethod.GET) void getTimeGraphData(Promise<Map<String, List<Object[]>>> promise, @ParamKey("file") String file, @ParamKey("dataTypes") String[] dateTypes) { final GCModel model = Analyzer.getOrOpenGCLogModel(file); promise.complete(model.getTimeGraphData(dateTypes)); } @RouteMeta(path = "/vmOptions", method = HttpMethod.POST) void setVMOptions(Promise<Void> promise, @ParamKey("file") String file, @ParamKey("options") String options) { final GCModel model = Analyzer.getOrOpenGCLogModel(file); model.setVmOptions(new VmOptions(options)); promise.complete(); } @RouteMeta(path = "/diagnoseInfo", method = HttpMethod.GET) void getDiagnoseInfo(Promise<GlobalDiagnoser.GlobalAbnormalInfo> promise, @ParamKey("file") String file, @ParamKey("config") AnalysisConfig config) { final GCModel model = Analyzer.getOrOpenGCLogModel(file); promise.complete(model.getGlobalAbnormalInfo(config)); } }
6,915
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/support/Analyzer.java
/******************************************************************************** * Copyright (c) 2020, 2022 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.support; import org.eclipse.jifa.gclog.model.GCModel; import org.eclipse.jifa.gclog.parser.GCLogAnalyzer; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import io.vertx.core.Promise; import org.eclipse.jifa.common.JifaException; import org.eclipse.jifa.common.enums.FileType; import org.eclipse.jifa.common.enums.ProgressState; import org.eclipse.jifa.common.util.ErrorUtil; import org.eclipse.jifa.common.util.FileUtil; import org.eclipse.jifa.common.listener.DefaultProgressListener; import org.eclipse.jifa.hda.api.HeapDumpAnalyzer; import org.eclipse.jifa.common.listener.ProgressListener; import org.eclipse.jifa.tda.ThreadDumpAnalyzer; import org.eclipse.jifa.worker.Worker; import org.eclipse.jifa.worker.WorkerGlobal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.ServiceLoader; import java.util.concurrent.TimeUnit; import static org.eclipse.jifa.common.enums.FileType.*; import static org.eclipse.jifa.common.util.Assertion.ASSERT; import static org.eclipse.jifa.worker.Constant.CacheConfig.*; public class Analyzer { public static final HeapDumpAnalyzer.Provider HEAP_DUMP_ANALYZER_PROVIDER; private static final Logger LOGGER = LoggerFactory.getLogger(Analyzer.class); static { try { Iterator<HeapDumpAnalyzer.Provider> iterator = ServiceLoader.load(HeapDumpAnalyzer.Provider.class, Worker.class.getClassLoader()).iterator(); ASSERT.isTrue(iterator.hasNext()); HEAP_DUMP_ANALYZER_PROVIDER = iterator.next(); } catch (Throwable t) { LOGGER.error("Init analyzer failed", t); throw new Error(t); } } private final Map<String, ProgressListener> listeners; private final Cache<String, Object> cache; private Analyzer() { listeners = new HashMap<>(); cache = CacheBuilder .newBuilder() .softValues() .recordStats() .expireAfterWrite( WorkerGlobal.intConfig(CACHE_CONFIG, EXPIRE_AFTER_ACCESS), TimeUnit.valueOf(WorkerGlobal.stringConfig(CACHE_CONFIG, EXPIRE_AFTER_ACCESS_TIME_UNIT)) ) .build(); } private static <T> T getOrBuild(String key, Builder<T> builder) { T result = getInstance().getCacheValueIfPresent(key); if (result != null) { return result; } synchronized (key.intern()) { result = getInstance().getCacheValueIfPresent(key); if (result != null) { return result; } try { result = builder.build(key); } catch (Throwable t) { throw new JifaException(t); } getInstance().putCacheValue(key, result); return result; } } public static HeapDumpAnalyzer getOrBuildHeapDumpAnalyzer(String dump, Map<String, String> options, ProgressListener listener) { return getOrBuild(dump, key -> HEAP_DUMP_ANALYZER_PROVIDER .provide(new File(FileSupport.filePath(HEAP_DUMP, dump)).toPath(), options, listener)); } public static Analyzer getInstance() { return Singleton.INSTANCE; } public boolean isFirstAnalysis(FileType fileType, String file) { switch (fileType) { case HEAP_DUMP: return !new File(FileSupport.indexPath(fileType, file)).exists() && !new File(FileSupport.errorLogPath(fileType, file)).exists() && getFileListener(file) == null; default: throw new IllegalArgumentException(fileType.name()); } } public void analyze(Promise<Void> promise, FileType fileType, String fileName, Map<String, String> options) { ProgressListener progressListener; if (getCacheValueIfPresent(fileName) != null || new File(FileSupport.errorLogPath(fileType, fileName)).exists()) { promise.complete(); return; } progressListener = new DefaultProgressListener(); boolean success = putFileListener(fileName, progressListener); promise.complete(); if (success) { try { switch (fileType) { case HEAP_DUMP: getOrBuildHeapDumpAnalyzer(fileName, options, progressListener); break; case GC_LOG: getOrOpenGCLogModel(fileName,progressListener); break; case THREAD_DUMP: threadDumpAnalyzerOf(fileName, progressListener); break; default: break; } } catch (Exception e) { LOGGER.error("task failed due to {}", ErrorUtil.toString(e)); LOGGER.error(progressListener.log()); File log = new File(FileSupport.errorLogPath(fileType, fileName)); FileUtil.write(log, progressListener.log(), false); FileUtil.write(log, ErrorUtil.toString(e), true); } finally { removeFileListener(fileName); } } } public void clean(FileType fileType, String fileName) { clearCacheValue(fileName); File errorLog = new File(FileSupport.errorLogPath(fileType, fileName)); if (errorLog.exists()) { ASSERT.isTrue(errorLog.delete(), "Delete error log failed"); } if (getFileListener(fileName) != null) { return; } File index = new File(FileSupport.indexPath(fileType, fileName)); if (index.exists()) { ASSERT.isTrue(index.delete(), "Delete index file failed"); } File kryo = new File(FileSupport.filePath(fileType, fileName, fileName + ".kryo")); if (kryo.exists()) { ASSERT.isTrue(kryo.delete(), "Delete kryo file failed"); } } public void release(String fileName) { clearCacheValue(fileName); } public org.eclipse.jifa.common.vo.Progress pollProgress(FileType fileType, String fileName) { ProgressListener progressListener = getFileListener(fileName); if (progressListener == null) { org.eclipse.jifa.common.vo.Progress progress = buildProgressIfFinished(fileType, fileName); return progress; } else { org.eclipse.jifa.common.vo.Progress progress = new org.eclipse.jifa.common.vo.Progress(); progress.setState(ProgressState.IN_PROGRESS); progress.setMessage(progressListener.log()); progress.setPercent(progressListener.percent()); return progress; } } @SuppressWarnings("unchecked") private synchronized <T> T getCacheValueIfPresent(String key) { return (T) cache.getIfPresent(key); } private synchronized void putCacheValue(String key, Object value) { cache.put(key, value); LOGGER.info("Put cache: {}", key); } private synchronized void clearCacheValue(String key) { Object value = cache.getIfPresent(key); if (value instanceof HeapDumpAnalyzer) { ((HeapDumpAnalyzer) value).dispose(); } cache.invalidate(key); LOGGER.info("Clear cache: {}", key); } private synchronized ProgressListener getFileListener(String fileName) { return listeners.get(fileName); } private synchronized boolean putFileListener(String fileName, ProgressListener listener) { if (listeners.containsKey(fileName)) { return false; } listeners.put(fileName, listener); return true; } private synchronized void removeFileListener(String fileName) { listeners.remove(fileName); } private org.eclipse.jifa.common.vo.Progress buildProgressIfFinished(FileType fileType, String fileName) { if (getCacheValueIfPresent(fileName) != null) { org.eclipse.jifa.common.vo.Progress result = new org.eclipse.jifa.common.vo.Progress(); result.setPercent(1); result.setState(ProgressState.SUCCESS); return result; } File failed = new File(FileSupport.errorLogPath(fileType, fileName)); if (failed.exists()) { org.eclipse.jifa.common.vo.Progress result = new org.eclipse.jifa.common.vo.Progress(); result.setState(ProgressState.ERROR); result.setMessage(FileUtil.content(failed)); return result; } org.eclipse.jifa.common.vo.Progress result = new org.eclipse.jifa.common.vo.Progress(); result.setState(ProgressState.NOT_STARTED); return result; } interface Builder<T> { T build(String key) throws Throwable; } private static class Singleton { static Analyzer INSTANCE = new Analyzer(); } public static GCModel getOrOpenGCLogModel(String info) { return getOrOpenGCLogModel(info, ProgressListener.NoOpProgressListener); } private static GCModel getOrOpenGCLogModel(String gclogFile, ProgressListener listener) { return getOrBuild(gclogFile, key -> new GCLogAnalyzer(new File(FileSupport.filePath(GC_LOG, gclogFile)), listener).parse()); } public static ThreadDumpAnalyzer threadDumpAnalyzerOf(String threadDumpFile) { return threadDumpAnalyzerOf(threadDumpFile, ProgressListener.NoOpProgressListener); } public static ThreadDumpAnalyzer threadDumpAnalyzerOf(String threadDumpFile, ProgressListener listener) { return getOrBuild(threadDumpFile, key -> ThreadDumpAnalyzer .build(new File(FileSupport.filePath(THREAD_DUMP, threadDumpFile)).toPath(), listener)); } }
6,916
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/support/TransferListener.java
/******************************************************************************** * Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.support; import lombok.Data; import org.eclipse.jifa.common.enums.FileTransferState; import org.eclipse.jifa.common.enums.FileType; import org.eclipse.jifa.common.enums.ProgressState; import org.eclipse.jifa.worker.support.FileSupport; @Data public class TransferListener { private ProgressState state; private long totalSize; private long transferredSize; private String errorMsg; private FileType fileType; private String fileName; public TransferListener(FileType fileType, String originalName, String fileName) { this.fileType = fileType; this.fileName = fileName; this.state = ProgressState.NOT_STARTED; FileSupport.initInfoFile(fileType, originalName, fileName); } public synchronized void updateState(ProgressState state) { if (this.state == state) { return; } if (state == ProgressState.SUCCESS) { FileSupport.updateTransferState(fileType, fileName, FileTransferState.SUCCESS); totalSize = FileSupport.info(fileType, fileName).getSize(); } if (state == ProgressState.ERROR) { FileSupport.updateTransferState(fileType, fileName, FileTransferState.ERROR); } if (state == ProgressState.IN_PROGRESS && this.state == ProgressState.NOT_STARTED) { FileSupport.updateTransferState(fileType, fileName, FileTransferState.IN_PROGRESS); } this.state = state; } public synchronized void addTransferredSize(long bytes) { this.transferredSize += bytes; } }
6,917
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/support/BinFunction.java
/******************************************************************************** * Copyright (c) 2020 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.support; public interface BinFunction<A, B, R> { R apply(A a, B b) throws Exception; }
6,918
0
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker
Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/support/FileSupport.java
/******************************************************************************** * Copyright (c) 2020, 2022 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 ********************************************************************************/ package org.eclipse.jifa.worker.support; import com.aliyun.oss.OSSClient; import com.aliyun.oss.event.ProgressEventType; import com.aliyun.oss.model.DownloadFileRequest; import com.aliyun.oss.model.ObjectMetadata; import com.amazonaws.ClientConfiguration; import com.amazonaws.Protocol; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.*; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.s3.model.ResponseHeaderOverrides; import com.amazonaws.services.s3.model.S3Object; import io.vertx.core.Promise; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.common.StreamCopier; import net.schmizz.sshj.xfer.FileSystemFile; import net.schmizz.sshj.xfer.scp.SCPDownloadClient; import net.schmizz.sshj.xfer.scp.SCPFileTransfer; import org.apache.commons.io.FileUtils; import org.eclipse.jifa.common.Constant; import org.eclipse.jifa.common.ErrorCode; import org.eclipse.jifa.common.JifaException; import org.eclipse.jifa.common.enums.FileTransferState; import org.eclipse.jifa.common.enums.FileType; import org.eclipse.jifa.common.enums.ProgressState; import org.eclipse.jifa.common.util.FileUtil; import org.eclipse.jifa.common.vo.FileInfo; import org.eclipse.jifa.common.vo.TransferringFile; import org.eclipse.jifa.worker.WorkerGlobal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static org.eclipse.jifa.common.util.Assertion.ASSERT; import static org.eclipse.jifa.common.util.GsonHolder.GSON; import static org.eclipse.jifa.worker.Constant.File.INFO_FILE_SUFFIX; public class FileSupport { public static final List<String> PUB_KEYS = new ArrayList<>(); private static final String ERROR_LOG = "error.log"; private static final Logger LOGGER = LoggerFactory.getLogger(FileSupport.class); private static final Map<String, TransferListener> transferListeners = new ConcurrentHashMap<>(); private static String[] keyLocations() { final String base = System.getProperty("user.home") + File.separator + ".ssh" + File.separator; return new String[]{base + "jifa-ssh-key"}; } private static String[] pubKeyLocations() { final String base = System.getProperty("user.home") + File.separator + ".ssh" + File.separator; return new String[]{base + "jifa-ssh-key.pub"}; } public static void init() { for (FileType type : FileType.values()) { File file = new File(WorkerGlobal.workspace() + File.separator + type.getTag()); if (file.exists()) { ASSERT.isTrue(file.isDirectory(), String.format("%s must be directory", file.getAbsolutePath())); } else { ASSERT.isTrue(file.mkdirs(), String.format("Can not create %s ", file.getAbsolutePath())); } } for (String loc : pubKeyLocations()) { File f = new File(loc); if (f.exists() && f.length() > 0) { PUB_KEYS.add(FileUtil.content(f)); } } } public static void initInfoFile(FileType type, String originalName, String name) { ASSERT.isTrue(new File(dirPath(type, name)).mkdirs(), "Make directory failed"); FileInfo info = buildInitFileInfo(type, originalName, name); try { FileUtils.write(infoFile(type, name), GSON.toJson(info), Charset.defaultCharset()); } catch (IOException e) { LOGGER.error("Write file information failed", e); throw new JifaException(e); } } private static FileInfo buildInitFileInfo(FileType type, String originalName, String name) { FileInfo info = new FileInfo(); info.setOriginalName(originalName); info.setName(name); info.setSize(0); info.setType(type); info.setTransferState(FileTransferState.NOT_STARTED); info.setDownloadable(false); info.setCreationTime(System.currentTimeMillis()); return info; } public static List<FileInfo> info(FileType type) { List<FileInfo> infoList = new ArrayList<>(); File dir = new File(dirPath(type)); ASSERT.isTrue(dir.isDirectory(), ErrorCode.SANITY_CHECK); File[] subDirs = dir.listFiles(File::isDirectory); if (subDirs == null) { return infoList; } for (File subDir : subDirs) { String infoFileName = subDir.getName() + INFO_FILE_SUFFIX; File[] files = subDir.listFiles((d, name) -> infoFileName.equals(name)); if (files != null && files.length == 1) { File infoFile = files[0]; try { FileInfo info = GSON.fromJson(FileUtils.readFileToString(infoFile, Charset.defaultCharset()), FileInfo.class); ensureValidFileInfo(info); infoList.add(info); } catch (Exception e) { LOGGER.error("Read file information failed: {}", infoFile.getAbsolutePath(), e); // should not throw exception here } } } return infoList; } private static void ensureValidFileInfo(FileInfo info) { ASSERT.notNull(info) .notNull(info.getOriginalName()) .notNull(info.getName()) .notNull(info.getType()) .notNull(info.getTransferState()) .isTrue(info.getSize() >= 0) .isTrue(info.getCreationTime() > 0); } public static FileInfo getOrGenInfo(FileType type, String name) { File file = new File(FileSupport.filePath(type, name)); ASSERT.isTrue(file.exists(), ErrorCode.FILE_DOES_NOT_EXIST); File infoFile = infoFile(type, name); if (infoFile.exists()) { return info(type, name); } FileInfo fileInfo = buildInitFileInfo(type, name, name); fileInfo.setCreationTime(file.lastModified()); fileInfo.setTransferState(FileTransferState.SUCCESS); fileInfo.setSize(file.length()); save(fileInfo); return fileInfo; } public static FileInfo info(FileType type, String name) { File infoFile = infoFile(type, name); FileInfo fileInfo; try { fileInfo = GSON.fromJson(FileUtils.readFileToString(infoFile, Charset.defaultCharset()), FileInfo.class); ensureValidFileInfo(fileInfo); } catch (IOException e) { LOGGER.error("Read file information failed", e); throw new JifaException(e); } return fileInfo; } public static FileInfo infoOrNull(FileType type, String name) { try { return info(type, name); } catch (Exception e) { return null; } } public static void save(FileInfo info) { try { FileUtils .write(infoFile(info.getType(), info.getName()), GSON.toJson(info), Charset.defaultCharset()); } catch (IOException e) { LOGGER.error("Save file information failed", e); throw new JifaException(e); } } public static void delete(FileType type, String name) { try { FileUtils.deleteDirectory(new File(dirPath(type, name))); } catch (IOException e) { LOGGER.error("Delete file failed", e); throw new JifaException(e); } } public static void delete(FileInfo[] fileInfos) { for (FileInfo fileInfo : fileInfos) { try { delete(fileInfo.getType(), fileInfo.getName()); } catch (Throwable t) { LOGGER.error("Delete file failed", t); } } } public static void sync(FileInfo[] fileInfos, boolean cleanStale) { Map<FileType, List<String>> files = new HashMap<>(){{ for (FileType ft : FileType.values()) { // In case no files returned this.put(ft, new ArrayList<>()); } }}; for (FileInfo fi : fileInfos) { files.get(fi.getType()).add(fi.getName()); } long lastModified = System.currentTimeMillis() - Constant.STALE_THRESHOLD; for (FileType ft : files.keySet()) { List<String> names = files.get(ft); File[] listFiles = new File(dirPath(ft)).listFiles(); if (listFiles == null) { continue; } for (File lf : listFiles) { if (names.contains(lf.getName())) { continue; } LOGGER.info("{} is not synchronized", lf.getName()); if (cleanStale && lf.lastModified() < lastModified) { LOGGER.info("Delete stale file {}", lf.getName()); delete(ft, lf.getName()); } } } } public static void updateTransferState(FileType type, String name, FileTransferState state) { FileInfo info = info(type, name); info.setTransferState(state); if (state == FileTransferState.SUCCESS) { // for worker, file is downloadable after transferred info.setSize(new File(FileSupport.filePath(type, name)).length()); info.setDownloadable(true); } save(info); } private static String dirPath(FileType type) { return WorkerGlobal.workspace() + File.separator + type.getTag(); } public static String dirPath(FileType type, String name) { String defaultDirPath = dirPath(type) + File.separator + name; return WorkerGlobal.hooks().mapDirPath(type, name, defaultDirPath); } private static String infoFilePath(FileType type, String name) { return dirPath(type, name) + File.separator + name + INFO_FILE_SUFFIX; } private static File infoFile(FileType type, String name) { return new File(infoFilePath(type, name)); } public static String filePath(FileType type, String name) { return filePath(type, name, name); } public static String filePath(FileType type, String name, String childrenName) { String defaultFilePath = dirPath(type, name) + File.separator + childrenName; return WorkerGlobal.hooks().mapFilePath(type, name, childrenName, defaultFilePath); } public static String errorLogPath(FileType fileType, String file) { return FileSupport.filePath(fileType, file, ERROR_LOG); } public static String indexPath(FileType fileType, String file) { String indexFileNamePrefix; int i = file.lastIndexOf('.'); if (i >= 0) { indexFileNamePrefix = file.substring(0, i + 1); } else { indexFileNamePrefix = file + '.'; } String defaultIndexPath = FileSupport.filePath(fileType, file, indexFileNamePrefix + "index"); return WorkerGlobal.hooks().mapIndexPath(fileType, file, defaultIndexPath); } public static TransferListener createTransferListener(FileType fileType, String originalName, String fileName) { TransferListener listener = new TransferListener(fileType, originalName, fileName); transferListeners.put(fileName, listener); return listener; } public static void removeTransferListener(String fileName) { transferListeners.remove(fileName); } public static TransferListener getTransferListener(String fileName) { return transferListeners.get(fileName); } public static void transferBySCP(String user, String hostname, String src, FileType fileType, String fileName, TransferListener transferProgressListener, Promise<TransferringFile> promise) { transferBySCP(user, null, hostname, src, fileType, fileName, transferProgressListener, promise); } public static void transferBySCP(String user, String pwd, String hostname, String src, FileType fileType, String fileName, TransferListener transferProgressListener, Promise<TransferringFile> promise) { transferProgressListener.updateState(ProgressState.IN_PROGRESS); SSHClient ssh = new SSHClient(); ssh.addHostKeyVerifier((h, port, key) -> true); try { ssh.connect(hostname); if (pwd != null) { ssh.authPassword(user, pwd); } else { ssh.authPublickey(user, keyLocations()); } SCPFileTransfer transfer = ssh.newSCPFileTransfer(); transfer.setTransferListener(new net.schmizz.sshj.xfer.TransferListener() { @Override public net.schmizz.sshj.xfer.TransferListener directory(String name) { return this; } @Override public StreamCopier.Listener file(String name, long size) { transferProgressListener.setTotalSize(size); return transferProgressListener::setTransferredSize; } }); SCPDownloadClient downloadClient = transfer.newSCPDownloadClient(); promise.complete(new TransferringFile(fileName)); // do not copy dir now downloadClient.setRecursiveMode(false); downloadClient.copy(src, new FileSystemFile(FileSupport.filePath(fileType, fileName))); transferProgressListener.updateState(ProgressState.SUCCESS); } catch (Exception e) { LOGGER.error("SSH transfer failed"); handleTransferError(fileName, transferProgressListener, promise, e); } finally { try { ssh.disconnect(); } catch (IOException e) { LOGGER.error("SSH disconnect failed", e); } } } public static void transferByURL(String url, FileType fileType, String fileName, TransferListener listener, Promise<TransferringFile> promise) { InputStream in = null; OutputStream out = null; String filePath = FileSupport.filePath(fileType, fileName); try { URLConnection conn = new URL(url).openConnection(); listener.updateState(ProgressState.IN_PROGRESS); promise.complete(new TransferringFile(fileName)); listener.setTotalSize(Math.max(conn.getContentLength(), 0)); in = conn.getInputStream(); out = new FileOutputStream(filePath); byte[] buffer = new byte[8192]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); listener.addTransferredSize(length); } listener.updateState(ProgressState.SUCCESS); } catch (Exception e) { LOGGER.error("URL transfer failed"); handleTransferError(fileName, listener, promise, e); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { LOGGER.error("Close stream failed", e); } } } public static void transferByOSS(String endpoint, String accessKeyId, String accessKeySecret, String bucketName, String objectName, FileType fileType, String fileName, TransferListener transferProgressListener, Promise<TransferringFile> promise) { OSSClient ossClient = null; try { ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); ObjectMetadata meta = ossClient.getObjectMetadata(bucketName, objectName); transferProgressListener.setTotalSize(meta.getContentLength()); promise.complete(new TransferringFile(fileName)); DownloadFileRequest downloadFileRequest = new DownloadFileRequest(bucketName, objectName); downloadFileRequest.setDownloadFile(new File(FileSupport.filePath(fileType, fileName)).getAbsolutePath()); // 128m per thread now downloadFileRequest.setPartSize(128 * 1024 * 1024); downloadFileRequest.setTaskNum(Runtime.getRuntime().availableProcessors()); downloadFileRequest.setEnableCheckpoint(true); downloadFileRequest.withProgressListener(progressEvent -> { long bytes = progressEvent.getBytes(); ProgressEventType eventType = progressEvent.getEventType(); switch (eventType) { case TRANSFER_STARTED_EVENT: transferProgressListener.updateState(ProgressState.IN_PROGRESS); break; case RESPONSE_BYTE_TRANSFER_EVENT: transferProgressListener.addTransferredSize(bytes); break; case TRANSFER_FAILED_EVENT: transferProgressListener.updateState(ProgressState.ERROR); break; default: break; } }); ossClient.downloadFile(downloadFileRequest); transferProgressListener.updateState(ProgressState.SUCCESS); } catch (Throwable t) { LOGGER.error("OSS transfer failed"); handleTransferError(fileName, transferProgressListener, promise, t); } finally { if (ossClient != null) { ossClient.shutdown(); } } } public static void transferByS3(String region, String accessKey, String secretKey, String bucketName, String objectName, FileType fileType, String fileName, TransferListener transferProgressListener, Promise<TransferringFile> promise) { AmazonS3 s3Client = null; try { AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); ClientConfiguration clientConfig = new ClientConfiguration(); clientConfig.setProtocol(Protocol.HTTPS); s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withCredentials(new InstanceProfileCredentialsProvider(false)) .withClientConfiguration(clientConfig) .withRegion(region) .withPathStyleAccessEnabled(true) .build(); GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectName) .withGeneralProgressListener(progressEvent -> { long bytes = progressEvent.getBytes(); switch (progressEvent.getEventType()) { case TRANSFER_STARTED_EVENT: transferProgressListener.updateState(ProgressState.IN_PROGRESS); break; case RESPONSE_BYTE_TRANSFER_EVENT: transferProgressListener.addTransferredSize(bytes); break; case TRANSFER_FAILED_EVENT: transferProgressListener.updateState(ProgressState.ERROR); break; default: break; } }); com.amazonaws.services.s3.model.ObjectMetadata objectMetadata = s3Client.getObjectMetadata(bucketName, objectName); transferProgressListener.setTotalSize(objectMetadata.getContentLength()); promise.complete(new TransferringFile(fileName)); s3Client.getObject(getObjectRequest, new File(FileSupport.filePath(fileType, fileName))); transferProgressListener.updateState(ProgressState.SUCCESS); } catch (Throwable t) { LOGGER.error("S3 transfer failed"); handleTransferError(fileName, transferProgressListener, promise, t); } finally { if (s3Client != null) { s3Client.shutdown(); } } } private static void handleTransferError(String fileName, TransferListener transferProgressListener, Promise<TransferringFile> promise, Throwable t) { if (promise.future().isComplete()) { transferProgressListener.updateState(ProgressState.ERROR); Throwable cause = t; while (cause.getCause() != null) { cause = cause.getCause(); } transferProgressListener.setErrorMsg(cause.toString()); } else { FileSupport.delete(transferProgressListener.getFileType(), fileName); removeTransferListener(fileName); } throw new JifaException(ErrorCode.TRANSFER_ERROR, t); } public static long getTotalDiskSpace() { return new File(System.getProperty("user.home")).getTotalSpace() >> 20; } public static long getUsedDiskSpace() { return FileUtils.sizeOfDirectory(new File(System.getProperty("user.home"))) >> 20; } }
6,919
0
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix/serialization/SerializationUtils.java
package com.netflix.serialization; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import com.google.common.base.Preconditions; public class SerializationUtils { public static <T> T deserializeFromString(Deserializer<T> deserializer, String content, TypeDef<T> typeDef) throws IOException { Preconditions.checkNotNull(deserializer); ByteArrayInputStream in = new ByteArrayInputStream(content.getBytes("UTF-8")); return deserializer.deserialize(in, typeDef); } public static <T> String serializeToString(Serializer<T> serializer, T obj, TypeDef<?> typeDef) throws IOException { return new String(serializeToBytes(serializer, obj, typeDef), "UTF-8"); } public static <T> byte[] serializeToBytes(Serializer<T> serializer, T obj, TypeDef<?> typeDef) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); serializer.serialize(out, obj, typeDef); return out.toByteArray(); } }
6,920
0
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix/serialization/Deserializer.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.serialization; import java.io.IOException; import java.io.InputStream; public interface Deserializer<T> { public T deserialize(InputStream in, TypeDef<T> type) throws IOException; }
6,921
0
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix/serialization/JacksonCodec.java
package com.netflix.serialization; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.Type; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectWriter; import org.codehaus.jackson.type.TypeReference; import com.google.common.base.Charsets; import com.google.common.io.CharStreams; public class JacksonCodec<T extends Object> implements Serializer<T>, Deserializer<T> { private static final JacksonCodec instance = new JacksonCodec(); private final ObjectMapper mapper = new ObjectMapper(); @Override public T deserialize(InputStream in, TypeDef<T> type) throws IOException { if (String.class.equals(type.getRawType())) { return (T) CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8)); } return mapper.readValue(in, new TypeTokenBasedReference<T>(type)); } @Override public void serialize(OutputStream out, T object, TypeDef<?> type) throws IOException { if (type == null) { mapper.writeValue(out, object); } else { ObjectWriter writer = mapper.writerWithType(new TypeTokenBasedReference(type)); writer.writeValue(out, object); } } public static final <T> JacksonCodec<T> getInstance() { return instance; } } class TypeTokenBasedReference<T> extends TypeReference<T> { final Type type; public TypeTokenBasedReference(TypeDef<T> typeToken) { type = typeToken.getType(); } @Override public Type getType() { return type; } }
6,922
0
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix/serialization/TypeDef.java
package com.netflix.serialization; import static com.google.common.base.Preconditions.checkArgument; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import com.google.common.reflect.TypeToken; public abstract class TypeDef<T> { // private final Type runtimeType; private TypeToken<?> delegate; @SuppressWarnings("unchecked") protected TypeDef() { Type superclass = getClass().getGenericSuperclass(); checkArgument(superclass instanceof ParameterizedType, "%s isn't parameterized", superclass); Type runtimeType = ((ParameterizedType) superclass).getActualTypeArguments()[0]; this.delegate = (TypeToken<T>) TypeToken.of(runtimeType); } public static <T> TypeDef<T> fromClass(Class<T> classType) { TypeDef<T> spec = new TypeDef<T>() { }; spec.delegate = TypeToken.of(classType); return spec; } public static TypeDef<?> fromType(Type type) { TypeDef<Object> spec = new TypeDef<Object>() { }; spec.delegate = TypeToken.of(type); return spec; } public Class<? super T> getRawType() { return (Class<? super T>) delegate.getRawType(); } public Type getType() { return delegate.getType(); } }
6,923
0
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix/serialization/StringDeserializer.java
package com.netflix.serialization; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import com.google.common.base.Charsets; import com.google.common.io.CharStreams; import com.google.common.io.Closeables; public class StringDeserializer implements Deserializer<String> { private static final StringDeserializer instance = new StringDeserializer(); private StringDeserializer() { } public static final StringDeserializer getInstance() { return instance; } @Override public String deserialize(InputStream in, TypeDef<String> type) throws IOException { try { String content = CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8)); return content; } finally { Closeables.close(in, true); } } }
6,924
0
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix/serialization/Serializer.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.serialization; import java.io.IOException; import java.io.OutputStream; public interface Serializer<T> { public void serialize(OutputStream out, T object, TypeDef<?> type) throws IOException; }
6,925
0
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix/ribbon/test
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix/ribbon/test/resources/EmbeddedResources.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.ribbon.test.resources; import java.io.IOException; import java.io.OutputStream; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.StatusType; import javax.ws.rs.core.StreamingOutput; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Ignore; import com.google.common.collect.Lists; @Ignore @Path("/testAsync") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class EmbeddedResources { public static class Person { public String name; public int age; public Person() {} public Person(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } private static ObjectMapper mapper = new ObjectMapper(); public static final Person defaultPerson = new Person("ribbon", 1); public static final List<String> streamContent = Lists.newArrayList(); public static final List<Person> entityStream = Lists.newArrayList(); static { for (int i = 0; i < 1000; i++) { streamContent.add("data: line " + i); } for (int i = 0; i < 1000; i++) { entityStream.add(new Person("ribbon", i)); } } @GET @Path("/person") public Response getPerson() throws IOException { String content = mapper.writeValueAsString(defaultPerson); return Response.ok(content).build(); } @GET @Path("/context") @Produces(MediaType.TEXT_PLAIN) public Response echoContext(@HeaderParam("X-RXNETTY-REQUEST-ID") String requestId) throws IOException { return Response.ok(requestId).build(); } @GET @Path("/noEntity") public Response getNoEntity() { return Response.ok().build(); } @GET @Path("/readTimeout") public Response getReadTimeout() throws IOException, InterruptedException { Thread.sleep(10000); String content = mapper.writeValueAsString(defaultPerson); return Response.ok(content).build(); } @POST @Path("/person") public Response createPerson(String content) throws IOException { Person person = mapper.readValue(content, Person.class); return Response.ok(mapper.writeValueAsString(person)).build(); } @GET @Path("/personQuery") public Response queryPerson(@QueryParam("name") String name, @QueryParam("age") int age) throws IOException { Person person = new Person(name, age); return Response.ok(mapper.writeValueAsString(person)).build(); } @POST @Path("/postTimeout") public Response postWithTimeout(String content) { try { Thread.sleep(10000); } catch (InterruptedException e) { } return Response.ok().build(); } @GET @Path("/throttle") public Response throttle() { return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("Rate exceeds limit").build(); } @GET @Path("/stream") @Produces("text/event-stream") public StreamingOutput getStream() { return new StreamingOutput() { @Override public void write(OutputStream output) throws IOException, WebApplicationException { for (String line: streamContent) { String eventLine = line + "\n"; output.write(eventLine.getBytes("UTF-8")); } } }; } @GET @Path("/redirect") public Response redirect(@QueryParam("port") int port) { return Response.status(301).header("Location", "http://localhost:" + port + "/testAsync/person").build(); } @GET @Path("/personStream") @Produces("text/event-stream") public StreamingOutput getEntityStream() { return new StreamingOutput() { @Override public void write(OutputStream output) throws IOException, WebApplicationException { for (Person person: entityStream) { String eventLine = "data: " + mapper.writeValueAsString(person) + "\n\n"; output.write(eventLine.getBytes("UTF-8")); } } }; } }
6,926
0
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix/ribbon/testutils/TestUtils.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.ribbon.testutils; import static org.junit.Assert.assertTrue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import rx.functions.Func0; public class TestUtils { public static void waitUntilTrueOrTimeout(int timeoutMilliseconds, final Func0<Boolean> func) { final Lock lock = new ReentrantLock(); final Condition condition = lock.newCondition(); final AtomicBoolean stopThread = new AtomicBoolean(false); if (!func.call()) { (new Thread() { @Override public void run() { while (!stopThread.get()) { if (func.call()) { lock.lock(); try { condition.signalAll(); } finally { lock.unlock(); } } try { Thread.sleep(20); } catch (Exception e) { e.printStackTrace(); } } } }).start(); lock.lock(); try { condition.await(timeoutMilliseconds, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); stopThread.set(true); } } assertTrue(func.call()); } }
6,927
0
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon-test/src/main/java/com/netflix/ribbon/testutils/MockedDiscoveryServerListTest.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.ribbon.testutils; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.MyDataCenterInfo; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.DiscoveryManager; import com.netflix.loadbalancer.Server; import org.easymock.EasyMock; import org.junit.Before; import org.junit.Ignore; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.ArrayList; import java.util.List; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.createMock; import static org.powermock.api.easymock.PowerMock.replay; @RunWith(PowerMockRunner.class) @PrepareForTest( {DiscoveryManager.class, DiscoveryClient.class} ) @PowerMockIgnore({"javax.management.*", "com.sun.jersey.*", "com.sun.*", "org.apache.*", "weblogic.*", "com.netflix.config.*", "com.sun.jndi.dns.*", "javax.naming.*", "com.netflix.logging.*", "javax.ws.*"}) @Ignore public abstract class MockedDiscoveryServerListTest { protected abstract List<Server> getMockServerList(); protected abstract String getVipAddress(); static List<InstanceInfo> getDummyInstanceInfo(String appName, List<Server> serverList){ List<InstanceInfo> list = new ArrayList<InstanceInfo>(); for (Server server: serverList) { InstanceInfo info = InstanceInfo.Builder.newBuilder().setAppName(appName) .setHostName(server.getHost()) .setPort(server.getPort()) .setDataCenterInfo(new MyDataCenterInfo(DataCenterInfo.Name.MyOwn)) .build(); list.add(info); } return list; } @Before public void setupMock(){ List<InstanceInfo> instances = getDummyInstanceInfo("dummy", getMockServerList()); PowerMock.mockStatic(DiscoveryManager.class); PowerMock.mockStatic(DiscoveryClient.class); DiscoveryClient mockedDiscoveryClient = createMock(DiscoveryClient.class); DiscoveryManager mockedDiscoveryManager = createMock(DiscoveryManager.class); expect(mockedDiscoveryClient.getEurekaClientConfig()).andReturn(new DefaultEurekaClientConfig()).anyTimes(); expect(DiscoveryManager.getInstance()).andReturn(mockedDiscoveryManager).anyTimes(); expect(mockedDiscoveryManager.getDiscoveryClient()).andReturn(mockedDiscoveryClient).anyTimes(); expect(mockedDiscoveryClient.getInstancesByVipAddress(getVipAddress(), false, null)).andReturn(instances).anyTimes(); replay(DiscoveryManager.class); replay(DiscoveryClient.class); replay(mockedDiscoveryManager); replay(mockedDiscoveryClient); } }
6,928
0
Create_ds/ribbon/ribbon-core/src/test/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/test/java/com/netflix/client/config/ClientConfigTest.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.client.config; import static org.junit.Assert.*; import com.netflix.config.ConfigurationManager; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.junit.runners.MethodSorters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Objects; import java.util.Properties; /** * Test cases to verify the correctness of the Client Configuration settings * * @author stonse * */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ClientConfigTest { private static final Logger LOG = LoggerFactory.getLogger(ClientConfigTest.class); @Rule public TestName testName = new TestName(); IClientConfigKey<Integer> INTEGER_PROPERTY; IClientConfigKey<Integer> DEFAULT_INTEGER_PROPERTY; @Before public void setUp() throws Exception { INTEGER_PROPERTY = new CommonClientConfigKey<Integer>( "niws.loadbalancer.%s." + testName.getMethodName(), 10) {}; DEFAULT_INTEGER_PROPERTY = new CommonClientConfigKey<Integer>( "niws.loadbalancer.default." + testName.getMethodName(), 30) {}; } @AfterClass public static void shutdown() throws Exception { } @Test public void testNiwsConfigViaProperties() throws Exception { DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); DefaultClientConfigImpl override = new DefaultClientConfigImpl(); clientConfig.loadDefaultValues(); Properties props = new Properties(); final String restClientName = "testRestClient"; props.setProperty("netflix.appinfo.stack","xbox"); props.setProperty("netflix.environment","test"); props.setProperty("appname", "movieservice"); props.setProperty(restClientName + ".ribbon." + CommonClientConfigKey.AppName.key(), "movieservice"); props.setProperty(restClientName + ".ribbon." + CommonClientConfigKey.DeploymentContextBasedVipAddresses.key(), "${appname}-${netflix.appinfo.stack}-${netflix.environment},movieservice--${netflix.environment}"); props.setProperty(restClientName + ".ribbon." + CommonClientConfigKey.EnableZoneAffinity.key(), "false"); ConfigurationManager.loadProperties(props); ConfigurationManager.getConfigInstance().setProperty("testRestClient.ribbon.customProperty", "abc"); clientConfig.loadProperties(restClientName); clientConfig.set(CommonClientConfigKey.ConnectTimeout, 1000); override.set(CommonClientConfigKey.Port, 8000); override.set(CommonClientConfigKey.ConnectTimeout, 5000); clientConfig.applyOverride(override); Assert.assertEquals("movieservice", clientConfig.get(CommonClientConfigKey.AppName)); Assert.assertEquals(false, clientConfig.get(CommonClientConfigKey.EnableZoneAffinity)); Assert.assertEquals("movieservice-xbox-test,movieservice--test", clientConfig.resolveDeploymentContextbasedVipAddresses()); Assert.assertEquals(5000, clientConfig.get(CommonClientConfigKey.ConnectTimeout).longValue()); Assert.assertEquals(8000, clientConfig.get(CommonClientConfigKey.Port).longValue()); System.out.println("AutoVipAddress:" + clientConfig.resolveDeploymentContextbasedVipAddresses()); ConfigurationManager.getConfigInstance().setProperty("testRestClient.ribbon.EnableZoneAffinity", "true"); assertEquals(true, clientConfig.get(CommonClientConfigKey.EnableZoneAffinity)); } @Test public void testresolveDeploymentContextbasedVipAddresses() throws Exception { final String restClientName = "testRestClient2"; DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); clientConfig.loadDefaultValues(); Properties props = new Properties(); props.setProperty(restClientName + ".ribbon." + CommonClientConfigKey.AppName.key(), "movieservice"); props.setProperty(restClientName + ".ribbon." + CommonClientConfigKey.DeploymentContextBasedVipAddresses.key(), "${<appname>}-${netflix.appinfo.stack}-${netflix.environment}:${<port>},${<appname>}--${netflix.environment}:${<port>}"); props.setProperty(restClientName + ".ribbon." + CommonClientConfigKey.Port.key(), "7001"); props.setProperty(restClientName + ".ribbon." + CommonClientConfigKey.EnableZoneAffinity.key(), "true"); ConfigurationManager.loadProperties(props); clientConfig.loadProperties(restClientName); Assert.assertEquals("movieservice", clientConfig.get(CommonClientConfigKey.AppName)); Assert.assertEquals(true, clientConfig.get(CommonClientConfigKey.EnableZoneAffinity)); ConfigurationManager.getConfigInstance().setProperty("testRestClient2.ribbon.DeploymentContextBasedVipAddresses", "movieservice-xbox-test:7001"); assertEquals("movieservice-xbox-test:7001", clientConfig.get(CommonClientConfigKey.DeploymentContextBasedVipAddresses)); ConfigurationManager.getConfigInstance().clearProperty("testRestClient2.ribbon.EnableZoneAffinity"); assertNull(clientConfig.get(CommonClientConfigKey.EnableZoneAffinity)); assertFalse(clientConfig.getOrDefault(CommonClientConfigKey.EnableZoneAffinity)); } @Test public void testFallback_noneSet() { DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); Property<Integer> prop = clientConfig.getGlobalProperty(INTEGER_PROPERTY.format(testName.getMethodName())) .fallbackWith(clientConfig.getGlobalProperty(DEFAULT_INTEGER_PROPERTY)); Assert.assertEquals(30, prop.getOrDefault().intValue()); } @Test public void testFallback_fallbackSet() { ConfigurationManager.getConfigInstance().setProperty(DEFAULT_INTEGER_PROPERTY.key(), "100"); DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); Property<Integer> prop = clientConfig.getGlobalProperty(INTEGER_PROPERTY.format(testName.getMethodName())) .fallbackWith(clientConfig.getGlobalProperty(DEFAULT_INTEGER_PROPERTY)); Assert.assertEquals(100, prop.getOrDefault().intValue()); } @Test public void testFallback_primarySet() { ConfigurationManager.getConfigInstance().setProperty(INTEGER_PROPERTY.format(testName.getMethodName()).key(), "200"); DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); Property<Integer> prop = clientConfig.getGlobalProperty(INTEGER_PROPERTY.format(testName.getMethodName())) .fallbackWith(clientConfig.getGlobalProperty(DEFAULT_INTEGER_PROPERTY)); Assert.assertEquals(200, prop.getOrDefault().intValue()); } static class CustomValueOf { private final String value; public static CustomValueOf valueOf(String value) { return new CustomValueOf(value); } public CustomValueOf(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomValueOf that = (CustomValueOf) o; return Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(value); } } public static IClientConfigKey<CustomValueOf> CUSTOM_KEY = new CommonClientConfigKey<CustomValueOf>("CustomValueOf", new CustomValueOf("default")) {}; @Test public void testValueOfWithDefault() { DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); CustomValueOf prop = clientConfig.getOrDefault(CUSTOM_KEY); Assert.assertEquals("default", prop.getValue()); } @Test public void testValueOf() { ConfigurationManager.getConfigInstance().setProperty("testValueOf.ribbon.CustomValueOf", "value"); DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); clientConfig.loadProperties("testValueOf"); Property<CustomValueOf> prop = clientConfig.getDynamicProperty(CUSTOM_KEY); Assert.assertEquals("value", prop.getOrDefault().getValue()); ConfigurationManager.getConfigInstance().setProperty("testValueOf.ribbon.CustomValueOf", "value2"); Assert.assertEquals("value2", prop.getOrDefault().getValue()); } @Test public void testDynamicConfig() { ConfigurationManager.getConfigInstance().setProperty("testValueOf.ribbon.CustomValueOf", "value"); DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); clientConfig.loadProperties("testValueOf"); Assert.assertEquals("value", clientConfig.get(CUSTOM_KEY).getValue()); ConfigurationManager.getConfigInstance().setProperty("testValueOf.ribbon.CustomValueOf", "value2"); Assert.assertEquals("value2", clientConfig.get(CUSTOM_KEY).getValue()); ConfigurationManager.getConfigInstance().clearProperty("testValueOf.ribbon.CustomValueOf"); Assert.assertNull(clientConfig.get(CUSTOM_KEY)); } }
6,929
0
Create_ds/ribbon/ribbon-core/src/test/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/test/java/com/netflix/client/config/DefaultClientConfigImplTest.java
package com.netflix.client.config; import static org.junit.Assert.*; import java.util.Collections; import java.util.Date; import java.util.Map; import java.util.TreeMap; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import com.netflix.config.ConfigurationManager; import org.junit.rules.TestName; public class DefaultClientConfigImplTest { class NewConfigKey<T> extends CommonClientConfigKey<T> { protected NewConfigKey(String configKey) { super(configKey); } } @Rule public TestName testName = new TestName(); @Test public void testTypedValue() { ConfigurationManager.getConfigInstance().setProperty("myclient.ribbon." + CommonClientConfigKey.ConnectTimeout, "1500"); DefaultClientConfigImpl config = new DefaultClientConfigImpl(); config.loadProperties("myclient"); assertEquals(1500, config.get(CommonClientConfigKey.ConnectTimeout).intValue()); config.set(CommonClientConfigKey.ConnectTimeout, 2000); // The archaius property should override code override assertEquals(1500, config.get(CommonClientConfigKey.ConnectTimeout).intValue()); } @Test public void testNewType() { CommonClientConfigKey<Date> key = new CommonClientConfigKey<Date>("date") {}; assertEquals(Date.class, key.type()); } @Test public void testSubClass() { NewConfigKey<Date> key = new NewConfigKey<Date>("date") {}; assertEquals(Date.class, key.type()); } public static class CustomType { private final Map<String, String> value; public CustomType(Map<String, String> value) { this.value = new TreeMap<>(value); } public static CustomType valueOf(Map<String, String> value) { return new CustomType(value); } } final CommonClientConfigKey<CustomType> CustomTypeKey = new CommonClientConfigKey<CustomType>("customMapped", new CustomType(Collections.emptyMap())) {}; @Test public void testMappedProperties() { String clientName = testName.getMethodName(); ConfigurationManager.getConfigInstance().setProperty("ribbon.customMapped.a", "1"); ConfigurationManager.getConfigInstance().setProperty("ribbon.customMapped.b", "2"); ConfigurationManager.getConfigInstance().setProperty("ribbon.customMapped.c", "3"); ConfigurationManager.getConfigInstance().setProperty(clientName + ".ribbon.customMapped.c", "4"); ConfigurationManager.getConfigInstance().setProperty(clientName + ".ribbon.customMapped.d", "5"); ConfigurationManager.getConfigInstance().setProperty(clientName + ".ribbon.customMapped.e", "6"); DefaultClientConfigImpl config = new DefaultClientConfigImpl(); config.loadProperties(clientName); CustomType customType = config.getPrefixMappedProperty(CustomTypeKey).get().get(); TreeMap<String, String> expected = new TreeMap<>(); expected.put("a", "1"); expected.put("b", "2"); expected.put("c", "4"); expected.put("d", "5"); expected.put("e", "6"); Assert.assertEquals(expected, customType.value); } }
6,930
0
Create_ds/ribbon/ribbon-core/src/test/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/test/java/com/netflix/client/config/ArchaiusPropertyResolverTest.java
package com.netflix.client.config; import com.netflix.config.ConfigurationManager; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import java.util.Map; import java.util.TreeMap; public class ArchaiusPropertyResolverTest { @Rule public TestName testName = new TestName(); @Test public void mapFromPrefixedKeys() { final String prefix = "client.ribbon." + testName.getMethodName(); final AbstractConfiguration config = ConfigurationManager.getConfigInstance(); config.setProperty(prefix + ".a", "1"); config.setProperty(prefix + ".b", "2"); config.setProperty(prefix + ".c", "3"); final ArchaiusPropertyResolver resolver = ArchaiusPropertyResolver.INSTANCE; final Map<String, String> map = new TreeMap<>(); resolver.forEach(prefix, map::put); final Map<String, String> expected = new TreeMap<>(); expected.put("a", "1"); expected.put("b", "2"); expected.put("c", "3"); Assert.assertEquals(expected, map); } @Test public void noCallbackIfNoValues() { final String prefix = "client.ribbon." + testName.getMethodName(); final ArchaiusPropertyResolver resolver = ArchaiusPropertyResolver.INSTANCE; final Map<String, String> map = new TreeMap<>(); resolver.forEach(prefix, map::put); Assert.assertTrue(map.toString(), map.isEmpty()); } }
6,931
0
Create_ds/ribbon/ribbon-core/src/test/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/test/java/com/netflix/client/config/CommonClientConfigKeyTest.java
package com.netflix.client.config; import static org.junit.Assert.*; import org.junit.Test; import com.google.common.collect.Sets; public class CommonClientConfigKeyTest { @Test public void testCommonKeys() { IClientConfigKey[] keys = CommonClientConfigKey.values(); assertTrue(keys.length > 30); assertEquals(Sets.newHashSet(keys), CommonClientConfigKey.keys()); assertTrue(CommonClientConfigKey.keys().contains(CommonClientConfigKey.ConnectTimeout)); } }
6,932
0
Create_ds/ribbon/ribbon-core/src/test/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/test/java/com/netflix/client/config/ReloadableClientConfigTest.java
package com.netflix.client.config; import com.netflix.config.ConfigurationManager; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; public class ReloadableClientConfigTest { @Rule public TestName testName = new TestName(); private CommonClientConfigKey<Integer> testKey; @Before public void before() { this.testKey = new CommonClientConfigKey<Integer>(getClass().getName() + "." + testName.getMethodName(), -1) {}; } @Test public void testOverrideLoadedConfig() { final DefaultClientConfigImpl overrideconfig = new DefaultClientConfigImpl(); overrideconfig.set(testKey, 123); final DefaultClientConfigImpl config = new DefaultClientConfigImpl(); config.loadDefaultValues(); config.applyOverride(overrideconfig); Assert.assertEquals(123, config.get(testKey).intValue()); } @Test public void setBeforeLoading() { // Ensure property is set before config is created ConfigurationManager.getConfigInstance().setProperty("ribbon." + testKey.key(), "123"); // Load config and attempt to set value to 0 final DefaultClientConfigImpl config = new DefaultClientConfigImpl(); config.loadProperties("foo"); config.set(testKey, 0); // Value should be 123 because of fast property Assert.assertEquals(123, config.get(testKey).intValue()); // Clearing property should make it null ConfigurationManager.getConfigInstance().clearProperty("ribbon." + testKey.key()); Assert.assertNull(config.get(testKey)); // Setting property again should give new value ConfigurationManager.getConfigInstance().setProperty("ribbon." + testKey.key(), "124"); Assert.assertEquals(124, config.get(testKey).intValue()); } @Test public void setAfterLoading() { final DefaultClientConfigImpl config = new DefaultClientConfigImpl(); config.loadProperties("foo"); config.set(testKey, 456); ConfigurationManager.getConfigInstance().setProperty("ribbon." + testKey.key(), "123"); Assert.assertEquals(123, config.get(testKey).intValue()); } }
6,933
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/VipAddressResolver.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.client; import com.netflix.client.config.IClientConfig; /** * A "VipAddress" is a logical name for a Target Server farm. * * @author stonse * */ public interface VipAddressResolver { public String resolve(String vipAddress, IClientConfig niwsClientConfig); }
6,934
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/IClientConfigAware.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.client; import com.netflix.client.config.IClientConfig; /** * There are multiple classes (and components) that need access to the configuration. * Its easier to do this by using {@link IClientConfig} as the object that carries these configurations * and to define a common interface that components that need this can implement and hence be aware of. * * @author stonse * @author awang * */ public interface IClientConfigAware { interface Factory { Object create(String type, IClientConfig config) throws InstantiationException, IllegalAccessException, ClassNotFoundException; } /** * Concrete implementation should implement this method so that the configuration set via * {@link IClientConfig} (which in turn were set via Archaius properties) will be taken into consideration * * @param clientConfig */ default void initWithNiwsConfig(IClientConfig clientConfig) { } default void initWithNiwsConfig(IClientConfig clientConfig, Factory factory) { initWithNiwsConfig(clientConfig); } }
6,935
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/RetryHandler.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.client; import java.net.ConnectException; /** * A handler that determines if an exception is retriable for load balancer, * and if an exception or error response should be treated as circuit related failures * so that the load balancer can avoid such server. * * @author awang */ public interface RetryHandler { public static final RetryHandler DEFAULT = new DefaultLoadBalancerRetryHandler(); /** * Test if an exception is retriable for the load balancer * * @param e the original exception * @param sameServer if true, the method is trying to determine if retry can be * done on the same server. Otherwise, it is testing whether retry can be * done on a different server */ public boolean isRetriableException(Throwable e, boolean sameServer); /** * Test if an exception should be treated as circuit failure. For example, * a {@link ConnectException} is a circuit failure. This is used to determine * whether successive exceptions of such should trip the circuit breaker to a particular * host by the load balancer. If false but a server response is absent, * load balancer will also close the circuit upon getting such exception. */ public boolean isCircuitTrippingException(Throwable e); /** * @return Number of maximal retries to be done on one server */ public int getMaxRetriesOnSameServer(); /** * @return Number of maximal different servers to retry */ public int getMaxRetriesOnNextServer(); }
6,936
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/DefaultLoadBalancerRetryHandler.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.client; import com.google.common.collect.Lists; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import java.net.ConnectException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.List; /** * A default {@link RetryHandler}. The implementation is limited to * known exceptions in java.net. Specific client implementation should provide its own * {@link RetryHandler} * * @author awang */ public class DefaultLoadBalancerRetryHandler implements RetryHandler { @SuppressWarnings("unchecked") private List<Class<? extends Throwable>> retriable = Lists.<Class<? extends Throwable>>newArrayList(ConnectException.class, SocketTimeoutException.class); @SuppressWarnings("unchecked") private List<Class<? extends Throwable>> circuitRelated = Lists.<Class<? extends Throwable>>newArrayList(SocketException.class, SocketTimeoutException.class); protected final int retrySameServer; protected final int retryNextServer; protected final boolean retryEnabled; public DefaultLoadBalancerRetryHandler() { this.retrySameServer = 0; this.retryNextServer = 0; this.retryEnabled = false; } public DefaultLoadBalancerRetryHandler(int retrySameServer, int retryNextServer, boolean retryEnabled) { this.retrySameServer = retrySameServer; this.retryNextServer = retryNextServer; this.retryEnabled = retryEnabled; } public DefaultLoadBalancerRetryHandler(IClientConfig clientConfig) { this.retrySameServer = clientConfig.getOrDefault(CommonClientConfigKey.MaxAutoRetries); this.retryNextServer = clientConfig.getOrDefault(CommonClientConfigKey.MaxAutoRetriesNextServer); this.retryEnabled = clientConfig.getOrDefault(CommonClientConfigKey.OkToRetryOnAllOperations); } @Override public boolean isRetriableException(Throwable e, boolean sameServer) { if (retryEnabled) { if (sameServer) { return Utils.isPresentAsCause(e, getRetriableExceptions()); } else { return true; } } return false; } /** * @return true if {@link SocketException} or {@link SocketTimeoutException} is a cause in the Throwable. */ @Override public boolean isCircuitTrippingException(Throwable e) { return Utils.isPresentAsCause(e, getCircuitRelatedExceptions()); } @Override public int getMaxRetriesOnSameServer() { return retrySameServer; } @Override public int getMaxRetriesOnNextServer() { return retryNextServer; } protected List<Class<? extends Throwable>> getRetriableExceptions() { return retriable; } protected List<Class<? extends Throwable>> getCircuitRelatedExceptions() { return circuitRelated; } }
6,937
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/ClientException.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.client; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; public class ClientException extends Exception{ /** * */ private static final long serialVersionUID = -7697654244064441234L; /** * define your error codes here * */ public enum ErrorType{ GENERAL, CONFIGURATION, NUMBEROF_RETRIES_EXEEDED, NUMBEROF_RETRIES_NEXTSERVER_EXCEEDED, SOCKET_TIMEOUT_EXCEPTION, READ_TIMEOUT_EXCEPTION, UNKNOWN_HOST_EXCEPTION, CONNECT_EXCEPTION, CLIENT_THROTTLED, SERVER_THROTTLED, NO_ROUTE_TO_HOST_EXCEPTION, CACHE_MISSING; // https://www.gamlor.info/wordpress/2017/08/javas-enum-values-hidden-allocations/ private static final ErrorType[] ERROR_TYPE_VALUES = values(); static String getName(int errorCode){ if (ERROR_TYPE_VALUES.length >= errorCode){ return ERROR_TYPE_VALUES[errorCode].name(); }else{ return "UNKNOWN ERROR CODE"; } } } protected int errorCode; protected String message; protected Object errorObject; protected ErrorType errorType = ErrorType.GENERAL; public ClientException(String message) { this(0, message, null); } public ClientException(int errorCode) { this(errorCode, null, null); } public ClientException(int errorCode, String message) { this(errorCode, message, null); } public ClientException(Throwable chainedException) { this(0, null, chainedException); } public ClientException(String message, Throwable chainedException) { this(0, message, chainedException); } public ClientException(int errorCode, String message, Throwable chainedException) { super((message == null && errorCode != 0) ? ", code=" + errorCode + "->" + ErrorType.getName(errorCode): message, chainedException); this.errorCode = errorCode; this.message = message; } public ClientException(ErrorType error) { this(error.ordinal(), null, null); this.errorType = error; } public ClientException(ErrorType error, String message) { this(error.ordinal(), message, null); this.errorType = error; } public ClientException( ErrorType error, String message, Throwable chainedException) { super((message == null && error.ordinal() != 0) ? ", code=" + error.ordinal() + "->" + error.name() : message, chainedException); this.errorCode = error.ordinal(); this.message = message; this.errorType = error; } public ErrorType getErrorType(){ return errorType; } public int getErrorCode() { return this.errorCode; } public void setErrorCode(int errorCode) { this.errorCode = errorCode; } public String getErrorMessage() { return this.message; } public void setErrorMessage(String msg) { this.message = msg; } public Object getErrorObject() { return this.errorObject; } public void setErrorObject(Object errorObject) { this.errorObject = errorObject; } /** * Return the message associated with such an exception. * * @return a message asssociated with current exception */ public String getInternalMessage () { return "{no message: " + errorCode + "}"; } /** * Return the codes that are defined on a subclass of our class. * * @param clazz a class that is a subclass of us. * @return a hashmap of int error codes mapped to the string names. */ static public HashMap getErrorCodes ( Class clazz ) { HashMap map = new HashMap(23); // Use reflection to populte the erroCodeMap to have the reverse mapping // of error codes to symbolic names. Field flds[] = clazz.getDeclaredFields(); for (int i = 0; i < flds.length; i++) { int mods = flds[i].getModifiers(); if (Modifier.isFinal(mods) && Modifier.isStatic(mods) && Modifier.isPublic(mods)) { try { map.put(flds[i].get(null), flds[i].getName()); } catch (Throwable t) { // NOPMD // ignore this. } } } return map; } }
6,938
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/IResponse.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.client; import java.io.Closeable; import java.net.URI; import java.util.Map; /** * Response interface for the client framework. * */ public interface IResponse extends Closeable { /** * Returns the raw entity if available from the response */ public Object getPayload() throws ClientException; /** * A "peek" kinda API. Use to check if your service returned a response with an Entity */ public boolean hasPayload(); /** * @return true if the response is deemed success, for example, 200 response code for http protocol. */ public boolean isSuccess(); /** * Return the Request URI that generated this response */ public URI getRequestedURI(); /** * * @return Headers if any in the response. */ public Map<String, ?> getHeaders(); }
6,939
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/IClient.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.client; import com.netflix.client.config.IClientConfig; /** * A client that can execute a single request. * * @author awang * */ public interface IClient<S extends ClientRequest, T extends IResponse> { /** * Execute the request and return the response. It is expected that there is no retry and all exceptions * are thrown directly. */ public T execute(S request, IClientConfig requestConfig) throws Exception; }
6,940
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/ClientRequest.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.client; import java.net.URI; import com.netflix.client.config.IClientConfig; /** * An object that represents a common client request that is suitable for all communication protocol. * It is expected that this object is immutable. * * @author awang * */ public class ClientRequest implements Cloneable { protected URI uri; protected Object loadBalancerKey = null; protected Boolean isRetriable = null; protected IClientConfig overrideConfig; public ClientRequest() { } public ClientRequest(URI uri) { this.uri = uri; } /** * Constructor to set all fields. * @deprecated request configuration should be now be passed * as a method parameter to client's execution API * * * @param uri URI to set * @param loadBalancerKey the object that is used by {@code com.netflix.loadbalancer.ILoadBalancer#chooseServer(Object)}, can be null * @param isRetriable if the operation is retriable on failures * @param overrideConfig client configuration that is used for this specific request. can be null. */ @Deprecated public ClientRequest(URI uri, Object loadBalancerKey, boolean isRetriable, IClientConfig overrideConfig) { this.uri = uri; this.loadBalancerKey = loadBalancerKey; this.isRetriable = isRetriable; this.overrideConfig = overrideConfig; } public ClientRequest(URI uri, Object loadBalancerKey, boolean isRetriable) { this.uri = uri; this.loadBalancerKey = loadBalancerKey; this.isRetriable = isRetriable; } public ClientRequest(ClientRequest request) { this.uri = request.uri; this.loadBalancerKey = request.loadBalancerKey; this.overrideConfig = request.overrideConfig; this.isRetriable = request.isRetriable; } public final URI getUri() { return uri; } protected final ClientRequest setUri(URI uri) { this.uri = uri; return this; } public final Object getLoadBalancerKey() { return loadBalancerKey; } protected final ClientRequest setLoadBalancerKey(Object loadBalancerKey) { this.loadBalancerKey = loadBalancerKey; return this; } public boolean isRetriable() { return (Boolean.TRUE.equals(isRetriable)); } protected final ClientRequest setRetriable(boolean isRetriable) { this.isRetriable = isRetriable; return this; } /** * @deprecated request configuration should be now be passed * as a method parameter to client's execution API */ @Deprecated public final IClientConfig getOverrideConfig() { return overrideConfig; } /** * @deprecated request configuration should be now be passed * as a method parameter to client's execution API */ @Deprecated protected final ClientRequest setOverrideConfig(IClientConfig overrideConfig) { this.overrideConfig = overrideConfig; return this; } /** * Create a client request using a new URI. This is used by {@code com.netflix.client.AbstractLoadBalancerAwareClient#computeFinalUriWithLoadBalancer(ClientRequest)}. * It first tries to clone the request and if that fails it will use the copy constructor {@link #ClientRequest(ClientRequest)}. * Sub classes are recommended to override this method to provide more efficient implementation. * * @param newURI */ public ClientRequest replaceUri(URI newURI) { ClientRequest req; try { req = (ClientRequest) this.clone(); } catch (CloneNotSupportedException e) { req = new ClientRequest(this); } req.uri = newURI; return req; } }
6,941
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/Utils.java
package com.netflix.client; import java.util.Collection; public class Utils { public static boolean isPresentAsCause(Throwable throwableToSearchIn, Collection<Class<? extends Throwable>> throwableToSearchFor) { int infiniteLoopPreventionCounter = 10; while (throwableToSearchIn != null && infiniteLoopPreventionCounter > 0) { infiniteLoopPreventionCounter--; for (Class<? extends Throwable> c: throwableToSearchFor) { if (c.isAssignableFrom(throwableToSearchIn.getClass())) { return true; } } throwableToSearchIn = throwableToSearchIn.getCause(); } return false; } }
6,942
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/RequestSpecificRetryHandler.java
package com.netflix.client; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import javax.annotation.Nullable; import java.net.SocketException; import java.util.List; import java.util.Optional; /** * Implementation of RetryHandler created for each request which allows for request * specific override */ public class RequestSpecificRetryHandler implements RetryHandler { private final RetryHandler fallback; private int retrySameServer = -1; private int retryNextServer = -1; private final boolean okToRetryOnConnectErrors; private final boolean okToRetryOnAllErrors; protected List<Class<? extends Throwable>> connectionRelated = Lists.<Class<? extends Throwable>>newArrayList(SocketException.class); public RequestSpecificRetryHandler(boolean okToRetryOnConnectErrors, boolean okToRetryOnAllErrors) { this(okToRetryOnConnectErrors, okToRetryOnAllErrors, RetryHandler.DEFAULT, null); } public RequestSpecificRetryHandler(boolean okToRetryOnConnectErrors, boolean okToRetryOnAllErrors, RetryHandler baseRetryHandler, @Nullable IClientConfig requestConfig) { Preconditions.checkNotNull(baseRetryHandler); this.okToRetryOnConnectErrors = okToRetryOnConnectErrors; this.okToRetryOnAllErrors = okToRetryOnAllErrors; this.fallback = baseRetryHandler; if (requestConfig != null) { requestConfig.getIfSet(CommonClientConfigKey.MaxAutoRetries).ifPresent( value -> retrySameServer = value ); requestConfig.getIfSet(CommonClientConfigKey.MaxAutoRetriesNextServer).ifPresent( value -> retryNextServer = value ); } } public boolean isConnectionException(Throwable e) { return Utils.isPresentAsCause(e, connectionRelated); } @Override public boolean isRetriableException(Throwable e, boolean sameServer) { if (okToRetryOnAllErrors) { return true; } else if (e instanceof ClientException) { ClientException ce = (ClientException) e; if (ce.getErrorType() == ClientException.ErrorType.SERVER_THROTTLED) { return !sameServer; } else { return false; } } else { return okToRetryOnConnectErrors && isConnectionException(e); } } @Override public boolean isCircuitTrippingException(Throwable e) { return fallback.isCircuitTrippingException(e); } @Override public int getMaxRetriesOnSameServer() { if (retrySameServer >= 0) { return retrySameServer; } return fallback.getMaxRetriesOnSameServer(); } @Override public int getMaxRetriesOnNextServer() { if (retryNextServer >= 0) { return retryNextServer; } return fallback.getMaxRetriesOnNextServer(); } }
6,943
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/ssl/AbstractSslContextFactory.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.client.ssl; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * Abstract class to represent what we logically associate with the ssl context on the client side, * namely, the keystore and truststore. * * @author jzarfoss * */ public abstract class AbstractSslContextFactory { private final static Logger LOGGER = LoggerFactory.getLogger(AbstractSslContextFactory.class); /** The secure socket algorithm that is to be used. */ public static final String SOCKET_ALGORITHM = "SSL"; /** The keystore resulting from loading keystore URL */ private KeyStore keyStore; /** The truststore resulting from loading the truststore URL */ private KeyStore trustStore; /** The password for the keystore */ private String keyStorePassword; private final int trustStorePasswordLength; private final int keyStorePasswordLength; protected AbstractSslContextFactory(final KeyStore trustStore, final String trustStorePassword, final KeyStore keyStore, final String keyStorePassword){ this.trustStore = trustStore; this.keyStorePassword = keyStorePassword; this.keyStore = keyStore; this.keyStorePasswordLength = keyStorePassword != null ? keyStorePassword.length() : -1; this.trustStorePasswordLength = trustStorePassword != null ? trustStorePassword.length() : -1; } public KeyStore getKeyStore(){ return this.keyStore; } public KeyStore getTrustStore(){ return this.trustStore; } public int getKeyStorePasswordLength(){ return this.keyStorePasswordLength; } public int getTrustStorePasswordLength(){ return this.trustStorePasswordLength; } /** * Creates the SSL context needed to create the socket factory used by this factory. The key and * trust store parameters are optional. If they are null then the JRE defaults will be used. * * @return the newly created SSL context * @throws ClientSslSocketFactoryException if an error is detected loading the specified key or * trust stores */ private SSLContext createSSLContext() throws ClientSslSocketFactoryException { final KeyManager[] keyManagers = this.keyStore != null ? createKeyManagers() : null; final TrustManager[] trustManagers = this.trustStore != null ? createTrustManagers() : null; try { final SSLContext sslcontext = SSLContext.getInstance(SOCKET_ALGORITHM); sslcontext.init(keyManagers, trustManagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { throw new ClientSslSocketFactoryException(String.format("Failed to create an SSL context that supports algorithm %s: %s", SOCKET_ALGORITHM, e.getMessage()), e); } catch (KeyManagementException e) { throw new ClientSslSocketFactoryException(String.format("Failed to initialize an SSL context: %s", e.getMessage()), e); } } /** * Creates the key managers to be used by the factory from the associated key store and password. * * @return the newly created array of key managers * @throws ClientSslSocketFactoryException if an exception is detected in loading the key store */ private KeyManager[] createKeyManagers() throws ClientSslSocketFactoryException { final KeyManagerFactory factory; try { factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); factory.init(this.keyStore, this.keyStorePassword.toCharArray()); } catch (NoSuchAlgorithmException e) { throw new ClientSslSocketFactoryException( String.format("Failed to create the key store because the algorithm %s is not supported. ", KeyManagerFactory.getDefaultAlgorithm()), e); } catch (UnrecoverableKeyException e) { throw new ClientSslSocketFactoryException("Unrecoverable Key Exception initializing key manager factory; this is probably fatal", e); } catch (KeyStoreException e) { throw new ClientSslSocketFactoryException("KeyStore exception initializing key manager factory; this is probably fatal", e); } KeyManager[] managers = factory.getKeyManagers(); LOGGER.debug("Key managers are initialized. Total {} managers. ", managers.length); return managers; } /** * Creates the trust managers to be used by the factory from the specified trust store file and * password. * * @return the newly created array of trust managers * @throws ClientSslSocketFactoryException if an error is detected in loading the trust store */ private TrustManager[] createTrustManagers() throws ClientSslSocketFactoryException { final TrustManagerFactory factory; try { factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init(this.trustStore); } catch (NoSuchAlgorithmException e) { throw new ClientSslSocketFactoryException(String.format("Failed to create the trust store because the algorithm %s is not supported. ", KeyManagerFactory.getDefaultAlgorithm()), e); } catch (KeyStoreException e) { throw new ClientSslSocketFactoryException("KeyStore exception initializing trust manager factory; this is probably fatal", e); } final TrustManager[] managers = factory.getTrustManagers(); LOGGER.debug("TrustManagers are initialized. Total {} managers: ", managers.length); return managers; } public SSLContext getSSLContext() throws ClientSslSocketFactoryException{ return createSSLContext(); } }
6,944
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/ssl/URLSslContextFactory.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.client.ssl; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.common.base.Strings; /** * Secure socket factory that is used the NIWS code if a non-standard key store or trust store * is specified. * * @author Danny Yuan * @author Peter D. Stout */ public class URLSslContextFactory extends AbstractSslContextFactory{ private final static Logger LOGGER = LoggerFactory.getLogger(URLSslContextFactory.class); private final URL keyStoreUrl; private final URL trustStoreUrl; /** * Creates a {@code ClientSSLSocketFactory} instance. This instance loads only the given trust * store file and key store file. Both trust store and key store must be protected by passwords, * even though it is not mandated by JSSE. * * @param trustStoreUrl A {@link URL} that points to a trust store file. If non-null, this URL * must refer to a JKS key store file that contains trusted certificates. * @param trustStorePassword The password of the given trust store file. If a trust store is * specified, then the password may not be empty. * @param keyStoreUrl A {@code URL} that points to a key store file that contains both client * certificate and the client's private key. If non-null, this URL must be of JKS format. * @param keyStorePassword the password of the given key store file. If a key store is * specified, then the password may not be empty. * @throws ClientSslSocketFactoryException thrown if creating this instance fails. */ public URLSslContextFactory(final URL trustStoreUrl, final String trustStorePassword, final URL keyStoreUrl, final String keyStorePassword) throws ClientSslSocketFactoryException { super(createKeyStore(trustStoreUrl, trustStorePassword), trustStorePassword, createKeyStore(keyStoreUrl, keyStorePassword), keyStorePassword); this.keyStoreUrl = keyStoreUrl; this.trustStoreUrl = trustStoreUrl; LOGGER.info("Loaded keyStore from: {}", keyStoreUrl); LOGGER.info("loaded trustStore from: {}", trustStoreUrl); } /** * Opens the specified key or trust store using the given password. * * In case of failure {@link com.netflix.client.ssl.ClientSslSocketFactoryException} is thrown, and wrapps the * underlying cause exception. That could be: * <ul> * <li>KeyStoreException if the JRE doesn't support the standard Java Keystore format, in other words: never</li> * <li>NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found</li> * <li>CertificateException if any of the certificates in the keystore could not be loaded</li> * <li> * IOException if there is an I/O or format problem with the keystore data, if a * password is required but not given, or if the given password was incorrect. If the * error is due to a wrong password, the cause of the IOException should be an UnrecoverableKeyException. * </li> * </ul> * * @param storeFile the location of the store to load * @param password the password protecting the store * @return the newly loaded key store * @throws ClientSslSocketFactoryException a wrapper exception for any problems encountered during keystore creation. */ private static KeyStore createKeyStore(final URL storeFile, final String password) throws ClientSslSocketFactoryException { if(storeFile == null){ return null; } Preconditions.checkArgument(StringUtils.isNotEmpty(password), "Null keystore should have empty password, defined keystore must have password"); KeyStore keyStore = null; try{ keyStore = KeyStore.getInstance("jks"); InputStream is = storeFile.openStream(); try { keyStore.load(is, password.toCharArray()); } catch (NoSuchAlgorithmException e) { throw new ClientSslSocketFactoryException(String.format("Failed to create a keystore that supports algorithm %s: %s", SOCKET_ALGORITHM, e.getMessage()), e); } catch (CertificateException e) { throw new ClientSslSocketFactoryException(String.format("Failed to create keystore with algorithm %s due to certificate exception: %s", SOCKET_ALGORITHM, e.getMessage()), e); } finally { try { is.close(); } catch (IOException ignore) { // NOPMD } } }catch(KeyStoreException e){ throw new ClientSslSocketFactoryException(String.format("KeyStore exception creating keystore: %s", e.getMessage()), e); } catch (IOException e) { throw new ClientSslSocketFactoryException(String.format("IO exception creating keystore: %s", e.getMessage()), e); } return keyStore; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("ClientSslSocketFactory [trustStoreUrl=").append(trustStoreUrl); if (trustStoreUrl != null) { builder.append(", trustStorePassword="); builder.append(Strings.repeat("*", this.getTrustStorePasswordLength())); } builder.append(", keyStoreUrl=").append(keyStoreUrl); if (keyStoreUrl != null) { builder.append(", keystorePassword = "); builder.append(Strings.repeat("*", this.getKeyStorePasswordLength())); } builder.append(']'); return builder.toString(); } }
6,945
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/ssl/ClientSslSocketFactoryException.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.client.ssl; /** * Reports problems detected by the ClientSslSocketFactory class. * * @author pstout@netflix.com (Peter D. Stout) */ public class ClientSslSocketFactoryException extends Exception { /** Serial version identifier for this class. */ private static final long serialVersionUID = 1L; /** Constructs a new instance with the specified message and cause. */ public ClientSslSocketFactoryException(final String message, final Throwable cause) { super(message, cause); } }
6,946
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/util/Resources.java
package com.netflix.client.util; import java.io.File; import java.net.URL; import java.net.URLDecoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class Resources { private static final Logger logger = LoggerFactory.getLogger(Resources.class); public static URL getResource(String resourceName) { URL url = null; // attempt to load from the context classpath ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader != null) { url = loader.getResource(resourceName); } if (url == null) { // attempt to load from the system classpath url = ClassLoader.getSystemResource(resourceName); } if (url == null) { try { resourceName = URLDecoder.decode(resourceName, "UTF-8"); url = (new File(resourceName)).toURI().toURL(); } catch (Exception e) { logger.error("Problem loading resource", e); } } return url; } }
6,947
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/config/ReloadableClientConfig.java
package com.netflix.client.config; import com.google.common.base.Preconditions; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; /** * Base implementation of an IClientConfig with configuration that can be reloaded at runtime from an underlying * property source while optimizing access to property values. * * Properties can either be scoped to a specific client or default properties that span all clients. By default * properties follow the name convention `{clientname}.{namespace}.{key}` and then fallback to `{namespace}.{key}` * if not found * * Internally the config tracks two maps, one for dynamic properties and one for code settable default values to use * when a property is not defined in the underlying property source. */ public abstract class ReloadableClientConfig implements IClientConfig { private static final Logger LOG = LoggerFactory.getLogger(ReloadableClientConfig.class); private static final String DEFAULT_CLIENT_NAME = ""; private static final String DEFAULT_NAMESPACE = "ribbon"; // Map of raw property names (without namespace or client name) to values. All values are non-null and properly // typed to match the key type private final Map<IClientConfigKey, Optional<?>> internalProperties = new ConcurrentHashMap<>(); private final Map<IClientConfigKey, ReloadableProperty<?>> dynamicProperties = new ConcurrentHashMap<>(); // List of actions to perform when configuration changes. This includes both updating the Property instances // as well as external consumers. private final Map<IClientConfigKey, Runnable> changeActions = new ConcurrentHashMap<>(); private final AtomicLong refreshCounter = new AtomicLong(); private final PropertyResolver resolver; private String clientName = DEFAULT_CLIENT_NAME; private String namespace = DEFAULT_NAMESPACE; private boolean isDynamic = false; protected ReloadableClientConfig(PropertyResolver resolver) { this.resolver = resolver; } protected PropertyResolver getPropertyResolver() { return this.resolver; } /** * Refresh all seen properties from the underlying property storage */ public final void reload() { changeActions.values().forEach(Runnable::run); dynamicProperties.values().forEach(ReloadableProperty::reload); cachedToString = null; } /** * @deprecated Use {@link #loadProperties(String)} */ @Deprecated public void setClientName(String clientName){ this.clientName = clientName; } @Override public final String getClientName() { return clientName; } @Override public String getNameSpace() { return namespace; } @Override public final void setNameSpace(String nameSpace) { this.namespace = nameSpace; } @Override public void loadProperties(String clientName) { LOG.info("[{}] loading config", clientName); this.clientName = clientName; this.isDynamic = true; loadDefaultValues(); resolver.onChange(this::reload); internalProperties.forEach((key, value) -> LOG.info("[{}] {}={}", clientName, key, value.orElse(null))); } /** * @return use {@link #forEach(BiConsumer)} */ @Override @Deprecated public final Map<String, Object> getProperties() { final Map<String, Object> result = new HashMap<>(internalProperties.size()); forEach((key, value) -> result.put(key.key(), String.valueOf(value))); return result; } @Override public void forEach(BiConsumer<IClientConfigKey<?>, Object> consumer) { internalProperties.forEach((key, value) -> { if (value.isPresent()) { consumer.accept(key, value.get()); } }); } /** * Register an action that will refresh the cached value for key. Uses the current value as a reference and will * update from the dynamic property source to either delete or set a new value. * * @param key - Property key without client name or namespace */ private <T> void autoRefreshFromPropertyResolver(final IClientConfigKey<T> key) { changeActions.computeIfAbsent(key, ignore -> { final Supplier<Optional<T>> valueSupplier = () -> resolveFromPropertyResolver(key); final Optional<T> current = valueSupplier.get(); if (current.isPresent()) { internalProperties.put(key, current); } final AtomicReference<Optional<T>> previous = new AtomicReference<>(current); return () -> { final Optional<T> next = valueSupplier.get(); if (!next.equals(previous.get())) { LOG.info("[{}] new value for {}: {} -> {}", clientName, key.key(), previous.get(), next); previous.set(next); internalProperties.put(key, next); } }; }); } interface ReloadableProperty<T> extends Property<T> { void reload(); } private synchronized <T> Property<T> getOrCreateProperty(final IClientConfigKey<T> key, final Supplier<Optional<T>> valueSupplier, final Supplier<T> defaultSupplier) { Preconditions.checkNotNull(valueSupplier, "defaultValueSupplier cannot be null"); return (Property<T>)dynamicProperties.computeIfAbsent(key, ignore -> new ReloadableProperty<T>() { private volatile Optional<T> current = Optional.empty(); private List<Consumer<T>> consumers = new CopyOnWriteArrayList<>(); { reload(); } @Override public void onChange(Consumer<T> consumer) { consumers.add(consumer); } @Override public Optional<T> get() { return current; } @Override public T getOrDefault() { return current.orElse(defaultSupplier.get()); } @Override public void reload() { refreshCounter.incrementAndGet(); Optional<T> next = valueSupplier.get(); if (!next.equals(current)) { current = next; consumers.forEach(consumer -> consumer.accept(next.orElseGet(defaultSupplier::get))); } } @Override public String toString() { return String.valueOf(get()); } }); } @Override public final <T> T get(IClientConfigKey<T> key) { Optional<T> value = (Optional<T>)internalProperties.get(key); if (value == null) { if (!isDynamic) { return null; } else { set(key, null); value = (Optional<T>) internalProperties.get(key); } } return value.orElse(null); } @Override public final <T> Property<T> getGlobalProperty(IClientConfigKey<T> key) { LOG.debug("[{}] get global property '{}' with default '{}'", clientName, key.key(), key.defaultValue()); return getOrCreateProperty( key, () -> resolver.get(key.key(), key.type()), key::defaultValue); } @Override public final <T> Property<T> getDynamicProperty(IClientConfigKey<T> key) { LOG.debug("[{}] get dynamic property key={} ns={}", clientName, key.key(), getNameSpace()); get(key); return getOrCreateProperty( key, () -> (Optional<T>)internalProperties.getOrDefault(key, Optional.empty()), key::defaultValue); } @Override public <T> Property<T> getPrefixMappedProperty(IClientConfigKey<T> key) { LOG.debug("[{}] get dynamic property key={} ns={} client={}", clientName, key.key(), getNameSpace()); return getOrCreateProperty( key, getPrefixedMapPropertySupplier(key), key::defaultValue); } /** * Resolve a property's final value from the property value. * - client scope * - default scope */ private <T> Optional<T> resolveFromPropertyResolver(IClientConfigKey<T> key) { Optional<T> value; if (!StringUtils.isEmpty(clientName)) { value = resolver.get(clientName + "." + getNameSpace() + "." + key.key(), key.type()); if (value.isPresent()) { return value; } } return resolver.get(getNameSpace() + "." + key.key(), key.type()); } @Override public <T> Optional<T> getIfSet(IClientConfigKey<T> key) { return (Optional<T>)internalProperties.getOrDefault(key, Optional.empty()); } private <T> T resolveValueToType(IClientConfigKey<T> key, Object value) { if (value == null) { return null; } final Class<T> type = key.type(); // Unfortunately there's some legacy code setting string values for typed keys. Here are do our best to parse // and store the typed value if (!value.getClass().equals(type)) { try { if (type.equals(String.class)) { return (T) value.toString(); } else if (value.getClass().equals(String.class)) { final String strValue = (String) value; if (Integer.class.equals(type)) { return (T) Integer.valueOf(strValue); } else if (Boolean.class.equals(type)) { return (T) Boolean.valueOf(strValue); } else if (Float.class.equals(type)) { return (T) Float.valueOf(strValue); } else if (Long.class.equals(type)) { return (T) Long.valueOf(strValue); } else if (Double.class.equals(type)) { return (T) Double.valueOf(strValue); } else if (TimeUnit.class.equals(type)) { return (T) TimeUnit.valueOf(strValue); } else { return PropertyUtils.resolveWithValueOf(type, strValue) .orElseThrow(() -> new IllegalArgumentException("Unsupported value type `" + type + "'")); } } else { return PropertyUtils.resolveWithValueOf(type, value.toString()) .orElseThrow(() -> new IllegalArgumentException("Incompatible value type `" + value.getClass() + "` while expecting '" + type + "`")); } } catch (Exception e) { throw new IllegalArgumentException("Error parsing value '" + value + "' for '" + key.key() + "'", e); } } else { return (T)value; } } private <T> Supplier<Optional<T>> getPrefixedMapPropertySupplier(IClientConfigKey<T> key) { final Method method; try { method = key.type().getDeclaredMethod("valueOf", Map.class); } catch (NoSuchMethodException e) { throw new UnsupportedOperationException("Class '" + key.type().getName() + "' must have static method valueOf(Map<String, String>)", e); } return () -> { final Map<String, String> values = new HashMap<>(); resolver.forEach(getNameSpace() + "." + key.key(), values::put); if (!StringUtils.isEmpty(clientName)) { resolver.forEach(clientName + "." + getNameSpace() + "." + key.key(), values::put); } try { return Optional.ofNullable((T)method.invoke(null, values)); } catch (Exception e) { LOG.warn("Unable to map value for '{}'", key.key(), e); return Optional.empty(); } }; } @Override public final <T> T get(IClientConfigKey<T> key, T defaultValue) { return Optional.ofNullable(get(key)).orElse(defaultValue); } /** * Store the implicit default value for key while giving precedence to default values in the property resolver */ protected final <T> void setDefault(IClientConfigKey<T> key) { setDefault(key, key.defaultValue()); } /** * Store the default value for key while giving precedence to default values in the property resolver */ protected final <T> void setDefault(IClientConfigKey<T> key, T value) { Preconditions.checkArgument(key != null, "key cannot be null"); value = resolveFromPropertyResolver(key).orElse(value); internalProperties.put(key, Optional.ofNullable(value)); if (isDynamic) { autoRefreshFromPropertyResolver(key); } cachedToString = null; } @Override public <T> IClientConfig set(IClientConfigKey<T> key, T value) { Preconditions.checkArgument(key != null, "key cannot be null"); value = resolveValueToType(key, value); if (isDynamic) { internalProperties.put(key, Optional.ofNullable(resolveFromPropertyResolver(key).orElse(value))); autoRefreshFromPropertyResolver(key); } else { internalProperties.put(key, Optional.ofNullable(value)); } cachedToString = null; return this; } @Override @Deprecated public void setProperty(IClientConfigKey key, Object value) { Preconditions.checkArgument(value != null, "Value may not be null"); set(key, value); } @Override @Deprecated public Object getProperty(IClientConfigKey key) { return get(key); } @Override @Deprecated public Object getProperty(IClientConfigKey key, Object defaultVal) { return Optional.ofNullable(get(key)).orElse(defaultVal); } @Override @Deprecated public boolean containsProperty(IClientConfigKey key) { return internalProperties.containsKey(key); } @Override @Deprecated public int getPropertyAsInteger(IClientConfigKey key, int defaultValue) { return Optional.ofNullable(getProperty(key)).map(Integer.class::cast).orElse(defaultValue); } @Override @Deprecated public String getPropertyAsString(IClientConfigKey key, String defaultValue) { return Optional.ofNullable(getProperty(key)).map(Object::toString).orElse(defaultValue); } @Override @Deprecated public boolean getPropertyAsBoolean(IClientConfigKey key, boolean defaultValue) { return Optional.ofNullable(getProperty(key)).map(Boolean.class::cast).orElse(defaultValue); } public IClientConfig applyOverride(IClientConfig override) { if (override == null) { return this; } override.forEach((key, value) -> setProperty(key, value)); return this; } private volatile String cachedToString = null; @Override public String toString() { if (cachedToString == null) { String newToString = generateToString(); cachedToString = newToString; return newToString; } return cachedToString; } /** * @return Number of individual properties refreshed. This can be used to identify patterns of excessive updates. */ public long getRefreshCount() { return refreshCounter.get(); } private String generateToString() { return "ClientConfig:" + internalProperties.entrySet().stream() .map(t -> { if (t.getKey().key().endsWith("Password") && t.getValue().isPresent()) { return t.getKey() + ":***"; } return t.getKey() + ":" + t.getValue().orElse(null); }) .collect(Collectors.joining(", ")); } }
6,948
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/config/PropertyResolver.java
package com.netflix.client.config; import java.util.Optional; import java.util.function.BiConsumer; /** * Internal abstraction to decouple the property source from Ribbon's internal configuration. */ public interface PropertyResolver { /** * @return Get the value of a property or Optional.empty() if not set */ <T> Optional<T> get(String key, Class<T> type); /** * Iterate through all properties with the specified prefix */ void forEach(String prefix, BiConsumer<String, String> consumer); /** * Provide action to invoke when config changes * @param action */ void onChange(Runnable action); }
6,949
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/config/Property.java
package com.netflix.client.config; import java.util.Optional; import java.util.function.Consumer; /** * Ribbon specific encapsulation of a dynamic configuration property * @param <T> */ public interface Property<T> { /** * Register a consumer to be called when the configuration changes * @param consumer */ void onChange(Consumer<T> consumer); /** * @return Get the current value. Can be null if not set */ Optional<T> get(); /** * @return Get the current value or the default value if not set */ T getOrDefault(); default Property<T> fallbackWith(Property<T> fallback) { return new FallbackProperty<>(this, fallback); } static <T> Property<T> of(T value) { return new Property<T>() { @Override public void onChange(Consumer<T> consumer) { // It's a static property so no need to track the consumer } @Override public Optional<T> get() { return Optional.ofNullable(value); } @Override public T getOrDefault() { return value; } @Override public String toString( ){ return String.valueOf(value); } }; } }
6,950
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/config/FallbackProperty.java
package com.netflix.client.config; import java.util.Optional; import java.util.function.Consumer; public final class FallbackProperty<T> implements Property<T> { private final Property<T> primary; private final Property<T> fallback; public FallbackProperty(Property<T> primary, Property<T> fallback) { this.primary = primary; this.fallback = fallback; } @Override public void onChange(Consumer<T> consumer) { primary.onChange(ignore -> consumer.accept(getOrDefault())); fallback.onChange(ignore -> consumer.accept(getOrDefault())); } @Override public Optional<T> get() { Optional<T> value = primary.get(); if (value.isPresent()) { return value; } return fallback.get(); } @Override public T getOrDefault() { return primary.get().orElseGet(fallback::getOrDefault); } @Override public String toString() { return String.valueOf(get()); } }
6,951
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/config/IClientConfig.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.client.config; import java.util.Map; import java.util.Optional; import java.util.function.BiConsumer; /** * Defines the client configuration used by various APIs to initialize clients or load balancers * and for method execution. * * @author awang */ public interface IClientConfig { String getClientName(); String getNameSpace(); void setNameSpace(String nameSpace); /** * Load the properties for a given client and/or load balancer. * @param clientName */ void loadProperties(String clientName); /** * load default values for this configuration */ void loadDefaultValues(); Map<String, Object> getProperties(); /** * Iterate all properties and report the final value. Can be null if a default value is not specified. * @param consumer */ default void forEach(BiConsumer<IClientConfigKey<?>, Object> consumer) { throw new UnsupportedOperationException(); } /** * @deprecated use {@link #set(IClientConfigKey, Object)} */ @Deprecated void setProperty(IClientConfigKey key, Object value); /** * @deprecated use {@link #get(IClientConfigKey)} */ @Deprecated Object getProperty(IClientConfigKey key); /** * @deprecated use {@link #get(IClientConfigKey, Object)} */ @Deprecated Object getProperty(IClientConfigKey key, Object defaultVal); /** * @deprecated use {@link #getIfSet(IClientConfigKey)} */ @Deprecated boolean containsProperty(IClientConfigKey key); /** * Returns the applicable virtual addresses ("vip") used by this client configuration. */ String resolveDeploymentContextbasedVipAddresses(); @Deprecated int getPropertyAsInteger(IClientConfigKey key, int defaultValue); @Deprecated String getPropertyAsString(IClientConfigKey key, String defaultValue); @Deprecated boolean getPropertyAsBoolean(IClientConfigKey key, boolean defaultValue); /** * Returns a typed property. If the property of IClientConfigKey is not set, it returns null. * <p> * <ul> * <li>Integer</li> * <li>Boolean</li> * <li>Float</li> * <li>Long</li> * <li>Double</li> * </ul> * <br><br> */ <T> T get(IClientConfigKey<T> key); /** * Returns a typed property. If the property of IClientConfigKey is not set, it returns the default value, which * could be null. * <p> * <ul> * <li>Integer</li> * <li>Boolean</li> * <li>Float</li> * <li>Long</li> * <li>Double</li> * </ul> * <br><br> */ default <T> T getOrDefault(IClientConfigKey<T> key) { return get(key, key.defaultValue()); } /** * Return a typed property if and only if it was explicitly set, skipping configuration loading. * @param key * @param <T> * @return */ default <T> Optional<T> getIfSet(IClientConfigKey<T> key) { return Optional.ofNullable(get(key)); } /** * @return Return a global dynamic property not scoped to the specific client. The property will be looked up as is using the * key without any client name or namespace prefix */ <T> Property<T> getGlobalProperty(IClientConfigKey<T> key); /** * @return Return a dynamic property scoped to the client name or namespace. */ <T> Property<T> getDynamicProperty(IClientConfigKey<T> key); /** * @return Return a dynamically updated property that is a mapping of all properties prefixed by the key name to an * object with static method valueOf(Map{@literal <}String, String{@literal >}) */ default <T> Property<T> getPrefixMappedProperty(IClientConfigKey<T> key) { throw new UnsupportedOperationException(); } /** * Returns a typed property. If the property of IClientConfigKey is not set, * it returns the default value passed in as the parameter. */ <T> T get(IClientConfigKey<T> key, T defaultValue); /** * Set the typed property with the given value. */ <T> IClientConfig set(IClientConfigKey<T> key, T value); @Deprecated class Builder { private IClientConfig config; Builder() { } /** * Create a builder with no initial property and value for the configuration to be built. */ public static Builder newBuilder() { Builder builder = new Builder(); builder.config = ClientConfigFactory.findDefaultConfigFactory().newConfig(); return builder; } /** * Create a builder with properties for the specific client loaded. The default * {@link IClientConfig} implementation loads properties from <a href="https://github.com/Netflix/archaius">Archaius</a> * * @param clientName Name of client. clientName.ribbon will be used as a prefix to find corresponding properties from * <a href="https://github.com/Netflix/archaius">Archaius</a> */ public static Builder newBuilder(String clientName) { Builder builder = new Builder(); builder.config = ClientConfigFactory.findDefaultConfigFactory().newConfig(); builder.config.loadProperties(clientName); return builder; } /** * Create a builder with properties for the specific client loaded. The default * {@link IClientConfig} implementation loads properties from <a href="https://github.com/Netflix/archaius">Archaius</a> * * @param clientName Name of client. clientName.propertyNameSpace will be used as a prefix to find corresponding properties from * <a href="https://github.com/Netflix/archaius">Archaius</a> */ public static Builder newBuilder(String clientName, String propertyNameSpace) { Builder builder = new Builder(); builder.config = ClientConfigFactory.findDefaultConfigFactory().newConfig(); builder.config.setNameSpace(propertyNameSpace); builder.config.loadProperties(clientName); return builder; } /** * Create a builder with properties for the specific client loaded. * * @param implClass the class of {@link IClientConfig} object to be built */ public static Builder newBuilder(Class<? extends IClientConfig> implClass, String clientName) { Builder builder = new Builder(); try { builder.config = implClass.newInstance(); builder.config.loadProperties(clientName); } catch (Exception e) { throw new IllegalArgumentException(e); } return builder; } /** * Create a builder to build the configuration with no initial properties set * * @param implClass the class of {@link IClientConfig} object to be built */ public static Builder newBuilder(Class<? extends IClientConfig> implClass) { Builder builder = new Builder(); try { builder.config = implClass.newInstance(); } catch (Exception e) { throw new IllegalArgumentException(e); } return builder; } public IClientConfig build() { return config; } /** * Load a set of default values for the configuration */ public Builder withDefaultValues() { config.loadDefaultValues(); return this; } public Builder withDeploymentContextBasedVipAddresses(String vipAddress) { config.set(CommonClientConfigKey.DeploymentContextBasedVipAddresses, vipAddress); return this; } public Builder withForceClientPortConfiguration(boolean forceClientPortConfiguration) { config.set(CommonClientConfigKey.ForceClientPortConfiguration, forceClientPortConfiguration); return this; } public Builder withMaxAutoRetries(int value) { config.set(CommonClientConfigKey.MaxAutoRetries, value); return this; } public Builder withMaxAutoRetriesNextServer(int value) { config.set(CommonClientConfigKey.MaxAutoRetriesNextServer, value); return this; } public Builder withRetryOnAllOperations(boolean value) { config.set(CommonClientConfigKey.OkToRetryOnAllOperations, value); return this; } public Builder withRequestSpecificRetryOn(boolean value) { config.set(CommonClientConfigKey.RequestSpecificRetryOn, value); return this; } public Builder withEnablePrimeConnections(boolean value) { config.set(CommonClientConfigKey.EnablePrimeConnections, value); return this; } public Builder withMaxConnectionsPerHost(int value) { config.set(CommonClientConfigKey.MaxHttpConnectionsPerHost, value); config.set(CommonClientConfigKey.MaxConnectionsPerHost, value); return this; } public Builder withMaxTotalConnections(int value) { config.set(CommonClientConfigKey.MaxTotalHttpConnections, value); config.set(CommonClientConfigKey.MaxTotalConnections, value); return this; } public Builder withSecure(boolean secure) { config.set(CommonClientConfigKey.IsSecure, secure); return this; } public Builder withConnectTimeout(int value) { config.set(CommonClientConfigKey.ConnectTimeout, value); return this; } public Builder withReadTimeout(int value) { config.set(CommonClientConfigKey.ReadTimeout, value); return this; } public Builder withConnectionManagerTimeout(int value) { config.set(CommonClientConfigKey.ConnectionManagerTimeout, value); return this; } public Builder withFollowRedirects(boolean value) { config.set(CommonClientConfigKey.FollowRedirects, value); return this; } public Builder withConnectionPoolCleanerTaskEnabled(boolean value) { config.set(CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled, value); return this; } public Builder withConnIdleEvictTimeMilliSeconds(int value) { config.set(CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds, value); return this; } public Builder withConnectionCleanerRepeatIntervalMills(int value) { config.set(CommonClientConfigKey.ConnectionCleanerRepeatInterval, value); return this; } public Builder withGZIPContentEncodingFilterEnabled(boolean value) { config.set(CommonClientConfigKey.EnableGZIPContentEncodingFilter, value); return this; } public Builder withProxyHost(String proxyHost) { config.set(CommonClientConfigKey.ProxyHost, proxyHost); return this; } public Builder withProxyPort(int value) { config.set(CommonClientConfigKey.ProxyPort, value); return this; } public Builder withKeyStore(String value) { config.set(CommonClientConfigKey.KeyStore, value); return this; } public Builder withKeyStorePassword(String value) { config.set(CommonClientConfigKey.KeyStorePassword, value); return this; } public Builder withTrustStore(String value) { config.set(CommonClientConfigKey.TrustStore, value); return this; } public Builder withTrustStorePassword(String value) { config.set(CommonClientConfigKey.TrustStorePassword, value); return this; } public Builder withClientAuthRequired(boolean value) { config.set(CommonClientConfigKey.IsClientAuthRequired, value); return this; } public Builder withCustomSSLSocketFactoryClassName(String value) { config.set(CommonClientConfigKey.CustomSSLSocketFactoryClassName, value); return this; } public Builder withHostnameValidationRequired(boolean value) { config.set(CommonClientConfigKey.IsHostnameValidationRequired, value); return this; } // see also http://hc.apache.org/httpcomponents-client-ga/tutorial/html/advanced.html public Builder ignoreUserTokenInConnectionPoolForSecureClient(boolean value) { config.set(CommonClientConfigKey.IgnoreUserTokenInConnectionPoolForSecureClient, value); return this; } public Builder withLoadBalancerEnabled(boolean value) { config.set(CommonClientConfigKey.InitializeNFLoadBalancer, value); return this; } public Builder withServerListRefreshIntervalMills(int value) { config.set(CommonClientConfigKey.ServerListRefreshInterval, value); return this; } public Builder withZoneAffinityEnabled(boolean value) { config.set(CommonClientConfigKey.EnableZoneAffinity, value); return this; } public Builder withZoneExclusivityEnabled(boolean value) { config.set(CommonClientConfigKey.EnableZoneExclusivity, value); return this; } public Builder prioritizeVipAddressBasedServers(boolean value) { config.set(CommonClientConfigKey.PrioritizeVipAddressBasedServers, value); return this; } public Builder withTargetRegion(String value) { config.set(CommonClientConfigKey.TargetRegion, value); return this; } } }
6,952
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/config/UnboxedIntProperty.java
package com.netflix.client.config; public class UnboxedIntProperty { private volatile int value; public UnboxedIntProperty(Property<Integer> delegate) { this.value = delegate.getOrDefault(); delegate.onChange(newValue -> this.value = newValue); } public UnboxedIntProperty(int constantValue) { this.value = constantValue; } public int get() { return value; } }
6,953
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/config/ClientConfigFactory.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.client.config; import java.util.Comparator; import java.util.ServiceLoader; import java.util.stream.StreamSupport; /** * Created by awang on 7/18/14. */ public interface ClientConfigFactory { IClientConfig newConfig(); ClientConfigFactory DEFAULT = findDefaultConfigFactory(); default int getPriority() { return 0; } static ClientConfigFactory findDefaultConfigFactory() { return StreamSupport.stream(ServiceLoader.load(ClientConfigFactory.class).spliterator(), false) .sorted(Comparator .comparingInt(ClientConfigFactory::getPriority) .thenComparing(f -> f.getClass().getCanonicalName()) .reversed()) .findFirst() .orElseGet(() -> { throw new IllegalStateException("Expecting at least one implementation of ClientConfigFactory discoverable via the ServiceLoader"); }); } }
6,954
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/config/AbstractDefaultClientConfigImpl.java
package com.netflix.client.config; import com.netflix.client.VipAddressResolver; import java.util.concurrent.TimeUnit; /** * This class only exists to support code that depends on these constants that are deprecated now that defaults have * moved into the key. */ @Deprecated public abstract class AbstractDefaultClientConfigImpl extends ReloadableClientConfig { @Deprecated public static final Boolean DEFAULT_PRIORITIZE_VIP_ADDRESS_BASED_SERVERS = CommonClientConfigKey.PrioritizeVipAddressBasedServers.defaultValue(); @Deprecated public static final String DEFAULT_NFLOADBALANCER_PING_CLASSNAME = CommonClientConfigKey.NFLoadBalancerPingClassName.defaultValue(); @Deprecated public static final String DEFAULT_NFLOADBALANCER_RULE_CLASSNAME = CommonClientConfigKey.NFLoadBalancerRuleClassName.defaultValue(); @Deprecated public static final String DEFAULT_NFLOADBALANCER_CLASSNAME = CommonClientConfigKey.NFLoadBalancerClassName.defaultValue(); @Deprecated public static final boolean DEFAULT_USEIPADDRESS_FOR_SERVER = CommonClientConfigKey.UseIPAddrForServer.defaultValue(); @Deprecated public static final String DEFAULT_CLIENT_CLASSNAME = CommonClientConfigKey.ClientClassName.defaultValue(); @Deprecated public static final String DEFAULT_VIPADDRESS_RESOLVER_CLASSNAME = CommonClientConfigKey.VipAddressResolverClassName.defaultValue(); @Deprecated public static final String DEFAULT_PRIME_CONNECTIONS_URI = CommonClientConfigKey.PrimeConnectionsURI.defaultValue(); @Deprecated public static final int DEFAULT_MAX_TOTAL_TIME_TO_PRIME_CONNECTIONS = CommonClientConfigKey.MaxTotalTimeToPrimeConnections.defaultValue(); @Deprecated public static final int DEFAULT_MAX_RETRIES_PER_SERVER_PRIME_CONNECTION = CommonClientConfigKey.MaxRetriesPerServerPrimeConnection.defaultValue(); @Deprecated public static final Boolean DEFAULT_ENABLE_PRIME_CONNECTIONS = CommonClientConfigKey.EnablePrimeConnections.defaultValue(); @Deprecated public static final int DEFAULT_MAX_REQUESTS_ALLOWED_PER_WINDOW = Integer.MAX_VALUE; @Deprecated public static final int DEFAULT_REQUEST_THROTTLING_WINDOW_IN_MILLIS = 60000; @Deprecated public static final Boolean DEFAULT_ENABLE_REQUEST_THROTTLING = Boolean.FALSE; @Deprecated public static final Boolean DEFAULT_ENABLE_GZIP_CONTENT_ENCODING_FILTER = CommonClientConfigKey.EnableGZIPContentEncodingFilter.defaultValue(); @Deprecated public static final Boolean DEFAULT_CONNECTION_POOL_CLEANER_TASK_ENABLED = CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled.defaultValue(); @Deprecated public static final Boolean DEFAULT_FOLLOW_REDIRECTS = CommonClientConfigKey.FollowRedirects.defaultValue(); @Deprecated public static final float DEFAULT_PERCENTAGE_NIWS_EVENT_LOGGED = 0.0f; @Deprecated public static final int DEFAULT_MAX_AUTO_RETRIES_NEXT_SERVER = CommonClientConfigKey.MaxAutoRetriesNextServer.defaultValue(); @Deprecated public static final int DEFAULT_MAX_AUTO_RETRIES = CommonClientConfigKey.MaxAutoRetries.defaultValue(); @Deprecated public static final int DEFAULT_BACKOFF_INTERVAL = CommonClientConfigKey.BackoffInterval.defaultValue(); @Deprecated public static final int DEFAULT_READ_TIMEOUT = CommonClientConfigKey.ReadTimeout.defaultValue(); @Deprecated public static final int DEFAULT_CONNECTION_MANAGER_TIMEOUT = CommonClientConfigKey.ConnectionManagerTimeout.defaultValue(); @Deprecated public static final int DEFAULT_CONNECT_TIMEOUT = CommonClientConfigKey.ConnectTimeout.defaultValue(); @Deprecated public static final Boolean DEFAULT_ENABLE_CONNECTION_POOL = CommonClientConfigKey.EnableConnectionPool.defaultValue(); @Deprecated public static final int DEFAULT_MAX_HTTP_CONNECTIONS_PER_HOST = CommonClientConfigKey.MaxHttpConnectionsPerHost.defaultValue(); @Deprecated public static final int DEFAULT_MAX_TOTAL_HTTP_CONNECTIONS = CommonClientConfigKey.MaxTotalHttpConnections.defaultValue(); @Deprecated public static final int DEFAULT_MAX_CONNECTIONS_PER_HOST = CommonClientConfigKey.MaxConnectionsPerHost.defaultValue(); @Deprecated public static final int DEFAULT_MAX_TOTAL_CONNECTIONS = CommonClientConfigKey.MaxTotalConnections.defaultValue(); @Deprecated public static final float DEFAULT_MIN_PRIME_CONNECTIONS_RATIO = CommonClientConfigKey.MinPrimeConnectionsRatio.defaultValue(); @Deprecated public static final String DEFAULT_PRIME_CONNECTIONS_CLASS = CommonClientConfigKey.PrimeConnectionsClassName.defaultValue(); @Deprecated public static final String DEFAULT_SEVER_LIST_CLASS = CommonClientConfigKey.NIWSServerListClassName.defaultValue(); @Deprecated public static final String DEFAULT_SERVER_LIST_UPDATER_CLASS = CommonClientConfigKey.ServerListUpdaterClassName.defaultValue(); @Deprecated public static final int DEFAULT_CONNECTION_IDLE_TIMERTASK_REPEAT_IN_MSECS = CommonClientConfigKey.ConnectionCleanerRepeatInterval.defaultValue(); // every half minute (30 secs) @Deprecated public static final int DEFAULT_CONNECTIONIDLE_TIME_IN_MSECS = CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds.defaultValue(); // all connections idle for 30 secs @Deprecated public static final int DEFAULT_POOL_MAX_THREADS = CommonClientConfigKey.MaxTotalHttpConnections.defaultValue(); @Deprecated public static final int DEFAULT_POOL_MIN_THREADS = CommonClientConfigKey.PoolMinThreads.defaultValue(); @Deprecated public static final long DEFAULT_POOL_KEEP_ALIVE_TIME = CommonClientConfigKey.PoolKeepAliveTime.defaultValue(); @Deprecated public static final TimeUnit DEFAULT_POOL_KEEP_ALIVE_TIME_UNITS = TimeUnit.valueOf(CommonClientConfigKey.PoolKeepAliveTimeUnits.defaultValue()); @Deprecated public static final Boolean DEFAULT_ENABLE_ZONE_AFFINITY = CommonClientConfigKey.EnableZoneAffinity.defaultValue(); @Deprecated public static final Boolean DEFAULT_ENABLE_ZONE_EXCLUSIVITY = CommonClientConfigKey.EnableZoneExclusivity.defaultValue(); @Deprecated public static final int DEFAULT_PORT = CommonClientConfigKey.Port.defaultValue(); @Deprecated public static final Boolean DEFAULT_ENABLE_LOADBALANCER = CommonClientConfigKey.InitializeNFLoadBalancer.defaultValue(); @Deprecated public static final Boolean DEFAULT_OK_TO_RETRY_ON_ALL_OPERATIONS = CommonClientConfigKey.OkToRetryOnAllOperations.defaultValue(); @Deprecated public static final Boolean DEFAULT_ENABLE_NIWS_EVENT_LOGGING = Boolean.TRUE; @Deprecated public static final Boolean DEFAULT_IS_CLIENT_AUTH_REQUIRED = Boolean.FALSE; private volatile VipAddressResolver vipResolver = null; protected AbstractDefaultClientConfigImpl(PropertyResolver resolver) { super(resolver); } public void setVipAddressResolver(VipAddressResolver resolver) { this.vipResolver = resolver; } public VipAddressResolver getResolver() { return vipResolver; } @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "DC_DOUBLECHECK") private VipAddressResolver getVipAddressResolver() { if (vipResolver == null) { synchronized (this) { if (vipResolver == null) { try { vipResolver = (VipAddressResolver) Class .forName(getOrDefault(CommonClientConfigKey.VipAddressResolverClassName)) .newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new RuntimeException("Cannot instantiate VipAddressResolver", e); } } } } return vipResolver; } @Override public String resolveDeploymentContextbasedVipAddresses(){ String deploymentContextBasedVipAddressesMacro = get(CommonClientConfigKey.DeploymentContextBasedVipAddresses); if (deploymentContextBasedVipAddressesMacro == null) { return null; } return getVipAddressResolver().resolve(deploymentContextBasedVipAddressesMacro, this); } @Deprecated public String getAppName(){ return get(CommonClientConfigKey.AppName); } @Deprecated public String getVersion(){ return get(CommonClientConfigKey.Version); } }
6,955
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/config/IClientConfigKey.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.client.config; /** * Defines the key used in {@link IClientConfig}. See {@link CommonClientConfigKey} * for the commonly defined client configuration keys. * * @author awang * */ public interface IClientConfigKey<T> { @SuppressWarnings("rawtypes") final class Keys extends CommonClientConfigKey { private Keys(String configKey) { super(configKey); } } /** * @return string representation of the key used for hash purpose. */ String key(); /** * @return Data type for the key. For example, Integer.class. */ Class<T> type(); default T defaultValue() { return null; } default IClientConfigKey<T> format(Object ... args) { return create(String.format(key(), args), type(), defaultValue()); } default IClientConfigKey<T> create(String key, Class<T> type, T defaultValue) { return new IClientConfigKey<T>() { @Override public int hashCode() { return key().hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof IClientConfigKey) { return key().equals(((IClientConfigKey)obj).key()); } return false; } @Override public String toString() { return key(); } @Override public String key() { return key; } @Override public Class<T> type() { return type; } @Override public T defaultValue() { return defaultValue; } }; } }
6,956
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/config/CommonClientConfigKey.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.client.config; import com.google.common.reflect.TypeToken; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; import static com.google.common.base.Preconditions.checkArgument; public abstract class CommonClientConfigKey<T> implements IClientConfigKey<T> { public static final String DEFAULT_NAME_SPACE = "ribbon"; public static final IClientConfigKey<String> AppName = new CommonClientConfigKey<String>("AppName"){}; public static final IClientConfigKey<String> Version = new CommonClientConfigKey<String>("Version"){}; public static final IClientConfigKey<Integer> Port = new CommonClientConfigKey<Integer>("Port", 7001){}; public static final IClientConfigKey<Integer> SecurePort = new CommonClientConfigKey<Integer>("SecurePort", 7001){}; public static final IClientConfigKey<String> VipAddress = new CommonClientConfigKey<String>("VipAddress"){}; public static final IClientConfigKey<Boolean> ForceClientPortConfiguration = new CommonClientConfigKey<Boolean>("ForceClientPortConfiguration"){}; // use client defined port regardless of server advert public static final IClientConfigKey<String> DeploymentContextBasedVipAddresses = new CommonClientConfigKey<String>("DeploymentContextBasedVipAddresses"){}; public static final IClientConfigKey<Integer> MaxAutoRetries = new CommonClientConfigKey<Integer>("MaxAutoRetries", 0){}; public static final IClientConfigKey<Integer> MaxAutoRetriesNextServer = new CommonClientConfigKey<Integer>("MaxAutoRetriesNextServer", 1){}; public static final IClientConfigKey<Boolean> OkToRetryOnAllOperations = new CommonClientConfigKey<Boolean>("OkToRetryOnAllOperations", false){}; public static final IClientConfigKey<Boolean> RequestSpecificRetryOn = new CommonClientConfigKey<Boolean>("RequestSpecificRetryOn"){}; public static final IClientConfigKey<Integer> ReceiveBufferSize = new CommonClientConfigKey<Integer>("ReceiveBufferSize"){}; public static final IClientConfigKey<Boolean> EnablePrimeConnections = new CommonClientConfigKey<Boolean>("EnablePrimeConnections", false){}; public static final IClientConfigKey<String> PrimeConnectionsClassName = new CommonClientConfigKey<String>("PrimeConnectionsClassName", "com.netflix.niws.client.http.HttpPrimeConnection"){}; public static final IClientConfigKey<Integer> MaxRetriesPerServerPrimeConnection = new CommonClientConfigKey<Integer>("MaxRetriesPerServerPrimeConnection", 9){}; public static final IClientConfigKey<Integer> MaxTotalTimeToPrimeConnections = new CommonClientConfigKey<Integer>("MaxTotalTimeToPrimeConnections", 30000){}; public static final IClientConfigKey<Float> MinPrimeConnectionsRatio = new CommonClientConfigKey<Float>("MinPrimeConnectionsRatio", 1.0f){}; public static final IClientConfigKey<String> PrimeConnectionsURI = new CommonClientConfigKey<String>("PrimeConnectionsURI", "/"){}; public static final IClientConfigKey<Integer> PoolMaxThreads = new CommonClientConfigKey<Integer>("PoolMaxThreads", 200){}; public static final IClientConfigKey<Integer> PoolMinThreads = new CommonClientConfigKey<Integer>("PoolMinThreads", 1){}; public static final IClientConfigKey<Integer> PoolKeepAliveTime = new CommonClientConfigKey<Integer>("PoolKeepAliveTime", 15 * 60){}; public static final IClientConfigKey<String> PoolKeepAliveTimeUnits = new CommonClientConfigKey<String>("PoolKeepAliveTimeUnits", TimeUnit.SECONDS.toString()){}; public static final IClientConfigKey<Boolean> EnableConnectionPool = new CommonClientConfigKey<Boolean>("EnableConnectionPool", true) {}; /** * Use {@link #MaxConnectionsPerHost} */ @Deprecated public static final IClientConfigKey<Integer> MaxHttpConnectionsPerHost = new CommonClientConfigKey<Integer>("MaxHttpConnectionsPerHost", 50){}; /** * Use {@link #MaxTotalConnections} */ @Deprecated public static final IClientConfigKey<Integer> MaxTotalHttpConnections = new CommonClientConfigKey<Integer>("MaxTotalHttpConnections", 200){}; public static final IClientConfigKey<Integer> MaxConnectionsPerHost = new CommonClientConfigKey<Integer>("MaxConnectionsPerHost", 50){}; public static final IClientConfigKey<Integer> MaxTotalConnections = new CommonClientConfigKey<Integer>("MaxTotalConnections", 200){}; public static final IClientConfigKey<Boolean> IsSecure = new CommonClientConfigKey<Boolean>("IsSecure"){}; public static final IClientConfigKey<Boolean> GZipPayload = new CommonClientConfigKey<Boolean>("GZipPayload"){}; public static final IClientConfigKey<Integer> ConnectTimeout = new CommonClientConfigKey<Integer>("ConnectTimeout", 2000){}; public static final IClientConfigKey<Integer> BackoffInterval = new CommonClientConfigKey<Integer>("BackoffTimeout", 0){}; public static final IClientConfigKey<Integer> ReadTimeout = new CommonClientConfigKey<Integer>("ReadTimeout", 5000){}; public static final IClientConfigKey<Integer> SendBufferSize = new CommonClientConfigKey<Integer>("SendBufferSize"){}; public static final IClientConfigKey<Boolean> StaleCheckingEnabled = new CommonClientConfigKey<Boolean>("StaleCheckingEnabled", false){}; public static final IClientConfigKey<Integer> Linger = new CommonClientConfigKey<Integer>("Linger", 0){}; public static final IClientConfigKey<Integer> ConnectionManagerTimeout = new CommonClientConfigKey<Integer>("ConnectionManagerTimeout", 2000){}; public static final IClientConfigKey<Boolean> FollowRedirects = new CommonClientConfigKey<Boolean>("FollowRedirects", false){}; public static final IClientConfigKey<Boolean> ConnectionPoolCleanerTaskEnabled = new CommonClientConfigKey<Boolean>("ConnectionPoolCleanerTaskEnabled", true){}; public static final IClientConfigKey<Integer> ConnIdleEvictTimeMilliSeconds = new CommonClientConfigKey<Integer>("ConnIdleEvictTimeMilliSeconds", 30*1000){}; public static final IClientConfigKey<Integer> ConnectionCleanerRepeatInterval = new CommonClientConfigKey<Integer>("ConnectionCleanerRepeatInterval", 30*1000){}; public static final IClientConfigKey<Boolean> EnableGZIPContentEncodingFilter = new CommonClientConfigKey<Boolean>("EnableGZIPContentEncodingFilter", false){}; public static final IClientConfigKey<String> ProxyHost = new CommonClientConfigKey<String>("ProxyHost"){}; public static final IClientConfigKey<Integer> ProxyPort = new CommonClientConfigKey<Integer>("ProxyPort"){}; public static final IClientConfigKey<String> KeyStore = new CommonClientConfigKey<String>("KeyStore"){}; public static final IClientConfigKey<String> KeyStorePassword = new CommonClientConfigKey<String>("KeyStorePassword"){}; public static final IClientConfigKey<String> TrustStore = new CommonClientConfigKey<String>("TrustStore"){}; public static final IClientConfigKey<String> TrustStorePassword = new CommonClientConfigKey<String>("TrustStorePassword"){}; // if this is a secure rest client, must we use client auth too? public static final IClientConfigKey<Boolean> IsClientAuthRequired = new CommonClientConfigKey<Boolean>("IsClientAuthRequired", false){}; public static final IClientConfigKey<String> CustomSSLSocketFactoryClassName = new CommonClientConfigKey<String>("CustomSSLSocketFactoryClassName"){}; // must host name match name in certificate? public static final IClientConfigKey<Boolean> IsHostnameValidationRequired = new CommonClientConfigKey<Boolean>("IsHostnameValidationRequired"){}; // see also http://hc.apache.org/httpcomponents-client-ga/tutorial/html/advanced.html public static final IClientConfigKey<Boolean> IgnoreUserTokenInConnectionPoolForSecureClient = new CommonClientConfigKey<Boolean>("IgnoreUserTokenInConnectionPoolForSecureClient"){}; // Client implementation public static final IClientConfigKey<String> ClientClassName = new CommonClientConfigKey<String>("ClientClassName", "com.netflix.niws.client.http.RestClient"){}; //LoadBalancer Related public static final IClientConfigKey<Boolean> InitializeNFLoadBalancer = new CommonClientConfigKey<Boolean>("InitializeNFLoadBalancer", true){}; public static final IClientConfigKey<String> NFLoadBalancerClassName = new CommonClientConfigKey<String>("NFLoadBalancerClassName", "com.netflix.loadbalancer.ZoneAwareLoadBalancer"){}; public static final IClientConfigKey<String> NFLoadBalancerRuleClassName = new CommonClientConfigKey<String>("NFLoadBalancerRuleClassName", "com.netflix.loadbalancer.AvailabilityFilteringRule"){}; public static final IClientConfigKey<String> NFLoadBalancerPingClassName = new CommonClientConfigKey<String>("NFLoadBalancerPingClassName", "com.netflix.loadbalancer.DummyPing"){}; public static final IClientConfigKey<Integer> NFLoadBalancerPingInterval = new CommonClientConfigKey<Integer>("NFLoadBalancerPingInterval"){}; public static final IClientConfigKey<Integer> NFLoadBalancerMaxTotalPingTime = new CommonClientConfigKey<Integer>("NFLoadBalancerMaxTotalPingTime"){}; public static final IClientConfigKey<String> NFLoadBalancerStatsClassName = new CommonClientConfigKey<String>("NFLoadBalancerStatsClassName", "com.netflix.loadbalancer.LoadBalancerStats"){}; public static final IClientConfigKey<String> NIWSServerListClassName = new CommonClientConfigKey<String>("NIWSServerListClassName", "com.netflix.loadbalancer.ConfigurationBasedServerList"){}; public static final IClientConfigKey<String> ServerListUpdaterClassName = new CommonClientConfigKey<String>("ServerListUpdaterClassName", "com.netflix.loadbalancer.PollingServerListUpdater"){}; public static final IClientConfigKey<String> NIWSServerListFilterClassName = new CommonClientConfigKey<String>("NIWSServerListFilterClassName"){}; public static final IClientConfigKey<Integer> ServerListRefreshInterval = new CommonClientConfigKey<Integer>("ServerListRefreshInterval"){}; public static final IClientConfigKey<Boolean> EnableMarkingServerDownOnReachingFailureLimit = new CommonClientConfigKey<Boolean>("EnableMarkingServerDownOnReachingFailureLimit"){}; public static final IClientConfigKey<Integer> ServerDownFailureLimit = new CommonClientConfigKey<Integer>("ServerDownFailureLimit"){}; public static final IClientConfigKey<Integer> ServerDownStatWindowInMillis = new CommonClientConfigKey<Integer>("ServerDownStatWindowInMillis"){}; public static final IClientConfigKey<Boolean> EnableZoneAffinity = new CommonClientConfigKey<Boolean>("EnableZoneAffinity", false){}; public static final IClientConfigKey<Boolean> EnableZoneExclusivity = new CommonClientConfigKey<Boolean>("EnableZoneExclusivity", false){}; public static final IClientConfigKey<Boolean> PrioritizeVipAddressBasedServers = new CommonClientConfigKey<Boolean>("PrioritizeVipAddressBasedServers", true){}; public static final IClientConfigKey<String> VipAddressResolverClassName = new CommonClientConfigKey<String>("VipAddressResolverClassName", "com.netflix.client.SimpleVipAddressResolver"){}; public static final IClientConfigKey<String> TargetRegion = new CommonClientConfigKey<String>("TargetRegion"){}; public static final IClientConfigKey<String> RulePredicateClasses = new CommonClientConfigKey<String>("RulePredicateClasses"){}; public static final IClientConfigKey<String> RequestIdHeaderName = new CommonClientConfigKey<String>("RequestIdHeaderName") {}; public static final IClientConfigKey<Boolean> UseIPAddrForServer = new CommonClientConfigKey<Boolean>("UseIPAddrForServer", false) {}; public static final IClientConfigKey<String> ListOfServers = new CommonClientConfigKey<String>("listOfServers", "") {}; private static final Set<IClientConfigKey> keys = new HashSet<IClientConfigKey>(); static { for (Field f: CommonClientConfigKey.class.getDeclaredFields()) { if (Modifier.isStatic(f.getModifiers()) //&& Modifier.isPublic(f.getModifiers()) && IClientConfigKey.class.isAssignableFrom(f.getType())) { try { keys.add((IClientConfigKey) f.get(null)); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } } /** * @deprecated see {@link #keys()} */ @edu.umd.cs.findbugs.annotations.SuppressWarnings @Deprecated public static IClientConfigKey[] values() { return keys().toArray(new IClientConfigKey[0]); } /** * return all the public static keys defined in this class */ public static Set<IClientConfigKey> keys() { return keys; } public static IClientConfigKey valueOf(final String name) { for (IClientConfigKey key: keys()) { if (key.key().equals(name)) { return key; } } return new IClientConfigKey() { @Override public String key() { return name; } @Override public Class type() { return String.class; } }; } private final String configKey; private final Class<T> type; private T defaultValue; @SuppressWarnings("unchecked") protected CommonClientConfigKey(String configKey) { this(configKey, null); } protected CommonClientConfigKey(String configKey, T defaultValue) { this.configKey = configKey; Type superclass = getClass().getGenericSuperclass(); checkArgument(superclass instanceof ParameterizedType, "%s isn't parameterized", superclass); Type runtimeType = ((ParameterizedType) superclass).getActualTypeArguments()[0]; type = (Class<T>) TypeToken.of(runtimeType).getRawType(); this.defaultValue = defaultValue; } @Override public Class<T> type() { return type; } /* (non-Javadoc) * @see com.netflix.niws.client.ClientConfig#key() */ @Override public String key() { return configKey; } @Override public String toString() { return configKey; } @Override public T defaultValue() { return defaultValue; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CommonClientConfigKey<?> that = (CommonClientConfigKey<?>) o; return Objects.equals(configKey, that.configKey); } @Override public int hashCode() { return Objects.hash(configKey); } }
6,957
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/config/PropertyUtils.java
package com.netflix.client.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; public class PropertyUtils { private static Logger LOG = LoggerFactory.getLogger(PropertyUtils.class); private PropertyUtils() {} /** * Returns the internal property to the desiredn type */ private static Map<Class<?>, Optional<Method>> valueOfMethods = new ConcurrentHashMap<>(); public static <T> Optional<T> resolveWithValueOf(Class<T> type, String value) { return valueOfMethods.computeIfAbsent(type, ignore -> { try { return Optional.of(type.getDeclaredMethod("valueOf", String.class)); } catch (NoSuchMethodException e) { return Optional.empty(); } catch (Exception e) { LOG.warn("Unable to determine if type " + type + " has a valueOf() static method", e); return Optional.empty(); } }).map(method -> { try { return (T)method.invoke(null, value); } catch (Exception e) { throw new RuntimeException(e); } }); } }
6,958
0
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client
Create_ds/ribbon/ribbon-core/src/main/java/com/netflix/client/http/UnexpectedHttpResponseException.java
package com.netflix.client.http; public class UnexpectedHttpResponseException extends Exception { /** * */ private static final long serialVersionUID = 1L; private final int statusCode; private final String line; public UnexpectedHttpResponseException(int statusCode, String statusLine) { super(statusLine); this.statusCode = statusCode; this.line = statusLine; } public int getStatusCode() { return statusCode; } public String getStatusLine() { return this.line; } }
6,959
0
Create_ds/ribbon/ribbon-examples/src/test/java/com/netflix/ribbon/examples
Create_ds/ribbon/ribbon-examples/src/test/java/com/netflix/ribbon/examples/rx/RxMovieServerTest.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.ribbon.examples.rx; import com.netflix.ribbon.examples.rx.common.Movie; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.util.internal.ConcurrentSet; import io.reactivex.netty.RxNetty; import io.reactivex.netty.channel.StringTransformer; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import io.reactivex.netty.protocol.http.server.HttpServer; import org.junit.After; import org.junit.Before; import org.junit.Test; import rx.Observable; import rx.functions.Func1; import java.nio.charset.Charset; import java.util.Random; import java.util.Set; import static com.netflix.ribbon.examples.rx.common.Movie.*; import static junit.framework.Assert.*; /** * @author Tomasz Bak */ public class RxMovieServerTest { private static final String TEST_USER_ID = "user1"; private static final Random RANDOM = new Random(); private int port = RANDOM.nextInt(1000) + 8000; private String baseURL = "http://localhost:" + port; private RxMovieServer movieServer; private HttpServer<ByteBuf, ByteBuf> httpServer; @Before public void setUp() throws Exception { movieServer = new RxMovieServer(port); httpServer = movieServer.createServer().start(); } @After public void tearDown() throws Exception { httpServer.shutdown(); } @Test public void testMovieRegistration() { String movieFormatted = ORANGE_IS_THE_NEW_BLACK.toString(); HttpResponseStatus statusCode = RxNetty.createHttpPost(baseURL + "/movies", Observable.just(movieFormatted), new StringTransformer()) .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<HttpResponseStatus>>() { @Override public Observable<HttpResponseStatus> call(HttpClientResponse<ByteBuf> httpClientResponse) { return Observable.just(httpClientResponse.getStatus()); } }).toBlocking().first(); assertEquals(HttpResponseStatus.CREATED, statusCode); assertEquals(ORANGE_IS_THE_NEW_BLACK, movieServer.movies.get(ORANGE_IS_THE_NEW_BLACK.getId())); } @Test public void testUpateRecommendations() { movieServer.movies.put(ORANGE_IS_THE_NEW_BLACK.getId(), ORANGE_IS_THE_NEW_BLACK); HttpResponseStatus statusCode = RxNetty.createHttpPost(baseURL + "/users/" + TEST_USER_ID + "/recommendations", Observable.just(ORANGE_IS_THE_NEW_BLACK.getId()), new StringTransformer()) .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<HttpResponseStatus>>() { @Override public Observable<HttpResponseStatus> call(HttpClientResponse<ByteBuf> httpClientResponse) { return Observable.just(httpClientResponse.getStatus()); } }).toBlocking().first(); assertEquals(HttpResponseStatus.OK, statusCode); assertTrue(movieServer.userRecommendations.get(TEST_USER_ID).contains(ORANGE_IS_THE_NEW_BLACK.getId())); } @Test public void testRecommendationsByUserId() throws Exception { movieServer.movies.put(ORANGE_IS_THE_NEW_BLACK.getId(), ORANGE_IS_THE_NEW_BLACK); movieServer.movies.put(BREAKING_BAD.getId(), BREAKING_BAD); Set<String> userRecom = new ConcurrentSet<String>(); userRecom.add(ORANGE_IS_THE_NEW_BLACK.getId()); userRecom.add(BREAKING_BAD.getId()); movieServer.userRecommendations.put(TEST_USER_ID, userRecom); Observable<HttpClientResponse<ByteBuf>> httpGet = RxNetty.createHttpGet(baseURL + "/users/" + TEST_USER_ID + "/recommendations"); Movie[] movies = handleGetMoviesReply(httpGet); assertTrue(movies[0] != movies[1]); assertTrue(userRecom.contains(movies[0].getId())); assertTrue(userRecom.contains(movies[1].getId())); } @Test public void testRecommendationsByMultipleCriteria() throws Exception { movieServer.movies.put(ORANGE_IS_THE_NEW_BLACK.getId(), ORANGE_IS_THE_NEW_BLACK); movieServer.movies.put(BREAKING_BAD.getId(), BREAKING_BAD); movieServer.movies.put(HOUSE_OF_CARDS.getId(), HOUSE_OF_CARDS); String relativeURL = String.format("/recommendations?category=%s&ageGroup=%s", BREAKING_BAD.getCategory(), BREAKING_BAD.getAgeGroup()); Movie[] movies = handleGetMoviesReply(RxNetty.createHttpGet(baseURL + relativeURL)); assertEquals(1, movies.length); assertEquals(BREAKING_BAD, movies[0]); } private Movie[] handleGetMoviesReply(Observable<HttpClientResponse<ByteBuf>> httpGet) { return httpGet .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<Movie[]>>() { @Override public Observable<Movie[]> call(HttpClientResponse<ByteBuf> httpClientResponse) { return httpClientResponse.getContent().map(new Func1<ByteBuf, Movie[]>() { @Override public Movie[] call(ByteBuf byteBuf) { String[] lines = byteBuf.toString(Charset.defaultCharset()).split("\n"); Movie[] movies = new Movie[lines.length]; for (int i = 0; i < movies.length; i++) { movies[i] = Movie.from(lines[i]); } return movies; } }); } }).toBlocking().first(); } }
6,960
0
Create_ds/ribbon/ribbon-examples/src/test/java/com/netflix/ribbon/examples
Create_ds/ribbon/ribbon-examples/src/test/java/com/netflix/ribbon/examples/rx/RxMovieClientTestBase.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.ribbon.examples.rx; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.server.HttpServer; import org.junit.After; import org.junit.Before; /** * @author Tomasz Bak */ public class RxMovieClientTestBase { protected int port = 0; private RxMovieServer movieServer; private HttpServer<ByteBuf, ByteBuf> httpServer; @Before public void setUp() throws Exception { movieServer = new RxMovieServer(port); httpServer = movieServer.createServer().start(); port = httpServer.getServerPort(); } @After public void tearDown() throws Exception { httpServer.shutdown(); } }
6,961
0
Create_ds/ribbon/ribbon-examples/src/test/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-examples/src/test/java/com/netflix/ribbon/examples/rx/transport/RxMovieTransportExampleTest.java
package com.netflix.ribbon.examples.rx.transport; import com.netflix.ribbon.examples.rx.RxMovieClientTestBase; import org.junit.Test; import static junit.framework.Assert.*; /** * @author Tomasz Bak */ public class RxMovieTransportExampleTest extends RxMovieClientTestBase { @Test public void testTemplateExample() throws Exception { assertTrue(new RxMovieTransportExample(port).runExample()); } }
6,962
0
Create_ds/ribbon/ribbon-examples/src/test/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-examples/src/test/java/com/netflix/ribbon/examples/rx/proxy/RxMovieProxyExampleTest.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.ribbon.examples.rx.proxy; import com.netflix.ribbon.examples.rx.RxMovieClientTestBase; import org.junit.Test; import static junit.framework.Assert.*; /** * @author Tomasz Bak */ public class RxMovieProxyExampleTest extends RxMovieClientTestBase { @Test public void testProxyExample() throws Exception { assertTrue(new RxMovieProxyExample(port).runExample()); } }
6,963
0
Create_ds/ribbon/ribbon-examples/src/test/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-examples/src/test/java/com/netflix/ribbon/examples/rx/template/RxMovieTemplateExampleTest.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.ribbon.examples.rx.template; import com.netflix.ribbon.examples.rx.RxMovieClientTestBase; import org.junit.Test; import static junit.framework.Assert.*; /** * @author Tomasz Bak */ public class RxMovieTemplateExampleTest extends RxMovieClientTestBase { @Test public void testTemplateExample() throws Exception { assertTrue(new RxMovieTemplateExample(port).runExample()); } }
6,964
0
Create_ds/ribbon/ribbon-examples/src/test/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-examples/src/test/java/com/netflix/ribbon/examples/rx/common/MovieTest.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.ribbon.examples.rx.common; import org.junit.Test; import static com.netflix.ribbon.examples.rx.common.Movie.*; import static org.junit.Assert.*; /** * @author Tomasz Bak */ public class MovieTest { @Test public void testStringParsing() { Movie fromString = Movie.from(ORANGE_IS_THE_NEW_BLACK.toString()); assertEquals(ORANGE_IS_THE_NEW_BLACK, fromString); } }
6,965
0
Create_ds/ribbon/ribbon-examples/src/test/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-examples/src/test/java/com/netflix/ribbon/examples/rx/common/RecommendationsTest.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.ribbon.examples.rx.common; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static junit.framework.Assert.*; /** * @author Tomasz Bak */ public class RecommendationsTest { @Test public void testStringParsing() throws Exception { List<Movie> movies = new ArrayList<Movie>(); movies.add(Movie.ORANGE_IS_THE_NEW_BLACK); movies.add(Movie.BREAKING_BAD); Recommendations recommendations = new Recommendations(movies); Recommendations fromString = Recommendations.from(recommendations.toString()); assertEquals(recommendations, fromString); } }
6,966
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/ExampleAppWithLocalResource.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.ribbon.examples; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.sun.jersey.api.container.httpserver.HttpServerFactory; import com.sun.jersey.api.core.PackagesResourceConfig; import com.sun.net.httpserver.HttpServer; /** * A base class for some sample applications that starts and stops a local server * * @author awang * */ public abstract class ExampleAppWithLocalResource { public int port = (new Random()).nextInt(1000) + 4000; public String SERVICE_URI = "http://localhost:" + port + "/"; HttpServer server = null; public abstract void run() throws Exception; @edu.umd.cs.findbugs.annotations.SuppressWarnings public final void runApp() throws Exception { PackagesResourceConfig resourceConfig = new PackagesResourceConfig("com.netflix.ribbon.examples.server"); ExecutorService service = Executors.newFixedThreadPool(50); try{ server = HttpServerFactory.create(SERVICE_URI, resourceConfig); server.setExecutor(service); server.start(); run(); } finally { System.err.println("Shut down server ..."); if (server != null) { server.stop(1); } service.shutdownNow(); } System.exit(0); } }
6,967
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/loadbalancer/URLConnectionLoadBalancer.java
package com.netflix.ribbon.examples.loadbalancer; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import rx.Observable; import com.google.common.collect.Lists; import com.netflix.client.DefaultLoadBalancerRetryHandler; import com.netflix.client.RetryHandler; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.LoadBalancerBuilder; import com.netflix.loadbalancer.LoadBalancerStats; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.reactive.LoadBalancerCommand; import com.netflix.loadbalancer.reactive.ServerOperation; /** * * @author Allen Wang * */ public class URLConnectionLoadBalancer { private final ILoadBalancer loadBalancer; // retry handler that does not retry on same server, but on a different server private final RetryHandler retryHandler = new DefaultLoadBalancerRetryHandler(0, 1, true); public URLConnectionLoadBalancer(List<Server> serverList) { loadBalancer = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(serverList); } public String call(final String path) throws Exception { return LoadBalancerCommand.<String>builder() .withLoadBalancer(loadBalancer) .build() .submit(new ServerOperation<String>() { @Override public Observable<String> call(Server server) { URL url; try { url = new URL("http://" + server.getHost() + ":" + server.getPort() + path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); return Observable.just(conn.getResponseMessage()); } catch (Exception e) { return Observable.error(e); } } }).toBlocking().first(); } public LoadBalancerStats getLoadBalancerStats() { return ((BaseLoadBalancer) loadBalancer).getLoadBalancerStats(); } public static void main(String[] args) throws Exception { URLConnectionLoadBalancer urlLoadBalancer = new URLConnectionLoadBalancer(Lists.newArrayList( new Server("www.google.com", 80), new Server("www.linkedin.com", 80), new Server("www.yahoo.com", 80))); for (int i = 0; i < 6; i++) { System.out.println(urlLoadBalancer.call("/")); } System.out.println("=== Load balancer stats ==="); System.out.println(urlLoadBalancer.getLoadBalancerStats()); } }
6,968
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/server/ServerResources.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.ribbon.examples.server; import java.io.IOException; import java.io.OutputStream; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import org.codehaus.jackson.map.ObjectMapper; import com.google.common.collect.Lists; import com.thoughtworks.xstream.XStream; @Path("/testAsync") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class ServerResources { public static class Person { public String name; public int age; public Person() {} public Person(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } private static ObjectMapper mapper = new ObjectMapper(); public static final Person defaultPerson = new Person("ribbon", 1); public static final List<Person> persons = Lists.newArrayList(); public static final List<String> streamContent = Lists.newArrayList(); static { for (int i = 0; i < 1000; i++) { streamContent.add("data: line " + i); } for (int i = 0; i < 100; i++) { persons.add(new Person(String.valueOf(i), 10)); } } @GET @Path("/person") public Response getPerson() throws IOException { String content = mapper.writeValueAsString(defaultPerson); return Response.ok(content).build(); } @GET @Path("/persons") public Response getPersons() throws IOException { String content = mapper.writeValueAsString(persons); return Response.ok(content).build(); } @GET @Path("/noEntity") public Response getNoEntity() { return Response.ok().build(); } @GET @Path("/readTimeout") public Response getReadTimeout() throws IOException, InterruptedException { Thread.sleep(10000); String content = mapper.writeValueAsString(defaultPerson); return Response.ok(content).build(); } @POST @Path("/person") public Response createPerson(String content) throws IOException { System.err.println("uploaded: " + content); Person person = mapper.readValue(content, Person.class); return Response.ok(mapper.writeValueAsString(person)).build(); } @GET @Path("/personQuery") public Response queryPerson(@QueryParam("name") String name, @QueryParam("age") int age) throws IOException { Person person = new Person(name, age); return Response.ok(mapper.writeValueAsString(person)).build(); } @GET @Path("/stream") @Produces("text/event-stream") public StreamingOutput getStream() { return new StreamingOutput() { @Override public void write(OutputStream output) throws IOException, WebApplicationException { for (String line: streamContent) { String eventLine = line + "\n\n"; output.write(eventLine.getBytes("UTF-8")); } output.close(); } }; } @GET @Path("/personStream") @Produces("text/event-stream") public StreamingOutput getPersonStream() { return new StreamingOutput() { @Override public void write(OutputStream output) throws IOException, WebApplicationException { for (Person p: persons) { String eventLine = "data: " + mapper.writeValueAsString(p) + "\n\n"; output.write(eventLine.getBytes("UTF-8")); } output.close(); } }; } @GET @Path("/customEvent") public StreamingOutput getCustomeEvents() { return new StreamingOutput() { @Override public void write(OutputStream output) throws IOException, WebApplicationException { for (String line: streamContent) { String eventLine = line + "\n"; output.write(eventLine.getBytes("UTF-8")); } output.close(); } }; } @GET @Path("/getXml") @Produces("application/xml") public Response getXml() { XStream xstream = new XStream(); String content = xstream.toXML(new Person("I am from XML", 1)); return Response.ok(content).build(); } }
6,969
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/netty
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/netty/http/LoadBalancingExample.java
package com.netflix.ribbon.examples.netty.http; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import java.util.List; import java.util.concurrent.CountDownLatch; import rx.Observer; import com.google.common.collect.Lists; import com.netflix.ribbon.transport.netty.RibbonTransport; import com.netflix.ribbon.transport.netty.http.LoadBalancingHttpClient; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.LoadBalancerBuilder; import com.netflix.loadbalancer.Server; public class LoadBalancingExample { public static void main(String[] args) throws Exception { List<Server> servers = Lists.newArrayList(new Server("www.google.com:80"), new Server("www.examples.com:80"), new Server("www.wikipedia.org:80")); BaseLoadBalancer lb = LoadBalancerBuilder.newBuilder() .buildFixedServerListLoadBalancer(servers); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb); final CountDownLatch latch = new CountDownLatch(servers.size()); Observer<HttpClientResponse<ByteBuf>> observer = new Observer<HttpClientResponse<ByteBuf>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { e.printStackTrace(); } @Override public void onNext(HttpClientResponse<ByteBuf> args) { latch.countDown(); System.out.println("Got response: " + args.getStatus()); } }; for (int i = 0; i < servers.size(); i++) { HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/"); client.submit(request).subscribe(observer); } latch.await(); System.out.println(lb.getLoadBalancerStats()); } }
6,970
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/netty
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/netty/http/SimpleGet.java
package com.netflix.ribbon.examples.netty.http; import com.netflix.ribbon.transport.netty.RibbonTransport; import com.netflix.ribbon.transport.netty.http.LoadBalancingHttpClient; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import rx.functions.Action1; import java.nio.charset.Charset; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class SimpleGet { @edu.umd.cs.findbugs.annotations.SuppressWarnings public static void main(String[] args) throws Exception { LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("http://www.google.com/"); final CountDownLatch latch = new CountDownLatch(1); client.submit(request) .toBlocking() .forEach(new Action1<HttpClientResponse<ByteBuf>>() { @Override public void call(HttpClientResponse<ByteBuf> t1) { System.out.println("Status code: " + t1.getStatus()); t1.getContent().subscribe(new Action1<ByteBuf>() { @Override public void call(ByteBuf content) { System.out.println("Response content: " + content.toString(Charset.defaultCharset())); latch.countDown(); } }); } }); latch.await(2, TimeUnit.SECONDS); } }
6,971
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/restclient/SampleApp.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.ribbon.examples.restclient; import java.net.URI; import com.netflix.client.ClientFactory; import com.netflix.client.http.HttpRequest; import com.netflix.client.http.HttpResponse; import com.netflix.config.ConfigurationManager; import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import com.netflix.niws.client.http.RestClient; public class SampleApp { public static void main(String[] args) throws Exception { ConfigurationManager.loadPropertiesFromResources("sample-client.properties"); // 1 System.out.println(ConfigurationManager.getConfigInstance().getProperty("sample-client.ribbon.listOfServers")); RestClient client = (RestClient) ClientFactory.getNamedClient("sample-client"); // 2 HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build(); // 3 for (int i = 0; i < 20; i++) { HttpResponse response = client.executeWithLoadBalancer(request); // 4 System.out.println("Status code for " + response.getRequestedURI() + " :" + response.getStatus()); } @SuppressWarnings("rawtypes") ZoneAwareLoadBalancer lb = (ZoneAwareLoadBalancer) client.getLoadBalancer(); System.out.println(lb.getLoadBalancerStats()); ConfigurationManager.getConfigInstance().setProperty( "sample-client.ribbon.listOfServers", "www.linkedin.com:80,www.google.com:80"); // 5 System.out.println("changing servers ..."); Thread.sleep(3000); // 6 for (int i = 0; i < 20; i++) { HttpResponse response = null; try { response = client.executeWithLoadBalancer(request); System.out.println("Status code for " + response.getRequestedURI() + " : " + response.getStatus()); } finally { if (response != null) { response.close(); } } } System.out.println(lb.getLoadBalancerStats()); // 7 } }
6,972
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx/AbstractRxMovieClient.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.ribbon.examples.rx; import com.netflix.hystrix.util.HystrixTimer; import com.netflix.ribbon.examples.rx.common.Movie; import io.netty.buffer.ByteBuf; import rx.Notification; import rx.Observable; import rx.functions.Func1; import rx.functions.Func2; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; import static java.lang.String.*; /** * Base class for the transport/template and proxy examples. It orchestrates application flow, and * handles result(s) from the server. The request execution is implemented in the derived classes, in a way * specific for each API abstration. This separation of concerns makes it is easy to compare complexity of different APIs. * * @author Tomasz Bak */ public abstract class AbstractRxMovieClient { protected static final String TEST_USER = "user1"; protected static final Pattern NEW_LINE_SPLIT_RE = Pattern.compile("\n"); protected abstract Observable<ByteBuf>[] triggerMoviesRegistration(); protected abstract Observable<ByteBuf>[] triggerRecommendationsUpdate(); protected abstract Observable<ByteBuf>[] triggerRecommendationsSearch(); protected Observable<ByteBuf> registerMovies() { return Observable.concat(Observable.from(triggerMoviesRegistration())); } protected Observable<ByteBuf> updateRecommendations() { return Observable.concat(Observable.from(triggerRecommendationsUpdate())); } protected Observable<Void> searchCatalog() { List<String> searches = new ArrayList<String>(2); Collections.addAll(searches, "findById", "findRawMovieById", "findMovie(name, category)"); return Observable .concat(Observable.from(triggerRecommendationsSearch())) .flatMap(new Func1<ByteBuf, Observable<List<Movie>>>() { @Override public Observable<List<Movie>> call(ByteBuf byteBuf) { List<Movie> movies = new ArrayList<Movie>(); String lines = byteBuf.toString(Charset.defaultCharset()); for (String line : NEW_LINE_SPLIT_RE.split(lines)) { movies.add(Movie.from(line)); } return Observable.just(movies); } }) .zipWith(searches, new Func2<List<Movie>, String, Void>() { @Override public Void call(List<Movie> movies, String query) { System.out.println(format(" %s=%s", query, movies)); return null; } }); } public boolean runExample() { boolean allGood = true; try { System.out.println("Registering movies..."); Notification<Void> result = executeServerCalls(); allGood = !result.isOnError(); if (allGood) { System.out.println("Application finished"); } else { System.err.println("ERROR: execution failure"); result.getThrowable().printStackTrace(); } } catch (Exception e) { e.printStackTrace(); allGood = false; } finally { shutdown(); } return allGood; } Notification<Void> executeServerCalls() { Observable<Void> resultObservable = registerMovies().materialize().flatMap( new Func1<Notification<ByteBuf>, Observable<Void>>() { @Override public Observable<Void> call(Notification<ByteBuf> notif) { if (!verifyStatus(notif)) { return Observable.error(notif.getThrowable()); } System.out.print("Updating user recommendations..."); return updateRecommendations().materialize().flatMap( new Func1<Notification<ByteBuf>, Observable<Void>>() { @Override public Observable<Void> call(Notification<ByteBuf> notif) { if (!verifyStatus(notif)) { return Observable.error(notif.getThrowable()); } System.out.println("Searching through the movie catalog..."); return searchCatalog(); } }); } } ); return resultObservable.materialize().toBlocking().last(); } protected void shutdown() { HystrixTimer.reset(); } private static boolean verifyStatus(Notification<ByteBuf> notif) { if (notif.isOnError()) { System.out.println("ERROR"); return false; } System.out.println("DONE"); return true; } }
6,973
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx/RxMovieServer.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.ribbon.examples.rx; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.netflix.ribbon.examples.rx.common.Movie; import io.netty.buffer.ByteBuf; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.logging.LogLevel; import io.netty.util.internal.ConcurrentSet; import io.reactivex.netty.RxNetty; import io.reactivex.netty.pipeline.PipelineConfigurators; import io.reactivex.netty.protocol.http.server.HttpServer; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.server.RequestHandler; import rx.Observable; import rx.functions.Func1; import static java.lang.String.*; /** * The client examples assume that the movie server runs on the default port 8080. * * @author Tomasz Bak */ public class RxMovieServer { public static final int DEFAULT_PORT = 8080; private static final Pattern USER_RECOMMENDATIONS_PATH_RE = Pattern.compile(".*/users/([^/]*)/recommendations"); private final int port; final Map<String, Movie> movies = new ConcurrentHashMap<String, Movie>(); final Map<String, Set<String>> userRecommendations = new ConcurrentHashMap<String, Set<String>>(); public RxMovieServer(int port) { this.port = port; } public HttpServer<ByteBuf, ByteBuf> createServer() { HttpServer<ByteBuf, ByteBuf> server = RxNetty.newHttpServerBuilder(port, new RequestHandler<ByteBuf, ByteBuf>() { @Override public Observable<Void> handle(HttpServerRequest<ByteBuf> request, final HttpServerResponse<ByteBuf> response) { if (request.getPath().contains("/users")) { if (request.getHttpMethod().equals(HttpMethod.GET)) { return handleRecommendationsByUserId(request, response); } else { return handleUpdateRecommendationsForUser(request, response); } } if (request.getPath().contains("/recommendations")) { return handleRecommendationsBy(request, response); } if (request.getPath().contains("/movies")) { return handleRegisterMovie(request, response); } response.setStatus(HttpResponseStatus.NOT_FOUND); return response.close(); } }).pipelineConfigurator(PipelineConfigurators.<ByteBuf, ByteBuf>httpServerConfigurator()).enableWireLogging(LogLevel.ERROR).build(); System.out.println("RxMovie server started..."); return server; } private Observable<Void> handleRecommendationsByUserId(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) { System.out.println("HTTP request -> recommendations by user id request: " + request.getPath()); final String userId = userIdFromPath(request.getPath()); if (userId == null) { response.setStatus(HttpResponseStatus.BAD_REQUEST); return response.close(); } if (!userRecommendations.containsKey(userId)) { response.setStatus(HttpResponseStatus.NOT_FOUND); return response.close(); } StringBuilder builder = new StringBuilder(); for (String movieId : userRecommendations.get(userId)) { System.out.println(" returning: " + movies.get(movieId)); builder.append(movies.get(movieId)).append('\n'); } ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.buffer(); byteBuf.writeBytes(builder.toString().getBytes(Charset.defaultCharset())); response.write(byteBuf); return response.close(); } private Observable<Void> handleRecommendationsBy(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) { System.out.println(format("HTTP request -> recommendations by multiple criteria: %s?%s", request.getPath(), request.getQueryString())); List<String> category = request.getQueryParameters().get("category"); List<String> ageGroup = request.getQueryParameters().get("ageGroup"); if (category.isEmpty() || ageGroup.isEmpty()) { response.setStatus(HttpResponseStatus.BAD_REQUEST); return response.close(); } boolean any = false; StringBuilder builder = new StringBuilder(); for (Movie movie : movies.values()) { if (movie.getCategory().equals(category.get(0)) && movie.getAgeGroup().equals(ageGroup.get(0))) { System.out.println(" returning: " + movie); builder.append(movie).append('\n'); any = true; } } if (!any) { System.out.println("No movie matched the given criteria:"); for (Movie movie : movies.values()) { System.out.print(" "); System.out.println(movie); } } ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.buffer(); byteBuf.writeBytes(builder.toString().getBytes(Charset.defaultCharset())); response.write(byteBuf); return response.close(); } private Observable<Void> handleUpdateRecommendationsForUser(HttpServerRequest<ByteBuf> request, final HttpServerResponse<ByteBuf> response) { System.out.println("HTTP request -> update recommendations for user: " + request.getPath()); final String userId = userIdFromPath(request.getPath()); if (userId == null) { response.setStatus(HttpResponseStatus.BAD_REQUEST); return response.close(); } return request.getContent().flatMap(new Func1<ByteBuf, Observable<Void>>() { @Override public Observable<Void> call(ByteBuf byteBuf) { String movieId = byteBuf.toString(Charset.defaultCharset()); System.out.println(format(" updating: {user=%s, movie=%s}", userId, movieId)); synchronized (this) { Set<String> recommendations; if (userRecommendations.containsKey(userId)) { recommendations = userRecommendations.get(userId); } else { recommendations = new ConcurrentSet<String>(); userRecommendations.put(userId, recommendations); } recommendations.add(movieId); } response.setStatus(HttpResponseStatus.OK); return response.close(); } }); } private Observable<Void> handleRegisterMovie(HttpServerRequest<ByteBuf> request, final HttpServerResponse<ByteBuf> response) { System.out.println("Http request -> register movie: " + request.getPath()); return request.getContent().flatMap(new Func1<ByteBuf, Observable<Void>>() { @Override public Observable<Void> call(ByteBuf byteBuf) { String formatted = byteBuf.toString(Charset.defaultCharset()); System.out.println(" movie: " + formatted); try { Movie movie = Movie.from(formatted); movies.put(movie.getId(), movie); response.setStatus(HttpResponseStatus.CREATED); } catch (Exception e) { System.err.println("Invalid movie content"); e.printStackTrace(); response.setStatus(HttpResponseStatus.BAD_REQUEST); } return response.close(); } }); } private static String userIdFromPath(String path) { Matcher matcher = USER_RECOMMENDATIONS_PATH_RE.matcher(path); return matcher.matches() ? matcher.group(1) : null; } public static void main(final String[] args) { new RxMovieServer(DEFAULT_PORT).createServer().startAndWait(); } }
6,974
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx/transport/RxMovieTransportExample.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.ribbon.examples.rx.transport; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.ribbon.transport.netty.RibbonTransport; import com.netflix.ribbon.transport.netty.http.LoadBalancingHttpClient; import com.netflix.ribbon.examples.rx.AbstractRxMovieClient; import com.netflix.ribbon.examples.rx.RxMovieServer; import com.netflix.ribbon.examples.rx.common.Movie; import com.netflix.ribbon.examples.rx.common.RxMovieTransformer; import io.netty.buffer.ByteBuf; import io.reactivex.netty.channel.StringTransformer; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import rx.Observable; import rx.functions.Func1; import static java.lang.String.*; /** * Run {@link com.netflix.ribbon.examples.rx.RxMovieServer} prior to runnng this example! * * @author Tomasz Bak */ public class RxMovieTransportExample extends AbstractRxMovieClient { private final LoadBalancingHttpClient<ByteBuf, ByteBuf> client; public RxMovieTransportExample(int port) { IClientConfig clientConfig = IClientConfig.Builder.newBuilder("movieServiceClient").build(); clientConfig.set(CommonClientConfigKey.ListOfServers, "localhost:" + port); client = RibbonTransport.newHttpClient(clientConfig); } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerMoviesRegistration() { return new Observable[]{ registerMovie(Movie.ORANGE_IS_THE_NEW_BLACK), registerMovie(Movie.BREAKING_BAD), registerMovie(Movie.HOUSE_OF_CARDS) }; } private Observable<Void> registerMovie(Movie movie) { HttpClientRequest<ByteBuf> httpRequest = HttpClientRequest.createPost("/movies") .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc") .withRawContentSource(Observable.just(movie), new RxMovieTransformer()); return client.submit(httpRequest).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<Void>>() { @Override public Observable<Void> call(HttpClientResponse<ByteBuf> httpClientResponse) { if (httpClientResponse.getStatus().code() / 100 != 2) { return Observable.error(new RuntimeException( format("HTTP request failed (status code=%s)", httpClientResponse.getStatus()))); } return Observable.empty(); } }); } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerRecommendationsUpdate() { return new Observable[]{ updateRecommendation(TEST_USER, Movie.ORANGE_IS_THE_NEW_BLACK), updateRecommendation(TEST_USER, Movie.BREAKING_BAD) }; } private Observable<Void> updateRecommendation(String user, Movie movie) { HttpClientRequest<ByteBuf> httpRequest = HttpClientRequest.createPost(format("/users/%s/recommendations", user)) .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc") .withRawContentSource(Observable.just(movie.getId()), new StringTransformer()); return client.submit(httpRequest).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<Void>>() { @Override public Observable<Void> call(HttpClientResponse<ByteBuf> httpClientResponse) { if (httpClientResponse.getStatus().code() / 100 != 2) { return Observable.error(new RuntimeException( format("HTTP request failed (status code=%s)", httpClientResponse.getStatus()))); } return Observable.empty(); } }); } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerRecommendationsSearch() { HttpClientRequest<ByteBuf> httpRequest = HttpClientRequest.createGet(format("/users/%s/recommendations", TEST_USER)) .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc"); Observable<ByteBuf> searchByUserObservable = client.submit(httpRequest).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>>() { @Override public Observable<ByteBuf> call(HttpClientResponse<ByteBuf> httpClientResponse) { if (httpClientResponse.getStatus().code() / 100 != 2) { return Observable.error(new RuntimeException( format("HTTP request failed (status code=%s)", httpClientResponse.getStatus()))); } return httpClientResponse.getContent(); } }); httpRequest = HttpClientRequest.createGet("/recommendations?category=Drama&ageGroup=Adults") .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc"); Observable<ByteBuf> searchByCriteriaObservable = client.submit(httpRequest).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>>() { @Override public Observable<ByteBuf> call(HttpClientResponse<ByteBuf> httpClientResponse) { if (httpClientResponse.getStatus().code() / 100 != 2) { return Observable.error(new RuntimeException( format("HTTP request failed (status code=%s)", httpClientResponse.getStatus()))); } return httpClientResponse.getContent(); } }); return new Observable[]{searchByUserObservable, searchByCriteriaObservable}; } public static void main(String[] args) { System.out.println("Starting transport based movie service..."); new RxMovieTransportExample(RxMovieServer.DEFAULT_PORT).runExample(); } }
6,975
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx/proxy/MovieService.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.ribbon.examples.rx.proxy; import com.netflix.ribbon.RibbonRequest; import com.netflix.ribbon.examples.rx.common.InMemoryCacheProviderFactory; import com.netflix.ribbon.examples.rx.common.Movie; import com.netflix.ribbon.examples.rx.common.RecommendationServiceFallbackHandler; import com.netflix.ribbon.examples.rx.common.RecommendationServiceResponseValidator; import com.netflix.ribbon.examples.rx.common.RxMovieTransformer; import com.netflix.ribbon.proxy.annotation.CacheProvider; import com.netflix.ribbon.proxy.annotation.ClientProperties; import com.netflix.ribbon.proxy.annotation.ClientProperties.Property; import com.netflix.ribbon.proxy.annotation.Content; import com.netflix.ribbon.proxy.annotation.ContentTransformerClass; import com.netflix.ribbon.proxy.annotation.Http; import com.netflix.ribbon.proxy.annotation.Http.Header; import com.netflix.ribbon.proxy.annotation.Http.HttpMethod; import com.netflix.ribbon.proxy.annotation.Hystrix; import com.netflix.ribbon.proxy.annotation.TemplateName; import com.netflix.ribbon.proxy.annotation.Var; import io.netty.buffer.ByteBuf; /** * @author Tomasz Bak */ @ClientProperties(properties = { @Property(name="ReadTimeout", value="2000"), @Property(name="ConnectTimeout", value="1000"), @Property(name="MaxAutoRetriesNextServer", value="2") }, exportToArchaius = true) public interface MovieService { @TemplateName("recommendationsByUserId") @Http( method = HttpMethod.GET, uri = "/users/{userId}/recommendations", headers = { @Header(name = "X-Platform-Version", value = "xyz"), @Header(name = "X-Auth-Token", value = "abc") }) @Hystrix( validator = RecommendationServiceResponseValidator.class, fallbackHandler = RecommendationServiceFallbackHandler.class) @CacheProvider(key = "{userId}", provider = InMemoryCacheProviderFactory.class) RibbonRequest<ByteBuf> recommendationsByUserId(@Var("userId") String userId); @TemplateName("recommendationsBy") @Http( method = HttpMethod.GET, uri = "/recommendations?category={category}&ageGroup={ageGroup}", headers = { @Header(name = "X-Platform-Version", value = "xyz"), @Header(name = "X-Auth-Token", value = "abc") }) @Hystrix( validator = RecommendationServiceResponseValidator.class, fallbackHandler = RecommendationServiceFallbackHandler.class) @CacheProvider(key = "{category},{ageGroup}", provider = InMemoryCacheProviderFactory.class) RibbonRequest<ByteBuf> recommendationsBy(@Var("category") String category, @Var("ageGroup") String ageGroup); @TemplateName("registerMovie") @Http( method = HttpMethod.POST, uri = "/movies", headers = { @Header(name = "X-Platform-Version", value = "xyz"), @Header(name = "X-Auth-Token", value = "abc") }) @Hystrix(validator = RecommendationServiceResponseValidator.class) @ContentTransformerClass(RxMovieTransformer.class) RibbonRequest<ByteBuf> registerMovie(@Content Movie movie); @TemplateName("updateRecommendations") @Http( method = HttpMethod.POST, uri = "/users/{userId}/recommendations", headers = { @Header(name = "X-Platform-Version", value = "xyz"), @Header(name = "X-Auth-Token", value = "abc") }) @Hystrix(validator = RecommendationServiceResponseValidator.class) RibbonRequest<ByteBuf> updateRecommendations(@Var("userId") String userId, @Content String movieId); }
6,976
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx/proxy/RxMovieProxyExample.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.ribbon.examples.rx.proxy; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.config.ConfigurationManager; import com.netflix.ribbon.Ribbon; import com.netflix.ribbon.examples.rx.AbstractRxMovieClient; import com.netflix.ribbon.examples.rx.RxMovieServer; import com.netflix.ribbon.examples.rx.common.Movie; import com.netflix.ribbon.proxy.ProxyLifeCycle; import io.netty.buffer.ByteBuf; import rx.Observable; /** * Run {@link com.netflix.ribbon.examples.rx.RxMovieServer} prior to running this example! * * @author Tomasz Bak */ public class RxMovieProxyExample extends AbstractRxMovieClient { private final MovieService movieService; public RxMovieProxyExample(int port) { ConfigurationManager.getConfigInstance().setProperty("MovieService.ribbon." + CommonClientConfigKey.MaxAutoRetriesNextServer, "3"); ConfigurationManager.getConfigInstance().setProperty("MovieService.ribbon." + CommonClientConfigKey.ListOfServers, "localhost:" + port); movieService = Ribbon.from(MovieService.class); } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerMoviesRegistration() { return new Observable[]{ movieService.registerMovie(Movie.ORANGE_IS_THE_NEW_BLACK).toObservable(), movieService.registerMovie(Movie.BREAKING_BAD).toObservable(), movieService.registerMovie(Movie.HOUSE_OF_CARDS).toObservable() }; } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerRecommendationsUpdate() { return new Observable[]{ movieService.updateRecommendations(TEST_USER, Movie.ORANGE_IS_THE_NEW_BLACK.getId()).toObservable(), movieService.updateRecommendations(TEST_USER, Movie.BREAKING_BAD.getId()).toObservable() }; } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerRecommendationsSearch() { return new Observable[]{ movieService.recommendationsByUserId(TEST_USER).toObservable(), movieService.recommendationsBy("Drama", "Adults").toObservable() }; } @Override public void shutdown() { super.shutdown(); ((ProxyLifeCycle) movieService).shutdown(); } public static void main(String[] args) { System.out.println("Starting proxy based movie service..."); new RxMovieProxyExample(RxMovieServer.DEFAULT_PORT).runExample(); } }
6,977
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx/template/RxMovieTemplateExample.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.ribbon.examples.rx.template; import com.netflix.ribbon.ClientOptions; import com.netflix.ribbon.Ribbon; import com.netflix.ribbon.examples.rx.AbstractRxMovieClient; import com.netflix.ribbon.examples.rx.RxMovieServer; import com.netflix.ribbon.examples.rx.common.Movie; import com.netflix.ribbon.examples.rx.common.RecommendationServiceFallbackHandler; import com.netflix.ribbon.examples.rx.common.RecommendationServiceResponseValidator; import com.netflix.ribbon.examples.rx.common.RxMovieTransformer; import com.netflix.ribbon.http.HttpRequestTemplate; import com.netflix.ribbon.http.HttpResourceGroup; import io.netty.buffer.ByteBuf; import io.reactivex.netty.channel.StringTransformer; import rx.Observable; /** * Run {@link com.netflix.ribbon.examples.rx.RxMovieServer} prior to runnng this example! * * @author Tomasz Bak */ public class RxMovieTemplateExample extends AbstractRxMovieClient { private final HttpResourceGroup httpResourceGroup; private final HttpRequestTemplate<ByteBuf> registerMovieTemplate; private final HttpRequestTemplate<ByteBuf> updateRecommendationTemplate; private final HttpRequestTemplate<ByteBuf> recommendationsByUserIdTemplate; private final HttpRequestTemplate<ByteBuf> recommendationsByTemplate; public RxMovieTemplateExample(int port) { httpResourceGroup = Ribbon.createHttpResourceGroup("movieServiceClient", ClientOptions.create() .withMaxAutoRetriesNextServer(3) .withConfigurationBasedServerList("localhost:" + port)); registerMovieTemplate = httpResourceGroup.newTemplateBuilder("registerMovie", ByteBuf.class) .withMethod("POST") .withUriTemplate("/movies") .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc") .withResponseValidator(new RecommendationServiceResponseValidator()).build(); updateRecommendationTemplate = httpResourceGroup.newTemplateBuilder("updateRecommendation", ByteBuf.class) .withMethod("POST") .withUriTemplate("/users/{userId}/recommendations") .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc") .withResponseValidator(new RecommendationServiceResponseValidator()).build(); recommendationsByUserIdTemplate = httpResourceGroup.newTemplateBuilder("recommendationsByUserId", ByteBuf.class) .withMethod("GET") .withUriTemplate("/users/{userId}/recommendations") .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc") .withFallbackProvider(new RecommendationServiceFallbackHandler()) .withResponseValidator(new RecommendationServiceResponseValidator()).build(); recommendationsByTemplate = httpResourceGroup.newTemplateBuilder("recommendationsBy", ByteBuf.class) .withMethod("GET") .withUriTemplate("/recommendations?category={category}&ageGroup={ageGroup}") .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc") .withFallbackProvider(new RecommendationServiceFallbackHandler()) .withResponseValidator(new RecommendationServiceResponseValidator()).build(); } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerMoviesRegistration() { return new Observable[]{ registerMovieTemplate.requestBuilder() .withRawContentSource(Observable.just(Movie.ORANGE_IS_THE_NEW_BLACK), new RxMovieTransformer()) .build().toObservable(), registerMovieTemplate.requestBuilder() .withRawContentSource(Observable.just(Movie.BREAKING_BAD), new RxMovieTransformer()) .build().toObservable(), registerMovieTemplate.requestBuilder() .withRawContentSource(Observable.just(Movie.HOUSE_OF_CARDS), new RxMovieTransformer()) .build().toObservable() }; } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerRecommendationsUpdate() { return new Observable[]{ updateRecommendationTemplate.requestBuilder() .withRawContentSource(Observable.just(Movie.ORANGE_IS_THE_NEW_BLACK.getId()), new StringTransformer()) .withRequestProperty("userId", TEST_USER) .build().toObservable(), updateRecommendationTemplate.requestBuilder() .withRawContentSource(Observable.just(Movie.BREAKING_BAD.getId()), new StringTransformer()) .withRequestProperty("userId", TEST_USER) .build().toObservable() }; } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerRecommendationsSearch() { return new Observable[]{ recommendationsByUserIdTemplate.requestBuilder() .withRequestProperty("userId", TEST_USER) .build().toObservable(), recommendationsByTemplate.requestBuilder() .withRequestProperty("category", "Drama") .withRequestProperty("ageGroup", "Adults") .build().toObservable() }; } public static void main(String[] args) { System.out.println("Starting templates based movie service..."); new RxMovieTemplateExample(RxMovieServer.DEFAULT_PORT).runExample(); } }
6,978
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx/common/Recommendations.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.ribbon.examples.rx.common; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Tomasz Bak */ public class Recommendations { private static final Pattern FORMAT_RE = Pattern.compile("\\{movies=\\[(\\{[^\\}]*\\})?(, \\{[^\\}]*\\})*\\]\\}"); private final List<Movie> movies; public Recommendations(List<Movie> movies) { this.movies = Collections.unmodifiableList(movies); } public List<Movie> getMovies() { return movies; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Recommendations that = (Recommendations) o; if (movies != null ? !movies.equals(that.movies) : that.movies != null) return false; return true; } @Override public int hashCode() { return movies != null ? movies.hashCode() : 0; } @Override public String toString() { return "{movies=" + movies + '}'; } public static Recommendations from(String formatted) { Matcher matcher = FORMAT_RE.matcher(formatted); if (!matcher.matches()) { throw new IllegalArgumentException("Syntax error in recommendations string: " + formatted); } List<Movie> movies = new ArrayList<Movie>(); for (int i = 1; i <= matcher.groupCount(); i++) { String movie = matcher.group(i); if (movie.startsWith(",")) { movie = movie.substring(1).trim(); } movies.add(Movie.from(movie)); } return new Recommendations(movies); } }
6,979
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx/common/RxMovieTransformer.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.ribbon.examples.rx.common; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.reactivex.netty.channel.ContentTransformer; import java.nio.charset.Charset; /** * @author Tomasz Bak */ public class RxMovieTransformer implements ContentTransformer<Movie> { @Override public ByteBuf call(Movie movie, ByteBufAllocator byteBufAllocator) { byte[] bytes = movie.toString().getBytes(Charset.defaultCharset()); ByteBuf byteBuf = byteBufAllocator.buffer(bytes.length); byteBuf.writeBytes(bytes); return byteBuf; } }
6,980
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx/common/RecommendationServiceFallbackHandler.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.ribbon.examples.rx.common; import com.netflix.hystrix.HystrixInvokableInfo; import com.netflix.ribbon.hystrix.FallbackHandler; import io.netty.buffer.ByteBuf; import io.netty.buffer.UnpooledByteBufAllocator; import rx.Observable; import java.nio.charset.Charset; import java.util.Map; /** * @author Tomasz Bak */ public class RecommendationServiceFallbackHandler implements FallbackHandler<ByteBuf> { @Override public Observable<ByteBuf> getFallback(HystrixInvokableInfo<?> hystrixInfo, Map<String, Object> requestProperties) { byte[] bytes = Movie.ORANGE_IS_THE_NEW_BLACK.toString().getBytes(Charset.defaultCharset()); ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.buffer(bytes.length); byteBuf.writeBytes(bytes); return Observable.just(byteBuf); } }
6,981
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx/common/RecommendationServiceResponseValidator.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.ribbon.examples.rx.common; import com.netflix.ribbon.ServerError; import com.netflix.ribbon.UnsuccessfulResponseException; import com.netflix.ribbon.http.HttpResponseValidator; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientResponse; /** * @author Tomasz Bak */ public class RecommendationServiceResponseValidator implements HttpResponseValidator { @Override public void validate(HttpClientResponse<ByteBuf> response) throws UnsuccessfulResponseException, ServerError { if (response.getStatus().code() / 100 != 2) { throw new UnsuccessfulResponseException("Unexpected HTTP status code " + response.getStatus()); } } }
6,982
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx/common/Movie.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.ribbon.examples.rx.common; import io.netty.buffer.ByteBuf; import java.nio.charset.Charset; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Tomasz Bak */ public class Movie { private static final Pattern FORMAT_RE = Pattern.compile("\\{id='([^']*)', name='([^']*)', category='([^']*)', ageGroup='([^']*)', contentURI='([^']*)'\\}"); public static final Movie ORANGE_IS_THE_NEW_BLACK = new Movie("1", "Orange is the New Black", "Drama", "Adults", "http://streaming.netflix.com/movies?id=1"); public static final Movie BREAKING_BAD = new Movie("2", "Breaking Bad", "Crime", "Adults", "http://streaming.netflix.com/movies?id=2"); public static final Movie HOUSE_OF_CARDS = new Movie("3", "House of Cards", "Political", "Adults", "http://streaming.netflix.com/movies?id=3"); private final String id; private final String name; private final String category; private final String ageGroup; private final String contentURI; public Movie(String id, String name, String category, String ageGroup, String contentURI) { this.id = id; this.name = name; this.category = category; this.ageGroup = ageGroup; this.contentURI = contentURI; } public String getId() { return id; } public String getName() { return name; } public String getCategory() { return category; } public String getContentURI() { return contentURI; } public String getAgeGroup() { return ageGroup; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Movie movie = (Movie) o; if (ageGroup != null ? !ageGroup.equals(movie.ageGroup) : movie.ageGroup != null) return false; if (category != null ? !category.equals(movie.category) : movie.category != null) return false; if (contentURI != null ? !contentURI.equals(movie.contentURI) : movie.contentURI != null) return false; if (id != null ? !id.equals(movie.id) : movie.id != null) return false; if (name != null ? !name.equals(movie.name) : movie.name != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (category != null ? category.hashCode() : 0); result = 31 * result + (ageGroup != null ? ageGroup.hashCode() : 0); result = 31 * result + (contentURI != null ? contentURI.hashCode() : 0); return result; } @Override public String toString() { return '{' + "id='" + id + '\'' + ", name='" + name + '\'' + ", category='" + category + '\'' + ", ageGroup='" + ageGroup + '\'' + ", contentURI='" + contentURI + '\'' + '}'; } public static Movie from(String formatted) { Matcher matcher = FORMAT_RE.matcher(formatted); if (!matcher.matches()) { throw new IllegalArgumentException("Syntax error in movie string: " + formatted); } return new Movie(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4), matcher.group(5)); } public static Movie from(ByteBuf byteBuf) { return from(byteBuf.toString(Charset.defaultCharset())); } }
6,983
0
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-examples/src/main/java/com/netflix/ribbon/examples/rx/common/InMemoryCacheProviderFactory.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.ribbon.examples.rx.common; import com.netflix.ribbon.CacheProvider; import com.netflix.ribbon.CacheProviderFactory; import rx.Observable; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author Tomasz Bak */ public class InMemoryCacheProviderFactory implements CacheProviderFactory<Movie> { @Override public CacheProvider<Movie> createCacheProvider() { return new InMemoryCacheProvider(); } public static class InMemoryCacheProvider implements CacheProvider<Movie> { private final Map<String, Object> cacheMap = new ConcurrentHashMap<String, Object>(); @Override public Observable<Movie> get(String key, Map<String, Object> requestProperties) { return null; } } }
6,984
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/BestAvailableRuleTest.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.loadbalancer; import static org.junit.Assert.*; import java.util.List; import org.junit.Test; import com.google.common.collect.Lists; public class BestAvailableRuleTest { @Test public void testRule() { List<Server> servers = Lists.newArrayList(); for (int i = 0; i < 10; i++) { servers.add(new Server(String.valueOf(i), 80)); } IRule rule = new BestAvailableRule(); BaseLoadBalancer lb = LoadBalancerBuilder.newBuilder().withRule(rule).buildFixedServerListLoadBalancer(servers); for (int i = 0; i < 10; i++) { ServerStats stats = lb.getLoadBalancerStats().getSingleServerStat(servers.get(i)); for (int j = 0; j < 10 - i; j++) { stats.incrementActiveRequestsCount(); } } Server server = lb.chooseServer(); assertEquals(servers.get(9), server); ServerStats stats = lb.getLoadBalancerStats().getSingleServerStat(servers.get(9)); for (int i = 0; i < 3; i++) { stats.incrementSuccessiveConnectionFailureCount(); } server = lb.chooseServer(); // server 9 has tripped circuit breaker assertEquals(servers.get(8), server); } }
6,985
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/ConfigurationBasedServerListTest.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.loadbalancer; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.config.ConfigurationManager; public class ConfigurationBasedServerListTest { @Test public void testList() { ConfigurationBasedServerList list = new ConfigurationBasedServerList(); DefaultClientConfigImpl config = DefaultClientConfigImpl.getClientConfigWithDefaultValues("junit1"); list.initWithNiwsConfig(config); assertTrue(list.getInitialListOfServers().isEmpty()); ConfigurationManager.getConfigInstance().setProperty("junit1.ribbon.listOfServers", "abc.com:80,microsoft.com,1.2.3.4:8080"); List<Server> servers = list.getUpdatedListOfServers(); List<Server> expected = new ArrayList<Server>(); expected.add(new Server("abc.com:80")); expected.add(new Server("microsoft.com:80")); expected.add(new Server("1.2.3.4:8080")); assertEquals(expected, servers); ConfigurationManager.getConfigInstance().setProperty("junit1.ribbon.listOfServers", ""); assertTrue(list.getUpdatedListOfServers().isEmpty()); ConfigurationManager.getConfigInstance().clearProperty("junit1.ribbon.listOfServers"); assertTrue(list.getUpdatedListOfServers().isEmpty()); } }
6,986
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/MockServerList.java
package com.netflix.loadbalancer; import java.util.List; import com.google.common.collect.Lists; import com.netflix.client.config.IClientConfig; public class MockServerList extends AbstractServerList<Server> { private List<Server> serverList = Lists.newArrayList(); public void setServerList(List<Server> serverList) { this.serverList = serverList; } @Override public List<Server> getInitialListOfServers() { return serverList; } @Override public List<Server> getUpdatedListOfServers() { return serverList; } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { } }
6,987
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/ServerListLoabBalancerTest.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.loadbalancer; import static org.junit.Assert.*; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.configuration.Configuration; import org.junit.BeforeClass; import org.junit.Test; import com.netflix.client.ClientFactory; import com.netflix.client.config.IClientConfig; import com.netflix.config.ConfigurationManager; import com.netflix.loadbalancer.DynamicServerListLoadBalancer; import com.netflix.loadbalancer.Server; public class ServerListLoabBalancerTest { static Server[] servers = {new Server("abc", 80), new Server("xyz", 90), new Server("www.netflix.com", 80)}; static List<Server> serverList = Arrays.asList(servers); public static class FixedServerList extends AbstractServerList<Server> { @Override public void initWithNiwsConfig(IClientConfig clientConfig) { } @Override public List<Server> getInitialListOfServers() { return serverList; } @Override public List<Server> getUpdatedListOfServers() { return serverList; } } static DynamicServerListLoadBalancer<Server> lb; @BeforeClass public static void init() { Configuration config = ConfigurationManager.getConfigInstance(); config.setProperty("ServerListLoabBalancerTest.ribbon.NFLoadBalancerClassName", com.netflix.loadbalancer.DynamicServerListLoadBalancer.class.getName()); config.setProperty("ServerListLoabBalancerTest.ribbon.NIWSServerListClassName", FixedServerList.class.getName()); lb = (DynamicServerListLoadBalancer<Server>) ClientFactory.getNamedLoadBalancer("ServerListLoabBalancerTest"); } @Test public void testChooseServer() { assertNotNull(lb); Set<Server> result = new HashSet<Server>(); for (int i = 0; i < 100; i++) { Server s = lb.chooseServer(null); result.add(s); } Set<Server> expected = new HashSet<Server>(); expected.addAll(serverList); assertEquals(expected, result); } }
6,988
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/SubsetFilterTest.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.loadbalancer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import com.google.common.util.concurrent.Uninterruptibles; import org.apache.commons.configuration.Configuration; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import com.google.common.collect.Lists; import com.netflix.client.ClientFactory; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.config.ConfigurationManager; public class SubsetFilterTest { @BeforeClass public static void init() { Configuration config = ConfigurationManager.getConfigInstance(); config.setProperty("SubsetFilerTest.ribbon.NFLoadBalancerClassName", com.netflix.loadbalancer.DynamicServerListLoadBalancer.class.getName()); config.setProperty("SubsetFilerTest.ribbon.NIWSServerListClassName", MockServerList.class.getName()); config.setProperty("SubsetFilerTest.ribbon.NIWSServerListFilterClassName", ServerListSubsetFilter.class.getName()); // turn off auto refresh config.setProperty("SubsetFilerTest.ribbon.ServerListRefreshInterval", String.valueOf(Integer.MAX_VALUE)); config.setProperty("SubsetFilerTest.ribbon.ServerListSubsetFilter.forceEliminatePercent", "0.6"); config.setProperty("SubsetFilerTest.ribbon.ServerListSubsetFilter.eliminationFailureThresold", 2); config.setProperty("SubsetFilerTest.ribbon.ServerListSubsetFilter.eliminationConnectionThresold", 2); config.setProperty("SubsetFilerTest.ribbon.ServerListSubsetFilter.size", "5"); } List<Server> getServersAndStats(LoadBalancerStats lbStats, Object[][] stats) { List<Server> list = Lists.newArrayList(); for (Object[] serverStats: stats) { Server server = new Server((String) serverStats[0]); list.add(server); int failureCount = (Integer) serverStats[1]; int connectionCount = (Integer) serverStats[2]; lbStats.getServerStats().put(server, new DummyServerStats(connectionCount, failureCount)); } return list; } @Test public void testSorting() { ServerListSubsetFilter<Server> filter = new ServerListSubsetFilter<Server>(); LoadBalancerStats stats = new LoadBalancerStats("default"); filter.setLoadBalancerStats(stats); Object[][] serverStats = { {"server0", 0, 0}, {"server1", 1, 0}, {"server2", 1, 1}, {"server3", 0, 1}, {"server4", 2, 0} }; List<Server> servers = getServersAndStats(stats, serverStats); Collections.sort(servers, filter); List<String> expected = Lists.newArrayList("server4", "server2", "server1", "server3", "server0"); for (int i = 0; i < servers.size(); i++) { assertEquals(expected.get(i), servers.get(i).getHost()); } } @Test public void testFiltering() { DefaultClientConfigImpl config = new DefaultClientConfigImpl(); config.loadProperties("SubsetFilerTest"); ServerListSubsetFilter<Server> filter = new ServerListSubsetFilter<Server>(config); LoadBalancerStats stats = new LoadBalancerStats("default"); stats.initWithNiwsConfig(config); filter.setLoadBalancerStats(stats); Object[][] serverStats = { {"server0", 0, 0}, {"server1", 0, 0}, {"server2", 0, 0}, {"server3", 0, 0}, {"server4", 0, 0}, {"server5", 0, 0}, {"server6", 0, 0}, {"server7", 0, 0}, {"server8", 0, 0}, {"server9", 0, 0} }; List<Server> list = getServersAndStats(stats, serverStats); List<Server> filtered = filter.getFilteredListOfServers(list); // first filtering, should get 5 servers assertEquals(filtered.size(), 5); Server s1 = filtered.get(0); Server s2 = filtered.get(1); Server s3 = filtered.get(2); Server s4 = filtered.get(3); Server s5 = filtered.get(4); // failure count > threshold DummyServerStats stats1 = (DummyServerStats) stats.getSingleServerStat(s1); stats1.setConnectionFailureCount(3); // active requests count > threshold DummyServerStats stats2 = (DummyServerStats) stats.getSingleServerStat(s2); stats2.setActiveRequestsCount(3); // will be forced eliminated after sorting DummyServerStats stats3 = (DummyServerStats) stats.getSingleServerStat(s3); stats3.setActiveRequestsCount(2); // will be forced eliminated after sorting DummyServerStats stats4 = (DummyServerStats) stats.getSingleServerStat(s4); stats4.setConnectionFailureCount(1); // filter again, this time some servers will be eliminated filtered = filter.getFilteredListOfServers(list); assertEquals(5, filtered.size()); assertTrue(!filtered.contains(s1)); assertTrue(!filtered.contains(s2)); assertTrue(filtered.contains(s3)); assertTrue(!filtered.contains(s4)); assertTrue(filtered.contains(s5)); // Not enough healthy servers, just get whatever is available List<Server> lastFiltered = filter.getFilteredListOfServers(Lists.newArrayList(filtered)); assertEquals(5, lastFiltered.size()); } @Test public void testWithLoadBalancer() { DynamicServerListLoadBalancer<Server> lb = (DynamicServerListLoadBalancer<Server>) ClientFactory.getNamedLoadBalancer("SubsetFilerTest"); MockServerList serverList = (MockServerList) lb.getServerListImpl(); Object[][] serverStats = { {"server0", 0, 0}, {"server1", 0, 0}, {"server2", 0, 0}, {"server3", 0, 0}, {"server4", 0, 0}, {"server5", 0, 0}, {"server6", 0, 0}, {"server7", 0, 0}, {"server8", 0, 0}, {"server9", 0, 0} }; LoadBalancerStats stats = lb.getLoadBalancerStats(); List<Server> list = getServersAndStats(stats, serverStats); serverList.setServerList(list); Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS); lb.updateListOfServers(); List<Server> filtered = lb.getAllServers(); // first filtering, should get 5 servers assertEquals(filtered.size(), 5); Server s1 = filtered.get(0); Server s2 = filtered.get(1); Server s3 = filtered.get(2); Server s4 = filtered.get(3); Server s5 = filtered.get(4); // failure count > threshold DummyServerStats stats1 = (DummyServerStats) stats.getSingleServerStat(s1); stats1.setConnectionFailureCount(3); // active requests count > threshold DummyServerStats stats2 = (DummyServerStats) stats.getSingleServerStat(s2); stats2.setActiveRequestsCount(3); // will be forced eliminated after sorting DummyServerStats stats3 = (DummyServerStats) stats.getSingleServerStat(s3); stats3.setActiveRequestsCount(2); // will be forced eliminated after sorting DummyServerStats stats4 = (DummyServerStats) stats.getSingleServerStat(s4); stats4.setConnectionFailureCount(1); // filter again, this time some servers will be eliminated serverList.setServerList(list); lb.updateListOfServers(); filtered = lb.getAllServers(); assertEquals(5, filtered.size()); assertTrue(!filtered.contains(s1)); assertTrue(!filtered.contains(s2)); assertTrue(filtered.contains(s3)); assertTrue(!filtered.contains(s4)); assertTrue(filtered.contains(s5)); // Not enough healthy servers, just get whatever is available serverList.setServerList(Lists.newArrayList(filtered)); lb.updateListOfServers(); List<Server> lastFiltered = lb.getAllServers(); assertEquals(5, lastFiltered.size()); } } class DummyServerStats extends ServerStats { int activeRequestsCount; int connectionFailureCount; public DummyServerStats(int activeRequestsCount, int connectionFailureCount) { this.activeRequestsCount = activeRequestsCount; this.connectionFailureCount = connectionFailureCount; } public final void setActiveRequestsCount(int activeRequestsCount) { this.activeRequestsCount = activeRequestsCount; } public final void setConnectionFailureCount(int connectionFailureCount) { this.connectionFailureCount = connectionFailureCount; } @Override public int getActiveRequestsCount() { return activeRequestsCount; } @Override public long getFailureCount() { return connectionFailureCount; } }
6,989
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/SimpleRoundRobinWithRetryLBTest.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.loadbalancer; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.Test; import java.util.HashMap; public class SimpleRoundRobinWithRetryLBTest { static ServerComparator serverComparator = new ServerComparator(); static HashMap<String, Boolean> isAliveMap = new HashMap<String, Boolean>(); static BaseLoadBalancer lb; @BeforeClass public static void setup(){ isAliveMap.put("dummyservice0.netflix.com:8080", Boolean.TRUE); isAliveMap.put("dummyservice1.netflix.com:8080", Boolean.TRUE); isAliveMap.put("dummyservice2.netflix.com:8080", Boolean.TRUE); isAliveMap.put("dummyservice3.netflix.com:8080", Boolean.TRUE); IPing ping = new PingFake(); IRule rule = new RetryRule(new RoundRobinRule(), 200); lb = new BaseLoadBalancer(ping,rule); lb.setPingInterval(1); lb.setMaxTotalPingTime(5); // the setting of servers is done by a call to DiscoveryService lb.setServers("dummyservice0.netflix.com:8080, dummyservice1.netflix.com:8080,dummyservice2.netflix.com:8080,dummyservice3.netflix.com:8080"); // just once more to see if forceQuickPing will be called lb.setServers("dummyservice0.netflix.com:8080, dummyservice1.netflix.com:8080,dummyservice2.netflix.com:8080,dummyservice3.netflix.com:8080, garbage:8080"); // set it back to original lb.setServers("dummyservice0.netflix.com:8080, dummyservice1.netflix.com:8080,dummyservice2.netflix.com:8080,dummyservice3.netflix.com:8080"); lb.setServers("dummyservice0.netflix.com:8080, dummyservice1.netflix.com:8080,dummyservice2.netflix.com:8080,dummyservice3.netflix.com:8080"); try { Thread.sleep(10000); } catch (InterruptedException e) { } } /** * Simulate a single user who should just round robin among the available servers */ @Test public void testRoundRobinWithAServerFailure(){ isAliveMap.put("dummyservice2.netflix.com:8080", Boolean.FALSE); try { Thread.sleep(5000); } catch (InterruptedException e) { } for (int i=0; i < 20; i++){ Server svc = lb.chooseServer("user1"); assertFalse(svc.getId().equals("dummyservice2.netflix.com:8080")); } } static class PingFake implements IPing { public boolean isAlive(Server server) { Boolean res = isAliveMap.get(server.getId()); return ((res != null) && (res.booleanValue())); } } }
6,990
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/WeightedResponseTimeRuleTest.java
package com.netflix.loadbalancer; import org.awaitility.core.ThrowingRunnable; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.List; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class WeightedResponseTimeRuleTest { private static final Object KEY = "key"; private AbstractLoadBalancer loadBalancer; private WeightedResponseTimeRule rule; @Before public void setUp() throws Exception { rule = new WeightedResponseTimeRule(); loadBalancer = mock(AbstractLoadBalancer.class); setupLoadBalancer(asList(server("first"), server("second"), server("third"))); rule.setLoadBalancer(loadBalancer); } @After public void tearDown() throws Exception { rule.shutdown(); } @Test public void shouldNotFailWithIndexOutOfBoundExceptionWhenChoosingServerWhenNumberOfServersIsDecreased() throws Exception { waitUntilWeightsAreCalculated(); setupLoadBalancer(singletonList(server("other"))); Server chosen = rule.choose(loadBalancer, KEY); assertNotNull(chosen); } private void waitUntilWeightsAreCalculated() { await().untilAsserted(new ThrowingRunnable() { @Override public void run() throws Throwable { List<Double> weights = rule.getAccumulatedWeights(); assertNotEquals(weights.size(), 0); } }); } private AbstractLoadBalancer setupLoadBalancer(List<Server> servers) { LoadBalancerStats loadBalancerStats = getLoadBalancerStats(servers); when(loadBalancer.getLoadBalancerStats()).thenReturn(loadBalancerStats); when(loadBalancer.getReachableServers()).thenReturn(servers); when(loadBalancer.getAllServers()).thenReturn(servers); return loadBalancer; } private LoadBalancerStats getLoadBalancerStats(List<Server> servers) { LoadBalancerStats stats = mock(LoadBalancerStats.class); // initialize first server with maximum response time // so that we could reproduce issue with decreased number of servers in loadbalancer int responseTimeMax = servers.size() * 100; for (Server server : servers) { ServerStats s1 = statsWithResponseTimeAverage(responseTimeMax); when(stats.getSingleServerStat(server)).thenReturn(s1); responseTimeMax -= 100; } return stats; } private ServerStats statsWithResponseTimeAverage(double responseTimeAverage) { ServerStats serverStats = mock(ServerStats.class); when(serverStats.getResponseTimeAvg()).thenReturn(responseTimeAverage); return serverStats; } private Server server(String id) { Server server = new Server(id); server.setAlive(true); return server; } }
6,991
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/ServerListChangeListenerTest.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.loadbalancer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import com.google.common.collect.Lists; public class ServerListChangeListenerTest { private volatile List<Server> oldList; private volatile List<Server> newList; @Test public void testListener() { BaseLoadBalancer lb = new BaseLoadBalancer(); lb.addServerListChangeListener(new ServerListChangeListener() { @Override public void serverListChanged(List<Server> oldList, List<Server> newList) { ServerListChangeListenerTest.this.oldList = oldList; ServerListChangeListenerTest.this.newList = newList; } }); List<Server> list1 = Lists.newArrayList(new Server("server1"), new Server("server2")); List<Server> list2 = Lists.newArrayList(new Server("server3"), new Server("server4")); lb.setServersList(list1); assertTrue(oldList.isEmpty()); assertEquals(list1, newList); lb.setServersList(list2); assertEquals(list1, oldList); assertEquals(list2, newList); } }
6,992
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/PredicatesTest.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.loadbalancer; import static org.junit.Assert.*; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.AfterClass; import org.junit.Test; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.netflix.config.ConfigurationManager; import com.netflix.config.DeploymentContext.ContextKey; public class PredicatesTest { static { ConfigurationManager.getConfigInstance().setProperty("niws.loadbalancer.default.circuitTripTimeoutFactorSeconds", 100000); ConfigurationManager.getConfigInstance().setProperty("niws.loadbalancer.default.circuitTripMaxTimeoutSeconds", 1000000); } @AfterClass public static void cleanup() { ConfigurationManager.getConfigInstance().clearProperty("niws.loadbalancer.default.circuitTripTimeoutFactorSeconds"); ConfigurationManager.getConfigInstance().clearProperty("niws.loadbalancer.default.circuitTripMaxTimeoutSeconds"); } public void setServerStats(LoadBalancerStats lbStats, Object[][] stats) { for (Object[] serverStats: stats) { Server server = (Server) serverStats[0]; Boolean circuitTripped = (Boolean) serverStats[1]; Integer activeConnections = (Integer) serverStats[2]; ServerStats ss = lbStats.getSingleServerStat(server); if (circuitTripped) { for (int i = 0; i < 3; i++) { ss.incrementSuccessiveConnectionFailureCount(); } } for (int i = 0; i < activeConnections; i++) { ss.incrementActiveRequestsCount(); } } } @Test public void testAvalabilityPredicate() { Object[][] stats = new Object[10][3]; List<Server> expectedFiltered = Lists.newArrayList(); for (int i = 0; i < 7; i++) { stats[i] = new Object[3]; stats[i][0] = new Server("good:" + i); stats[i][1] = false; stats[i][2] = 0; expectedFiltered.add((Server) stats[i][0]); } for (int i = 7; i < 10; i++) { stats[i] = new Object[3]; stats[i][0] = new Server("bad:" + i); stats[i][1] = true; stats[i][2] = 0; } LoadBalancerStats lbStats = new LoadBalancerStats("default"); setServerStats(lbStats, stats); AvailabilityPredicate predicate = new AvailabilityPredicate(lbStats, null); assertFalse(predicate.apply(new PredicateKey((Server) stats[8][0]))); assertTrue(predicate.apply(new PredicateKey((Server) stats[0][0]))); List<Server> servers = Lists.newArrayList(); for (int i = 0; i < 10; i++) { servers.add((Server) stats[i][0]); } List<Server> filtered = predicate.getEligibleServers(servers); assertEquals(expectedFiltered, filtered); Set<Server> chosen = Sets.newHashSet(); for (int i = 0; i < 20; i++) { Server s = predicate.chooseRoundRobinAfterFiltering(servers).get(); assertEquals("good:" + (i % 7), s.getId()); chosen.add(s); } assertEquals(7, chosen.size()); } @Test public void testAvalabilityPredicateAfterFailure() { LoadBalancerStats lbStats = new LoadBalancerStats("default"); AvailabilityPredicate predicate = new AvailabilityPredicate(lbStats, null); Server server1 = new Server("good2bad:0"); Server server2 = new Server("good:1"); List<Server> servers = Arrays.asList(server1, server2); setServerStats(lbStats, new Object[][] { new Object[]{server1, false, 0}, new Object[]{server2, false, 0}}); Server first = predicate.chooseRoundRobinAfterFiltering(servers).get(); assertEquals("good2bad:0", first.getId()); setServerStats(lbStats, new Object[][] { new Object[]{server1, true, 0}, new Object[]{server2, false, 0}}); Server second = predicate.chooseRoundRobinAfterFiltering(servers).get(); assertEquals("good:1", second.getId()); } @Test public void testZoneAvoidancePredicate() { Object[][] stats = new Object[10][3]; Map<String, List<Server>> zoneMap = Maps.newHashMap(); List<Server> expectedFiltered = Lists.newArrayList(); List<Server> list0 = Lists.newArrayList(); for (int i = 0; i < 3; i++) { stats[i] = new Object[3]; stats[i][0] = new Server("good:" + i); ((Server) stats[i][0]).setZone("0"); list0.add((Server) stats[i][0]); stats[i][1] = false; stats[i][2] = 0; expectedFiltered.add((Server) stats[i][0]); } zoneMap.put("0", list0); List<Server> list1 = Lists.newArrayList(); for (int i = 3; i < 7; i++) { stats[i] = new Object[3]; stats[i][0] = new Server("bad:" + i); ((Server) stats[i][0]).setZone("1"); list1.add((Server) stats[i][0]); stats[i][1] = false; stats[i][2] = 2; } zoneMap.put("1", list1); List<Server> list2 = Lists.newArrayList(); for (int i = 7; i < 10; i++) { stats[i] = new Object[3]; stats[i][0] = new Server("good:" + i); ((Server) stats[i][0]).setZone("2"); list2.add((Server) stats[i][0]); stats[i][1] = false; stats[i][2] = 1; } zoneMap.put("2", list2); LoadBalancerStats lbStats = new LoadBalancerStats("default"); setServerStats(lbStats, stats); lbStats.updateZoneServerMapping(zoneMap); ZoneAvoidancePredicate predicate = new ZoneAvoidancePredicate(lbStats, null); assertFalse(predicate.apply(new PredicateKey((Server) stats[5][0]))); assertTrue(predicate.apply(new PredicateKey((Server) stats[0][0]))); assertTrue(predicate.apply(new PredicateKey((Server) stats[9][0]))); } @Test public void testCompositePredicate() { ConfigurationManager.getConfigInstance().setProperty(ContextKey.zone.getKey(), "0"); Object[][] stats = new Object[10][3]; Map<String, List<Server>> zoneMap = Maps.newHashMap(); List<Server> expectedFiltered = Lists.newArrayList(); for (int i = 0; i < 3; i++) { stats[i] = new Object[3]; stats[i][0] = new Server("good:" + i); ((Server) stats[i][0]).setZone("0"); stats[i][1] = false; stats[i][2] = 0; expectedFiltered.add((Server) stats[i][0]); } List<Server> list1 = Lists.newArrayList(); for (int i = 3; i < 7; i++) { stats[i] = new Object[3]; stats[i][0] = new Server("bad:" + i); ((Server) stats[i][0]).setZone("0"); list1.add((Server) stats[i][0]); stats[i][1] = true; stats[i][2] = 0; } zoneMap.put("1", list1); List<Server> list2 = Lists.newArrayList(); for (int i = 7; i < 10; i++) { stats[i] = new Object[3]; stats[i][0] = new Server("good:" + i); ((Server) stats[i][0]).setZone("1"); list2.add((Server) stats[i][0]); stats[i][1] = false; stats[i][2] = 0; } zoneMap.put("2", list2); LoadBalancerStats lbStats = new LoadBalancerStats("default"); setServerStats(lbStats, stats); lbStats.updateZoneServerMapping(zoneMap); AvailabilityPredicate p1 = new AvailabilityPredicate(lbStats, null); ZoneAffinityPredicate p2 = new ZoneAffinityPredicate("0"); CompositePredicate c = CompositePredicate.withPredicates(p2, p1).build(); assertFalse(c.apply(new PredicateKey((Server) stats[5][0]))); assertTrue(c.apply(new PredicateKey((Server) stats[0][0]))); assertFalse(c.apply(new PredicateKey((Server) stats[9][0]))); List<Server> servers = Lists.newArrayList(); for (int i = 0; i < 10; i++) { servers.add((Server) stats[i][0]); } List<Server> filtered = c.getEligibleServers(servers); assertEquals(3, filtered.size()); CompositePredicate c2 = CompositePredicate.withPredicates(p2, p1) .setFallbackThresholdAsMinimalFilteredNumberOfServers(5) .addFallbackPredicate(p1).build(); filtered = c2.getEligibleServers(servers); assertEquals(6, filtered.size()); } }
6,993
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/ServerStatsTest.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.loadbalancer; import static org.junit.Assert.*; import org.junit.Test; import com.netflix.servo.monitor.Monitors; public class ServerStatsTest { @Test public void testRegisterWithServo() { // Make sure annotations are correct: // https://github.com/Netflix/ribbon/issues/191 // Monitors.registerObject(new ServerStats()); } }
6,994
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/ZoneAwareLoadBalancerTest.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.loadbalancer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.netflix.client.config.DefaultClientConfigImpl; import org.junit.Ignore; import org.junit.Test; import com.netflix.client.ClientFactory; import com.netflix.config.ConfigurationManager; public class ZoneAwareLoadBalancerTest { private Server createServer(String host, String zone) { return createServer(host, 7001, zone); } private Server createServer(String host, int port, String zone) { Server server = new Server(host, port); server.setZone(zone); server.setAlive(true); return server; } private Server createServer(int hostId, String zoneSuffix) { return createServer(zoneSuffix + "-" + "server" + hostId, "us-eAst-1" + zoneSuffix); } private void testChooseServer(ZoneAwareLoadBalancer<Server> balancer, String... expectedZones) { Set<String> result = new HashSet<String>(); for (int i = 0; i < 100; i++) { Server server = balancer.chooseServer(null); String zone = server.getZone().toLowerCase(); result.add(zone); } Set<String> expected = new HashSet<String>(); expected.addAll(Arrays.asList(expectedZones)); assertEquals(expected, result); } @Test public void testChooseZone() throws Exception { ConfigurationManager.getConfigInstance().setProperty("niws.loadbalancer.serverStats.activeRequestsCount.effectiveWindowSeconds", 10); DefaultClientConfigImpl config = new DefaultClientConfigImpl(); config.loadProperties("testChooseZone"); ZoneAwareLoadBalancer<Server> balancer = new ZoneAwareLoadBalancer<Server>(); balancer.init(); IRule globalRule = new RoundRobinRule(); balancer.setRule(globalRule); LoadBalancerStats loadBalancerStats = balancer.getLoadBalancerStats(); loadBalancerStats.initWithNiwsConfig(config); assertNotNull(loadBalancerStats); List<Server> servers = new ArrayList<Server>(); servers.add(createServer(1, "a")); servers.add(createServer(2, "a")); servers.add(createServer(3, "a")); servers.add(createServer(4, "a")); servers.add(createServer(1, "b")); servers.add(createServer(2, "b")); servers.add(createServer(3, "b")); servers.add(createServer(1, "c")); servers.add(createServer(2, "c")); servers.add(createServer(3, "c")); servers.add(createServer(4, "c")); balancer.setServersList(servers); balancer.setUpServerList(servers); assertTrue(balancer.getLoadBalancer("us-east-1a").getRule() instanceof RoundRobinRule); assertNotSame(globalRule, balancer.getLoadBalancer("us-east-1a").getRule()); // System.out.println("=== LB Stats at testChooseZone 1: " + loadBalancerStats); testChooseServer(balancer, "us-east-1a", "us-east-1b", "us-east-1c"); loadBalancerStats.incrementActiveRequestsCount(createServer(1, "c")); loadBalancerStats.incrementActiveRequestsCount(createServer(3, "c")); loadBalancerStats.incrementActiveRequestsCount(createServer(3, "c")); loadBalancerStats.decrementActiveRequestsCount(createServer(3, "c")); assertEquals(2, loadBalancerStats.getActiveRequestsCount("us-east-1c")); assertEquals(0.5d, loadBalancerStats.getActiveRequestsPerServer("us-east-1c"), 0.0001d); testChooseServer(balancer, "us-east-1a", "us-east-1b"); for (int i = 0; i < 3; i++) { loadBalancerStats.incrementSuccessiveConnectionFailureCount(createServer(1, "a")); } assertEquals(1, loadBalancerStats.getCircuitBreakerTrippedCount("us-east-1a")); loadBalancerStats.incrementSuccessiveConnectionFailureCount(createServer(2, "b")); assertEquals(0, loadBalancerStats.getCircuitBreakerTrippedCount("us-east-1b")); // loadPerServer on both zone a and b should still be 0 testChooseServer(balancer, "us-east-1a", "us-east-1b"); // make a load on zone a loadBalancerStats.incrementActiveRequestsCount(createServer(2, "a")); assertEquals(1d/3, loadBalancerStats.getActiveRequestsPerServer("us-east-1a"), 0.0001); // zone c will be dropped as the worst zone testChooseServer(balancer, "us-east-1b", "us-east-1a"); Thread.sleep(15000); assertEquals(0, loadBalancerStats.getCircuitBreakerTrippedCount("us-east-1a")); assertEquals(3, loadBalancerStats.getSingleServerStat(createServer(1, "a")).getSuccessiveConnectionFailureCount()); assertEquals(0, loadBalancerStats.getActiveRequestsCount("us-east-1c")); assertEquals(0, loadBalancerStats.getSingleServerStat(createServer(1, "c")).getActiveRequestsCount()); loadBalancerStats.clearSuccessiveConnectionFailureCount(createServer(1, "a")); assertEquals(0, loadBalancerStats.getSingleServerStat(createServer(1, "a")).getSuccessiveConnectionFailureCount()); assertEquals(0, loadBalancerStats.getCircuitBreakerTrippedCount("us-east-1a")); loadBalancerStats.decrementActiveRequestsCount(createServer(2, "a")); assertEquals(0, loadBalancerStats.getActiveRequestsPerServer("us-east-1b"), 0.000001); assertEquals(0, loadBalancerStats.getActiveRequestsPerServer("us-east-1c"), 0.000001); assertEquals(0, loadBalancerStats.getActiveRequestsPerServer("us-east-1a"), 0.000001); testChooseServer(balancer, "us-east-1a", "us-east-1b", "us-east-1c"); List<Server> emptyList = Collections.emptyList(); Map<String, List<Server>> map = new HashMap<String, List<Server>>(); map.put("us-east-1a", emptyList); map.put("us-east-1b", emptyList); balancer.setServerListForZones(map); testChooseServer(balancer, "us-east-1a", "us-east-1b", "us-east-1c"); } @Test public void testZoneOutage() throws Exception { ConfigurationManager.getConfigInstance().clearProperty("niws.loadbalancer.serverStats.activeRequestsCount.effectiveWindowSeconds"); ZoneAwareLoadBalancer<Server> balancer = new ZoneAwareLoadBalancer<Server>(); balancer.init(); LoadBalancerStats loadBalancerStats = balancer.getLoadBalancerStats(); assertNotNull(loadBalancerStats); List<Server> servers = new ArrayList<Server>(); servers.add(createServer(1, "a")); servers.add(createServer(2, "a")); servers.add(createServer(1, "b")); servers.add(createServer(2, "b")); servers.add(createServer(1, "c")); servers.add(createServer(2, "c")); balancer.setServersList(servers); balancer.setUpServerList(servers); testChooseServer(balancer, "us-east-1a", "us-east-1b", "us-east-1c"); for (int i = 0; i < 3; i++) { loadBalancerStats.incrementSuccessiveConnectionFailureCount(createServer(1, "a")); loadBalancerStats.incrementSuccessiveConnectionFailureCount(createServer(2, "a")); } assertEquals(2, loadBalancerStats.getCircuitBreakerTrippedCount("us-east-1a")); testChooseServer(balancer, "us-east-1b", "us-east-1c"); loadBalancerStats.incrementActiveRequestsCount(createServer(1, "b")); loadBalancerStats.incrementActiveRequestsCount(createServer(1, "c")); testChooseServer(balancer, "us-east-1b", "us-east-1c"); loadBalancerStats.decrementActiveRequestsCount(createServer(1, "b")); // zone a all instances are blacked out, zone c is worst in terms of load testChooseServer(balancer, "us-east-1b"); } @Test public void testNonZoneOverride() { ZoneAwareLoadBalancer<Server> balancer = new ZoneAwareLoadBalancer<Server>(); balancer.init(); LoadBalancerStats loadBalancerStats = balancer.getLoadBalancerStats(); assertNotNull(loadBalancerStats); List<Server> servers = new ArrayList<Server>(); for (int i = 1; i <= 11; i++) { servers.add(createServer(i, "a")); servers.add(createServer(i, "b")); servers.add(createServer(i, "c")); } balancer.setServersList(servers); balancer.setUpServerList(servers); // should not triggering zone override loadBalancerStats.incrementActiveRequestsCount(createServer(1, "b")); loadBalancerStats.incrementActiveRequestsCount(createServer(1, "c")); testChooseServer(balancer, "us-east-1a", "us-east-1b", "us-east-1c"); loadBalancerStats.incrementActiveRequestsCount(createServer(1, "b")); loadBalancerStats.incrementActiveRequestsCount(createServer(1, "b")); testChooseServer(balancer, "us-east-1a", "us-east-1c"); loadBalancerStats.incrementActiveRequestsCount(createServer(2, "c")); loadBalancerStats.incrementActiveRequestsCount(createServer(4, "c")); // now b and c are equally bad, no guarantee which zone will be chosen testChooseServer(balancer, "us-east-1a", "us-east-1b", "us-east-1c"); } @Test public void testAvailabilityFiltering() { ZoneAwareLoadBalancer balancer = new ZoneAwareLoadBalancer(); balancer.init(); balancer.setRule(new AvailabilityFilteringRule()); LoadBalancerStats loadBalancerStats = balancer.getLoadBalancerStats(); assertNotNull(loadBalancerStats); List<Server> servers = new ArrayList<Server>(); servers.add(createServer(1, "a")); servers.add(createServer(2, "a")); servers.add(createServer(1, "b")); servers.add(createServer(2, "b")); servers.add(createServer(1, "c")); servers.add(createServer(2, "c")); balancer.setServersList(servers); balancer.setUpServerList(servers); // cause both zone a and b outage for (int i = 0; i < 4; i++) { Server server = servers.get(i); for (int j = 0; j < 3; j++) { loadBalancerStats.getSingleServerStat(server).incrementSuccessiveConnectionFailureCount(); } } Set<Server> expected = new HashSet<Server>(); expected.add(createServer(1, "c")); expected.add(createServer(2, "c")); Set<Server> result = new HashSet<Server>(); for (int i = 0; i < 20; i++) { Server server = balancer.chooseServer(null); result.add(server); } assertEquals(expected, result); // cause one server in c circuit tripped for (int i = 0; i < 3; i++) { loadBalancerStats.getSingleServerStat(servers.get(4)).incrementSuccessiveConnectionFailureCount(); } // should only use the other server in zone c for (int i = 0; i < 20; i++) { Server server = balancer.chooseServer(null); assertEquals(servers.get(5), server); } // now every server is tripped for (int i = 0; i < 3; i++) { loadBalancerStats.getSingleServerStat(servers.get(5)).incrementSuccessiveConnectionFailureCount(); } expected = new HashSet<Server>(servers); result = new HashSet<Server>(); for (int i = 0; i < 20; i++) { Server server = balancer.chooseServer(null); if (server == null) { fail("Unexpected null server"); } result.add(server); } assertEquals(expected, result); servers = new ArrayList<Server>(); servers.add(createServer(1, "a")); servers.add(createServer(2, "a")); servers.add(createServer(1, "b")); servers.add(createServer(2, "b")); balancer.setServersList(servers); assertTrue(balancer.getLoadBalancer("us-east-1c").getAllServers().isEmpty()); AvailabilityFilteringRule rule = (AvailabilityFilteringRule) balancer.getLoadBalancer("us-east-1c").getRule(); assertEquals(0, rule.getAvailableServersCount()); } @Test public void testConstruction() { ConfigurationManager.getConfigInstance().setProperty("mylb.ribbon.NFLoadBalancerRuleClassName", RandomRule.class.getName()); ZoneAwareLoadBalancer lb = (ZoneAwareLoadBalancer) ClientFactory.getNamedLoadBalancer("mylb"); assertTrue(lb.getLoadBalancer("myzone").getRule() instanceof RandomRule); } @Test public void testActiveConnectionsLimit() { ConfigurationManager.getConfigInstance().clearProperty("niws.loadbalancer.serverStats.activeRequestsCount.effectiveWindowSeconds"); ConfigurationManager.getConfigInstance().setProperty("testlb.ribbon.ActiveConnectionsLimit", 1); ZoneAwareLoadBalancer balancer = (ZoneAwareLoadBalancer) ClientFactory.getNamedLoadBalancer("testlb"); LoadBalancerStats loadBalancerStats = balancer.getLoadBalancerStats(); assertNotNull(loadBalancerStats); List<Server> servers = new ArrayList<Server>(); servers.add(createServer(1, "a")); servers.add(createServer(2, "a")); servers.add(createServer(3, "a")); servers.add(createServer(4, "a")); servers.add(createServer(5, "a")); servers.add(createServer(6, "a")); servers.add(createServer(1, "b")); servers.add(createServer(2, "b")); servers.add(createServer(3, "b")); servers.add(createServer(4, "b")); servers.add(createServer(5, "b")); servers.add(createServer(6, "b")); servers.add(createServer(7, "b")); servers.add(createServer(8, "b")); balancer.setServersList(servers); balancer.setUpServerList(servers); // cause both zone a and b outage Server server = servers.get(0); loadBalancerStats.getSingleServerStat(server).incrementActiveRequestsCount(); server = servers.get(8); loadBalancerStats.getSingleServerStat(server).incrementActiveRequestsCount(); server = servers.get(servers.size() - 1); for (int j = 0; j < 3; j++) { loadBalancerStats.getSingleServerStat(server).incrementSuccessiveConnectionFailureCount(); } Set<Server> expected = new HashSet<Server>(); expected.add(createServer(2, "a")); expected.add(createServer(3, "a")); expected.add(createServer(4, "a")); expected.add(createServer(5, "a")); expected.add(createServer(6, "a")); expected.add(createServer(1, "b")); expected.add(createServer(2, "b")); expected.add(createServer(4, "b")); expected.add(createServer(5, "b")); expected.add(createServer(6, "b")); expected.add(createServer(7, "b")); AvailabilityFilteringRule rule = (AvailabilityFilteringRule) balancer.getRule(); assertEquals(expected.size(), rule.getAvailableServersCount()); AvailabilityFilteringRule rule1 = (AvailabilityFilteringRule) balancer.getLoadBalancer("us-east-1a").getRule(); assertEquals(5, rule1.getAvailableServersCount()); AvailabilityFilteringRule rule2 = (AvailabilityFilteringRule) balancer.getLoadBalancer("us-east-1b").getRule(); assertEquals(6, rule2.getAvailableServersCount()); Set<Server> result = new HashSet<Server>(); for (int i = 0; i < 100; i++) { result.add(balancer.chooseServer(null)); } assertEquals(expected, result); } }
6,995
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/SimpleRoundRobinLBTest.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.loadbalancer; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class SimpleRoundRobinLBTest { static BaseLoadBalancer lb; static Map<String, Boolean> isAliveMap = new ConcurrentHashMap<String, Boolean>(); @BeforeClass public static void setup(){ LogManager.getRootLogger().setLevel((Level)Level.DEBUG); isAliveMap.put("dummyservice0.netflix.com:8080", Boolean.TRUE); isAliveMap.put("dummyservice1.netflix.com:8080", Boolean.TRUE); isAliveMap.put("dummyservice2.netflix.com:8080", Boolean.TRUE); isAliveMap.put("dummyservice3.netflix.com:8080", Boolean.TRUE); IPing ping = new PingFake(); IRule rule = new RoundRobinRule(); lb = new BaseLoadBalancer(ping,rule); lb.setPingInterval(1); lb.setMaxTotalPingTime(2); // the setting of servers is done by a call to DiscoveryService List<Server> servers = new ArrayList<Server>(); for (String svc: isAliveMap.keySet()){ servers.add(new Server(svc)); } lb.addServers(servers); // make sure the ping cycle has kicked in and all servers are set to alive try { Thread.sleep(5000); } catch (InterruptedException e) { } } @AfterClass public static void cleanup() { LogManager.getRootLogger().setLevel((Level)Level.INFO); } @Test public void testAddingServers() { BaseLoadBalancer baseLb = new BaseLoadBalancer(new PingFake(), new RoundRobinRule()); List<Server> servers = new ArrayList<Server>(); servers.add(new Server("dummyservice0.netflix.com:8080")); baseLb.addServers(servers); servers.clear(); // add 1 servers.add(new Server("dummyservice1.netflix.com:8080")); int originalCount = servers.size(); baseLb.addServers(servers); assertEquals(originalCount, servers.size()); } /** * Simulate a single user who should just round robin among the available servers */ @Test public void testRoundRobin(){ Set<String> servers = new HashSet<String>(); System.out.println("Simple Round Robin Test"); for (int i=0; i < 9; i++){ Server svc = lb.chooseServer("user1"); servers.add(svc.getId()); } assertEquals(isAliveMap.keySet(), servers); System.out.println("Round Robin Test With Server SERVER DOWN"); isAliveMap.put("dummyservice2.netflix.com:8080", Boolean.FALSE); ((BaseLoadBalancer)lb).markServerDown("dummyservice2.netflix.com:8080"); try { Thread.sleep(3000); } catch (Exception e) { // NOPMD } for (int i=0; i < 12; i++){ Server svc = lb.chooseServer("user1"); assertNotNull(svc); System.out.println("server: " + svc.getHost()); assertFalse(svc.getId().equals("dummyservice2.netflix.com:8080")); } } static class PingFake implements IPing { public boolean isAlive(Server server) { Boolean res = isAliveMap.get(server.getId()); return ((res != null) && (res.booleanValue())); } } }
6,996
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/DynamicServerListLoadBalancerTest.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.loadbalancer; import static org.junit.Assert.*; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.ClassRule; import org.junit.Test; import com.google.common.collect.Lists; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.client.testutil.MockHttpServer; public class DynamicServerListLoadBalancerTest { @ClassRule public static MockHttpServer server = new MockHttpServer(); public static class MyServerList extends AbstractServerList<Server> { public final static CountDownLatch latch = new CountDownLatch(5); public final static AtomicInteger counter = new AtomicInteger(0); public static final List<Server> list = Lists.newArrayList(new Server(server.getServerUrl())); public MyServerList() { } public MyServerList(IClientConfig clientConfig) { } @Override public List<Server> getInitialListOfServers() { return list; } @Override public List<Server> getUpdatedListOfServers() { counter.incrementAndGet(); latch.countDown(); return list; } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { } } @Test public void testDynamicServerListLoadBalancer() throws Exception { DefaultClientConfigImpl config = DefaultClientConfigImpl.getClientConfigWithDefaultValues(); config.set(CommonClientConfigKey.NIWSServerListClassName, MyServerList.class.getName()); config.set(CommonClientConfigKey.NFLoadBalancerClassName, DynamicServerListLoadBalancer.class.getName()); config.set(CommonClientConfigKey.ServerListRefreshInterval, 50); DynamicServerListLoadBalancer<Server> lb = new DynamicServerListLoadBalancer<Server>(config); try { assertTrue(MyServerList.latch.await(2, TimeUnit.SECONDS)); } catch (InterruptedException e) { // NOPMD } assertEquals(lb.getAllServers(), MyServerList.list); lb.stopServerListRefreshing(); Thread.sleep(1000); int count = MyServerList.counter.get(); assertTrue(count >= 5); Thread.sleep(1000); assertEquals(count, MyServerList.counter.get()); } }
6,997
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/PollingServerListUpdaterTest.java
package com.netflix.loadbalancer; import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import static org.junit.Assert.assertTrue; /** * @author David Liu */ public class PollingServerListUpdaterTest { private final long updateIntervalMs = 50; @Test public void testUpdating() throws Exception { PollingServerListUpdater serverListUpdater = new PollingServerListUpdater(0, updateIntervalMs); try { final AtomicLong lastUpdateTimestamp = new AtomicLong(); final CountDownLatch countDownLatch = new CountDownLatch(2); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { countDownLatch.countDown(); lastUpdateTimestamp.set(System.currentTimeMillis()); } }); assertTrue(countDownLatch.await(2, TimeUnit.SECONDS)); assertTrue(serverListUpdater.getDurationSinceLastUpdateMs() <= updateIntervalMs); } finally { serverListUpdater.stop(); } } }
6,998
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/LoadBalancerCommandTest.java
package com.netflix.loadbalancer; import static org.junit.Assert.assertEquals; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import com.google.common.collect.Lists; import com.netflix.client.RetryHandler; import com.netflix.loadbalancer.reactive.LoadBalancerCommand; import com.netflix.loadbalancer.reactive.ServerOperation; public class LoadBalancerCommandTest { static Server server1 = new Server("1", 80); static Server server2 = new Server("2", 80); static Server server3 = new Server("3", 80); static List<Server> list = Lists.newArrayList(server1, server2, server3); @Test public void testRetrySameServer() { BaseLoadBalancer loadBalancer = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(list); RetryHandler handler = new RetryHandler() { @Override public boolean isRetriableException(Throwable e, boolean sameServer) { return (e instanceof IllegalArgumentException); } @Override public boolean isCircuitTrippingException(Throwable e) { return false; } @Override public int getMaxRetriesOnSameServer() { return 3; } @Override public int getMaxRetriesOnNextServer() { return 0; } }; LoadBalancerCommand<String> command = LoadBalancerCommand.<String>builder() .withLoadBalancer(loadBalancer) .withRetryHandler(handler) .withServer(server1) .build(); ServerOperation<String> operation = new ServerOperation<String>() { AtomicInteger count = new AtomicInteger(); @Override public Observable<String> call(final Server server) { return Observable.create(new OnSubscribe<String>(){ @Override public void call(Subscriber<? super String> t1) { if (count.incrementAndGet() < 3) { t1.onError(new IllegalArgumentException()); } else { t1.onNext(server.getHost()); t1.onCompleted(); } } }); } }; String result = command.submit(operation).toBlocking().single(); assertEquals(3, loadBalancer.getLoadBalancerStats().getSingleServerStat(server1).getTotalRequestsCount()); assertEquals("1", result); } @Test public void testRetryNextServer() { BaseLoadBalancer loadBalancer = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(list); RetryHandler handler = new RetryHandler() { @Override public boolean isRetriableException(Throwable e, boolean sameServer) { return (e instanceof IllegalArgumentException); } @Override public boolean isCircuitTrippingException(Throwable e) { return false; } @Override public int getMaxRetriesOnSameServer() { return 1; } @Override public int getMaxRetriesOnNextServer() { return 5; } }; ServerOperation<String> operation = new ServerOperation<String>() { AtomicInteger count = new AtomicInteger(); @Override public Observable<String> call(final Server server) { return Observable.create(new OnSubscribe<String>(){ @Override public void call(Subscriber<? super String> t1) { if (count.incrementAndGet() < 3) { t1.onError(new IllegalArgumentException()); } else { t1.onNext(server.getHost()); t1.onCompleted(); } } }); } }; LoadBalancerCommand<String> command = LoadBalancerCommand.<String>builder() .withLoadBalancer(loadBalancer) .withRetryHandler(handler) .build(); String result = command.submit(operation).toBlocking().single(); assertEquals("3", result); // server2 is picked first assertEquals(1, loadBalancer.getLoadBalancerStats().getSingleServerStat(server3).getTotalRequestsCount()); } }
6,999