com.google.common.base.Joiner Java Examples

The following examples show how to use com.google.common.base.Joiner. 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: TableMessageStatReporter.java    From DBus with Apache License 2.0 6 votes vote down vote up
public void mark(HeartbeatPulse pulse) {
    // 判断心跳类型是否为checkpoint
    if (!pulse.getPacket().contains(CHECKPOINT_FLAG)) {
        return;
    }

    String key = Joiner.on(".").join(pulse.getSchemaName(), pulse.getTableName());
    logger.debug("mark: {}", key);
    StatMessage message;
    if (!statMessageMap.containsKey(key)) {
        message = new StatMessage(pulse.getDsName(), pulse.getSchemaName(), pulse.getTableName(), STAT_TYPE);
        statMessageMap.put(key, message);
    } else {
        message = statMessageMap.get(key);
    }

    HeartBeatPacket packet = HeartBeatPacket.parse(pulse.getPacket());
    message.setCheckpointMS(packet.getTime());
    message.setTxTimeMS(packet.getTxtime());
    message.setLocalMS(System.currentTimeMillis());
    message.setLatencyMS(message.getLocalMS() - message.getCheckpointMS());
    sender.sendStat(message.toJSONString(), message.getDsName(), message.getSchemaName(), message.getTableName());
    message.cleanUp();
}
 
Example #2
Source File: RTInspection.java    From react-templates-plugin with MIT License 6 votes vote down vote up
@NotNull
    private HyperlinkLabel createHyperLink() {
        //JSBundle.message("settings.javascript.root.configurable.name")
        List<String> path = ContainerUtil.newArrayList("HTML", getDisplayName());

        String title = Joiner.on(" / ").join(path);
        final HyperlinkLabel settingsLink = new HyperlinkLabel(title);
        settingsLink.addHyperlinkListener(new HyperlinkAdapter() {
            public void hyperlinkActivated(HyperlinkEvent e) {
//                DataContext dataContext = DataManager.getInstance().getDataContext(settingsLink);
//                OptionsEditor optionsEditor = OptionsEditor.KEY.getData(dataContext);
//                if (optionsEditor == null) {
//                    Project project = CommonDataKeys.PROJECT.getData(dataContext);
//                    if (project != null) {
//                        showSettings(project);
//                    }
//                    return;
//                }
//                Configurable configurable = optionsEditor.findConfigurableById(RTInspection.this.getId());
//                if (configurable != null) {
//                    optionsEditor.clearSearchAndSelect(configurable);
//                }
            }
        });
        return settingsLink;
    }
 
Example #3
Source File: SetLimitsCustomizer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void customize(MachineLocation machine) {
    if (!(machine instanceof SshMachineLocation)) {
        throw new IllegalStateException("Machine must be a SshMachineLocation, but got "+machine);
    }
    String file = config.get(FILE_NAME);
    List<String> contents = config.get(CONTENTS);
    checkArgument(Strings.isNonBlank(config.get(FILE_NAME)), "File must be non-empty");
    
    log.info("SetLimitsCustomizer setting limits on "+machine+" in file "+file+" to: "+Joiner.on("; ").join(contents));

    try {
        List<String> cmds = new ArrayList<>();
        for (String content : contents) {
            cmds.add(sudo(String.format("echo \"%s\" | tee -a %s", content, file)));
        }
        exec((SshMachineLocation)machine, true, cmds.toArray(new String[cmds.size()]));
    } catch (Exception e) {
        log.info("SetLimitsCustomizer failed to set limits on "+machine+" (rethrowing)", e);
        throw e;
    }
}
 
Example #4
Source File: AppleConfiguration.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public String getOutputDirectoryName() {
  List<String> components = new ArrayList<>();
  if (!appleSplitCpu.isEmpty()) {
    components.add(applePlatformType.toString().toLowerCase());
    components.add(appleSplitCpu);

    if (options.getMinimumOsVersion() != null) {
      components.add("min" + options.getMinimumOsVersion());
    }
  }
  if (configurationDistinguisher != ConfigurationDistinguisher.UNKNOWN) {
    components.add(configurationDistinguisher.getFileSystemName());
  }

  if (components.isEmpty()) {
    return null;
  }
  return Joiner.on('-').join(components);
}
 
Example #5
Source File: FirebaseApp.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the instance identified by the unique name, or throws if it does not exist.
 *
 * @param name represents the name of the {@link FirebaseApp} instance.
 * @return the {@link FirebaseApp} corresponding to the name.
 * @throws IllegalStateException if the {@link FirebaseApp} was not initialized, either via {@link
 *     #initializeApp(FirebaseOptions, String)} or {@link #getApps()}.
 */
public static FirebaseApp getInstance(@NonNull String name) {
  synchronized (appsLock) {
    FirebaseApp firebaseApp = instances.get(normalize(name));
    if (firebaseApp != null) {
      return firebaseApp;
    }

    List<String> availableAppNames = getAllAppNames();
    String availableAppNamesMessage;
    if (availableAppNames.isEmpty()) {
      availableAppNamesMessage = "";
    } else {
      availableAppNamesMessage =
          "Available app names: " + Joiner.on(", ").join(availableAppNames);
    }
    String errorMessage =
        String.format(
            "FirebaseApp with name %s doesn't exist. %s", name, availableAppNamesMessage);
    throw new IllegalStateException(errorMessage);
  }
}
 
Example #6
Source File: HiveStreamingDataWriter.java    From spark-llap with Apache License 2.0 6 votes vote down vote up
@Override
public void write(final InternalRow record) throws IOException {
  String delimitedRow = Joiner.on(",").useForNull("")
    .join(scala.collection.JavaConversions.seqAsJavaList(record.toSeq(schema)));
  try {
    streamingConnection.write(delimitedRow.getBytes(Charset.forName("UTF-8")));
    rowsWritten++;
    if (rowsWritten > 0 && commitAfterNRows > 0 && (rowsWritten % commitAfterNRows == 0)) {
      LOG.info("Committing transaction after rows: {}", rowsWritten);
      streamingConnection.commitTransaction();
      streamingConnection.beginTransaction();
    }
  } catch (StreamingException e) {
    throw new IOException(e);
  }
}
 
Example #7
Source File: TomcatSqoopRunner.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
private void configureSentryAuthorization(Map<String, String> properties) {
  properties.put("org.apache.sqoop.security.authorization.handler",
      "org.apache.sentry.sqoop.authz.SentryAuthorizationHander");
  properties.put("org.apache.sqoop.security.authorization.access_controller",
      "org.apache.sentry.sqoop.authz.SentryAccessController");
  properties.put("org.apache.sqoop.security.authorization.validator",
      "org.apache.sentry.sqoop.authz.SentryAuthorizationValidator");
  properties.put("org.apache.sqoop.security.authorization.server_name", serverName);
  properties.put("sentry.sqoop.site.url", sentrySite);
  /** set Sentry related jars into classpath */
  List<String> extraClassPath = new LinkedList<String>();
  for (String jar : System.getProperty("java.class.path").split(":")) {
    if ((jar.contains("sentry") || jar.contains("shiro-core") || jar.contains("libthrift"))
        && jar.endsWith("jar")) {
      extraClassPath.add(jar);
    }
  }
  properties.put("org.apache.sqoop.classpath.extra",Joiner.on(":").join(extraClassPath));
}
 
Example #8
Source File: HaxelibClasspathUtils.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param project
 * @param dir
 * @param executable
 * @param sdk
 * @return
 */
@NotNull
public static List<String> getProjectDisplayInformation(@NotNull Project project, @NotNull File dir, @NotNull String executable, @NotNull Sdk sdk) {
  List<String> strings1 = Collections.EMPTY_LIST;

  if (getInstalledLibraries(sdk).contains(executable)) {
    ArrayList<String> commandLineArguments = new ArrayList<String>();
    commandLineArguments.add(HaxelibCommandUtils.getHaxelibPath(sdk));
    commandLineArguments.add("run");
    commandLineArguments.add(executable);
    commandLineArguments.add("display");
    commandLineArguments.add("flash");

    List<String> strings = HaxelibCommandUtils.getProcessStdout(commandLineArguments,
                                                                dir,
                                                                HaxeSdkUtilBase.getSdkData(sdk));
    String s = Joiner.on("\n").join(strings);
    strings1 = getHXMLFileClasspaths(project, s);
  }

  return strings1;
}
 
Example #9
Source File: TestingPrestoServer.java    From presto with Apache License 2.0 6 votes vote down vote up
private static void updateConnectorIdAnnouncement(Announcer announcer, CatalogName catalogName, InternalNodeManager nodeManager)
{
    //
    // This code was copied from PrestoServer, and is a hack that should be removed when the connectorId property is removed
    //

    // get existing announcement
    ServiceAnnouncement announcement = getPrestoAnnouncement(announcer.getServiceAnnouncements());

    // update connectorIds property
    Map<String, String> properties = new LinkedHashMap<>(announcement.getProperties());
    String property = nullToEmpty(properties.get("connectorIds"));
    Set<String> connectorIds = new LinkedHashSet<>(Splitter.on(',').trimResults().omitEmptyStrings().splitToList(property));
    connectorIds.add(catalogName.toString());
    properties.put("connectorIds", Joiner.on(',').join(connectorIds));

    // update announcement
    announcer.removeServiceAnnouncement(announcement.getId());
    announcer.addServiceAnnouncement(serviceAnnouncement(announcement.getType()).addProperties(properties).build());
    announcer.forceAnnounce();

    nodeManager.refreshNodes();
}
 
Example #10
Source File: AbstractMetricSubject.java    From java-monitoring-client-library with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that the metric has any (non-default) value for the specified label values.
 *
 * @param labels the labels for which the value is being asserted; the number and order of labels
 *     should match the definition of the metric
 */
public And<S> hasAnyValueForLabels(String... labels) {
  MetricPoint<T> metricPoint = findMetricPointForLabels(ImmutableList.copyOf(labels));
  if (metricPoint == null) {
    failWithBadResults(
        "has a value for labels",
        Joiner.on(':').join(labels),
        "has labeled values",
        Lists.transform(
            Ordering.<MetricPoint<T>>natural().sortedCopy(actual.getTimestampedValues()),
            metricPointConverter));
  }
  if (hasDefaultValue(metricPoint)) {
    failWithBadResults(
        "has a non-default value for labels",
        Joiner.on(':').join(labels),
        "has a value of",
        getMessageRepresentation(metricPoint.value()));
  }
  expectedNondefaultLabelTuples.add(ImmutableList.copyOf(labels));
  return andChainer();
}
 
Example #11
Source File: Type.java    From turbine with Apache License 2.0 6 votes vote down vote up
@Override
public final String toString() {
  StringBuilder sb = new StringBuilder();
  boolean first = true;
  for (SimpleClassTy c : classes()) {
    for (AnnoInfo anno : c.annos()) {
      sb.append(anno);
      sb.append(' ');
    }
    if (!first) {
      sb.append('.');
      sb.append(c.sym().binaryName().substring(c.sym().binaryName().lastIndexOf('$') + 1));
    } else {
      sb.append(c.sym().binaryName().replace('/', '.').replace('$', '.'));
    }
    if (!c.targs().isEmpty()) {
      sb.append('<');
      Joiner.on(',').appendTo(sb, c.targs());
      sb.append('>');
    }
    first = false;
  }
  return sb.toString();
}
 
Example #12
Source File: ByteFragmentUtilsTest.java    From clickhouse-jdbc with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "dateArray")
public void testParseArray(Date[] array) throws Exception {
    final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    String sourceString = "[" + Joiner.on(",").join(Iterables.transform(Arrays.asList(array), new Function<Date, String>() {
        @Override
        public String apply(Date s) {
            return dateFormat.format(s);
        }
    })) + "]";

    byte[] bytes = sourceString.getBytes(StreamUtils.UTF_8);
    ByteFragment fragment = new ByteFragment(bytes, 0, bytes.length);
    Date[] parsedArray = (Date[]) ByteFragmentUtils.parseArray(fragment, Date.class, dateFormat, 1);

    assertEquals(parsedArray.length, array.length);
    for (int i = 0; i < parsedArray.length; i++) {
        assertEquals(parsedArray[i], array[i]);
    }
}
 
Example #13
Source File: SqlFormatter.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 6 votes vote down vote up
@Override
protected Void visitSampledRelation(SampledRelation node, Integer indent) {
  process(node.getRelation(), indent);

  builder.append(" TABLESAMPLE ")
          .append(node.getType())
          .append(" (")
          .append(node.getSamplePercentage())
          .append(')');

  if (node.getColumnsToStratifyOn().isPresent()) {
    builder.append(" STRATIFY ON ")
            .append(" (")
            .append(Joiner.on(",").join(node.getColumnsToStratifyOn().get()));
    builder.append(')');
  }

  return null;
}
 
Example #14
Source File: ApiPermissionInfoGenerator.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private static String getMethodType(Method method) {
    Set<String> httpAnnotations = Lists.newArrayList(GET.class, DELETE.class, PUT.class, POST.class, HEAD.class, OPTIONS.class, PATCH.class)
            .stream()
            .filter(httpAnnotation -> method.isAnnotationPresent(httpAnnotation))
            .map(httpAnnotation -> httpAnnotation.getSimpleName())
            .collect(Collectors.toSet());
    return Joiner.on(" ").join(httpAnnotations);
}
 
Example #15
Source File: TransformMapToQueryString.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void convert_map_to_querystring_guava() {

	String mapJoined = Joiner.on("&").withKeyValueSeparator("=")
			.join(mapToConvert);

	assertEquals("end-date=2014-11-26&itemsPerPage=25", mapJoined);
}
 
Example #16
Source File: SanitizeUnknownSolrFieldsBuilder.java    From kite with Apache License 2.0 5 votes vote down vote up
public SanitizeUnknownSolrFields(CommandBuilder builder, Config config, Command parent, Command child, MorphlineContext context) {
  super(builder, config, parent, child, context);      
  
  Config solrLocatorConfig = getConfigs().getConfig(config, "solrLocator");
  SolrLocator locator = new SolrLocator(solrLocatorConfig, context);
  LOG.debug("solrLocator: {}", locator);
  this.schema = locator.getIndexSchema();
  Preconditions.checkNotNull(schema);
  LOG.trace("Solr schema: \n{}", Joiner.on("\n").join(new TreeMap(schema.getFields()).values()));
  
  String str = getConfigs().getString(config, "renameToPrefix", "").trim();
  this.renameToPrefix = str.length() > 0 ? str : null;  
  validateArguments();
}
 
Example #17
Source File: CassandraServer.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public void batch_mutate(Map<ByteBuffer,Map<String,List<Mutation>>> mutation_map, ConsistencyLevel consistency_level)
throws InvalidRequestException, UnavailableException, TimedOutException
{
    if (startSessionIfRequested())
    {
        Map<String, String> traceParameters = Maps.newLinkedHashMap();
        for (Map.Entry<ByteBuffer, Map<String, List<Mutation>>> mutationEntry : mutation_map.entrySet())
        {
            traceParameters.put(ByteBufferUtil.bytesToHex(mutationEntry.getKey()),
                                Joiner.on(";").withKeyValueSeparator(":").join(mutationEntry.getValue()));
        }
        traceParameters.put("consistency_level", consistency_level.name());
        Tracing.instance.begin("batch_mutate", traceParameters);
    }
    else
    {
        logger.debug("batch_mutate");
    }

    try
    {
        doInsert(consistency_level, createMutationList(consistency_level, mutation_map, true));
    }
    catch (RequestValidationException e)
    {
        throw ThriftConversion.toThrift(e);
    }
    finally
    {
        Tracing.instance.stopSession();
    }
}
 
Example #18
Source File: TreeBackedTypesTest.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * We're not exactly sure why intersection types with the same bounds but in a different order are
 * considered the same type; after all, they can have different erasures. However, the javac
 * implementation behaves that way, so we must as well.
 *
 * <p>The relevant JLS8 sections are 4.4 and 4.9, if any future person wants to go see if they can
 * grok why this behavior is correct.
 */
@Test
public void testIsSameTypeIntersectionTypeDifferentOrder() throws IOException {
  compile(
      Joiner.on('\n')
          .join(
              "class Foo<T extends java.lang.CharSequence & java.lang.Runnable> { }",
              "class Bar<T extends java.lang.Runnable & java.lang.CharSequence> { }"));

  IntersectionType fooType = (IntersectionType) getTypeParameterUpperBound("Foo", 0);
  IntersectionType barType = (IntersectionType) getTypeParameterUpperBound("Bar", 0);

  assertSameType(fooType, barType);
}
 
Example #19
Source File: DeleteStatementHandlerTest.java    From scalardb with Apache License 2.0 5 votes vote down vote up
@Test
public void prepare_DeleteOperationWithIfGiven_ShouldPrepareProperQuery() {
  // Arrange
  String expected =
      Joiner.on(" ")
          .skipNulls()
          .join(
              new String[] {
                "DELETE",
                "FROM",
                ANY_KEYSPACE_NAME + "." + ANY_TABLE_NAME,
                "WHERE",
                ANY_NAME_1 + "=?",
                "AND",
                ANY_NAME_2 + "=?",
                "IF",
                ANY_NAME_3 + "=?",
                "AND",
                ANY_NAME_4 + "=?;"
              });
  configureBehavior(expected);
  del = prepareDeleteWithClusteringKey();
  del.withCondition(
      new DeleteIf(
          new ConditionalExpression(ANY_NAME_3, new IntValue(ANY_INT_1), Operator.EQ),
          new ConditionalExpression(ANY_NAME_4, new TextValue(ANY_TEXT_3), Operator.EQ)));

  // Act
  handler.prepare(del);

  // Assert
  verify(session).prepare(expected);
}
 
Example #20
Source File: PhoenixMetricsIT.java    From phoenix with Apache License 2.0 5 votes vote down vote up
private void assertReadMetricValuesForSelectSql(ArrayList<Long> numRows, ArrayList<Long> numExpectedTasks,
        PhoenixResultSet resultSetBeingTested, Set<String> expectedTableNames) throws SQLException {
    Map<String, Map<MetricType, Long>> metrics = PhoenixRuntime.getRequestReadMetricInfo(resultSetBeingTested);
    int counter = 0;
    for (Entry<String, Map<MetricType, Long>> entry : metrics.entrySet()) {
        String tableName = entry.getKey();
        expectedTableNames.remove(tableName);
        Map<MetricType, Long> metricValues = entry.getValue();
        boolean taskCounterMetricsPresent = false;
        boolean taskExecutionTimeMetricsPresent = false;
        boolean memoryMetricsPresent = false;
        for (Entry<MetricType, Long> pair : metricValues.entrySet()) {
        	MetricType metricType = pair.getKey();
            long metricValue = pair.getValue();
            long numTask = numExpectedTasks.get(counter);
            if (metricType.equals(TASK_EXECUTED_COUNTER)) {
                assertEquals(numTask, metricValue);
                taskCounterMetricsPresent = true;
            } else if (metricType.equals(TASK_EXECUTION_TIME)) {
                assertEquals(numTask * TASK_EXECUTION_TIME_DELTA, metricValue);
                taskExecutionTimeMetricsPresent = true;
            } else if (metricType.equals(MEMORY_CHUNK_BYTES)) {
                assertEquals(numTask * MEMORY_CHUNK_BYTES_DELTA, metricValue);
                memoryMetricsPresent = true;
            }
        }
        counter++;
        assertTrue(taskCounterMetricsPresent);
        assertTrue(taskExecutionTimeMetricsPresent);
        assertTrue(memoryMetricsPresent);
    }
    PhoenixRuntime.resetMetrics(resultSetBeingTested);
    assertTrue("Metrics not found tables " + Joiner.on(",").join(expectedTableNames),
            expectedTableNames.size() == 0);
}
 
Example #21
Source File: SqlFormatter.java    From presto with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitSetPath(SetPath node, Integer indent)
{
    builder.append("SET PATH ");
    builder.append(Joiner.on(", ").join(node.getPathSpecification().getPath()));
    return null;
}
 
Example #22
Source File: DataNode.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Remove volumes from DataNode.
 *
 * It does three things:
 * <li>
 *   <ul>Remove volumes and block info from FsDataset.</ul>
 *   <ul>Remove volumes from DataStorage.</ul>
 *   <ul>Reset configuration DATA_DIR and {@link dataDirs} to represent
 *   active volumes.</ul>
 * </li>
 * @param absoluteVolumePaths the absolute path of volumes.
 * @param clearFailure if true, clears the failure information related to the
 *                     volumes.
 * @throws IOException
 */
private synchronized void removeVolumes(
    final Set<File> absoluteVolumePaths, boolean clearFailure)
    throws IOException {
  for (File vol : absoluteVolumePaths) {
    Preconditions.checkArgument(vol.isAbsolute());
  }

  if (absoluteVolumePaths.isEmpty()) {
    return;
  }

  LOG.info(String.format("Deactivating volumes (clear failure=%b): %s",
      clearFailure, Joiner.on(",").join(absoluteVolumePaths)));

  IOException ioe = null;
  // Remove volumes and block infos from FsDataset.
  data.removeVolumes(absoluteVolumePaths, clearFailure);

  // Remove volumes from DataStorage.
  try {
    storage.removeVolumes(absoluteVolumePaths);
  } catch (IOException e) {
    ioe = e;
  }

  // Set configuration and dataDirs to reflect volume changes.
  for (Iterator<StorageLocation> it = dataDirs.iterator(); it.hasNext(); ) {
    StorageLocation loc = it.next();
    if (absoluteVolumePaths.contains(loc.getFile().getAbsoluteFile())) {
      it.remove();
    }
  }
  conf.set(DFS_DATANODE_DATA_DIR_KEY, Joiner.on(",").join(dataDirs));

  if (ioe != null) {
    throw ioe;
  }
}
 
Example #23
Source File: SarlBatchCompiler.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Change the boot classpath.
 * This option is only supported on JDK 8 and older and will be ignored when source level is 9 or newer.
 *
 * @param bootClasspath the new boot classpath.
 * @see "https://www.oracle.com/technetwork/java/javase/9-relnote-issues-3704069.html"
 */
public void setBootClassPath(Collection<File> bootClasspath) {
	final JavaVersion version = JavaVersion.fromQualifier(getJavaSourceVersion());
	if (version.isAtLeast(JavaVersion.JAVA9)) {
		reportInternalWarning(MessageFormat.format(Messages.SarlBatchCompiler_63,
				Joiner.on(File.pathSeparator).join(bootClasspath)));
	}
	if (bootClasspath == null || bootClasspath.isEmpty()) {
		this.bootClasspath = null;
	} else {
		this.bootClasspath = new ArrayList<>(bootClasspath);
	}
}
 
Example #24
Source File: FunctionExpression.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
  return getFunction().getName()
      + "("
      + Joiner.on(", ").join(Iterables.transform(getArgs(), Object::toString))
      + ")";
}
 
Example #25
Source File: SortTypeDialog.java    From StringManipulation with Apache License 2.0 5 votes vote down vote up
protected void preview() {
	if (this.editor != null) {
		if (!validateRegexp()) {
			return;
		}
		List<String> result = sort(editor, getSettings());

		ApplicationManager.getApplication().runWriteAction(() -> {
			myPreviewEditor.getDocument().setText(Joiner.on("\n").join(result));
			myPreviewPanel.validate();
			myPreviewPanel.repaint();
		});
	}
}
 
Example #26
Source File: MqPullService.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public MqPullService(final String server, final int index) {
    this.mqPullServiceName = Joiner.on("-").join("mqPullServiceName", index);

    CarreraConfig carreraConfig = new CarreraConfig();
    carreraConfig.setServers(server);
    carreraConfig.setGroupId(PULL_CONFIG.getInnerGroup());
    carreraConfig.setRetryInterval(PULL_CONFIG.getRetryIntervalMs());
    carreraConfig.setTimeout(PULL_CONFIG.getTimeoutMs());
    carreraConfig.setMaxBatchSize(PULL_CONFIG.getMaxBatchSize());

    carreraConsumer = new SimpleCarreraConsumer(carreraConfig);
    LOGGER.info("{} init carrera consumer, carreraConfig:{}", mqPullServiceName, carreraConfig);
}
 
Example #27
Source File: TreeBackedAnnotatedConstructTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAnnotationAndGetFieldWithSingleClass() throws Exception {
  testCompiler.addClasspathFileContents(
      "AnnotationWithSingleClassForTreeBackedTest.java",
      AnnotationWithSingleClassForTreeBackedTest.SOURCE_CODE);

  if (!testingTrees()) {
    testCompiler.addClasspathFileContents("Bar.java", "public class Bar {}");
  }

  initCompiler(
      ImmutableMap.of(
          "Foo.java",
          Joiner.on('\n')
              .join(
                  "@com.facebook.buck.jvm.java.abi.source.AnnotationWithSingleClassForTreeBackedTest(single = Bar.class)",
                  "public class Foo {",
                  "}")));
  testCompiler.setProcessors(
      Collections.singletonList(
          new ProcessorCallingGetAnnotation<>(
              AnnotationWithSingleClassForTreeBackedTest.class,
              (a) -> {
                try {
                  a.single();
                } catch (MirroredTypeException e) { // NOPMD: Expected.
                  // NOPMD: No problem.
                }
              })));

  testCompiler.parse();
  testCompiler.enter();
}
 
Example #28
Source File: IncrementalLoadingTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
void modifyFile(String fileName, String... content) throws IOException {
  Path path = workspace.getRelative(fileName);
  Preconditions.checkState(path.exists());
  Preconditions.checkState(path.delete());
  FileSystemUtils.writeContentAsLatin1(path, Joiner.on('\n').join(content));
  changes.add(path);
}
 
Example #29
Source File: DeleteReservedListCommand.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Override
protected void init() {
  checkArgument(
      ReservedList.get(name).isPresent(),
      "Cannot delete the reserved list %s because it doesn't exist.",
      name);
  ReservedList existing = ReservedList.get(name).get();
  ImmutableSet<String> tldsUsedOn = existing.getReferencingTlds();
  checkArgument(
      tldsUsedOn.isEmpty(),
      "Cannot delete reserved list because it is used on these tld(s): %s",
      Joiner.on(", ").join(tldsUsedOn));
  stageEntityChange(existing, null);
}
 
Example #30
Source File: LoginController.java    From maven-framework-project with MIT License 5 votes vote down vote up
protected Map<String, String> userWithGroups() {
    Map<String, String> temp = Maps.newHashMap();
    Map<String, List<String>> userGroups = userService.userWithAssignmentGroupStr();
    for (String user : userGroups.keySet()) {
        List<String> groupIds = userGroups.get(user);
        temp.put(user, Joiner.on(", ").join(groupIds));
    }
    return temp;
}