Java 类com.google.common.base.Joiner 实例源码

项目:Reer    文件:RelativeFileNameTransformer.java   
private String findRelativePath(String from, String to) {
    List<String> fromPath = splitPath(from);
    List<String> toPath = splitPath(to);
    List<String> relativePath = new ArrayList<String>();

    while (!fromPath.isEmpty() && !toPath.isEmpty() && fromPath.get(0).equals(toPath.get(0))) {
        fromPath.remove(0);
        toPath.remove(0);
    }
    for (String ignored : fromPath) {
        relativePath.add("..");
    }
    for (String entry : toPath) {
        relativePath.add(entry);
    }
    return Joiner.on(File.separatorChar).join(relativePath);
}
项目:app-service-java-manage-functions    文件:Utils.java   
/**
 * Print a key vault.
 *
 * @param vault the key vault resource
 */
public static void print(Vault vault) {
    StringBuilder info = new StringBuilder().append("Key Vault: ").append(vault.id())
            .append("Name: ").append(vault.name())
            .append("\n\tResource group: ").append(vault.resourceGroupName())
            .append("\n\tRegion: ").append(vault.region())
            .append("\n\tSku: ").append(vault.sku().name()).append(" - ").append(vault.sku().family())
            .append("\n\tVault URI: ").append(vault.vaultUri())
            .append("\n\tAccess policies: ");
    for (AccessPolicy accessPolicy : vault.accessPolicies()) {
        info.append("\n\t\tIdentity:").append(accessPolicy.objectId())
                .append("\n\t\tKey permissions: ").append(Joiner.on(", ").join(accessPolicy.permissions().keys()))
                .append("\n\t\tSecret permissions: ").append(Joiner.on(", ").join(accessPolicy.permissions().secrets()));
    }
    System.out.println(info.toString());
}
项目:cmakeify    文件:TestCmakeify.java   
@Test
public void testSQLite() throws IOException {
  File yaml = new File("test-files/testScript/cmakeify.yml");
  yaml.getParentFile().mkdirs();
  Files.write("targets: [android]\n" +
          "buildTarget: sqlite\n" +
          "android:\n" +
          "  ndk:\n" +
          "    runtimes: [c++, gnustl, stlport]\n" +
          "    platforms: [12, 21]\n" +
          "example: |\n" +
          "   #include <sqlite3.h>\n" +
          "   void test() {\n" +
          "     sqlite3_initialize();\n" +
          "   }",
      yaml, StandardCharsets.UTF_8);
  main("-wf", yaml.getParent(),
      "--host", "Linux",
      "--group-id", "my-group-id",
      "--artifact-id", "my-artifact-id",
      "--target-version", "my-target-version");
  File scriptFile = new File(".cmakeify/build.sh");
  String script = Joiner.on("\n").join(Files.readLines(scriptFile, Charsets.UTF_8));
  assertThat(script).contains("cmake-3.7.2-Linux-x86_64.tar.gz");
}
项目:ArchUnit    文件:SliceDependencyErrorMatcher.java   
@Override
public Result filterMatching(List<String> lines) {
    List<String> mismatches = new ArrayList<>();
    List<String> remainingLines = new ArrayList<>(lines);
    boolean matches = remainingLines.remove(dependencyDescription + ":");
    if (!matches) {
        mismatches.add("Description " + dependencyDescription + " was missing");
    }
    for (ExpectedAccess expectedAccess : expectedAccesses) {
        if (!remainingLines.remove(expectedAccess.toString())) {
            mismatches.add("Expected Access " + expectedAccess.toString() + " was missing");
            matches = false;
        }
    }
    if (!matches) {
        return new Result(false, lines, Joiner.on(System.lineSeparator()).join(mismatches));
    }
    return new Result(true, remainingLines);
}
项目:hadoop    文件:MetricsConfig.java   
/**
 * Load configuration from a list of files until the first successful load
 * @param conf  the configuration object
 * @param files the list of filenames to try
 * @return  the configuration object
 */
static MetricsConfig loadFirst(String prefix, String... fileNames) {
  for (String fname : fileNames) {
    try {
      Configuration cf = new PropertiesConfiguration(fname)
          .interpolatedConfiguration();
      LOG.info("loaded properties from "+ fname);
      LOG.debug(toString(cf));
      MetricsConfig mc = new MetricsConfig(cf, prefix);
      LOG.debug(mc);
      return mc;
    }
    catch (ConfigurationException e) {
      if (e.getMessage().startsWith("Cannot locate configuration")) {
        continue;
      }
      throw new MetricsConfigException(e);
    }
  }
  LOG.warn("Cannot locate configuration: tried "+
           Joiner.on(",").join(fileNames));
  // default to an empty configuration
  return new MetricsConfig(new PropertiesConfiguration(), prefix);
}
项目:hadoop    文件:CacheAdmin.java   
@Override
public int run(Configuration conf, List<String> args) throws IOException {
  String name = StringUtils.popFirstNonOption(args);
  if (name == null) {
    System.err.println("You must specify a name when deleting a " +
        "cache pool.");
    return 1;
  }
  if (!args.isEmpty()) {
    System.err.print("Can't understand arguments: " +
      Joiner.on(" ").join(args) + "\n");
    System.err.println("Usage is " + getShortUsage());
    return 1;
  }
  DistributedFileSystem dfs = AdminHelper.getDFS(conf);
  try {
    dfs.removeCachePool(name);
  } catch (IOException e) {
    System.err.println(AdminHelper.prettifyException(e));
    return 2;
  }
  System.out.println("Successfully removed cache pool " + name + ".");
  return 0;
}
项目:Reer    文件:ExternalResourceResolver.java   
protected void checkMetadataConsistency(ModuleComponentIdentifier expectedId, MutableModuleComponentResolveMetadata metadata) throws MetaDataParseException {
    List<String> errors = new ArrayList<String>();
    if (!expectedId.getGroup().equals(metadata.getId().getGroup())) {
        errors.add("bad group: expected='" + expectedId.getGroup() + "' found='" + metadata.getId().getGroup() + "'");
    }
    if (!expectedId.getModule().equals(metadata.getId().getName())) {
        errors.add("bad module name: expected='" + expectedId.getModule() + "' found='" + metadata.getId().getName() + "'");
    }
    if (!expectedId.getVersion().equals(metadata.getId().getVersion())) {
        errors.add("bad version: expected='" + expectedId.getVersion() + "' found='" + metadata.getId().getVersion() + "'");
    }
    if (errors.size() > 0) {
        throw new MetaDataParseException(String.format("inconsistent module metadata found. Descriptor: %s Errors: %s",
            metadata.getId(), Joiner.on(SystemProperties.getInstance().getLineSeparator()).join(errors)));
    }
}
项目:hue    文件:VeroGenExpFormatter.java   
@Override
protected String visitSimpleCaseExpression(SimpleCaseExpression node, Void context)
{
    ImmutableList.Builder<String> parts = ImmutableList.builder();

    parts.add("CASE").add(process(node.getOperand(), context));

    for (WhenClause whenClause : node.getWhenClauses()) {
        parts.add(process(whenClause, context));
    }
    if (node.getDefaultValue() != null) {
        parts.add("ELSE").add(process(node.getDefaultValue(), context));
    }
    parts.add("END");

    return "(" + Joiner.on(' ').join(parts.build()) + ")";
}
项目:Re-Collector    文件:IsOneOfValidator.java   
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value == null) {
        return true;
    }
    final boolean valid = Arrays.asList(strings).contains(value);

    if (!valid) {
        HibernateConstraintValidatorContext hibernateContext = context.unwrap(HibernateConstraintValidatorContext.class);
        hibernateContext.disableDefaultConstraintViolation();

        hibernateContext.addExpressionVariable("validValues", Joiner.on(" ").join(strings))
                .buildConstraintViolationWithTemplate(hibernateContext.getDefaultConstraintMessageTemplate())
                .addConstraintViolation();
    }

    return valid;
}
项目:n4js    文件:LazyProjectDescriptionHandle.java   
protected ProjectDescription loadManifest(URI manifest) {
    ResourceSet resourceSet = resourceSetProvider.get();
    Resource resource = resourceSet.getResource(manifest, true);
    List<EObject> contents = resource.getContents();
    if (contents.isEmpty() || !(contents.get(0) instanceof ProjectDescription)) {
        return null;
    }
    // do some error handling:
    if (!resource.getErrors().isEmpty()) {
        throw new N4JSBrokenProjectException("Reading project description from "
                + manifest
                + " raised the following errors: "
                + Joiner.on('\n').join(
                        resource.getErrors().stream().map(
                                error -> error.getMessage() + "  at line " + error.getLine())
                                .iterator()));
    }
    ProjectDescription result = (ProjectDescription) contents.get(0);
    contents.clear();
    return result;
}
项目:AthenaX    文件:ValidatorTest.java   
@Test
public void testCreateFunction() throws IOException, ParseException {
  String sql = Joiner.on(";\n").join(
      "CREATE FUNCTION udf AS 'foo.udf'",
      "CREATE FUNCTION udf1 AS 'foo.udf' USING JAR 'mock://foo'",
      "CREATE FUNCTION udf2 AS 'foo.udf' USING JAR 'mock://foo', JAR 'mock://bar'"
  );
  SqlNodeList nodes = Planner.parse(sql);
  Validator validator = new Validator();
  validator.extract(nodes);
  assertEquals(ImmutableList.of(
      URI.create("mock://foo"),
      URI.create("mock://foo"),
      URI.create("mock://bar")
  ), ImmutableList.copyOf(validator.additionalResources()));
}
项目:i_stolbov    文件:MenuTest.java   
/**
 * Check result.
 * @param question - question
 * @param answer - answer
 */
private void checkResult(String question, String answer) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    System.setOut(new PrintStream(out));

    Menu menu = new Menu();
    menu.show();
    menu.select(question);

    String target = Joiner.on(System.getProperty("line.separator")).join("1: Date And Time",
            "  1.1: Date",
            "    1.1.1: Day Of the Week",
            "    1.1.2: Month",
            "  1.2: Time",
            answer) + System.getProperty("line.separator");

    assertThat(out.toString(), is(target));
}
项目:atlas    文件:MainDexLister.java   
private Map<String, String> getClassObfMap(GradleVariantConfiguration config) {
    Map<String, String> classMap = new HashMap<String, String>();
    boolean isMinifyEnabled = config.isMinifyEnabled();
    File proguardOut = new File(Joiner.on(File.separatorChar).join(
        String.valueOf(appVariantContext.getScope().getGlobalScope().getBuildDir()), FD_OUTPUTS, "mapping",
        appVariantContext.getScope().getVariantConfiguration().getDirName()));
    File mappingFile = new File(proguardOut, "mapping.txt");
    // Parse the mapping file to generate the new mainDexListFile
    if (isMinifyEnabled && mappingFile.exists()) {
        MappingReader mappingReader = new MappingReader(mappingFile);
        MappingReaderProcess process = new MappingReaderProcess();
        try {
            mappingReader.pump(process);
        } catch (IOException e) {
            throw new GradleException(e.getMessage(), e);
        }
        classMap = process.classMapping;
    }
    return classMap;
}
项目:dremio-oss    文件:ScanRelBase.java   
@Override
public RelWriter explainTerms(RelWriter pw) {
  pw.item("table", tableMetadata.getName());
  if(projectedColumns != null){
    pw.item("columns", FluentIterable.from(projectedColumns).transform(new Function<SchemaPath, String>(){

      @Override
      public String apply(SchemaPath input) {
        return input.toString();
      }}).join(Joiner.on(", ")));
  }

  pw.item("splits", getTableMetadata().getSplitCount());

  if(observedRowcountAdjustment != 1.0d){
    pw.item("rowAdjust", observedRowcountAdjustment);
  }

  return pw;
}
项目:dble    文件:Procedure.java   
public String toChangeCallSql(String dbType) {
    StringBuilder sb = new StringBuilder();
    sb.append("call ");
    sb.append(this.getName()).append("(");
    Collection<ProcedureParameter> parameters = this.getParameterMap().values();
    int j = 0;
    for (ProcedureParameter parameter : parameters) {
        Object value = parameter.getValue() != null && Types.VARCHAR == parameter.getJdbcType() ? "'" + parameter.getValue() + "'" : parameter.getValue();
        String strParameter = parameter.getValue() == null ? parameter.getName() : String.valueOf(value);
        String joinStr = j == this.getParameterMap().size() - 1 ? strParameter : strParameter + ",";
        sb.append(joinStr);
        j++;
    }
    sb.append(")");
    if (isResultSimpleValue()) {
        sb.append(";select ");
        sb.append(Joiner.on(",").join(selectColumns));
    }
    return sb.toString();
}
项目:presto-query-formatter    文件:StatementFormatter.java   
@Override
protected Void visitInsert(Insert node, Integer indent)
{
    builder.append("INSERT INTO ")
            .append(node.getTarget())
            .append(" ");

    if (node.getColumns().isPresent()) {
        builder.append("(")
                .append(Joiner.on(", ").join(node.getColumns().get()))
                .append(") ");
    }

    process(node.getQuery(), indent);

    return null;
}
项目:morf    文件:MySqlDialect.java   
/**
 * @see org.alfasoftware.morf.jdbc.SqlDialect#indexDeploymentStatements(org.alfasoftware.morf.metadata.Table, org.alfasoftware.morf.metadata.Index)
 */
@Override
public String indexDeploymentStatement(Table table, Index index) {
  StringBuilder statement = new StringBuilder();

  statement.append("ALTER TABLE `");
  statement.append(table.getName());
  statement.append("` ADD ");
  if (index.isUnique()) {
    statement.append("UNIQUE ");
  }
  statement.append("INDEX `")
           .append(index.getName())
           .append("` (`")
           .append(Joiner.on("`, `").join(index.columnNames()))
           .append("`)");

  return statement.toString();
}
项目:autorest.java    文件:PathsInner.java   
/**
 * Get a 200 to test a valid base uri.
 *
 * @param accountName Account Name
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the {@link ServiceResponse} object if successful.
 */
public Observable<ServiceResponse<Void>> getEmptyWithServiceResponseAsync(String accountName) {
    if (accountName == null) {
        throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
    }
    if (this.client.host() == null) {
        throw new IllegalArgumentException("Parameter this.client.host() is required and cannot be null.");
    }
    String parameterizedHost = Joiner.on(", ").join("{accountName}", accountName, "{host}", this.client.host());
    return service.getEmpty(this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
        .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
            @Override
            public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                try {
                    ServiceResponse<Void> clientResponse = getEmptyDelegate(response);
                    return Observable.just(clientResponse);
                } catch (Throwable t) {
                    return Observable.error(t);
                }
            }
        });
}
项目:tools    文件:SiaSeedServiceTest.java   
@Test
    public void getSiaSeed() throws Exception {
        final SiaSeedService siaSeedService = new SiaSeedService(new StaticEncyptionKeyProvider("123"));
//        final List<String> strings = siaSeedService.buildSiaSeed("123");
        final Multiset<Long> counts;
        counts = HashMultiset.create();
        for (int i = 0; i < 100000; i++) {
            final String secretKey = "abc123782567825784__" + i;
            final List<String> words = siaSeedService.buildSiaSeed(secretKey);
            final String wordsList = Joiner.on(" ").join(words);
            final String errrorMessage = "secret produced unexpected length: " + secretKey + " words: " + wordsList;
            counts.add((long) words.size());
//            Assert.assertEquals(errrorMessage, 29, words.size());

        }
        counts.forEachEntry((length, count) -> System.out.println(length + " occurred " + count + " times"));
    }
项目:empiria.player    文件:OrderInteractionViewItemStylesImpl.java   
private String buildStyleName(OrderingItem orderingItem) {
    String itemStyle = styleNames.QP_ORDERED_ITEM();
    String answerTypeStyle = stylesMap.get(orderingItem.getAnswerType());

    Set<String> styles = Sets.newLinkedHashSet();
    styles.add(itemStyle);
    styles.add(answerTypeStyle);

    if (orderingItem.isLocked()) {
        styles.add(styleNames.QP_ORDERED_ITEM_LOCKED());
    }

    if (orderingItem.isSelected()) {
        styles.add(styleNames.QP_ORDERED_ITEM_SELECTED());
    }

    return Joiner.on(SEPARATOR)
            .join(styles);
}
项目:n4js    文件:N4JSGenerateImmediatelyBuilderState.java   
private void logBuildData(BuildData buildData, String... tags) {
    // This log call sometimes yields a ConcurrentModificationException (see GHOLD-296)
    // We disable it as a temporary fix only until GHOLD-296 is resolved.
    // TODO Uncomment the following code when GHOLD-296 is resolved and remove the SuppressWarnings annotation.

    // UPDATE as of Nov 2017 (mor):
    // commented logging back in after (hopefully) fixing the ConcurrentModificationException
    // (but keeping these comments for reference, for now; if this does not cause problems over the next few weeks,
    // this comment and the previous comments in this method can be removed)

    String tag = Arrays2.isEmpty(tags) ? "" : Joiner.on(" - ").join(tags);
    String header = "---------------------- Build data" + tag + " --------------------------------------";
    builderStateLogger.log(header);
    builderStateLogger.log("Project name: " + buildData.getProjectName());
    builderStateLogger.log("To be deleted: " + ensureNotNull(buildData.getToBeDeleted()));
    builderStateLogger.log("To be updated: " + ensureNotNull(buildData.getToBeUpdated()));
    builderStateLogger.log("URI queue: " + buildData.getURIQueue());
    builderStateLogger.log("All remaining URIs: " + buildData.getAllRemainingURIs());
    builderStateLogger.log(Strings.repeat("-", header.length()) + "\n");
}
项目:ditb    文件:GenericTestUtils.java   
/**
 * List all of the files in 'dir' that match the regex 'pattern'.
 * Then check that this list is identical to 'expectedMatches'.
 * @throws IOException if the dir is inaccessible
 */
public static void assertGlobEquals(File dir, String pattern,
    String ... expectedMatches) throws IOException {

  Set<String> found = Sets.newTreeSet();
  for (File f : FileUtil.listFiles(dir)) {
    if (f.getName().matches(pattern)) {
      found.add(f.getName());
    }
  }
  Set<String> expectedSet = Sets.newTreeSet(
      Arrays.asList(expectedMatches));
  Assert.assertEquals("Bad files matching " + pattern + " in " + dir,
      Joiner.on(",").join(expectedSet),
      Joiner.on(",").join(found));
}
项目:AthenaX    文件:ValidatorTest.java   
@Test
public void testSetOptions() throws IOException, ParseException {
  String sql = Joiner.on(";\n").join(
      "SET spam = 1",
      "SET foo = 'bar'",
      "RESET foo",
      "ALTER SESSION SET bar = OFF"
  );
  SqlNodeList nodes = Planner.parse(sql);
  Validator validator = new Validator();
  validator.extract(nodes);
  Configuration options = validator.options();
  assertEquals(1, options.getInt("spam"));
  assertNull(options.getString("foo", null));
  assertEquals("OFF", options.getString("bar"));
}
项目:circus-train    文件:ComparisonToolHelp.java   
@Override
public String toString() {
  Iterable<String> errorMessages = FluentIterable.from(errors).transform(OBJECT_ERROR_TO_TABBED_MESSAGE);

  StringBuilder help = new StringBuilder(500)
      .append("Usage: compare-tables.sh --config=<config_file>[,<config_file>,...] --"
          + ComparisonToolArgs.OUTPUT_FILE
          + "=<output_file> [--"
          + ComparisonToolArgs.SOURCE_PARTITION_BATCH_SIZE
          + "=1000] [--"
          + ComparisonToolArgs.REPLICA_PARTITION_BUFFER_SIZE
          + "=1000]")
      .append(System.lineSeparator())
      .append("Errors found in the provided configuration file:")
      .append(System.lineSeparator())
      .append(Joiner.on(System.lineSeparator()).join(errorMessages))
      .append(System.lineSeparator())
      .append("Configuration file help:")
      .append(System.lineSeparator())
      .append(TAB)
      .append("For more information and help please refer to ")
      .append(
          "https://github.com/HotelsDotCom/circus-train/blob/master/circus-train-tool/circus-train-comparison-tool/README.md");
  return help.toString();
}
项目:dremio-oss    文件:S3PluginConfig.java   
/**
 * Helper method to get configuration for S3 implementation of {@link FileSystem} from
 * given S3 access credentials and property list.
 */
private static Map<String, String> getConfig(final String accessKey, final String accessSecret,
    final boolean secure, List<String> externalBuckets, final Map<String, String> properties) {
  final Map<String, String> finalProperties = Maps.newHashMap();
  finalProperties.put(FileSystem.FS_DEFAULT_NAME_KEY, "dremioS3:///");
  finalProperties.put("fs.dremioS3.impl", S3FileSystem.class.getName());
  finalProperties.put(MAXIMUM_CONNECTIONS, String.valueOf(DEFAULT_MAX_CONNECTIONS));
  if(accessKey != null){
    finalProperties.put(ACCESS_KEY, accessKey);
    finalProperties.put(SECRET_KEY, accessSecret);
  } else {
    // don't use Constants here as it breaks when using older MapR/AWS files.
    finalProperties.put("fs.s3a.aws.credentials.provider", "org.apache.hadoop.fs.s3a.AnonymousAWSCredentialsProvider");
  }

  if (properties != null && !properties.isEmpty()) {
    for (Entry<String, String> property : properties.entrySet()) {
      finalProperties.put(property.getKey(), property.getValue());
    }
  }


  finalProperties.put(SECURE_CONNECTIONS, String.valueOf(secure));
  if(externalBuckets != null && !externalBuckets.isEmpty()){
    finalProperties.put(EXTERNAL_BUCKETS, Joiner.on(",").join(externalBuckets));
  }else {
    if(accessKey == null){
      throw UserException.validationError()
        .message("Failure creating S3 connection. You must provide at least one of: (1) access key and secret key or (2) one or more external buckets.")
        .build(logger);
    }
  }

  return finalProperties;
}
项目:apkfile    文件:ResourceConfiguration.java   
@Override
public final String toString() {
    if (isDefault()) {  // Prevent the default configuration from returning the empty string
        return "default";
    }
    Collection<String> parts = toStringParts().values();
    parts.removeAll(Collections.singleton(""));
    return Joiner.on('-').join(parts);
}
项目:dremio-oss    文件:DescribeTransformation.java   
@Override
public String visit(TransformGroupBy groupBy) throws Exception {
  List<String> cols = new ArrayList<>();
  List<Dimension> columnsDimensionsList = groupBy.getColumnsDimensionsList();
  if (columnsDimensionsList != null) {
    for (Dimension dimension : columnsDimensionsList) {
      cols.add(dimension.getColumn());
    }
  }
  return "Group by " + Joiner.on(", ").join(cols);
}
项目:presto-query-formatter    文件:StatementFormatter.java   
private static void appendAliasColumns(StringBuilder builder, List<String> columns)
{
    if ((columns != null) && (!columns.isEmpty())) {
        builder.append(" (");
        Joiner.on(", ").appendTo(builder, columns);
        builder.append(')');
    }
}
项目:twister2    文件:JavaCheckstyle.java   
private static void checkStyle(String[] files, String config) throws IOException {
  if (files.length == 0) {
    LOG.fine("No java files found by checkstyle");
    return;
  }

  LOG.fine(files.length + " java files found by checkstyle");

  String[] checkstyleArgs = (String[]) ArrayUtils.addAll(
      new String[]{"-c", config}, files);

  LOG.fine("checkstyle args: " + Joiner.on(" ").join(checkstyleArgs));
  com.puppycrawl.tools.checkstyle.Main.main(checkstyleArgs);
}
项目:DBus    文件:MysqlDefaultProcessor.java   
@Override
public void process(ConsumerRecord<String, byte[]> record, Object... args) {
 try {
     logger.debug("[BEGIN] Receive data,offset:{}", record.offset());
     List<MessageEntry> msgEntryLst = parser.getEntry(record.value());
     dataFilter(msgEntryLst);
     if(!msgEntryLst.isEmpty()){
         EmitData data = new EmitData();
         data.add(EmitData.OFFSET, record.offset());
         data.add(EmitData.GENERIC_DATA_LIST, msgEntryLst);
         List<Object> values = new Values(data, Command.UNKNOWN_CMD);
         this.listener.emitData(values, record);
         values = null;
         logger.debug("[END] emit data,offset:{}", record.offset());
     }else{
         logger.info("Table not configured in t_dbus_tables {}", Joiner.on(",").join(msgEntryLst.stream()
                       .map(msgEntry->msgEntry.getEntryHeader().getTableName()).collect(Collectors.toList())));
            listener.reduceFlowSize(record.serializedValueSize());
            // 当前记录不需要处理则直接commit
            consumerListener.syncOffset(record);
     }
     msgEntryLst = null;
 }catch (Exception e) {
     listener.reduceFlowSize(record.serializedValueSize());
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
 }
}
项目:presto-query-formatter    文件:StatementFormatter.java   
@Override
protected Void visitExplain(Explain node, Integer indent)
{
    builder.append("EXPLAIN ");
    if (node.isAnalyze()) {
        builder.append("ANALYZE ");
    }

    List<String> options = new ArrayList<>();

    for (ExplainOption option : node.getOptions()) {
        if (option instanceof ExplainType) {
            options.add("TYPE " + ((ExplainType) option).getType());
        }
        else if (option instanceof ExplainFormat) {
            options.add("FORMAT " + ((ExplainFormat) option).getType());
        }
        else {
            throw new UnsupportedOperationException("unhandled explain option: " + option);
        }
    }

    if (!options.isEmpty()) {
        builder.append("(");
        Joiner.on(", ").appendTo(builder, options);
        builder.append(")");
    }

    builder.append("\n");

    process(node.getStatement(), indent);

    return null;
}
项目:Equella    文件:InstitutionFilter.java   
@Override
protected FilterResult doFilterInternal(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
{
    final Set<String> matchStrings = getMatchStrings(request);
    final Pair<String, Pair<String, InstitutionStatus>> matchInstPair = getInstitutionForUrl(matchStrings);

    // I'm not sure this is ever going to be null ...?
    if( matchInstPair == null )
    {
        if( LOGGER.isDebugEnabled() )
        {
            LOGGER.debug("No institutions were matched for request [" + request.getRequestURL()
                + "] where it was matching as [" + Joiner.on("] or [").join(matchStrings)
                + "] against enabled institutions with URLs [" + Joiner.on("] and [")
                    .join(Collections2.transform(getInstitutions(), new Function<Pair<String, ?>, String>()
                    {
                        @Override
                        public String apply(Pair<String, ?> input)
                        {
                            return input.getFirst();
                        }
                    }))
                + "]");
        }

        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return FilterResult.FILTER_CONTINUE;
    }
    else
    {
        // We're accessing the admin URL ...
        return doNormal(request, response, matchInstPair);
    }
}
项目:hadoop    文件:ShortCircuitRegistry.java   
public synchronized String getClientNames(ExtendedBlockId blockId) {
  if (!enabled) return "";
  final HashSet<String> clientNames = new HashSet<String>();
  final Set<Slot> affectedSlots = slots.get(blockId);
  for (Slot slot : affectedSlots) {
    clientNames.add(((RegisteredShm)slot.getShm()).getClientName());
  }
  return Joiner.on(",").join(clientNames);
}
项目:hadoop    文件:NameNode.java   
/**
 * Clone the supplied configuration but remove the shared edits dirs.
 *
 * @param conf Supplies the original configuration.
 * @return Cloned configuration without the shared edit dirs.
 * @throws IOException on failure to generate the configuration.
 */
private static Configuration getConfigurationWithoutSharedEdits(
    Configuration conf)
    throws IOException {
  List<URI> editsDirs = FSNamesystem.getNamespaceEditsDirs(conf, false);
  String editsDirsString = Joiner.on(",").join(editsDirs);

  Configuration confWithoutShared = new Configuration(conf);
  confWithoutShared.unset(DFSConfigKeys.DFS_NAMENODE_SHARED_EDITS_DIR_KEY);
  confWithoutShared.setStrings(DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_KEY,
      editsDirsString);
  return confWithoutShared;
}
项目:grpc-java-contrib    文件:ProtoTypeMap.java   
/**
 * Returns the full Java type name based on the given protobuf type parameters.
 *
 * @param className the protobuf type name
 * @param enclosingClassName the optional enclosing class for the given type
 * @param javaPackage the proto file's configured java package name
 */
public static String toJavaTypeName(
        @Nonnull String className,
        @Nullable String enclosingClassName,
        @Nullable String javaPackage) {

    Preconditions.checkNotNull(className, "className");

    Joiner dotJoiner = Joiner.on('.').skipNulls();
    return dotJoiner.join(javaPackage, enclosingClassName, className);
}
项目:dremio-oss    文件:DescribeTransformation.java   
@Override
public String visit(TransformSorts sortMultiple) throws Exception {
  List<Order> columnsList = sortMultiple.getColumnsList();
  List<String> display = new ArrayList<>();
  for (Order order : columnsList) {
    display.add(describe(order));
  }
  return "Sort by " + Joiner.on(',').join(display);
}
项目:ts-cards    文件:GetApplicationIds.java   
@Override
public void validateResponse(ApduResponse response) {
    super.validateResponse(response);

    if (response.getStatus() != 0x9100) {
        throw new RuntimeException("Error response (" +
                Integer.toHexString(response.getStatus()) + ")");
    } else {

        List<String> aids = new ArrayList<>();

        int macSize = !DesfireAuth.isAuthenticated(getSession()) ? 0 : 8;

        for (int i = 0; i < response.getData().length - macSize; i += 3 ) {
            byte[] aid = Arrays.copyOfRange(response.getData(),
                    i, i + 3);
            aids.add(Hex.encode(aid));
        }

        if (aids.size() > 0) {
            String aidsAsString = Joiner.on(';').join(aids);
            getSession().setParameter(
                    AIDS_KEY + "_" + getIndex(),
                    aidsAsString);
        }

        done();
    }
}
项目:morf    文件:MockDialect.java   
/**
 * @see org.alfasoftware.morf.jdbc.SqlDialect#indexDeploymentStatements(org.alfasoftware.morf.metadata.Table,
 *      org.alfasoftware.morf.metadata.Index)
 */
@Override
public String indexDeploymentStatement(Table table, Index index) {
  StringBuilder statement = new StringBuilder();

  statement.append("CREATE ");
  if (index.isUnique()) {
    statement.append("UNIQUE ");
  }
  statement.append("INDEX ").append(index.getName()).append(" ON ").append(table.getName()).append(" (")
      .append(Joiner.on(',').join(index.columnNames())).append(")");

  return statement.toString();
}
项目:presto-query-formatter    文件:ExpressionFormatter.java   
static String formatGroupBy(List<GroupingElement> groupingElements, Optional<List<Expression>> parameters, int indent)
{
    ImmutableList.Builder<String> resultStrings = ImmutableList.builder();

    for (GroupingElement groupingElement : groupingElements) {
        String result = "";
        if (groupingElement instanceof SimpleGroupBy) {
            Set<Expression> columns = ImmutableSet.copyOf(((SimpleGroupBy) groupingElement).getColumnExpressions());
            if (columns.size() == 1) {
                result = formatExpression(getOnlyElement(columns), parameters, indent);
            }
            else {
                result = formatGroupingSet(columns, parameters, indent);
            }
        }
        else if (groupingElement instanceof GroupingSets) {
            result = format("GROUPING SETS (%s)", Joiner.on(", ").join(
                    ((GroupingSets) groupingElement).getSets().stream()
                            .map(ExpressionFormatter::formatGroupingSet)
                            .iterator()));
        }
        else if (groupingElement instanceof Cube) {
            result = format("CUBE %s", formatGroupingSet(((Cube) groupingElement).getColumns()));
        }
        else if (groupingElement instanceof Rollup) {
            result = format("ROLLUP %s", formatGroupingSet(((Rollup) groupingElement).getColumns()));
        }
        resultStrings.add(result);
    }
    return Joiner.on(", ").join(resultStrings.build());
}
项目:ArchUnit    文件:ClassesShouldThatEvaluator.java   
private String getRelevantFailures(JavaClasses classes) {
    List<String> relevant = new ArrayList<>();
    for (String line : linesIn(rule.evaluate(classes).getFailureReport())) {
        if (!isDefaultConstructor(line) && !isSelfReference(line)) {
            relevant.add(line);
        }
    }
    return Joiner.on("#").join(relevant);
}