com.google.common.base.Function Java Examples

The following examples show how to use com.google.common.base.Function. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SQLiteStoreImpl.java    From bistoury with GNU General Public License v3.0 7 votes vote down vote up
private static String getDeleteSql(List<String> keys) {
    List<String> newKeys = Lists.transform(keys, new Function<String, String>() {
        @Override
        public String apply(String input) {
            return "'" + input + "'";
        }
    });
    StringBuilder sb = new StringBuilder("delete from bistoury where b_key in (");

    Joiner joiner = Joiner.on(",").skipNulls();

    HashSet<String> set = Sets.newHashSet(newKeys);
    if (set.size() == 0) {
        return null;
    }

    joiner.appendTo(sb, set);
    sb.append(")");
    return sb.toString();
}
 
Example #2
Source File: Main.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private static Predicate<Entry> or(List<String> queries, Function<String, Predicate<Entry>> transform) {
   Preconditions.checkNotNull(transform);
   if(queries == null || queries.isEmpty()) {
      return Predicates.alwaysTrue();
   }
   List<Predicate<Entry>> predicates = new ArrayList<>(queries.size());
   for(String query: queries) {
      Predicate<Entry> p = transform.apply(query);
      if(p != null) {
         predicates.add(p);
      }
   }
   if(predicates.isEmpty()) {
      return Predicates.alwaysTrue();
   }
   else if(predicates.size() == 1) {
      return predicates.get(0);
   }
   else {
      return Predicates.or(predicates);
   }
}
 
Example #3
Source File: StorageResponseGTScatter.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public Iterator<GTRecord> iterator() {
    Iterator<PartitionResultIterator> iterators = Iterators.transform(blocks,
            new Function<byte[], PartitionResultIterator>() {
                public PartitionResultIterator apply(byte[] input) {
                    return new PartitionResultIterator(input, info, columns);
                }
            });

    if (!needSorted) {
        logger.debug("Using Iterators.concat to pipeline partition results");
        return Iterators.concat(iterators);
    }

    return new SortMergedPartitionResultIterator(iterators, info, GTRecord.getComparator(groupByDims));
}
 
Example #4
Source File: I18NServiceImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ClientFuture<LoadLocalizedStringsResponse> loadLocalizedStrings(Set<String> strings, String s) {
 ClientRequest request = new ClientRequest();
 Map<String, Object> elements = new HashMap<>();
 elements.put("bundleNames", strings);
 elements.put("locale", s);
 request.setAttributes(elements);
 request.setTimeoutMs(10000);
 request.setAddress(getAddress());
 request.setCommand(I18NService.CMD_LOADLOCALIZEDSTRINGS);
 request.setConnectionURL(client.getConnectionURL());
 request.setRestfulRequest(true);

    return Futures.transform(client.request(request), new Function<ClientEvent, LoadLocalizedStringsResponse>() {
        @Override
        public LoadLocalizedStringsResponse apply(ClientEvent input) {
            return (new LoadLocalizedStringsResponse(input));
        }
    });
}
 
Example #5
Source File: ProductCatalogServiceImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ClientFuture<GetProductCatalogResponse> getProductCatalog(String place) {
	GetProductCatalogRequest request = new GetProductCatalogRequest();
	request.setAddress(getAddress());
	request.setRestfulRequest(true);
	request.setPlace(place);

	ClientFuture<ClientEvent> result = client.request(request);

	return Futures.transform(result, new Function<ClientEvent, GetProductCatalogResponse>() {
		@Override
		public GetProductCatalogResponse apply(ClientEvent input) {
			GetProductCatalogResponse response = new GetProductCatalogResponse(input);
			return response;
		}
	});
}
 
Example #6
Source File: GraphViewerUtils.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a rectangle that contains all give vertices
 * 
 * @param viewer the viewer containing the UI
 * @param vertices the vertices 
 * @return a rectangle that contains all give vertices
 */
public static <V, E> Rectangle getBoundsForVerticesInLayoutSpace(
		VisualizationServer<V, E> viewer, Collection<V> vertices) {

	Layout<V, E> layout = viewer.getGraphLayout();
	RenderContext<V, E> renderContext = viewer.getRenderContext();
	Function<? super V, Shape> shapeTransformer = renderContext.getVertexShapeTransformer();

	Function<V, Rectangle> transformer = v -> {

		Shape shape = shapeTransformer.apply(v);
		Rectangle bounds = shape.getBounds();
		Point2D point = layout.apply(v);
		bounds.setLocation(new Point((int) point.getX(), (int) point.getY()));
		return bounds;
	};
	return getBoundsForVerticesInLayoutSpace(vertices, transformer);
}
 
Example #7
Source File: RuleServiceImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ClientFuture<GetRuleTemplatesByCategoryResponse> getRuleTemplatesByCategory(String placeId, String category) {
   ClientRequest request = buildRequest(
         RuleService.CMD_GETRULETEMPLATESBYCATEGORY,
         ImmutableMap.<String,Object>of(GetRuleTemplatesByCategoryRequest.ATTR_PLACEID, placeId,
                                        GetRuleTemplatesByCategoryRequest.ATTR_CATEGORY, category));
   ClientFuture<ClientEvent> result = client.request(request);
   return Futures.transform(result, new Function<ClientEvent, GetRuleTemplatesByCategoryResponse>() {
      @Override
      public GetRuleTemplatesByCategoryResponse apply(ClientEvent input) {
         GetRuleTemplatesByCategoryResponse response = new GetRuleTemplatesByCategoryResponse(input);
         IrisClientFactory.getModelCache().addOrUpdate(response.getRuleTemplates());
         return response;
      }
   });
}
 
Example #8
Source File: AnnotatedSubsystem.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
protected final void handleRequest(MessageReceivedEvent event, SubsystemContext<M> context) {
   PlatformMessage request = event.getMessage();
   String type = request.getMessageType();
   Function<SubsystemEventAndContext, MessageBody> handler = requestHandlers.get(type);
   if(handler == null) {
      context.sendResponse(request, Errors.invalidRequest(type));
   }
   else {
      MessageBody response;
      try {
         response = handler.apply(new SubsystemEventAndContext(context, event));
      }
      catch(Exception e) {
         context.logger().warn("Error handling request {}", request, e);
         response = Errors.fromException(e);
      }
      if(response != null) {
         context.sendResponse(request, response);
      }
   }
}
 
Example #9
Source File: SessionServiceImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ClientFuture<LockDeviceResponse> lockDevice(String deviceIdentifier, String reason) {
	LockDeviceRequest request = new LockDeviceRequest();
     request.setAddress(getAddress());
     request.setRestfulRequest(true);
     request.setDeviceIdentifier(deviceIdentifier);
     request.setReason(reason);

     ClientFuture<ClientEvent> result = client.request(request);
     return Futures.transform(result, new Function<ClientEvent, LockDeviceResponse>() {
        @Override
        public LockDeviceResponse apply(ClientEvent response) {
           return new LockDeviceResponse(response);
        }
     });
}
 
Example #10
Source File: RuleServiceImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ClientFuture<ListRuleTemplatesResponse> listRuleTemplates(String placeId) {
   ClientRequest request = buildRequest(
         RuleService.CMD_LISTRULETEMPLATES,
         ImmutableMap.<String, Object>of(ListRuleTemplatesRequest.ATTR_PLACEID, placeId)
   );
   ClientFuture<ClientEvent> result = client.request(request);
   return Futures.transform(result, new Function<ClientEvent, ListRuleTemplatesResponse>() {
      @Override
      public ListRuleTemplatesResponse apply(ClientEvent input) {
         ListRuleTemplatesResponse response = new ListRuleTemplatesResponse(input);
         IrisClientFactory.getModelCache().retainAll(RuleTemplate.NAMESPACE, response.getRuleTemplates());
         return response;
      }

   });
}
 
Example #11
Source File: YamlIntegratedTest.java    From sharding-jdbc-1.5.1 with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithDataSource() throws SQLException, URISyntaxException, IOException {
    File yamlFile = new File(YamlIntegratedTest.class.getResource(filePath).toURI());
    DataSource dataSource;
    if (hasDataSource) {
        dataSource = new YamlShardingDataSource(yamlFile);
    } else {
        dataSource = new YamlShardingDataSource(Maps.asMap(Sets.newHashSet("db0", "db1"), new Function<String, DataSource>() {
            @Override
            public DataSource apply(final String key) {
                return createDataSource(key);
            }
        }), yamlFile);
    }
    
    try (Connection conn = dataSource.getConnection();
         Statement stm = conn.createStatement()) {
        stm.executeQuery("SELECT * FROM t_order");
        stm.executeQuery("SELECT * FROM t_order_item");
        stm.executeQuery("SELECT * FROM config");
    }
}
 
Example #12
Source File: NotifyServiceImpl.java    From qconfig with MIT License 6 votes vote down vote up
@Override
public void notifyPushIp(final ConfigMeta meta, final long version, List<Host> destinations) {
    List<String> serverUrls = getServerUrls();
    if (serverUrls.isEmpty()) {
        logger.warn("notify push server, {}, version: {}, but no server, {}", meta, version, destinations);
        return;
    }

    String uri = this.notifyIpPushUrl;
    logger.info("notify push server, {}, version: {}, uri: {}, servers: {}, {}", meta, version, uri, serverUrls, destinations);
    StringBuilder sb = new StringBuilder();
    for (Host item : destinations) {
        sb.append(item.getIp()).append(Constants.LINE);
    }
    final String destinationsStr = sb.toString();

    doNotify(serverUrls, uri, "admin/notifyIpPush", new Function<String, Request>() {
        @Override
        public Request apply(String url) {
            AsyncHttpClient.BoundRequestBuilder builder = getBoundRequestBuilder(url, meta, version, destinationsStr);
            return builder.build();
        }
    });
}
 
Example #13
Source File: SchedulerServiceImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ClientFuture<ScheduleCommandsResponse> scheduleCommands(
      String target, String group, List<Map<String, Object>> commands) {
   ScheduleCommandsRequest request = new ScheduleCommandsRequest();
   request.setAddress(getAddress());
   request.setTarget(target);
   request.setGroup(group);
   request.setCommands(commands);
   
   ClientFuture<ClientEvent> result = client.request(request);
   return Futures.transform(result, new Function<ClientEvent, ScheduleCommandsResponse>() {
      @Override
      public ScheduleCommandsResponse apply(ClientEvent response) {
         return new ScheduleCommandsResponse(response);
      }
   });
}
 
Example #14
Source File: EventResolverFactory.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public Function<? super SubsystemEventAndContext, ?> getResolverForParameter(Method method, Type parameter, Annotation[] annotations) {
   if(parameter instanceof Class) {
      Class<?> type = (Class<?>) parameter;
      if(type.isAssignableFrom(eventType)) {
         return GetEvent;
      }
      if(type.isAssignableFrom(Address.class)) {
         return GetAddress;
      }
      if(type.equals(Model.class)) {
         return GetModel;
      }
   }
   else if(parameter instanceof ParameterizedType) {
      return getResolverForParameter(method, ((ParameterizedType) parameter).getRawType(), annotations);
   }
   return super.getResolverForParameter(method, parameter, annotations);
}
 
Example #15
Source File: SearchResultsImplTest.java    From aem-core-cif-components with Apache License 2.0 6 votes vote down vote up
private static AemContext createContext(String contentPath) {
    return new AemContext(
        (AemContextCallback) context -> {
            // Load page structure
            context.load().json(contentPath, "/content");

            UrlProviderImpl urlProvider = new UrlProviderImpl();
            urlProvider.activate(new MockUrlProviderConfiguration());
            context.registerService(UrlProvider.class, urlProvider);

            context.registerInjectActivateService(new SearchFilterServiceImpl());
            context.registerInjectActivateService(new SearchResultsServiceImpl());
            context.registerAdapter(Resource.class, ComponentsConfiguration.class,
                (Function<Resource, ComponentsConfiguration>) input -> MOCK_CONFIGURATION_OBJECT);
        },
        ResourceResolverType.JCR_MOCK);
}
 
Example #16
Source File: RegexDfaByte.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public <T> RegexDfaByte<T> transform(Function<V,T> transformer) {
   IdentityHashMap<State<V>,State<T>> stateMap = new IdentityHashMap<>();

   State<T> newInitialState = null;
   for (State<V> state : states) {
      State<T> transformed = state.transform(transformer);
      if (transformed.isInitialState()) {
         newInitialState = transformed;
      }

      stateMap.put(state, transformed);
   }

   for (Map.Entry<State<V>,State<T>> entry : stateMap.entrySet()) {
      State<V> oldState = entry.getKey();
      State<T> newState = entry.getValue();
      newState.setTransitions(oldState.getTransitions().transform(stateMap,transformer));
   }

   if (newInitialState == null) {
      throw new IllegalStateException("no initial state");
   }

   Set<State<T>> newStates = ImmutableSet.copyOf(stateMap.values());
   return new RegexDfaByte<T>(newInitialState, newStates);
}
 
Example #17
Source File: RuleTemplateRequestor.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public ListenableFuture<List<Map<String, Object>>> listTemplatesForPlace(UUID placeId) {
	MessageBody listTemplates =
		ListRuleTemplatesRequest
			.builder()
			.withPlaceId(placeId.toString())
			.build();
	PlatformMessage request =
		PlatformMessage
			.request(RuleService.ADDRESS)
			.from(PairingDeviceService.ADDRESS)
			.withCorrelationId(IrisUUID.randomUUID().toString())
			.withPlaceId(placeId)
			.withPopulation(populationCacheMgr.getPopulationByPlaceId(placeId))
			.withPayload(listTemplates)
			.create();
	return 
		Futures.transform(
			requestor.request(request), 
			(Function<PlatformMessage, List<Map<String, Object>>>) (message) -> ListRuleTemplatesResponse.getRuleTemplates(message.getValue(), ImmutableList.of()),
			MoreExecutors.directExecutor()
		);
}
 
Example #18
Source File: SessionServiceImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ClientFuture<LogResponse> log(String category, String code, String message) {
   LogRequest request = new LogRequest();
   request.setAddress(getAddress());
   request.setRestfulRequest(false);

   request.setCategory(category);
   request.setCode(code);
   request.setMessage(message);

   ClientFuture<ClientEvent> result = client.request(request);
   return Futures.transform(result, new Function<ClientEvent, LogResponse>() {
      @Override
      public LogResponse apply(ClientEvent input) {
         return new LogResponse(input);
      }
   });
}
 
Example #19
Source File: SessionServiceImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ClientFuture<SetActivePlaceResponse> setActivePlace(String placeId) {
   SetActivePlaceRequest request = new SetActivePlaceRequest();
   request.setAddress(getAddress());
   request.setRestfulRequest(false);

   request.setPlaceId(placeId);

   ClientFuture<ClientEvent> result = client.request(request);
   return Futures.transform(result, new Function<ClientEvent, SetActivePlaceResponse>() {
      @Override
      public SetActivePlaceResponse apply(ClientEvent input) {
         return new SetActivePlaceResponse(input);
      }
   });
}
 
Example #20
Source File: HubAlarmSubsystem.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Request(SubsystemCapability.SuspendRequest.NAME)
public void suspend(final SubsystemContext<AlarmSubsystemModel> context, PlatformMessage request) {
   if(!AlarmUtil.isActive(context)) {
      return;
   }

   assertValidSuspendState(context);

   AlarmUtil.sendHubRequest(context, request, HubAlarmCapability.SuspendRequest.instance(),
      new Function<PlatformMessage, MessageBody>() {
         @Override
         public MessageBody apply(PlatformMessage input) {
            context.model().setState(SubsystemCapability.STATE_SUSPENDED);
            context.model().setAvailable(false);
            return SubsystemCapability.SuspendResponse.instance();
         }
      }
   );
}
 
Example #21
Source File: GraphqlServletTest.java    From aem-core-cif-components with Apache License 2.0 6 votes vote down vote up
private static AemContext createContext(String contentPath) {
    return new AemContext(
        (AemContextCallback) context -> {
            // Load page structure
            context.load().json(contentPath, "/content");
            context.registerService(ImplementationPicker.class, new ResourceTypeImplementationPicker());

            UrlProviderImpl urlProvider = new UrlProviderImpl();
            urlProvider.activate(new MockUrlProviderConfiguration());
            context.registerService(UrlProvider.class, urlProvider);

            context.registerInjectActivateService(new SearchFilterServiceImpl());
            context.registerInjectActivateService(new SearchResultsServiceImpl());
            context.registerAdapter(Resource.class, ComponentsConfiguration.class,
                (Function<Resource, ComponentsConfiguration>) input -> MOCK_CONFIGURATION_OBJECT);
        },
        ResourceResolverType.JCR_MOCK);
}
 
Example #22
Source File: VarVersionsGraph.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
private static void addToReversePostOrderListIterative(VarVersionNode root, List<? super VarVersionNode> lst, Set<? super VarVersionNode> setVisited) {
    Map<VarVersionNode, List<VarVersionEdge>> mapNodeSuccs = new HashMap<>();
    LinkedList<VarVersionNode> stackNode = new LinkedList<>();
    LinkedList<Integer> stackIndex = new LinkedList<>();

    stackNode.add(root);
    stackIndex.add(0);

    while (!stackNode.isEmpty()) {
        VarVersionNode node = stackNode.getLast();
        int index = stackIndex.removeLast();

        setVisited.add(node);

        //List<VarVersionEdge> lstSuccs = mapNodeSuccs.computeIfAbsent(node, n -> new ArrayList<>(n.succs));
        List<VarVersionEdge> lstSuccs = Map827.computeIfAbsent(mapNodeSuccs, node, new Function<VarVersionNode, List<VarVersionEdge>>() {
            @Override
            public List<VarVersionEdge> apply(VarVersionNode input) {
                return new ArrayList<>(input.succs);
            }
        });
        for (; index < lstSuccs.size(); index++) {
            VarVersionNode succ = lstSuccs.get(index).dest;

            if (!setVisited.contains(succ)) {
                stackIndex.add(index + 1);
                stackNode.add(succ);
                stackIndex.add(0);
                break;
            }
        }

        if (index == lstSuccs.size()) {
            lst.add(0, node);
            stackNode.removeLast();
        }
    }
}
 
Example #23
Source File: StateManagerImpl.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Remove a user mapping from Google for specified Google identity. If {@link IdentityUser#unmap}
 * is successful, corresponding {@link IdentityUser} is removed from {@link IdentityState}.
 *
 * @param googleIdentity to unmap
 * @param service to unmap user identity
 * @throws IOException if unmap operation fails.
 */
@Override
public ListenableFuture<Boolean> removeUser(String googleIdentity, IdentityService service)
    throws IOException {
  checkState(isRunning(), "state manager is not active");
  IdentityUser identityUser = identityState.get().getUser(googleIdentity);
  if (identityUser == null) {
    return Futures.immediateFuture(true);
  }
  ListenableFuture<Boolean> unmap = identityUser.unmap(service);
  return Futures.transform(
      unmap,
      new Function<Boolean, Boolean>() {
        @Override
        @Nullable
        public Boolean apply(@Nullable Boolean result) {
          checkNotNull(result);
          if (result) {
            identityState.get().removeUser(googleIdentity);
            logger.log(Level.FINE, "Successfully unmapped identity user {0}", googleIdentity);
          } else {
            logger.log(Level.WARNING, "Failed to unmapped identity user {0}", googleIdentity);
          }
          return result;
        }
      },
      getExecutor());
}
 
Example #24
Source File: ExampleClient.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Function<List<ExampleTable>, Map<String, ExampleTable>> resolveAndIndexTables(final URI metadataUri)
{
    return tables -> {
        Iterable<ExampleTable> resolvedTables = transform(tables, tableUriResolver(metadataUri));
        return ImmutableMap.copyOf(uniqueIndex(resolvedTables, ExampleTable::getName));
    };
}
 
Example #25
Source File: BowTieExpandVerticesJob.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private int getHeight(List<FcgVertex> vertices) {

		RenderContext<FcgVertex, FcgEdge> renderContext = viewer.getRenderContext();
		Function<? super FcgVertex, Shape> shaper = renderContext.getVertexShapeTransformer();

		int height = 0;
		for (FcgVertex v : vertices) {
			height = Math.max(height, shaper.apply(v).getBounds().height);
		}

		return height;
	}
 
Example #26
Source File: SmartHomeSkillV2Handler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<AlexaMessage> handle(AlexaMessage message, UUID placeId) {

   if(message.getPayload() instanceof HealthCheckRequest) {
      ShsMetrics.incHealthCheck();
      return Futures.transform(
         healthCheckHandler.handle(),
         (Function<ResponsePayload, AlexaMessage>) input -> {
            Preconditions.checkNotNull(input, "input cannot be null");
            Header h = Header.v2(message.getHeader().getMessageId(), input.getName(), input.getNamespace());
            return new AlexaMessage(h, input);
         },
         MoreExecutors.directExecutor()
      );
   }

   if(message.getPayload() instanceof RequestPayload) {
      ShsMetrics.incShsRequest();
      long startTime = System.nanoTime();
      Txfm txfm = Txfm.transformerFor(message);
      PlatformMessage platformMessage = txfm.txfmRequest(message, placeId, populationCacheMgr.getPopulationByPlaceId(placeId), (int) config.getRequestTimeoutMs());
      logger.debug("[{}] transformed to platform message [{}]", message, platformMessage);
      return Futures.transformAsync(
         busClient.request(platformMessage),
         (AsyncFunction<PlatformMessage, AlexaMessage>) input -> {
            metrics.timeServiceSuccess(platformMessage.getMessageType(), startTime);
            return Futures.immediateFuture(txfm.transformResponse(message, input));
         },
         executor
      );
   } else {
      logger.warn("received non-directive request from Alexa {}", message);
      ShsMetrics.incNonDirective();
      return Futures.immediateFailedFuture(new AlexaException(AlexaErrors.unsupportedDirective(message.getHeader().getName())));
   }
}
 
Example #27
Source File: Coordinator.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * sync the consumers in the replicaSet, ensure that all consumers in the group consume to the same position
 *
 * @param streamingSource
 * @param cubeName
 * @param replicaSet
 * @return the consume position info.
 */
private ISourcePosition syncAndStopConsumersInRs(IStreamingSource streamingSource, String cubeName,
        ReplicaSet replicaSet) throws IOException {
    if (replicaSet.getNodes().size() > 1) { // when group nodes more than 1, force to sync the group
        logger.info("sync consume for cube:{}, replicaSet:{}", cubeName, replicaSet.getReplicaSetID());

        PauseConsumersRequest suspendRequest = new PauseConsumersRequest();
        suspendRequest.setCube(cubeName);
        List<ConsumerStatsResponse> allReceiverConsumeState = pauseConsumersInReplicaSet(replicaSet,
                suspendRequest);

        List<ISourcePosition> consumePositionList = Lists.transform(allReceiverConsumeState,
                new Function<ConsumerStatsResponse, ISourcePosition>() {
                    @Nullable
                    @Override
                    public ISourcePosition apply(@Nullable ConsumerStatsResponse input) {
                        return streamingSource.getSourcePositionHandler().parsePosition(input.getConsumePosition());
                    }
                });
        ISourcePosition consumePosition = streamingSource.getSourcePositionHandler()
                .mergePositions(consumePositionList, MergeStrategy.KEEP_LARGE);
        ResumeConsumerRequest resumeRequest = new ResumeConsumerRequest();
        resumeRequest.setCube(cubeName);
        resumeRequest
                .setResumeToPosition(streamingSource.getSourcePositionHandler().serializePosition(consumePosition));
        // assume that the resume will always succeed when the replica set can be paused successfully
        resumeConsumersInReplicaSet(replicaSet, resumeRequest);
        return consumePosition;
    } else if (replicaSet.getNodes().size() == 1) {
        Node receiver = replicaSet.getNodes().iterator().next();
        StopConsumersRequest request = new StopConsumersRequest();
        request.setCube(cubeName);
        logger.info("stop consumers for cube:{}, receiver:{}", cubeName, receiver);
        List<ConsumerStatsResponse> stopResponse = stopConsumersInReplicaSet(replicaSet, request);
        return streamingSource.getSourcePositionHandler().parsePosition(stopResponse.get(0).getConsumePosition());
    } else {
        return null;
    }
}
 
Example #28
Source File: AqlViewer.java    From CQL with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Unit visit(String k, JTabbedPane pane, ApgTypeside t) throws RuntimeException {

	Object[][] rowData = new Object[t.Bs.size()][3];
	Object[] colNames = new Object[2];
	colNames[0] = "Base Type";
	colNames[1] = "Java Class";
	int j = 0;
	for (Entry<String, Pair<Class<?>, java.util.function.Function<String, Object>>> lt : t.Bs.entrySet()) {
		rowData[j][0] = lt.getKey();
		rowData[j][1] = lt.getValue().first.getName();
	 	j++;
	}
	JPanel x = GuiUtil.makeTable(BorderFactory.createEmptyBorder(), null, rowData, colNames);

	JPanel c = new JPanel();
	c.setLayout(new BoxLayout(c, BoxLayout.PAGE_AXIS));

	x.setAlignmentX(Component.LEFT_ALIGNMENT);
	x.setMinimumSize(x.getPreferredSize());
	c.add(x);
	
	JPanel p = new JPanel(new GridLayout(1, 1));
	p.add(c);
	JScrollPane jsp = new JScrollPane(p);

	c.setBorder(BorderFactory.createEmptyBorder());
	p.setBorder(BorderFactory.createEmptyBorder());
	jsp.setBorder(BorderFactory.createEmptyBorder());
	
	pane.addTab("Table", p);
	
	return Unit.unit;
}
 
Example #29
Source File: MultipleDictionaryValueEnumeratorTest.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private String[] enumerateDictInfoList(List<DictionaryInfo> dictionaryInfoList, String dataType) throws IOException {
    List<Dictionary<String>> dictList = Lists.transform(dictionaryInfoList, new Function<DictionaryInfo, Dictionary<String>>() {
        @Nullable
        @Override
        public Dictionary<String> apply(@Nullable DictionaryInfo input) {
            return input.dictionaryObject;
        }
    });
    enumerator = new MultipleDictionaryValueEnumerator(DataType.getType(dataType), dictList);
    List<String> values = new ArrayList<>();
    while (enumerator.moveNext()) {
        values.add(enumerator.current());
    }
    return values.toArray(new String[0]);
}
 
Example #30
Source File: MultimapExts.java    From beihu-boot with Apache License 2.0 5 votes vote down vote up
public static <K, V, NV> ListMultimap<K, NV> mapValue(ListMultimap<K, V> map, java.util.function.Function<? super V, ? extends NV> mapper) {

        ImmutableListMultimap.Builder<K, NV> builder =
                ImmutableListMultimap.builder();
        for (K t : map.keySet()) {
            builder.putAll(t, CollectionUtils.map(map.get(t), mapper::apply));
        }
        return builder.build();
    }