Java Code Examples for com.google.common.base.Joiner

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project airlift, under directory /testing/src/main/java/io/airlift/testing/.

Source file: Assertions.java

  22 
vote

public static void assertEqualsIgnoreOrder(Iterable<?> actual,Iterable<?> expected,String message){
  assertNotNull(actual,"actual is null");
  assertNotNull(expected,"expected is null");
  ImmutableMultiset<?> actualSet=ImmutableMultiset.copyOf(actual);
  ImmutableMultiset<?> expectedSet=ImmutableMultiset.copyOf(expected);
  if (!actualSet.equals(expectedSet)) {
    Joiner joiner=Joiner.on("\n      ");
    fail("%sexpected: collections to be equal (ignoring order).%nActual:%n      %s%nExpected:%n      %s",toMessageString(message),joiner.join(actual),joiner.join(expected));
  }
}
 

Example 2

From project clustermeister, under directory /cli/src/main/java/com/github/nethad/clustermeister/provisioning/cli/.

Source file: ProvisioningCLI.java

  22 
vote

private void registerCompletors(ConsoleReader reader){
  List<String> completionTerms=Lists.newArrayList();
  Joiner joiner=Joiner.on(' ');
  for (  String commandName : userInputEvaluation.commands()) {
    Command command=userInputEvaluation.getCommand(commandName);
    completionTerms.add(commandName);
    recursivelyExpandTerms(command,completionTerms,joiner);
  }
  reader.addCompletor(new SimpleCompletor(completionTerms.toArray(new String[0])));
}
 

Example 3

From project core_4, under directory /api/src/test/java/org/richfaces/util/.

Source file: FastJoinerTest.java

  22 
vote

@Test public void testGuavaJoinerPerformance() throws Exception {
  Joiner joiner=Joiner.on("-separator-").skipNulls();
  for (int i=0; i < PERFORMANCE_TEST_STEPS; i++) {
    joiner.join("big:table:id:string","cell:id");
  }
}
 

Example 4

From project jclouds-abiquo, under directory /core/src/main/java/org/jclouds/abiquo/domain/enterprise/.

Source file: User.java

  22 
vote

private void setAvailableVirtualDatacenters(final List<Integer> ids){
  if (ids == null || ids.size() == 0) {
    target.setAvailableVirtualDatacenters("");
  }
 else {
    Joiner joiner=Joiner.on(",").skipNulls();
    target.setAvailableVirtualDatacenters(joiner.join(ids));
  }
}
 

Example 5

From project platform_3, under directory /testing/src/main/java/com/proofpoint/testing/.

Source file: Assertions.java

  22 
vote

public static void assertEqualsIgnoreOrder(Iterable<?> actual,Iterable<?> expected,String message){
  assertNotNull(actual,"actual is null");
  assertNotNull(expected,"expected is null");
  ImmutableMultiset<?> actualSet=ImmutableMultiset.copyOf(actual);
  ImmutableMultiset<?> expectedSet=ImmutableMultiset.copyOf(expected);
  if (!actualSet.equals(expectedSet)) {
    Joiner joiner=Joiner.on("\n      ");
    fail("%sexpected: collections to be equal (ignoring order).%nActual:%n      %s%nExpected:%n      %s",toMessageString(message),joiner.join(actual),joiner.join(expected));
  }
}
 

Example 6

From project agorava-core, under directory /agorava-core-impl/src/main/java/org/agorava/core/oauth/.

Source file: PropertyOAuthAppSettingsBuilder.java

  21 
vote

/** 
 * {@inheritDoc} <p/>This implementation will build the  {@link OAuthAppSettings} from a {@link ResourceBundle}<p/> It'll first try to load all binding (mandatory) fields from the bundle by looking for the key prefix.fieldName (or fieldName if prefix is empty) <p/> In a second time it'll check if optional fields are present in the bundle (with the same key construction) and load them if they are. If they are not present it'll try to load them without prefix
 * @return the built OAuthAppSettings
 * @throws java.util.MissingResourceException if the bundle can't be open
 * @throws AgoravaException if a binding field is missing in the bundle
 */
@Override public OAuthAppSettings build(){
  String key;
  String value;
  Joiner kj=Joiner.on('.').skipNulls();
  ResourceBundle rb=ResourceBundle.getBundle(bundleName);
  for (  String k : bindingKeys) {
    key=kj.join(prefix,k);
    if (!rb.containsKey(key)) {
      throw new AgoravaException("Unable to find binding key: " + key + " in bundle "+ bundleName+ " to build settings");
    }
    value=rb.getString(key);
    invokeSetter(k,value);
  }
  for (  String k : optionalKeys) {
    key=kj.join(prefix,k);
    if (rb.containsKey(key)) {
      value=rb.getString(key);
      invokeSetter(k,value);
    }
 else     if (rb.containsKey(k)) {
      value=rb.getString(k);
      invokeSetter(k,value);
    }
  }
  return super.build();
}
 

Example 7

From project flume, under directory /flume-ng-channels/flume-file-channel/src/test/java/org/apache/flume/channel/file/encryption/.

Source file: EncryptionTestUtils.java

  21 
vote

public static Map<String,String> configureForKeyStore(File keyStoreFile,File keyStorePasswordFile,Map<String,File> keyAliasPassword) throws Exception {
  Map<String,String> context=Maps.newHashMap();
  List<String> keys=Lists.newArrayList();
  Joiner joiner=Joiner.on(".");
  for (  String alias : keyAliasPassword.keySet()) {
    File passwordFile=keyAliasPassword.get(alias);
    if (passwordFile == null) {
      keys.add(alias);
    }
 else {
      String propertyName=joiner.join(EncryptionConfiguration.KEY_PROVIDER,EncryptionConfiguration.JCE_FILE_KEYS,alias,EncryptionConfiguration.JCE_FILE_KEY_PASSWORD_FILE);
      keys.add(alias);
      context.put(propertyName,passwordFile.getAbsolutePath());
    }
  }
  context.put(joiner.join(EncryptionConfiguration.KEY_PROVIDER,EncryptionConfiguration.JCE_FILE_KEY_STORE_FILE),keyStoreFile.getAbsolutePath());
  if (keyStorePasswordFile != null) {
    context.put(joiner.join(EncryptionConfiguration.KEY_PROVIDER,EncryptionConfiguration.JCE_FILE_KEY_STORE_PASSWORD_FILE),keyStorePasswordFile.getAbsolutePath());
  }
  context.put(joiner.join(EncryptionConfiguration.KEY_PROVIDER,EncryptionConfiguration.JCE_FILE_KEYS),Joiner.on(" ").join(keys));
  return context;
}
 

Example 8

From project LastCalc, under directory /src/com/lastcalc/parsers/amounts/.

Source file: UnitParser.java

  21 
vote

private static void addParsers(final Set<UnitParser> ret,final Class<? extends SystemOfUnits> cls){
  final Joiner joiner=Joiner.on(' ');
  for (  final Field f : cls.getDeclaredFields()) {
    if (!Modifier.isStatic(f.getModifiers())) {
      continue;
    }
    final Class<?> fieldType=f.getType();
    if (Unit.class.isAssignableFrom(fieldType)) {
      final Object[] longName=f.getName().toLowerCase().split("_");
      if (longName.length == 1 && longName[0].toString().length() < 3) {
        continue;
      }
      try {
        final Unit<?> unit=(Unit<?>)f.get(null);
        if (longName.length > 0) {
          ret.add(new UnitParser(unit,TokenList.create(Lists.newArrayList(longName))));
          verboseNamesSing.put(unit,joiner.join(longName));
          if (longName[0].toString().charAt(longName[0].toString().length() - 1) != 's') {
            final ArrayList<Object> pluralLongName=Lists.<Object>newArrayList(longName);
            pluralLongName.set(0,pluralLongName.get(0) + "s");
            ret.add(new UnitParser(unit,TokenList.create(pluralLongName)));
            verboseNamesPlur.put(unit,joiner.join(pluralLongName));
          }
        }
        final TokenList shortName=Tokenizer.tokenize(unit.toString());
        if (shortName.size() > 0) {
          if (((shortName.size() > 1) || ((shortName.get(0).toString().length() > 1) && (!dontUse.contains(shortName.get(0)))))) {
            ret.add(new UnitParser(unit,shortName));
          }
        }
      }
 catch (      final IllegalArgumentException e) {
        e.printStackTrace();
      }
catch (      final IllegalAccessException e) {
        e.printStackTrace();
      }
    }
  }
}
 

Example 9

From project AdminCmd, under directory /src/main/java/be/Balor/Manager/Commands/Player/.

Source file: PlayerList.java

  19 
vote

@Override public void execute(final CommandSender sender,final CommandArgs args) throws ActionNotPermitedException, PlayerNotFound {
  final Collection<String> list=Utils.getPlayerList(sender);
  sender.sendMessage(Utils.I18n("onlinePlayers") + " " + ChatColor.WHITE+ list.size());
  final String toDisplay=Joiner.on(", ").join(list);
  if (toDisplay.length() >= ACMinecraftFontWidthCalculator.chatwidth) {
    sender.sendMessage(toDisplay.substring(0,ACMinecraftFontWidthCalculator.chatwidth));
    sender.sendMessage(toDisplay.substring(ACMinecraftFontWidthCalculator.chatwidth,toDisplay.length()));
    return;
  }
  sender.sendMessage(toDisplay);
}
 

Example 10

From project agorava-facebook, under directory /agorava-facebook-cdi/src/main/java/org/agorava/facebook/impl/.

Source file: GraphApiImpl.java

  19 
vote

@Override public <T>List<T> fetchConnections(String objectId,String connectionType,Class<T> type,String... fields){
  Map<String,String> queryParameters=newHashMap();
  if (fields.length > 0) {
    String joinedFields=Joiner.on(',').join(fields);
    queryParameters.put("fields",joinedFields);
  }
  return fetchConnections(objectId,connectionType,type,queryParameters);
}
 

Example 11

From project aim3-tu-berlin, under directory /seminar/exercises/datamining/core/src/main/java/de/tuberlin/dima/aim/exercises/two/.

Source file: SecondarySortBookSort.java

  19 
vote

@Override protected void reduce(BookSortKey bookSortKey,Iterable<Text> values,Context ctx) throws IOException, InterruptedException {
  for (  Text value : values) {
    String out=Joiner.on('\t').skipNulls().join(new Object[]{bookSortKey.toString(),value.toString()});
    ctx.write(new Text(out),NullWritable.get());
  }
}
 

Example 12

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/activity/adapter/.

Source file: SessionAdapter.java

  19 
vote

private void fillTypes(View view,Session session){
  TextView dataTypes=(TextView)view.findViewById(R.id.data_types);
  if (selectedSensor == null) {
    Iterable<String> types=transform(session.getActiveMeasurementStreams(),new Function<MeasurementStream,String>(){
      @Override public String apply(      MeasurementStream input){
        return input.getShortType();
      }
    }
);
    types=Ordering.natural().sortedCopy(types);
    String text=Joiner.on("/").join(types);
    dataTypes.setText(text);
  }
 else {
    dataTypes.setText(selectedSensor.getShortType());
  }
}
 

Example 13

From project appdriver, under directory /android/src/com/google/android/testing/nativedriver/client/.

Source file: AdbConnectionBuilder.java

  19 
vote

private static String joinPath(String root,String[] path){
  if (root.endsWith(File.separator)) {
    root=root.substring(0,root.length() - 1);
  }
  return Joiner.on(File.separator).join(Lists.asList(root,path));
}
 

Example 14

From project Arecibo, under directory /dashboard/src/main/java/com/ning/arecibo/dashboard/config/.

Source file: LegendConfigurationsManager.java

  19 
vote

@Inject public LegendConfigurationsManager(final DashboardConfig config) throws Exception {
  if (config.getLegendGroupsFile() != null) {
    final File legendGroupsFile=new File(config.getLegendGroupsFile());
    final LegendConfiguration legendConfiguration=mapper.readValue(legendGroupsFile,new TypeReference<LegendConfiguration>(){
    }
);
    this.legendConfiguration.putAll(legendConfiguration);
  }
  if (config.getLegendFixturesFile() != null) {
    final File legendFixturesFile=new File(config.getLegendFixturesFile());
    legendFixtures=Joiner.on("\n").join(Files.readLines(legendFixturesFile,Charsets.UTF_8));
  }
 else {
    legendFixtures="";
  }
}
 

Example 15

From project atlas, under directory /src/main/java/com/ning/atlas/components/files/.

Source file: ScriptInstaller.java

  19 
vote

@Override public String perform(Host host,Uri<? extends Component> uri,Deployment d) throws Exception {
  Iterator<String> argv=Splitter.on(Pattern.compile("\\s+")).split(uri.getFragment()).iterator();
  String script_path=argv.next();
  File script=new File(script_path);
  SSH ssh=new SSH(host,d.getSpace(),creds);
  try {
    ssh.scpUpload(script,"/tmp/script_installer_script");
    ssh.exec("chmod +x /tmp/script_installer_script");
    String cmd="/tmp/script_installer_script " + Joiner.on(" ").join(Lists.newArrayList(argv));
    String out=ssh.exec(cmd);
    log.info(out);
    return out;
  }
  finally {
    ssh.close();
  }
}
 

Example 16

From project atlassian-rest-cli, under directory /rest-cli-runner/src/main/java/com/galeoconsulting/leonardinius/rest/service/.

Source file: ScriptRunner.java

  19 
vote

@Override public void destroy() throws Exception {
  final Map<SessionId,ScriptSession> idSessionMap=sessionManager.listAllSessions();
  if (idSessionMap != null && !idSessionMap.isEmpty()) {
    LOG.warn("Alive sessions are found and shall be destroyed: {}",Joiner.on(',').skipNulls().join(Iterables.transform(idSessionMap.keySet(),new Function<SessionId,Object>(){
      @Override public Object apply(      @Nullable SessionId sessionId){
        if (sessionId != null) {
          return sessionId.getSessionId();
        }
        return null;
      }
    }
)));
  }
  sessionManager.clear();
}
 

Example 17

From project atunit, under directory /atunit/src/main/java/atunit/spi/exception/.

Source file: IncompatiblePluginsException.java

  19 
vote

private static String join(Class<?>[] classes){
  int s=classes.length;
  if (s < 2) {
    throw new IllegalArgumentException("Must specify at least two incompatible plugin classes");
  }
  List<Class<?>> list=Arrays.asList(classes);
  return Joiner.on(", ").join(list.subList(0,list.size() - 1)) + (s > 2 ? "," : "") + " and "+ list.get(list.size() - 1);
}
 

Example 18

From project baseunits, under directory /src/main/java/jp/xet/baseunits/time/formatter/.

Source file: DetailedDurationFormatter.java

  19 
vote

@Override public String format(Duration target,Locale locale){
  Validate.notNull(target);
  Validate.notNull(locale);
  TimeUnitFormat format=new TimeUnitFormat(locale);
  List<TimeUnitAmount> amounts=divide(target);
  if (amounts.isEmpty()) {
    TimeUnit lastUnit=timeUnits[timeUnits.length - 1];
    return format.format(new TimeUnitAmount(0,TIME_UNIT_MAP.get(lastUnit)));
  }
  List<String> sections=Lists.newArrayListWithCapacity(amounts.size());
  for (  TimeUnitAmount amount : amounts) {
    sections.add(format.format(amount));
  }
  return Joiner.on(' ').join(sections);
}
 

Example 19

From project ChessCraft, under directory /src/main/java/me/desht/chesscraft/chess/pieces/.

Source file: ChessSet.java

  19 
vote

/** 
 * Save this chess set to a file with the new name.
 * @param newName
 * @throws ChessException
 */
public void save(String newName) throws ChessException {
  File f=DirectoryStructure.getResourceFileForSave(DirectoryStructure.getPieceStyleDirectory(),ChessPersistence.makeSafeFileName(newName));
  YamlConfiguration conf=new YamlConfiguration();
  conf.options().header(Joiner.on("\n").join(CHESS_SET_HEADER_LINES));
  try {
    conf.set("name",name);
    conf.set("comment",comment);
    for (    char c : materialMapWhite.getMap().keySet()) {
      conf.set("materials.white." + c,materialMapWhite.get(c).toString());
    }
    for (    char c : materialMapBlack.getMap().keySet()) {
      conf.set("materials.black." + c,materialMapBlack.get(c).toString());
    }
    for (int piece=Chess.MIN_PIECE + 1; piece <= Chess.MAX_PIECE; piece++) {
      conf.set("pieces." + Chess.pieceToChar(piece),templates[piece].getPieceData());
    }
    conf.save(f);
    LogUtils.fine("saved chess set '" + name + "' to "+ f);
  }
 catch (  IOException e) {
    throw new ChessException(e.getMessage());
  }
}
 

Example 20

From project Citizens, under directory /src/core/net/citizensnpcs/.

Source file: Citizens.java

  19 
vote

private void loadNPCTypes(){
  File dir=new File(getDataFolder(),"types");
  dir.mkdirs();
  for (  String f : dir.list()) {
    if (f.contains(".jar")) {
      CitizensNPCType type=CitizensNPCLoader.loadNPCType(new File(dir,f),this);
      if (type != null) {
        loadedTypes.add(type.getName());
        Bukkit.getPluginManager().callEvent(new CitizensEnableTypeEvent(type));
      }
    }
  }
  if (loadedTypes.size() > 0) {
    Messaging.log("NPC types loaded: " + Joiner.on(", ").join(loadedTypes));
  }
 else {
    Messaging.log("No NPC types loaded.");
  }
}
 

Example 21

From project closure-templates, under directory /java/src/com/google/template/soy/javasrc/internal/.

Source file: TranslateToJavaExprVisitor.java

  19 
vote

/** 
 * Private helper for visitDataRefNode(DataRefNode).
 * @param node -
 * @param startIndex -
 */
private String buildKeyStringExprText(DataRefNode node,int startIndex){
  List<String> keyStrParts=Lists.newArrayList();
  StringBuilder currStringLiteralPart=new StringBuilder();
  for (int i=startIndex; i < node.numChildren(); i++) {
    ExprNode child=node.getChild(i);
    if (i != startIndex) {
      currStringLiteralPart.append(".");
    }
    if (child instanceof DataRefKeyNode) {
      currStringLiteralPart.append(CharEscapers.javaStringEscaper().escape(((DataRefKeyNode)child).getKey()));
    }
 else     if (child instanceof DataRefIndexNode) {
      currStringLiteralPart.append(Integer.toString(((DataRefIndexNode)child).getIndex()));
    }
 else {
      JavaExpr childJavaExpr=visit(child);
      keyStrParts.add("\"" + currStringLiteralPart.toString() + "\"");
      keyStrParts.add(genMaybeProtect(childJavaExpr,Integer.MAX_VALUE) + ".toString()");
      currStringLiteralPart=new StringBuilder();
    }
  }
  if (currStringLiteralPart.length() > 0) {
    keyStrParts.add("\"" + currStringLiteralPart.toString() + "\"");
  }
  return Joiner.on(" + ").join(keyStrParts);
}
 

Example 22

From project Cloud9, under directory /src/dist/edu/umd/cloud9/collection/clue/.

Source file: ClueWarcDocnoMappingBuilder.java

  19 
vote

/** 
 * Runs this tool.
 */
public int run(String[] args) throws IOException {
  DocnoMapping.DefaultBuilderOptions options=DocnoMapping.BuilderUtils.parseDefaultOptions(args);
  if (options == null) {
    return -1;
  }
  LOG.info("Tool name: " + ClueWarcDocnoMappingBuilder.class.getCanonicalName());
  LOG.info(" - input path: " + options.collection);
  LOG.info(" - output file: " + options.docnoMapping);
  FileSystem fs=FileSystem.get(getConf());
  FSDataOutputStream out=fs.create(new Path(options.docnoMapping),true);
  final InputStream in=ClueWarcDocnoMapping.class.getResourceAsStream("docno.mapping");
  List<String> lines=CharStreams.readLines(CharStreams.newReaderSupplier(new InputSupplier<InputStream>(){
    @Override public InputStream getInput() throws IOException {
      return in;
    }
  }
,Charsets.UTF_8));
  out.write((Joiner.on("\n").join(lines) + "\n").getBytes());
  out.close();
  return 0;
}
 

Example 23

From project clutter, under directory /src/clutter/hypertoolkit/html/.

Source file: Tag.java

  19 
vote

public void render(PrintWriter printWriter) throws IOException {
  if (cssClasses.size() > 0) {
    Collection<String> names=Collections2.transform(cssClasses,new Function<CssClass,String>(){
      @Override public String apply(      CssClass cssClass){
        return cssClass.name();
      }
    }
);
    String display=Joiner.on(" ").join(names);
    attr(Html.attr("class",display));
  }
  if (id != null) {
    attr(Html.attr("id",id));
  }
  printWriter.print("<" + name);
  for (  Attribute attribute : attributes) {
    printWriter.print(" " + attribute.getName() + "=\""+ attribute.getValue()+ "\"");
  }
  if (children.size() > 0) {
    printWriter.print(">");
    for (    Renderable child : children) {
      child.render(printWriter);
    }
    printWriter.print("</" + name + ">");
  }
 else {
    printWriter.print(" />");
  }
}
 

Example 24

From project cogroo4, under directory /cogroo-ann/src/main/java/org/cogroo/text/tree/.

Source file: Leaf.java

  19 
vote

private String createTag(){
  boolean hasLemma=getLemma() != null && getLemma().length > 0;
  boolean hasFeats=getFeatureTag() != null && !getFeatureTag().equals("-");
  if (getLexeme().equals(getMorphologicalTag())) {
    return "PUNCT";
  }
  StringBuilder sb=new StringBuilder(getMorphologicalTag().replace("-",""));
  if (hasLemma || hasFeats) {
    sb.append("-");
    if (hasFeats) {
      sb.append(getFeatureTag());
    }
 else {
      sb.append("*");
    }
    if (hasLemma) {
      sb.append("-");
      sb.append(Joiner.on('|').join(getLemma()));
    }
  }
  return sb.toString();
}
 

Example 25

From project crunch, under directory /crunch/src/main/java/org/apache/crunch/lib/.

Source file: Sort.java

  19 
vote

public static void configureOrdering(Configuration conf,Order... orders){
  conf.set(CRUNCH_ORDERING_PROPERTY,Joiner.on(",").join(Iterables.transform(Arrays.asList(orders),new Function<Order,String>(){
    @Override public String apply(    Order o){
      return o.name();
    }
  }
)));
}
 

Example 26

From project daleq, under directory /integration/src/test/java/de/brands4friends/daleq/integration/tests/.

Source file: FieldTypeTest.java

  19 
vote

private void assertInsertValueInAllFields(final long value){
  final List<String> errors=Lists.newArrayList();
  for (  FieldType fieldType : tableType.getFields()) {
    final String templatized=templatizeValue(fieldType,value);
    final Table table=aTable(tableProvider.allTypesTable()).with(aRow(1L).f(fieldType.getOrigin(),templatized));
    try {
      daleq.insertIntoDatabase(table);
    }
 catch (    DaleqException e) {
      final String name=fieldType.getName();
      final String msg="Could not insert " + name + " with templatized value "+ templatized+ " (derived from "+ value+ "), because "+ e.getMessage();
      errors.add(msg);
    }
  }
  if (!errors.isEmpty()) {
    Assert.fail("Could not insert due to the following reasons:\n" + Joiner.on("\n").join(errors));
  }
}
 

Example 27

From project dev-examples, under directory /iteration-demo/src/main/java/org/richfaces/demo/model/tree/adaptors/.

Source file: Entry.java

  19 
vote

public String getPath(){
  List<Entry> entries=Lists.newLinkedList();
  Entry entry=this;
  while (entry != null) {
    entries.add(0,entry);
    entry=entry.getParent();
  }
  return Joiner.on(" -> ").join(entries);
}
 

Example 28

From project eclipse-task-editor, under directory /plugins/de.sebastianbenz.task/src/de/sebastianbenz/task/query/.

Source file: QueryInterpreter.java

  19 
vote

private String valueOf(Expression value,Task task){
  if (value instanceof TagReference) {
    for (    Tag tag : task.getTags()) {
      TagReference tagReference=(TagReference)value;
      if (tag.getName().equals(tagReference.getValue())) {
        return tag.getValue();
      }
    }
    return "";
  }
 else   if (value instanceof Value) {
    return ((Value)value).getValue();
  }
 else   if (value instanceof Words) {
    Words words=(Words)value;
    return Joiner.on(" ").join(words.getValues());
  }
 else {
    return "";
  }
}
 

Example 29

From project elephant-twin, under directory /com.twitter.elephanttwin/src/main/java/com/twitter/elephanttwin/retrieval/.

Source file: ScanUsingIndexJob.java

  19 
vote

@Override public int run(String[] args) throws Exception {
  params=new IndexConfig();
  LOG.info(" - input: " + Joiner.on(" ").join(params.getInput()));
  LOG.info(" - output: " + IndexConfig.output.get());
  Configuration conf=getConf();
  Path outputDir=new Path(params.getOutput());
  FileSystem fs=outputDir.getFileSystem(conf);
  fs.delete(outputDir,true);
  int totalInputFiles=0;
  List<FileStatus> stats=Lists.newArrayList();
  for (  String s : params.getInput()) {
    Path spath=new Path(IndexConfig.index.get() + s);
    HdfsUtils.addInputPathRecursively(stats,fs,spath,hiddenDirectoryFilter,indexDataFilter);
  }
  totalInputFiles=stats.size();
  LOG.info(totalInputFiles + " total index files to be scanned");
  conf.set(IndexScanMapper.searchColumnName,params.getColumnName());
  Job job=new Job(new Configuration(conf));
  job.setJarByClass(getClass());
  job.setInputFormatClass(SequenceFileInputFormat.class);
  job.setOutputFormatClass(TextOutputFormat.class);
  TextOutputFormat.setOutputPath(job,new Path(params.getOutput()));
  for (  FileStatus file : stats)   FileInputFormat.addInputPath(job,file.getPath());
  job.setMapOutputKeyClass(Text.class);
  job.setMapOutputValueClass(LongWritable.class);
  job.setOutputKeyClass(Text.class);
  job.setOutputValueClass(LongWritable.class);
  job.setNumReduceTasks(1);
  job.setMapperClass(IndexScanMapper.class);
  job.setCombinerClass(LongSumReducer.class);
  job.setReducerClass(LongSumReducer.class);
  job.setJobName("ScanUsingIndexJob:" + IndexConfig.input.get());
  BlockIndexedFileInputFormat.setSearchOptions(job,params.getinputFormat(),params.getValueClass(),params.getIndex(),(String)null);
  job.waitForCompletion(true);
  return 0;
}
 

Example 30

From project Empire, under directory /core/src/com/clarkparsia/empire/util/apt/.

Source file: EmpireAnnotationProcessorFactory.java

  19 
vote

private SimpleAnnotationProcessor(final AnnotationProcessorEnvironment theEnv){
  mEnv=theEnv;
  mEnv.addListener(new RoundCompleteListener(){
    public void roundComplete(    final RoundCompleteEvent theEvent){
      Properties aProps=new Properties();
      for (      String aClass : mAnnotationClassMap.keySet()) {
        aProps.setProperty(aClass,Joiner.on(",").join(mAnnotationClassMap.get(aClass)));
      }
      OutputStream aStream=null;
      try {
        aStream=new FileOutputStream(new File("empire.apt.config"));
        aProps.store(aStream,"Empire Config generated by APT");
      }
 catch (      IOException e) {
        System.err.println("There was a failure generating Empire config using APT");
        e.printStackTrace();
      }
 finally {
        if (aStream != null) {
          try {
            aStream.flush();
            aStream.close();
          }
 catch (          IOException e) {
          }
        }
      }
    }
  }
);
}
 

Example 31

From project event-collector, under directory /event-collector/src/main/java/com/proofpoint/event/collector/.

Source file: EventResource.java

  19 
vote

@POST @Consumes(MediaType.APPLICATION_JSON) public Response post(List<Event> events) throws IOException {
  Set<String> badEvents=Sets.newHashSet();
  for (  Event event : events) {
    if (acceptedEventType(event.getType())) {
      for (      EventWriter writer : writers) {
        writer.write(event);
      }
    }
 else {
      badEvents.add(event.getType());
    }
  }
  if (!badEvents.isEmpty()) {
    String errorMessage="Invalid event type(s): " + Joiner.on(", ").join(badEvents);
    return Response.status(Status.BAD_REQUEST).entity(errorMessage).build();
  }
  return Response.status(Response.Status.ACCEPTED).build();
}
 

Example 32

From project FML, under directory /bukkit/cpw/mods/fml/server/.

Source file: FMLBukkitProfiler.java

  19 
vote

public void end(){
  int timing=(int)((System.nanoTime() - timestamp) / 1000L);
  String label=Joiner.on('.').join(profiles);
  profiles.pop();
  hitCounter.add(label);
  timings.add(label,timing);
  if (System.currentTimeMillis() > endTime) {
    endProfiling();
  }
}
 

Example 33

From project gag, under directory /gag-agent/src/main/java/com/github/stokito/gag/instrument/info/.

Source file: ClassInfo.java

  19 
vote

public String toFormattedString(){
  List<String> lines=Lists.newArrayList();
  lines.add(this.toString());
  for (  FieldInfo field : fields) {
    lines.add("  " + field);
    formatAnnos(lines,"    ",field.getAnnos());
  }
  for (  MethodInfo method : methods.values()) {
    lines.add("  " + method);
    formatAnnos(lines,"    ",method.getAnnos());
    for (    LocalVarInfo localVar : method.getLocalVars()) {
      lines.add("    Local Var " + localVar);
      formatAnnos(lines,"      ",localVar.getAnnos());
    }
  }
  return Joiner.on("\n").join(lines);
}
 

Example 34

From project greplin-lucene-utils, under directory /src/main/java/com/greplin/lucene/query/.

Source file: PhrasePrefixQuery.java

  19 
vote

@Override public final String toString(final String field){
  StringBuilder buffer=new StringBuilder();
  if (!this.field.equals(field)) {
    buffer.append(this.field);
    buffer.append(":");
  }
  buffer.append('"');
  buffer.append(Joiner.on(' ').join(terms));
  buffer.append("*\"");
  buffer.append(ToStringUtils.boost(getBoost()));
  return buffer.toString();
}
 

Example 35

From project guice-jit-providers, under directory /extensions/grapher/src/com/google/inject/grapher/graphviz/.

Source file: GraphvizGrapher.java

  19 
vote

/** 
 * Creates the "label" for a node. This is a string of HTML that defines a table with a heading at the top and (in the case of {@link ImplementationNode}s) rows for each of the member fields.
 */
protected String getNodeLabel(GraphvizNode node){
  String cellborder=node.getStyle() == NodeStyle.INVISIBLE ? "1" : "0";
  StringBuilder html=new StringBuilder();
  html.append("<");
  html.append("<table cellspacing=\"0\" cellpadding=\"5\" cellborder=\"");
  html.append(cellborder).append("\" border=\"0\">");
  html.append("<tr>").append("<td align=\"left\" port=\"header\" ");
  html.append("bgcolor=\"" + node.getHeaderBackgroundColor() + "\">");
  String subtitle=Joiner.on("<br align=\"left\"/>").join(node.getSubtitles());
  if (subtitle.length() != 0) {
    html.append("<font color=\"").append(node.getHeaderTextColor());
    html.append("\" point-size=\"10\">");
    html.append(subtitle).append("<br align=\"left\"/>").append("</font>");
  }
  html.append("<font color=\"" + node.getHeaderTextColor() + "\">");
  html.append(htmlEscape(node.getTitle())).append("<br align=\"left\"/>");
  html.append("</font>").append("</td>").append("</tr>");
  for (  Map.Entry<String,String> field : node.getFields().entrySet()) {
    html.append("<tr>");
    html.append("<td align=\"left\" port=\"").append(htmlEscape(field.getKey())).append("\">");
    html.append(htmlEscape(field.getValue()));
    html.append("</td>").append("</tr>");
  }
  html.append("</table>");
  html.append(">");
  return html.toString();
}
 

Example 36

From project gxa, under directory /annotator/src/main/java/uk/ac/ebi/gxa/annotator/annotationsrc/.

Source file: AnnotationSourceProperties.java

  19 
vote

public void addListPropertiesWithPrefix(String propNamePrefix,Multimap<String,String> atlasNameToBioMartNames){
  for (  String beProp : atlasNameToBioMartNames.keySet()) {
    Collection<String> bmNames=atlasNameToBioMartNames.get(beProp);
    properties.addProperty(propNamePrefix + "." + beProp,Joiner.on(',').join(bmNames));
  }
}
 

Example 37

From project hdfs-nfs-proxy, under directory /src/main/java/com/cloudera/hadoop/hdfs/nfs/nfs4/state/.

Source file: HDFSState.java

  19 
vote

public File getTemporaryFile(String identifer,String name) throws IOException {
  int hashCode=name.hashCode() & Integer.MAX_VALUE;
  int fileIndex=hashCode % mTempDirs.length;
  File base=mTempDirs[fileIndex];
  int bucketIndex=hashCode % 512;
  File dir=new File(base,Joiner.on(File.separator).join(identifer,bucketIndex));
  if (!dir.isDirectory()) {
    if (!(dir.mkdirs() || dir.isDirectory())) {
      throw new IOException("Unable to create " + dir);
    }
  }
  return new File(dir,name);
}
 

Example 38

From project hive-serde_1, under directory /src/test/java/fm/last/commons/hive/serde/.

Source file: TableDefinitionTest.java

  19 
vote

@Test public void typical(){
  table.setProperty("columns",Joiner.on(',').join(COLUMN_NAMES));
  table.setProperty("columns.types",Joiner.on(',').join(COLUMN_TYPES));
  tableDefinition=new TableDefinition(table,TestField.Factory.INSTANCE);
  Set<Integer> columnIdsForField=tableDefinition.getColumnIdsForField(TestField.RECORD_ID);
  assertEquals(1,columnIdsForField.size());
  assertTrue(columnIdsForField.contains(0));
  columnIdsForField=tableDefinition.getColumnIdsForField(TestField.USER_ID);
  assertEquals(1,columnIdsForField.size());
  assertTrue(columnIdsForField.contains(1));
  columnIdsForField=tableDefinition.getColumnIdsForField(TestField.UNIX_TIME);
  assertEquals(1,columnIdsForField.size());
  assertTrue(columnIdsForField.contains(2));
  columnIdsForField=tableDefinition.getColumnIdsForField(TestField.VALUE_1);
  assertEquals(1,columnIdsForField.size());
  assertTrue(columnIdsForField.contains(3));
  columnIdsForField=tableDefinition.getColumnIdsForField(TestField.VALUE_2);
  assertEquals(1,columnIdsForField.size());
  assertTrue(columnIdsForField.contains(4));
  columnIdsForField=tableDefinition.getColumnIdsForField(TestField.VALUE_3);
  assertEquals(1,columnIdsForField.size());
  assertTrue(columnIdsForField.contains(5));
  columnIdsForField=tableDefinition.getColumnIdsForField(TestField.VALUE_4);
  assertEquals(1,columnIdsForField.size());
  assertTrue(columnIdsForField.contains(6));
  columnIdsForField=tableDefinition.getColumnIdsForField(TestField.VALUE_5);
  assertEquals(1,columnIdsForField.size());
  assertTrue(columnIdsForField.contains(7));
}
 

Example 39

From project httpcache4j, under directory /httpcache4j-api/src/main/java/org/codehaus/httpcache4j/.

Source file: AuthDirective.java

  19 
vote

@Override public String toString(){
  String output=name;
  if (value != null && !value.isEmpty()) {
    output+=" " + value;
  }
  if (!getParameters().isEmpty()) {
    output=output + " " + Joiner.on(", ").join(getParameters());
  }
  return output;
}
 

Example 40

From project iPage, under directory /src/test/java/com/github/zhongl/util/.

Source file: FileTestContext.java

  19 
vote

protected File testDir(String name) throws IOException {
  File file=new File(BASE_ROOT,Joiner.on('.').join(getClass().getSimpleName(),name));
  if (file.exists())   delete(file);
  file.mkdirs();
  return file;
}
 

Example 41

From project Ivory_1, under directory /src/java/integration/ivory/integration/.

Source file: VerifyClueNonPositionalIndexIP.java

  19 
vote

@Test public void runBuildIndex() throws Exception {
  Configuration conf=IntegrationUtils.getBespinConfiguration();
  FileSystem fs=FileSystem.get(conf);
  assertTrue(fs.exists(collectionPath));
  fs.delete(new Path(index),true);
  List<String> jars=Lists.newArrayList();
  jars.add(IntegrationUtils.getJar("lib","cloud9"));
  jars.add(IntegrationUtils.getJar("lib","guava"));
  jars.add(IntegrationUtils.getJar("lib","dsiutils"));
  jars.add(IntegrationUtils.getJar("lib","fastutil"));
  jars.add(IntegrationUtils.getJar("lib","jsap"));
  jars.add(IntegrationUtils.getJar("lib","sux4j"));
  jars.add(IntegrationUtils.getJar("lib","commons-collections"));
  jars.add(IntegrationUtils.getJar("dist","ivory"));
  String libjars=String.format("-libjars=%s",Joiner.on(",").join(jars));
  PreprocessClueWebEnglish.main(new String[]{libjars,IntegrationUtils.D_JT,IntegrationUtils.D_NN,collectionPath.toString(),index,"1"});
  BuildNonPositionalIndexIP.main(new String[]{libjars,IntegrationUtils.D_JT,IntegrationUtils.D_NN,index,"200"});
  fs.copyFromLocalFile(false,true,new Path("data/clue/run.web09catB.nonpositional.baselines.xml"),new Path(index + "/run.web09catB.nonpositional.baselines.xml"));
  fs.copyFromLocalFile(false,true,new Path("data/clue/queries.web09.xml"),new Path(index + "/queries.web09.xml"));
  String[] params=new String[]{index + "/run.web09catB.nonpositional.baselines.xml",index + "/queries.web09.xml"};
  BatchQueryRunner qr=new BatchQueryRunner(params,fs,index);
  long start=System.currentTimeMillis();
  qr.runQueries();
  long end=System.currentTimeMillis();
  LOG.info("Total query time: " + (end - start) + "ms");
  Web09catB_All.verifyAllResults(qr.getModels(),qr.getAllResults(),qr.getDocnoMapping(),new Qrels("data/clue/qrels.web09catB.txt"));
  LOG.info("Done!");
}
 

Example 42

From project jagger, under directory /chassis/core/src/main/java/com/griddynamics/jagger/storage/.

Source file: Namespace.java

  19 
vote

@Override public String toString(){
  if (values.isEmpty()) {
    return SEPARATOR;
  }
  return Joiner.on(SEPARATOR).join(values);
}
 

Example 43

From project janbanery, under directory /janbanery-core/src/main/java/pl/project13/janbanery/encoders/utils/.

Source file: FieldNameToArrayNotationWithValueFunction.java

  19 
vote

@VisibleForTesting String camelCaseToUnderscore(String fieldName){
  List<Character> chars=newArrayList(asList(fieldName.toCharArray()));
  for (int i=0; i < chars.size(); i++) {
    Character aChar=chars.get(i);
    if (Character.isUpperCase(aChar)) {
      chars.remove(i);
      chars.add(i,Character.toLowerCase(aChar));
      chars.add(i,'_');
    }
  }
  return Joiner.on("").join(chars);
}
 

Example 44

From project jclouds-bean-cleaner, under directory /src/main/java/org/jclouds/cleanup/.

Source file: DomainObjectDocletCleaner.java

  19 
vote

/** 
 * Bootstrapping javadoc application to save users having to remember all the arguments.
 * @param args the path to locate the source code and the path to the compiled classes
 * @throws IOException          if there are problems traversing the source code hierarchy
 * @throws InterruptedException if the spawned javadoc process is interrupted
 */
public static void main(String[] args) throws IOException, InterruptedException {
  checkArgument(args.length > 1,"You need to supply a sourcePath and a classPath");
  String sourcePath=args[args.length - 2];
  String classPath=args[args.length - 1];
  List<String> command=Lists.newArrayList("javadoc","-classpath",System.getProperty("java.class.path") + ":" + classPath,"-docletpath",System.getProperty("java.class.path"),"-private","-doclet",DomainObjectDocletCleaner.class.getCanonicalName());
  if (args.length > 2) {
    Collections.addAll(command,Arrays.copyOfRange(args,0,args.length - 2));
  }
  command.addAll(listFileNames(new File(sourcePath)));
  Process process=Runtime.getRuntime().exec(command.toArray(new String[command.size()]));
  StreamGobbler in=new StreamGobbler(process.getInputStream(),"INFO");
  StreamGobbler err=new StreamGobbler(process.getErrorStream(),"ERROR");
  in.start();
  err.start();
  int returnCode=process.waitFor();
  if (returnCode == 0) {
    LOG.info("Javadoc returned successfully");
    LOG.info("You passed the following arguments: " + Joiner.on(" ").join(args));
  }
 else {
    LOG.error("Javadoc returned error code " + returnCode);
    LOG.info("You passed the following arguments: " + Joiner.on(" ").join(args));
  }
}
 

Example 45

From project jclouds-chef, under directory /core/src/main/java/org/jclouds/ohai/functions/.

Source file: ByteArrayToMacAddress.java

  19 
vote

@Override public String apply(byte[] from){
  return Joiner.on(':').join(transform(partition(asList(from),1),new Function<List<Byte>,String>(){
    @Override public String apply(    List<Byte> from){
      return CryptoStreams.hex(toArray(from));
    }
  }
));
}
 

Example 46

From project jira-rest-java-client, under directory /atlassian-jira-rest-java-client/src/main/java/com/atlassian/jira/rest/client/internal/jersey/.

Source file: JerseyIssueRestClient.java

  19 
vote

@Override public Issue getIssue(final String issueKey,Iterable<Expandos> expand,ProgressMonitor progressMonitor){
  final UriBuilder uriBuilder=UriBuilder.fromUri(baseUri);
  final Iterable<Expandos> expands=Iterables.concat(DEFAULT_EXPANDS,expand);
  uriBuilder.path("issue").path(issueKey).queryParam("expand",Joiner.on(',').join(Iterables.transform(expands,EXPANDO_TO_PARAM)));
  return getAndParse(uriBuilder.build(),issueParser,progressMonitor);
}
 

Example 47

From project JsTestDriver, under directory /idea-plugin/src/com/google/jstestdriver/idea/.

Source file: TestRunnerState.java

  19 
vote

private String buildClasspath(){
  Set<String> classpath=Sets.newHashSet();
  String pathToJstd=getJarPathForClass(JsTestDriverServer.class);
  boolean isRunningInIde=!pathToJstd.endsWith(".jar");
  if (isRunningInIde) {
    classpath.add(pathToJstd);
    String pathToLibJar=getJarPathForClass(Module.class);
    File[] libs=new File(pathToLibJar.substring(0,pathToLibJar.lastIndexOf(separatorChar))).listFiles();
    classpath.addAll(transform(asList(libs),getAbsolutePath));
  }
 else {
    File[] libs=new File(pathToJstd.substring(0,pathToJstd.lastIndexOf(separatorChar))).listFiles();
    classpath.addAll(transform(asList(libs),getAbsolutePath));
  }
  return Joiner.on(pathSeparator).join(classpath);
}
 

Example 48

From project junit-quickcheck, under directory /src/test/java/com/pholser/junit/quickcheck/reflect/.

Source file: TypeVariableImpl.java

  19 
vote

@Override public String toString(){
  StringBuilder buffer=new StringBuilder(getName());
  String boundDisplay=Joiner.on(" & ").join(getBounds());
  if (!boundDisplay.isEmpty())   buffer.append(" extends ").append(boundDisplay);
  return buffer.toString();
}
 

Example 49

From project kawala, under directory /kawala-testing/src/main/java/com/kaching/platform/testing/.

Source file: BadCodeSnippetsRunner.java

  19 
vote

private void checkBadCodeSnippet(Check check,String fileExtension) throws IOException {
  Map<Snippet,Set<File>> snippetsToUses=new MapMaker().makeComputingMap(new Function<Snippet,Set<File>>(){
    @Override public Set<File> apply(    Snippet key){
      return newHashSet();
    }
  }
);
  Map<Snippet,Pattern> compiledPatterns=new MapMaker().makeComputingMap(new Function<Snippet,Pattern>(){
    @Override public Pattern apply(    Snippet key){
      return Pattern.compile(key.value());
    }
  }
);
  Map<Snippet,Set<File>> snippetsToExceptions=snippetsToExceptions(check.snippets());
  Set<Snippet> snippets=snippetsToExceptions.keySet();
  for (  String path : check.paths()) {
    collectUses(fileExtension,new File(path),snippets,snippetsToUses,compiledPatterns);
  }
  CombinedAssertionFailedError error=new CombinedAssertionFailedError("bad code uses");
  for (  Snippet snippet : snippets) {
    Set<File> exceptions=snippetsToExceptions.get(snippet);
    Set<File> uses=snippetsToUses.get(snippet);
    List<File> spuriousExceptions=newArrayList(exceptions);
    spuriousExceptions.removeAll(uses);
    if (snippet.verificationMode().reportMissing && !spuriousExceptions.isEmpty()) {
      error.addError(format("%s: marked as exception to snippet but didn't occur:\n    %s",snippet.value(),Joiner.on("\n   ").join(spuriousExceptions)));
      continue;
    }
    uses.removeAll(exceptions);
    if (snippet.verificationMode().reportMatches && !uses.isEmpty()) {
      String rationale=snippet.rationale().isEmpty() ? "" : format("\nrationale: %s",snippet.rationale());
      error.addError(format("%s: found %s bad snippets in:\n    %s%s",snippet.value(),uses.size(),Joiner.on("\n   ").join(uses),rationale));
    }
  }
  error.throwIfHasErrors();
}
 

Example 50

From project lucene-interval-fields, under directory /src/test/java/com/greplin/interval/.

Source file: BaseIntervalQueryTest.java

  19 
vote

protected void assertSearch(IndexSearcher searcher,Query query,Integer... expectedResults) throws IOException {
  Set<Integer> expected=ImmutableSet.copyOf(expectedResults);
  TopDocs docs=searcher.search(query,100);
  Set<Integer> actual=Sets.newHashSet();
  for (  ScoreDoc scoreDoc : docs.scoreDocs) {
    Document doc=searcher.doc(scoreDoc.doc);
    actual.add(Integer.valueOf(doc.get("id")));
  }
  Assert.assertEquals(query + " should match [" + Joiner.on(", ").join(expectedResults)+ "]",expected,actual);
}
 

Example 51

From project maven-git-commit-id-plugin, under directory /src/main/java/pl/project13/jgit/.

Source file: DescribeResult.java

  19 
vote

/** 
 * The format of a describe result is defined as: <pre> v1.0.4-14-g2414721-DEV ^    ^    ^       ^ |    |    |       |-- if a dirtyMarker was given, it will appear here if the repository is in "dirty" state |    |    |---------- the "g" prefixed commit id. The prefix is compatible with what git-describe would return - weird, but true. |    |--------------- the number of commits away from the found tag. So "2414721" is 14 commits ahead of "v1.0.4", in this example. |-------------------- the "nearest" tag, to the mentioned commit. </pre> <p/> Other outputs may look like: <pre> v1.0.4 -- if the repository is "on a tag" v1.0.4-DEV -- if the repository is "on a tag", but in "dirty" state 2414721 -- a plain commit id hash if not tags were defined (of determined "near" this commit). It does NOT include the "g" prefix, that is used in the "full" describe output format! </pre> <p/> For more details (on when what output will be returned etc), see <code>man git-describe</code>. In general, you can assume it's a "best effort" approach, to give you as much info about the repo state as possible.
 * @return the String representation of this Describe command
 */
@Override public String toString(){
  List<String> parts;
  if (abbrevZeroHidesCommitsPartOfDescribe()) {
    parts=newArrayList(tag(),dirtyMarker());
  }
 else {
    parts=newArrayList(tag(),commitsAwayFromTag(),prefixedCommitId(),dirtyMarker());
  }
  return Joiner.on("-").skipNulls().join(parts);
}
 

Example 52

From project mdk, under directory /apps/benchmark/src/main/java/uk/ac/ebi/apps/benchmark/.

Source file: ChemicalNameSearch.java

  19 
vote

@Override public void process(){
  loadNames();
  if (getCommandLine().getOptionValues("s").length > 1) {
    testMultiple();
    return;
  }
  final NameService<Identifier> service=(NameService<Identifier>)getNameService(get("service","none"));
  if (!service.startup()) {
    LOGGER.error("Unable to start service");
  }
  service.setMaxResults(100);
  Multimap<String,Identifier> results=ArrayListMultimap.create();
  long searchStart=System.currentTimeMillis();
  for (  String name : names) {
    Collection<? extends Identifier> hits=service.searchName(name,has("a"));
    results.putAll(name,hits);
    found+=hits.isEmpty() ? 0 : 1;
  }
  long searchEnd=System.currentTimeMillis();
  Long searchTime=(searchEnd - searchStart);
  Multimap<String,Set<String>> nameResults=ArrayListMultimap.create();
  System.out.println("Transforming for performance test");
  long resolveStart=System.currentTimeMillis();
  for (  Map.Entry<String,Identifier> e : results.entries()) {
    Identifier id=e.getValue();
    nameResults.put(e.getKey(),new HashSet<String>(service.getNames(id)));
  }
  long resolveEnd=System.currentTimeMillis();
  Long resolveTime=(resolveEnd - resolveStart);
  int trueFound=getRealScore(nameResults,new ChemicalFingerprintEncoder(),null);
  SummaryStatistics statistics=getHitIndices(nameResults,new ChemicalFingerprintEncoder());
  String[] row=new String[]{get("service","unknown"),searchTime.toString(),resolveTime.toString(),Integer.toString(found),Integer.toString(trueFound),Double.toString(statistics.getMax()),Double.toString(statistics.getMean()),Double.toString(statistics.getStandardDeviation())};
  System.out.println(Joiner.on("\t").join(row));
}
 

Example 53

From project metric, under directory /src/main/java/com/gnapse/metric/app/.

Source file: Main.java

  19 
vote

/** 
 * Runs the application's core functionality.
 * @param args the command line arguments
 * @throws SyntaxError if a syntax error occurs parsing unit definitions or conversion queries
 * @throws MetricException if a logical error occurs while interpreting and performing the unitconversion queries
 * @throws IOException if an I/O error occurs while trying to read the unit definition file orthe currency exchange rates
 */
private static void run(String[] args) throws SyntaxError, MetricException, IOException {
  final File universeFile=copyResource(UNIVERSE_FILE_NAME);
  final Universe universe=new Universe(universeFile);
  String queryStr=Joiner.on(" ").join(args);
  ConversionQuery query=universe.convert(queryStr);
  System.out.println(query.toStringResults());
}
 

Example 54

From project mylyn-mantis, under directory /com.itsolut.mantis.core/src/com/itsolut/mantis/core/.

Source file: MantisTaskDataMigrator.java

  19 
vote

private void refreshOldMonitors(TaskData taskData,IMantisClient mantisClient) throws MantisException {
  TaskAttribute attribute=taskData.getRoot().getAttribute(MantisAttributeMapper.Attribute.MONITORS.getKey());
  if (attribute == null)   return;
  if (attribute.getValue().isEmpty())   return;
  String oldValue=attribute.getMetaData().getValue(MantisAttributeMapper.TASK_ATTRIBUTE_ORIGINAL_MONITORS);
  List<String> monitorNames=userIdsToUserNames(mantisClient,new NullProgressMonitor(),MantisUtils.fromCsvString(oldValue));
  String originalValues=Joiner.on(',').join(monitorNames);
  attribute.getMetaData().putValue(MantisAttributeMapper.TASK_ATTRIBUTE_ORIGINAL_MONITORS,originalValues);
}
 

Example 55

From project narya, under directory /tools/src/main/java/com/threerings/presents/tools/cpp/.

Source file: GenCPPServiceTask.java

  19 
vote

@Override protected void generateMarshaller(File source,ServiceDescription sdesc) throws Exception {
  String name=sdesc.sname.replace("Service","Marshaller");
  String mpackage=sdesc.spackage.replace(".client",".data");
  List<String> namespaces=makeNamespaces(mpackage);
  Map<String,Object> ctx=Maps.newHashMap();
  ctx.put("name",name);
  ctx.put("javaName",mpackage + "." + name);
  ctx.put("namespaces",namespaces);
  ctx.put("namespace",Joiner.on("::").join(namespaces));
  ctx.put("methods",MethodDescriptor.from(sdesc.methods));
  ctx.put("listeners",sdesc.listeners);
  ctx.put("argbuilder",new CPPArgBuilder());
  Set<String> includes=Sets.newTreeSet();
  Set<String> implIncludes=Sets.newTreeSet();
  for (  ServiceMethod meth : sdesc.methods) {
    for (    Type type : meth.method.getGenericParameterTypes()) {
      CPPType cppType=new CPPType(type);
      if (cppType.primitive) {
        implIncludes.add("presents/box/Boxed" + cppType.interpreter + ".h");
      }
      while (cppType != null) {
        if (cppType.representationImport != null) {
          includes.add(cppType.representationImport);
        }
        cppType=cppType.dependent;
      }
    }
  }
  ctx.put("includes",implIncludes);
  writeTemplate(CPP_TMPL,makePath(_cpproot,namespaces,name,".cpp"),ctx);
  ctx.put("includes",includes);
  writeTemplate(HEADER_TMPL,makePath(_cpproot,namespaces,name,".h"),ctx);
  super.generateMarshaller(source,sdesc);
}
 

Example 56

From project nodebox, under directory /src/main/java/nodebox/node/.

Source file: Node.java

  19 
vote

public static String path(String parentPath,String nodeName){
  checkNotNull(parentPath);
  checkNotNull(nodeName);
  checkArgument(parentPath.startsWith("/"),"Only absolute paths are supported.");
  if (parentPath.equals("/")) {
    return "/" + nodeName;
  }
 else {
    return Joiner.on("/").join(parentPath,nodeName);
  }
}
 

Example 57

From project objectos-comuns-jdbc, under directory /src/main/java/br/com/objectos/comuns/relational/jdbc/.

Source file: Insert.java

  19 
vote

public String toUpdate(PrimaryKey primaryKey){
  Set<String> keys=values.keySet();
  Iterable<String> escapedCols=Iterables.transform(keys,new ToUpdate());
  String columns=Joiner.on(", ").join(escapedCols);
  String keyColumn=primaryKey.getColumn();
  Object val=primaryKey.getValue();
  addValue(keyColumn,ParamValue.valueOf(next(),val));
  return String.format("update %s set %s where `%s`=?",table,columns,primaryKey.getColumn());
}
 

Example 58

From project objectos-comuns-sitebricks, under directory /src/main/java/br/com/objectos/comuns/sitebricks/form/.

Source file: QueryString.java

  19 
vote

@Override public String toString(){
  Set<Entry<String,String>> entries=params.entrySet();
  Iterable<String> parts=Iterables.transform(entries,new ToPart());
  String postUrl=Joiner.on("&").join(parts);
  return String.format("%s?%s",url,postUrl);
}
 

Example 59

From project openengsb-framework, under directory /components/ekb/graphdb-orient/src/main/java/org/openengsb/core/ekb/graph/orient/internal/.

Source file: OrientModelGraphUtils.java

  19 
vote

/** 
 * Converts a complex property connection map (key:String, value:Set of Strings) to a simple property connection map, so that the connections can easily be saved to the edges in the model graph.
 */
public static Map<String,String> convertPropertyConnectionsToSimpleForm(Map<String,Set<String>> connections){
  Map<String,String> result=new HashMap<String,String>();
  if (connections == null) {
    return result;
  }
  for (  Map.Entry<String,Set<String>> entry : connections.entrySet()) {
    result.put(entry.getKey(),Joiner.on(',').join(entry.getValue()));
  }
  return result;
}
 

Example 60

From project OpenID-Connect-Java-Spring-Server, under directory /openid-connect-server/src/main/java/org/mitre/openid/connect/web/.

Source file: ClientDynamicRegistrationEndpoint.java

  19 
vote

/** 
 * Bind a space-separated string to a Set<String>
 * @param binder
 */
@InitBinder({"contacts","redirect_uris"}) public void stringSetInitbinder(WebDataBinder binder){
  binder.registerCustomEditor(Set.class,new PropertyEditorSupport(){
    @Override public void setAsText(    String text) throws IllegalArgumentException {
      if (Strings.isNullOrEmpty(text)) {
        setValue(null);
      }
 else {
        setValue(Sets.newHashSet(Splitter.on(" ").split(text)));
      }
    }
    @Override public String getAsText(){
      Set<String> set=(Set<String>)getValue();
      return set == null ? null : Joiner.on(" ").join(set);
    }
  }
);
}
 

Example 61

From project overthere, under directory /src/main/java/com/xebialabs/overthere/ssh/.

Source file: SshScpFile.java

  19 
vote

protected void mkdir(String... mkdirOptions) throws RuntimeIOException {
  CmdLine mkdirCmdLine=CmdLine.build(NOCD_PSEUDO_COMMAND,"mkdir");
  for (  String opt : mkdirOptions) {
    mkdirCmdLine.addArgument(opt);
  }
  mkdirCmdLine.addArgument(getPath());
  CapturingOverthereProcessOutputHandler capturedOutput=capturingHandler();
  int errno=executeCommand(multiHandler(loggingHandler(logger),capturedOutput),mkdirCmdLine);
  if (errno != 0) {
    throw new RuntimeIOException(format("Cannot create directory or -ies %s: %s (errno=%d)",this,capturedOutput.getError(),errno));
  }
  if (logger.isDebugEnabled()) {
    logger.debug("Created directory " + this + " (with options:"+ Joiner.on(' ').join(mkdirOptions));
  }
}
 

Example 62

From project Please, under directory /modules/acceptance-tests/src/test/java/com/atoito/please/uat/.

Source file: BaseUat.java

  19 
vote

@BeforeClass public void setUp() throws Exception {
  File cc=ClasspathUtil.getClasspathForClass(BasicFunctionalitySmokeUat.class);
  File modules=cc.getParentFile().getParentFile().getParentFile().getParentFile();
  String installPath=Joiner.on(File.separatorChar).join(modules.getAbsolutePath(),"cli","target","install","please");
  installedHome=new File(installPath);
  testDataPath=Joiner.on(File.separatorChar).join(modules.getAbsolutePath(),"acceptance-tests","src","test","data");
  Environment.refreshWithHome(installedHome);
  Environment environment=Environment.getCurrent();
  String installOpsDirPath=environment.distributionOpsFileDirPath();
  File installOpsDir=new File(installOpsDirPath);
  Directories.ensureExists(installOpsDir);
  String uatOpsDirectoryPath=Joiner.on(File.separatorChar).join(modules.getAbsolutePath(),"acceptance-tests","src","test","ops");
  File uatOpsDirectory=new File(uatOpsDirectoryPath);
  File[] uatOps=uatOpsDirectory.listFiles();
  for (int i=0; i < uatOps.length; i++) {
    copyOpsFile(uatOps[i],installOpsDir);
  }
}
 

Example 63

From project scoutdoc, under directory /main/src/scoutdoc/main/check/.

Source file: RedirectionChecker.java

  19 
vote

private static String getRedirectionsPath(List<Page> redirections){
  List<String> names=new ArrayList<String>();
  for (  Page page : redirections) {
    names.add("'" + PageUtility.toFullPageName(page) + "'");
  }
  return Joiner.on(" => ").join(names);
}
 

Example 64

From project see, under directory /src/main/java/see/tree/immutable/.

Source file: ImmutablePropertyNode.java

  19 
vote

@Override public String toString(){
  final StringBuilder sb=new StringBuilder();
  sb.append("Prop(");
  sb.append(target).append(Joiner.on("").join(properties));
  sb.append(')');
  return sb.toString();
}
 

Example 65

From project service-discovery, under directory /jms/src/main/java/com/nesscomputing/jms/activemq/.

Source file: ServiceDiscoveryTransportFactory.java

  19 
vote

/** 
 * From a list of ServiceInformation, build a failover transport that balances between the brokers.
 */
private Transport buildTransport(Map<String,String> params,final List<ServiceInformation> services) throws IOException {
  final String configPostfix=getConfig(params).getServiceConfigurationPostfix();
  final StringBuilder uriBuilder=new StringBuilder();
  uriBuilder.append("failover:(");
  uriBuilder.append(Joiner.on(',').join(Collections2.transform(services,SERVICE_TO_URI)));
  uriBuilder.append(")");
  if (!StringUtils.isBlank(configPostfix)) {
    uriBuilder.append("?");
    uriBuilder.append(configPostfix);
  }
  try {
    final URI uri=URI.create(uriBuilder.toString());
    LOG.debug("Service discovery transport discovered %s",uri);
    return interceptPropertySetters(TransportFactory.compositeConnect(uri));
  }
 catch (  final Exception e) {
    Throwables.propagateIfPossible(e,IOException.class);
    throw new IOException("Could not create failover transport",e);
  }
}
 

Example 66

From project sisu-guice, under directory /extensions/grapher/src/com/google/inject/grapher/graphviz/.

Source file: GraphvizGrapher.java

  19 
vote

/** 
 * Creates the "label" for a node. This is a string of HTML that defines a table with a heading at the top and (in the case of {@link ImplementationNode}s) rows for each of the member fields.
 */
protected String getNodeLabel(GraphvizNode node){
  String cellborder=node.getStyle() == NodeStyle.INVISIBLE ? "1" : "0";
  StringBuilder html=new StringBuilder();
  html.append("<");
  html.append("<table cellspacing=\"0\" cellpadding=\"5\" cellborder=\"");
  html.append(cellborder).append("\" border=\"0\">");
  html.append("<tr>").append("<td align=\"left\" port=\"header\" ");
  html.append("bgcolor=\"" + node.getHeaderBackgroundColor() + "\">");
  String subtitle=Joiner.on("<br align=\"left\"/>").join(node.getSubtitles());
  if (subtitle.length() != 0) {
    html.append("<font color=\"").append(node.getHeaderTextColor());
    html.append("\" point-size=\"10\">");
    html.append(subtitle).append("<br align=\"left\"/>").append("</font>");
  }
  html.append("<font color=\"" + node.getHeaderTextColor() + "\">");
  html.append(htmlEscape(node.getTitle())).append("<br align=\"left\"/>");
  html.append("</font>").append("</td>").append("</tr>");
  for (  Map.Entry<String,String> field : node.getFields().entrySet()) {
    html.append("<tr>");
    html.append("<td align=\"left\" port=\"").append(htmlEscape(field.getKey())).append("\">");
    html.append(htmlEscape(field.getValue()));
    html.append("</td>").append("</tr>");
  }
  html.append("</table>");
  html.append(">");
  return html.toString();
}
 

Example 67

From project social_1, under directory /services/facebook/src/main/java/org/jboss/seam/social/facebook/impl/.

Source file: GraphApiImpl.java

  19 
vote

@Override public <T>List<T> fetchConnections(String objectId,String connectionType,Class<T> type,String... fields){
  Map<String,String> queryParameters=newHashMap();
  if (fields.length > 0) {
    String joinedFields=Joiner.on(',').join(fields);
    queryParameters.put("fields",joinedFields);
  }
  return fetchConnections(objectId,connectionType,type,queryParameters);
}
 

Example 68

From project springside4, under directory /examples/showcase/src/main/java/org/springside/examples/showcase/demos/utilities/string/.

Source file: StringDemo.java

  19 
vote

/** 
 * Guava??????Joiner? Splitter??????Joiner??????????????
 */
@Test public void joinerByGuava(){
  String[] fantasyGenres={"Space Opera",null,"Horror","Magic realism",null,"Religion"};
  String joined=Joiner.on(", ").skipNulls().join(fantasyGenres);
  assertEquals("Space Opera, Horror, Magic realism, Religion",joined);
  String[] fantasyGenres2={"Space Opera",null,"Horror","Magic realism",null,"Religion"};
  joined=Joiner.on(", ").useForNull("NULL!!!").join(fantasyGenres2);
  assertEquals("Space Opera, NULL!!!, Horror, Magic realism, NULL!!!, Religion",joined);
  Map<Integer,String> map=Maps.newHashMap();
  map.put(1,"Space Opera");
  map.put(2,"Horror");
  map.put(3,"Magic realism");
  joined=Joiner.on(",").withKeyValueSeparator(":").join(map);
  assertEquals("1:Space Opera,2:Horror,3:Magic realism",joined);
  StringBuilder sb=new StringBuilder("Append StringBulder demo: ");
  joined=Joiner.on(", ").skipNulls().appendTo(sb,fantasyGenres).toString();
  assertEquals("Append StringBulder demo: Space Opera, Horror, Magic realism, Religion",joined);
}
 

Example 69

From project tb-diamond_1, under directory /diamond-server/src/test/java/com/taobao/diamond/server/controller/.

Source file: AdminControllerUnitTest.java

  19 
vote

private String generateBatchOpString(Map<String,String> dataId2ContentMap){
  List<String> dataIdAndContentList=new LinkedList<String>();
  for (  String dataId : dataId2ContentMap.keySet()) {
    String content=dataId2ContentMap.get(dataId);
    dataIdAndContentList.add(dataId + Constants.WORD_SEPARATOR + content);
  }
  String allDataIdAndContent=Joiner.on(Constants.LINE_SEPARATOR).join(dataIdAndContentList);
  return allDataIdAndContent;
}
 

Example 70

From project Terasology, under directory /src/main/java/org/terasology/logic/commands/.

Source file: Commands.java

  19 
vote

@Command(shortDescription="Adds a block to your inventory",helpText="Puts a desired number of the given block into your inventory") public void giveBlock(@CommandParam(name="blockId") String uri,@CommandParam(name="quantity") int quantity){
  List<BlockUri> matchingUris=resolveBlockUri(uri);
  if (matchingUris.size() == 1) {
    BlockFamily blockFamily=BlockManager.getInstance().getBlockFamily(matchingUris.get(0));
    giveBlock(blockFamily,quantity);
    return;
  }
 else   if (matchingUris.isEmpty()) {
    MessageManager.getInstance().addMessage("No block found for '" + uri + "'",EMessageScope.PRIVATE);
    return;
  }
 else {
    StringBuilder builder=new StringBuilder();
    builder.append("Non-unique block name, possible matches: ");
    Joiner.on(", ").appendTo(builder,matchingUris);
    MessageManager.getInstance().addMessage(builder.toString(),EMessageScope.PRIVATE);
    return;
  }
}