Example usage for com.google.common.collect Maps newConcurrentMap

List of usage examples for com.google.common.collect Maps newConcurrentMap

Introduction

In this page you can find the example usage for com.google.common.collect Maps newConcurrentMap.

Prototype

public static <K, V> ConcurrentMap<K, V> newConcurrentMap() 

Source Link

Document

Returns a general-purpose instance of ConcurrentMap , which supports all optional operations of the ConcurrentMap interface.

Usage

From source file:com.palantir.atlasdb.transaction.impl.SerializableTransaction.java

private void setRangeEnd(String table, RangeRequest range, byte[] maxRow) {
    Validate.notNull(maxRow);//from   w ww  .  j  a  v  a 2s.  c  om
    ConcurrentMap<RangeRequest, byte[]> rangeEnds = rangeEndByTable.get(table);
    if (rangeEnds == null) {
        ConcurrentMap<RangeRequest, byte[]> newMap = Maps.newConcurrentMap();
        rangeEndByTable.putIfAbsent(table, newMap);
        rangeEnds = rangeEndByTable.get(table);
    }

    if (maxRow.length == 0) {
        rangeEnds.put(range, maxRow);
    }

    while (true) {
        byte[] curVal = rangeEnds.get(range);
        if (curVal == null) {
            byte[] oldVal = rangeEnds.putIfAbsent(range, maxRow);
            if (oldVal == null) {
                return;
            } else {
                continue;
            }
        }
        if (curVal.length == 0) {
            return;
        }
        if (UnsignedBytes.lexicographicalComparator().compare(curVal, maxRow) >= 0) {
            return;
        }
        if (rangeEnds.replace(range, curVal, maxRow)) {
            return;
        }
    }
}

From source file:com.baidu.rigel.biplatform.ma.resource.QueryDataResource.java

/**
 * ??,??//from   www  .  j  ava 2s .  c o m
 * @param reportId
 * @param request
 * @return ResponseResult
 */
@RequestMapping(value = "/{reportId}/init_params", method = { RequestMethod.POST })
public ResponseResult initParams(@PathVariable("reportId") String reportId, HttpServletRequest request) {
    long begin = System.currentTimeMillis();
    logger.info("[INFO]--- ---begin init params with report id {}", reportId);
    String[] areaIds = request.getParameter("paramList").split(",");
    if (areaIds == null || areaIds.length == 0) {
        ResponseResult rs = new ResponseResult();
        rs.setStatus(0);
        logger.info("[INFO]--- --- not needed init global params");
        return rs;
    }
    final ReportDesignModel model = getDesignModelFromRuntimeModel(reportId);
    final ReportRuntimeModel runtimeModel = reportModelCacheManager.getRuntimeModel(reportId);
    Map<String, Map<String, List<Map<String, String>>>> datas = Maps.newConcurrentMap();
    Map<String, String> params = Maps.newHashMap();
    runtimeModel.getContext().getParams().forEach((k, v) -> {
        params.put(k, v == null ? "" : v.toString());
    });
    //        DataSourceInfo dsInfo = null;
    //        try {
    //            dsInfo = DataSourceDefineUtil.parseToDataSourceInfo(dsService.getDsDefine(model.getDsId()), 
    //                    securityKey);
    //        } catch (DataSourceOperationException e1) {
    //            logger.error(e1.getMessage(), e1);
    //        }
    for (final String areaId : areaIds) {
        ExtendArea area = model.getExtendById(areaId);
        if (area != null && isQueryComp(area.getType()) && !area.listAllItems().isEmpty()) {
            Item item = area.listAllItems().values().toArray(new Item[0])[0];
            Cube cube = model.getSchema().getCubes().get(area.getCubeId());
            Cube tmpCube = QueryUtils.transformCube(cube);
            String dimId = item.getOlapElementId();
            Dimension dim = cube.getDimensions().get(dimId);
            if (dim != null) {
                List<Map<String, String>> values;
                try {
                    values = Lists.newArrayList();
                    params.remove(dim.getId());
                    params.put(Constants.LEVEL_KEY, "1");
                    List<Member> members = reportModelQueryService.getMembers(tmpCube,
                            tmpCube.getDimensions().get(dim.getName()), params, securityKey).get(0);
                    members.forEach(m -> {
                        Map<String, String> tmp = Maps.newHashMap();
                        tmp.put("value", m.getUniqueName());
                        tmp.put("text", m.getCaption());
                        if (dim.getLevels().size() <= 1) {
                            tmp.put("isLeaf", "1");
                        }
                        MiniCubeMember realMember = (MiniCubeMember) m;
                        if (realMember.getParent() != null) {
                            tmp.put("parent", realMember.getParent().getUniqueName());
                        } else {
                            tmp.put("parent", "");
                        }
                        values.add(tmp);
                        List<Map<String, String>> children = getChildren(realMember, realMember.getChildren());
                        if (children != null && !children.isEmpty()) {
                            values.addAll(children);
                        }
                    });
                    //                        List<Map<String, String>> values = 
                    //                                QueryUtils.getMembersWithChildrenValue(members, tmpCube, dsInfo, Maps.newHashMap());
                    Map<String, List<Map<String, String>>> datasource = Maps.newHashMap();
                    datasource.put("datasource", values);
                    datas.put(areaId, datasource);
                } catch (Exception e) {
                    logger.info(e.getMessage(), e);
                }
            }
        }
    }
    ResponseResult rs = new ResponseResult();
    rs.setStatus(0);
    rs.setData(datas);
    rs.setStatusInfo("OK");
    logger.info("[INFO]--- --- successfully init params, cost {} ms", (System.currentTimeMillis() - begin));
    return rs;
}

From source file:co.cask.cdap.hive.serde.ObjectSerializer.java

private Object fromLazyObject(TypeInfo type, Object data) {
    if (data == null) {
        return null;
    }//from w w  w . ja va  2 s  . com

    switch (type.getCategory()) {
    case PRIMITIVE:
        Writable writable = ((LazyPrimitive) data).getWritableObject();
        return fromWritable(writable);

    case LIST:
        ListTypeInfo listType = (ListTypeInfo) type;
        TypeInfo listElementType = listType.getListElementTypeInfo();

        List<Object> list = ((LazyArray) data).getList();
        if (list.isEmpty()) {
            return ImmutableList.of();
        }

        Object[] arrayContent = new Object[list.size()];
        for (int i = 0; i < arrayContent.length; i++) {
            arrayContent[i] = fromLazyObject(listElementType, list.get(i));
        }
        return arrayContent;

    case MAP:
        MapTypeInfo mapType = (MapTypeInfo) type;

        Map<Object, Object> mapContent = Maps.newConcurrentMap();
        Map<Object, Object> map = ((LazyMap) data).getMap();

        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            mapContent.put(fromLazyObject(mapType.getMapKeyTypeInfo(), entry.getKey()),
                    fromLazyObject(mapType.getMapValueTypeInfo(), entry.getValue()));
        }
        return mapContent;

    case STRUCT:
        StructTypeInfo structType = (StructTypeInfo) type;
        List<TypeInfo> info = structType.getAllStructFieldTypeInfos();
        List<String> names = structType.getAllStructFieldNames();

        Map<String, Object> structMap = Maps.newConcurrentMap();
        List<Object> struct = ((LazyStruct) data).getFieldsAsList();

        for (int structIndex = 0; structIndex < info.size(); structIndex++) {
            structMap.put(names.get(structIndex),
                    fromLazyObject(info.get(structIndex), struct.get(structIndex)));
        }
        return structMap;
    case UNION:
        throw new UnsupportedOperationException("union not yet supported");

    default:
        return data.toString();
    }
}

From source file:com.kolich.curacao.mappers.MapperTable.java

public MapperTable(@Nonnull final ComponentTable componentTable) {
    componentTable_ = checkNotNull(componentTable, "Component table cannot be null.");
    final String bootPackage = CuracaoConfigLoader.getBootPackage();
    logger__.info("Loading mappers from declared boot-package: {}", bootPackage);
    // Scan the boot package and find all "mapper classes" that are
    // annotated with our mapper annotation.  We do this reflection scan
    // of the boot package once at the front door for performance reasons.
    final Set<Class<?>> mappers = getTypesInPackageAnnotatedWith(bootPackage, Mapper.class);
    // Build the argument mapper table.
    argMapperTable_ = buildArgumentMapperTable(mappers);
    // Build the return return type mapper table and its cache.
    returnTypeMapperTable_ = buildReturnTypeMapperTable(mappers);
    returnTypeMapperCache_ = Maps.newConcurrentMap();
    logger__.info("Application argument mapper table: {}", argMapperTable_);
    logger__.info("Application return type mapper table: {}", returnTypeMapperTable_);
}

From source file:co.cask.cdap.explore.service.hive.BaseHiveExploreService.java

protected BaseHiveExploreService(TransactionSystemClient txClient, DatasetFramework datasetFramework,
        CConfiguration cConf, Configuration hConf, HiveConf hiveConf, File previewsDir, StreamAdmin streamAdmin,
        Store store, SystemDatasetInstantiatorFactory datasetInstantiatorFactory) {
    this.cConf = cConf;
    this.hConf = hConf;
    this.hiveConf = hiveConf;
    this.schedulerQueueResolver = new SchedulerQueueResolver(cConf, store);
    this.previewsDir = previewsDir;
    this.metastoreClientLocal = new ThreadLocal<>();
    this.metastoreClientReferences = Maps.newConcurrentMap();
    this.metastoreClientReferenceQueue = new ReferenceQueue<>();
    this.datasetFramework = datasetFramework;
    this.streamAdmin = streamAdmin;
    this.exploreTableManager = new ExploreTableManager(this, datasetInstantiatorFactory);
    this.datasetInstantiatorFactory = datasetInstantiatorFactory;

    // Create a Timer thread to periodically collect metastore clients that are no longer in used and call close on them
    this.metastoreClientsExecutorService = Executors
            .newSingleThreadScheduledExecutor(Threads.createDaemonThreadFactory("metastore-client-gc"));

    this.scheduledExecutorService = Executors
            .newSingleThreadScheduledExecutor(Threads.createDaemonThreadFactory("explore-handle-timeout"));

    this.activeHandleCache = CacheBuilder.newBuilder()
            .expireAfterWrite(cConf.getLong(Constants.Explore.ACTIVE_OPERATION_TIMEOUT_SECS), TimeUnit.SECONDS)
            .removalListener(new ActiveOperationRemovalHandler(this, scheduledExecutorService)).build();
    this.inactiveHandleCache = CacheBuilder.newBuilder().expireAfterWrite(
            cConf.getLong(Constants.Explore.INACTIVE_OPERATION_TIMEOUT_SECS), TimeUnit.SECONDS).build();

    this.cliService = createCLIService();

    this.txClient = txClient;
    ContextManager.saveContext(datasetFramework, streamAdmin, datasetInstantiatorFactory);

    cleanupJobSchedule = cConf.getLong(Constants.Explore.CLEANUP_JOB_SCHEDULE_SECS);

    LOG.info("Active handle timeout = {} secs", cConf.getLong(Constants.Explore.ACTIVE_OPERATION_TIMEOUT_SECS));
    LOG.info("Inactive handle timeout = {} secs",
            cConf.getLong(Constants.Explore.INACTIVE_OPERATION_TIMEOUT_SECS));
    LOG.info("Cleanup job schedule = {} secs", cleanupJobSchedule);
}

From source file:org.apache.tajo.master.querymaster.Query.java

public Query(final QueryMasterTask.QueryMasterTaskContext context, final QueryId id, final long appSubmitTime,
        final String queryStr, final EventHandler eventHandler, final MasterPlan plan) {
    this.context = context;
    this.systemConf = context.getConf();
    this.id = id;
    this.clock = context.getClock();
    this.appSubmitTime = appSubmitTime;
    this.queryStr = queryStr;
    this.stages = Maps.newConcurrentMap();
    this.eventHandler = eventHandler;
    this.plan = plan;
    this.cursor = new ExecutionBlockCursor(plan, true);

    StringBuilder sb = new StringBuilder("\n=======================================================");
    sb.append("\nThe order of execution: \n");
    int order = 1;
    while (cursor.hasNext()) {
        ExecutionBlock currentEB = cursor.nextBlock();
        sb.append("\n").append(order).append(": ").append(currentEB.getId());
        order++;/* www  .  j  ava 2 s.  c o m*/
    }
    sb.append("\n=======================================================");
    LOG.info(sb);
    cursor.reset();

    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    this.readLock = readWriteLock.readLock();
    this.writeLock = readWriteLock.writeLock();

    stateMachine = stateMachineFactory.make(this);
    queryState = stateMachine.getCurrentState();
}

From source file:com.google.android.apps.paco.FindExperimentsActivity.java

public void updateDownloadedExperiments(String contentAsString) {
    try {//from  w ww  .  j av a  2  s.co m
        Map<String, Object> results = ExperimentProviderUtil.fromEntitiesJson(contentAsString);
        String newExperimentCursor = (String) results.get("cursor");
        List<Experiment> newExperiments = (List<Experiment>) results.get("results");

        if (experimentCursor == null) { // we have either not loaded before or are starting over
            experiments = newExperiments;
            Collections.sort(experiments, new Comparator<Experiment>() {

                @Override
                public int compare(Experiment lhs, Experiment rhs) {
                    return lhs.getTitle().toLowerCase().compareTo(rhs.getTitle().toLowerCase());
                }

            });
            experimentCursor = newExperimentCursor;
            saveExperimentsToDisk();
        } else {
            Map<Long, Experiment> existingAndNewExperimentsMap = Maps.newConcurrentMap();
            for (Experiment existingExperiment : experiments) {
                existingAndNewExperimentsMap.put(existingExperiment.getServerId(), existingExperiment);
            }
            for (Experiment experiment : newExperiments) {
                existingAndNewExperimentsMap.put(experiment.getServerId(), experiment);
            }
            experiments = Lists.newArrayList(existingAndNewExperimentsMap.values());
            Collections.sort(experiments, new Comparator<Experiment>() {

                @Override
                public int compare(Experiment lhs, Experiment rhs) {
                    return lhs.getTitle().toLowerCase().compareTo(rhs.getTitle().toLowerCase());
                }

            });
            experimentCursor = newExperimentCursor;
            saveExperimentsToDisk();
        }
        if (newExperiments.size() == 0 || newExperimentCursor == null) {
            experimentCursor = null; // we have hit the end. The next refresh starts over
            refreshButton.setText(getString(R.string.refresh_experiments_list_from_server));
        } else {
            refreshButton.setText(getString(R.string.load_more_experiments_from_server));
        }
        reloadAdapter();
    } catch (JsonParseException e) {
        showFailureDialog(DownloadHelper.CONTENT_ERROR);
    } catch (JsonMappingException e) {
        showFailureDialog(DownloadHelper.CONTENT_ERROR);
    } catch (UnsupportedCharsetException e) {
        showFailureDialog(DownloadHelper.CONTENT_ERROR);
    } catch (IOException e) {
        showFailureDialog(DownloadHelper.CONTENT_ERROR);
    }
}

From source file:org.onosproject.vtnweb.resources.TenantNetworkWebResource.java

/**
 * Returns a collection of tenantNetworks.
 *
 * @param flag the flag//from w  w w .j  av  a 2s.  c om
 * @param networkId network identifier
 * @param node the network json node
 * @return a collection of tenantNetworks
 */
public Iterable<TenantNetwork> changeJson2obj(String flag, TenantNetworkId networkId, JsonNode node) {
    checkNotNull(node, JSON_NOT_NULL);
    TenantNetwork network = null;
    ConcurrentMap<TenantNetworkId, TenantNetwork> networksMap = Maps.newConcurrentMap();
    if (node != null) {
        checkArgument(node.get("admin_state_up").isBoolean(), "admin_state_up should be boolean");
        checkArgument(node.get("shared").isBoolean(), "shared should be boolean");
        checkArgument(node.get("router:external").isBoolean(), "router:external should be boolean");
        String name = node.get("name").asText();
        boolean adminStateUp = node.get("admin_state_up").asBoolean();
        String state = node.get("status").asText();
        boolean shared = node.get("shared").asBoolean();
        String tenantId = node.get("tenant_id").asText();
        boolean routerExternal = node.get("router:external").asBoolean();
        String type = node.get("provider:network_type").asText();
        String physicalNetwork = node.get("provider:physical_network").asText();
        String segmentationId = node.get("provider:segmentation_id").asText();
        TenantNetworkId id = null;
        if (flag == CREATE_NETWORK) {
            id = TenantNetworkId.networkId(node.get("id").asText());
        } else if (flag == UPDATE_NETWORK) {
            id = networkId;
        }
        network = new DefaultTenantNetwork(id, name, adminStateUp, isState(state), shared,
                TenantId.tenantId(tenantId), routerExternal, isType(type),
                PhysicalNetwork.physicalNetwork(physicalNetwork),
                SegmentationId.segmentationId(segmentationId));
        networksMap.putIfAbsent(id, network);
    }
    return Collections.unmodifiableCollection(networksMap.values());
}

From source file:com.attribyte.essem.ESUserStore.java

/**
 * Caches a graph./*from   w  ww.  j a v  a  2s  .  co  m*/
 * @param graph The graph.
 * @return The input graph.
 */
private StoredGraph cacheGraph(StoredGraph graph) {
    recentGraphCache.put(graph.id, graph);
    Map<MetricKey, StoredGraph> userMap = recentUserGraphCache.getIfPresent(graph.uid);
    if (userMap == null) {
        userMap = Maps.newConcurrentMap();
        recentUserGraphCache.put(graph.uid, userMap);
    }
    userMap.put(graph.key, graph);
    return graph;
}

From source file:com.jivesoftware.os.miru.writer.deployable.MiruWriterMain.java

void run(String[] args) throws Exception {
    ServiceStartupHealthCheck serviceStartupHealthCheck = new ServiceStartupHealthCheck();
    try {/*from   ww  w  . j a va 2s . c om*/
        final Deployable deployable = new Deployable(args);
        InstanceConfig instanceConfig = deployable.config(InstanceConfig.class);
        HealthFactory.initialize(deployable::config, new DeployableHealthCheckRegistry(deployable));
        deployable.addManageInjectables(HasUI.class, new HasUI(Arrays
                .asList(new UI("Miru-Writer", "main", "/ui"), new UI("Miru-Writer-Amza", "main", "/amza/ui"))));

        deployable.addHealthCheck(new GCPauseHealthChecker(
                deployable.config(GCPauseHealthChecker.GCPauseHealthCheckerConfig.class)));
        deployable.addHealthCheck(new GCLoadHealthChecker(
                deployable.config(GCLoadHealthChecker.GCLoadHealthCheckerConfig.class)));
        deployable.addHealthCheck(new SystemCpuHealthChecker(
                deployable.config(SystemCpuHealthChecker.SystemCpuHealthCheckerConfig.class)));
        deployable.addHealthCheck(new LoadAverageHealthChecker(
                deployable.config(LoadAverageHealthChecker.LoadAverageHealthCheckerConfig.class)));
        deployable.addHealthCheck(new FileDescriptorCountHealthChecker(deployable
                .config(FileDescriptorCountHealthChecker.FileDescriptorCountHealthCheckerConfig.class)));
        deployable.addHealthCheck(serviceStartupHealthCheck);
        deployable.addErrorHealthChecks(deployable.config(ErrorHealthCheckConfig.class));
        AtomicReference<Callable<Boolean>> isAmzaReady = new AtomicReference<>(() -> false);
        deployable.addManageInjectables(FullyOnlineVersion.class, (FullyOnlineVersion) () -> {
            if (serviceStartupHealthCheck.startupHasSucceeded() && isAmzaReady.get().call()) {
                return instanceConfig.getVersion();
            } else {
                return null;
            }
        });
        deployable.buildManageServer().start();

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapper.registerModule(new GuavaModule());

        TenantRoutingProvider tenantRoutingProvider = deployable.getTenantRoutingProvider();
        TenantRoutingHttpClientInitializer<String> tenantRoutingHttpClientInitializer = deployable
                .getTenantRoutingHttpClientInitializer();
        HttpDeliveryClientHealthProvider clientHealthProvider = new HttpDeliveryClientHealthProvider(
                instanceConfig.getInstanceKey(), HttpRequestHelperUtils.buildRequestHelper(false, false, null,
                        instanceConfig.getRoutesHost(), instanceConfig.getRoutesPort()),
                instanceConfig.getConnectionsHealth(), 5_000, 100);

        MiruLogAppenderConfig miruLogAppenderConfig = deployable.config(MiruLogAppenderConfig.class);
        @SuppressWarnings("unchecked")
        TenantAwareHttpClient<String> miruStumptownClient = tenantRoutingHttpClientInitializer
                .builder(tenantRoutingProvider.getConnections("miru-stumptown", "main", 10_000),
                        clientHealthProvider)
                .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).build();
        new MiruLogAppenderInitializer().initialize(instanceConfig.getDatacenter(),
                instanceConfig.getClusterName(), instanceConfig.getHost(), instanceConfig.getServiceName(),
                String.valueOf(instanceConfig.getInstanceName()), instanceConfig.getVersion(),
                miruLogAppenderConfig, miruStumptownClient).install();

        MiruMetricSamplerConfig metricSamplerConfig = deployable.config(MiruMetricSamplerConfig.class);
        @SuppressWarnings("unchecked")
        TenantAwareHttpClient<String> miruAnomalyClient = tenantRoutingHttpClientInitializer
                .builder(tenantRoutingProvider.getConnections("miru-anomaly", "main", 10_000),
                        clientHealthProvider)
                .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).build();
        new MiruMetricSamplerInitializer().initialize(instanceConfig.getDatacenter(),
                instanceConfig.getClusterName(), instanceConfig.getHost(), instanceConfig.getServiceName(),
                String.valueOf(instanceConfig.getInstanceName()), instanceConfig.getVersion(),
                metricSamplerConfig, miruAnomalyClient).start();

        MiruClientConfig clientConfig = deployable.config(MiruClientConfig.class);

        @SuppressWarnings("unchecked")
        TenantAwareHttpClient<String> manageHttpClient = tenantRoutingHttpClientInitializer
                .builder(tenantRoutingProvider.getConnections("miru-manage", "main", 10_000), // TODO config
                        clientHealthProvider)
                .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).build(); // TODO expose to conf

        @SuppressWarnings("unchecked")
        TenantAwareHttpClient<String> walHttpClient = tenantRoutingHttpClientInitializer
                .builder(tenantRoutingProvider.getConnections("miru-wal", "main", 10_000), // TODO config
                        clientHealthProvider)
                .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).build(); // TODO expose to conf

        final Map<MiruTenantId, Boolean> latestAlignmentCache = Maps.newConcurrentMap();

        WriterAmzaServiceConfig miruAmzaServiceConfig = deployable.config(WriterAmzaServiceConfig.class);
        Lifecycle amzaLifecycle = new MiruAmzaServiceInitializer().initialize(deployable, clientHealthProvider,
                instanceConfig.getInstanceName(), instanceConfig.getInstanceKey(),
                instanceConfig.getServiceName(), instanceConfig.getDatacenter(), instanceConfig.getRack(),
                instanceConfig.getHost(), instanceConfig.getMainPort(),
                instanceConfig.getMainServiceAuthEnabled(), null, //"miru-writer-" + instanceConfig.getClusterName(),
                miruAmzaServiceConfig, true, -1, changes -> {
                    if (changes.getVersionedPartitionName().getPartitionName()
                            .equals(AmzaPartitionIdProvider.LATEST_PARTITIONS_PARTITION_NAME)) {
                        for (WALKey key : changes.getApply().keySet()) {
                            MiruTenantId tenantId = AmzaPartitionIdProvider
                                    .extractTenantForLatestPartition(key);
                            latestAlignmentCache.remove(tenantId);
                        }
                    }
                });

        SickThreads walClientSickThreads = new SickThreads();
        deployable.addHealthCheck(new SickThreadsHealthCheck(
                deployable.config(WALClientSickThreadsHealthCheckConfig.class), walClientSickThreads));

        MiruWALConfig walConfig = deployable.config(MiruWALConfig.class);
        MiruWALClient<?, ?> walClient;
        if (walConfig.getActivityWALType().equals("rcvs")
                || walConfig.getActivityWALType().equals("rcvs_amza")) {
            MiruWALClient<RCVSCursor, RCVSSipCursor> rcvsWALClient = new MiruWALClientInitializer().initialize(
                    "", walHttpClient, mapper, walClientSickThreads, 10_000, "/miru/wal/rcvs", RCVSCursor.class,
                    RCVSSipCursor.class);
            walClient = rcvsWALClient;
        } else if (walConfig.getActivityWALType().equals("amza")
                || walConfig.getActivityWALType().equals("amza_rcvs")) {
            MiruWALClient<AmzaCursor, AmzaSipCursor> amzaWALClient = new MiruWALClientInitializer().initialize(
                    "", walHttpClient, mapper, walClientSickThreads, 10_000, "/miru/wal/amza", AmzaCursor.class,
                    AmzaSipCursor.class);
            walClient = amzaWALClient;
        } else {
            throw new IllegalStateException("Invalid activity WAL type: " + walConfig.getActivityWALType());
        }

        String indexClass = "lab";

        EmbeddedClientProvider clientProvider = new EmbeddedClientProvider(amzaLifecycle.amzaService);
        AmzaPartitionIdProvider amzaPartitionIdProvider = new AmzaPartitionIdProvider(amzaLifecycle.amzaService,
                clientProvider, miruAmzaServiceConfig.getReplicateLatestPartitionTimeoutMillis(),
                miruAmzaServiceConfig.getReplicateCursorTimeoutMillis(), indexClass,
                clientConfig.getTotalCapacity(), walClient);

        MiruStats miruStats = new MiruStats();
        MiruClusterClient clusterClient = new MiruClusterClientInitializer().initialize(miruStats, "",
                manageHttpClient, mapper);

        MiruPartitioner miruPartitioner = new MiruPartitioner(instanceConfig.getInstanceName(),
                amzaPartitionIdProvider, walClient, clusterClient,
                clientConfig.getPartitionMaximumAgeInMillis());

        ExecutorService sendActivitiesExecutorService = Executors
                .newFixedThreadPool(clientConfig.getSendActivitiesThreadPoolSize());
        MiruActivityIngress activityIngress = new MiruActivityIngress(miruPartitioner, latestAlignmentCache,
                sendActivitiesExecutorService);

        MiruSoyRendererConfig rendererConfig = deployable.config(MiruSoyRendererConfig.class);

        File staticResourceDir = new File(System.getProperty("user.dir"));
        System.out.println("Static resources rooted at " + staticResourceDir.getAbsolutePath());
        Resource sourceTree = new Resource(staticResourceDir)
                //.addResourcePath("../../../../../src/main/resources") // fluff?
                .addResourcePath(rendererConfig.getPathToStaticResources()).setDirectoryListingAllowed(false)
                .setContext("/ui/static");

        MiruSoyRenderer renderer = new MiruSoyRendererInitializer().initialize(rendererConfig);

        MiruWriterUIService miruWriterUIService = new MiruWriterUIServiceInitializer().initialize(
                instanceConfig.getClusterName(), instanceConfig.getInstanceName(), renderer, miruStats,
                tenantRoutingProvider);

        if (instanceConfig.getMainServiceAuthEnabled()) {
            deployable.addRouteOAuth("/miru/*");
            deployable.addSessionAuth("/ui/*", "/miru/*");
        } else {
            deployable.addNoAuth("/miru/*");
            deployable.addSessionAuth("/ui/*");
        }

        deployable.addEndpoints(MiruWriterEndpoints.class);
        deployable.addInjectables(MiruWriterUIService.class, miruWriterUIService);

        deployable.addEndpoints(MiruIngressEndpoints.class);
        deployable.addInjectables(MiruStats.class, miruStats);
        deployable.addInjectables(MiruActivityIngress.class, activityIngress);

        deployable.addResource(sourceTree);
        deployable.addEndpoints(LoadBalancerHealthCheckEndpoints.class);
        deployable.buildServer().start();
        clientHealthProvider.start();
        isAmzaReady.set(amzaLifecycle::isReady);
        serviceStartupHealthCheck.success();
    } catch (Throwable t) {
        serviceStartupHealthCheck.info("Encountered the following failure during startup.", t);
    }
}