Java Code Examples for org.apache.commons.lang.StringUtils.join()

The following are Jave code examples for showing how to use join() of the org.apache.commons.lang.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: hadoop   File: WordListAnonymizerUtility.java   View Source Code Vote up 6 votes
/**
 * Extracts a known suffix from the given data.
 * 
 * @throws RuntimeException if the data doesn't have a suffix. 
 *         Use {@link #hasSuffix(String, String[])} to make sure that the 
 *         given data has a suffix.
 */
public static String[] extractSuffix(String data, String[] suffixes) {
  // check if they end in known suffixes
  String suffix = "";
  for (String ks : suffixes) {
    if (data.endsWith(ks)) {
      suffix = ks;
      // stripe off the suffix which will get appended later
      data = data.substring(0, data.length() - suffix.length());
      return new String[] {data, suffix};
    }
  }
  
  // throw exception
  throw new RuntimeException("Data [" + data + "] doesn't have a suffix from" 
      + " known suffixes [" + StringUtils.join(suffixes, ',') + "]");
}
 
Example 2
Project: BUbiNG   File: Filters.java   View Source Code Vote up 6 votes
/** Produces the conjunction of the given filters.
 *
 * @param <T> the type of objects that the filters deal with.
 * @param f the filters.
 * @return the conjunction.
 */
@SafeVarargs
public static<T> Filter<T> and(final Filter<T>... f) {
	return new Filter<T>() {
		@Override
		public boolean apply(final T x) {
			for (final Filter<T> filter: f) if (! filter.apply(x)) return false;
			return true;
		}

		@Override
		public String toString() {
			return "(" + StringUtils.join(f, " and ") + ")";
		}

		@Override
		public Filter<T> copy() {
			return Filters.and(Filters.copy(f));
		}
	};
}
 
Example 3
Project: distmq   File: MetadataManager.java   View Source Code Vote up 5 votes
public void subscribeBroker() {
    try {
        final String brokerParentPath = zkConf.getZKBasePath() + "/brokers";
        List<String> shardings = zkClient.getChildren().forPath(brokerParentPath);
        for (String sharding : shardings) {
            final int shardingId = Integer.valueOf(sharding);
            final String shardingPath = brokerParentPath + "/" + sharding;
            List<String> brokerAddressList = zkClient.getChildren().forPath(shardingPath);
            if ((isProducer || isConsumer) && CollectionUtils.isNotEmpty(brokerAddressList)) {
                BrokerClient brokerClient = new BrokerClient(brokerAddressList, rpcClientOptions);
                BrokerClient oldBrokerClient = metadata.getBrokerMap().putIfAbsent(shardingId, brokerClient);
                if (oldBrokerClient != null) {
                    oldBrokerClient.getRpcClient().stop();
                    String oldIpPorts = StringUtils.join(oldBrokerClient.getAddressList(), ",");
                    metadata.getBrokerMap().get(shardingId).getRpcClient().addEndPoints(oldIpPorts);
                }
            }

            // 监听broker分片变化
            zkClient.getChildren().usingWatcher(new BrokerShardingWather(shardingId)).forPath(shardingPath);
        }
        // 监听/brokers孩子节点变化
        zkClient.getChildren().usingWatcher(new BrokersWatcher()).forPath(brokerParentPath);
    } catch (Exception ex) {
        LOG.warn("subscribeBroker exception:", ex);
    }
}
 
Example 4
Project: cockroach   File: Task.java   View Source Code Vote up 5 votes
public String getUrl() {
    if (this.getParams().isEmpty()) {
        return url;
    } else {
        List<String> paramsList = this.getParams().entrySet().stream().map(entity -> String.format("%s=%s", entity.getKey(), entity.getValue())).collect(Collectors.toList());
        String param = StringUtils.join(paramsList.toArray(), "&");
        return String.format("%s?%s", url, param);
    }
}
 
Example 5
Project: Uranium   File: TileEntityCommand.java   View Source Code Vote up 5 votes
public TileEntityCommand()
{
    super("cauldron_te");
    this.description = "Toggle certain TileEntity options";

    this.usageMessage = "/cauldron_te [" + StringUtils.join(COMMANDS, '|') + "] <option> [value]";
    this.setPermission("cauldron.command.cauldron_te");
}
 
Example 6
Project: skip-assistant   File: SpotifyPollingService.java   View Source Code Vote up 5 votes
/**
 * determine if a song was skipped and if so, save it to the repository
 * @param prevSong
 * @param nextSong
 */
private void checkSkipped(CurrentlyPlayingTrack prevSong, CurrentlyPlayingTrack nextSong)
        throws WebApiException, IOException {

    // find which songs were skipped and save them to the repository
    if (spotifyHelperService.wasSkipped(prevSong, nextSong) &&
            spotifyHelperService.isValidPlaylistTrack(prevSong, user)) {

        String userId = user.getId();
        String songUri = prevSong.getItem().getUri();
        String songName = prevSong.getItem().getName();
        List<String> artistList = prevSong.getItem().getArtists().stream().map(x -> x.getName()).collect(Collectors.toList());
        String songArtistNames = songName + " - " + StringUtils.join(artistList, ", ");

        String playlistHref = prevSong.getContext().getHref();
        String playlistId = playlistHref.substring(playlistHref.lastIndexOf("/") + 1, playlistHref.length());
        String playlistName = api.getPlaylist(userId, playlistId).build().get().getName();

        String previewUrl = api.getTrack(songUri.split(":")[2]).build().get().getPreviewUrl();

        if (previewUrl.equals("null")) {
            previewUrl = null;
        }

        LOGGER.info("Skipped song detected! \n    "
                + userId + " skipped " + songName
                + "\n    in playlist " + playlistName);

        skippedTrackRepository.insertOrUpdateCount(1, playlistId, songUri, userId, songArtistNames, playlistName, previewUrl);
    }
}
 
Example 7
Project: BIMplatform   File: ColladaSerializer.java   View Source Code Vote up 5 votes
@SuppressWarnings("unused")
private String byteBufferToIntPointSpaceDelimitedString(ByteBuffer buffer) {
	// Prepare to store integers as a list of strings.
	List<String> stringScalars = intBufferToStringList(buffer, intFormat);
	// Send back a space-delimited list of the strings: 1 2 0
	return StringUtils.join(stringScalars, " ");
}
 
Example 8
Project: personium-core   File: UrlUtils.java   View Source Code Vote up 5 votes
/**
 * BOXアクセス.
 * @param cellName セル名
 * @param boxName ボックス名
 * @param pathInBox ボックス内パス
 * @return 認証エンドポイントURL
 */
public static String box(final String cellName, final String boxName, final String... pathInBox) {
    String path = "";
    if (pathInBox != null) {
        path = StringUtils.join(pathInBox, "/");
    }
    return String.format("%s/%s/%s/%s", baseUrl, cellName, boxName, path);
}
 
Example 9
Project: DBus   File: MysqlDefaultProcessor.java   View Source Code Vote up 5 votes
private void dataFilter(List<MessageEntry> msgEntryLst) {
// 过滤掉没有在系统中配置的表或者没有经过拉全量的表的数据
for(Iterator<MessageEntry> it = msgEntryLst.iterator(); it.hasNext(); ){
 EntryHeader header = it.next().getEntryHeader();
 String schemaName = header.getSchemaName();
 String tableName = header.getTableName();
 String key = StringUtils.join(new String[]{schemaName,tableName}, ".");
 if (ThreadLocalCache.get(Constants.CacheNames.DATA_TABLES, key) == null) {
	 it.remove();
           logger.info("The message of {} was filtered, the data table is not configured", tableName);
       }
}
 }
 
Example 10
Project: BIMplatform   File: ColladaSerializer.java   View Source Code Vote up 5 votes
@SuppressWarnings("unused")
private String doubleBufferToFloatingPointSpaceDelimitedString(DoubleBuffer buffer) {
	// For each scalar in the buffer, turn it into a string, adding it to the overall list.
	List<String> stringScalars = doubleBufferToStringList(buffer, decimalFormat);
	// Send back a space-delimited list of the strings: 1 2.45 0
	return StringUtils.join(stringScalars, " ");
}
 
Example 11
Project: Stats4   File: PlaytimeStat.java   View Source Code Vote up 4 votes
public String generateLocationString() {
    return StringUtils.join(new String[]{
            this.locWorld, Integer.toString(this.locX), Integer.toString(this.locY), Integer.toString(this.locZ),
            Float.toString(this.locYaw), Float.toString(this.locPitch)
    }, ',');
}
 
Example 12
Project: hadoop   File: AbstractCSQueue.java   View Source Code Vote up 4 votes
synchronized void setupQueueConfigs(Resource clusterResource)
    throws IOException {
  // get labels
  this.accessibleLabels =
      csContext.getConfiguration().getAccessibleNodeLabels(getQueuePath());
  this.defaultLabelExpression = csContext.getConfiguration()
      .getDefaultNodeLabelExpression(getQueuePath());

  // inherit from parent if labels not set
  if (this.accessibleLabels == null && parent != null) {
    this.accessibleLabels = parent.getAccessibleNodeLabels();
  }
  
  // inherit from parent if labels not set
  if (this.defaultLabelExpression == null && parent != null
      && this.accessibleLabels.containsAll(parent.getAccessibleNodeLabels())) {
    this.defaultLabelExpression = parent.getDefaultNodeLabelExpression();
  }

  // After we setup labels, we can setup capacities
  setupConfigurableCapacities();
  
  this.maximumAllocation =
      csContext.getConfiguration().getMaximumAllocationPerQueue(
          getQueuePath());
  
  authorizer = YarnAuthorizationProvider.getInstance(csContext.getConf());
  
  this.state = csContext.getConfiguration().getState(getQueuePath());
  this.acls = csContext.getConfiguration().getAcls(getQueuePath());

  // Update metrics
  CSQueueUtils.updateQueueStatistics(
      resourceCalculator, this, parent,
      labelManager.getResourceByLabel(RMNodeLabelsManager.NO_LABEL, clusterResource), minimumAllocation);
  
  // Check if labels of this queue is a subset of parent queue, only do this
  // when we not root
  if (parent != null && parent.getParent() != null) {
    if (parent.getAccessibleNodeLabels() != null
        && !parent.getAccessibleNodeLabels().contains(RMNodeLabelsManager.ANY)) {
      // if parent isn't "*", child shouldn't be "*" too
      if (this.getAccessibleNodeLabels().contains(RMNodeLabelsManager.ANY)) {
        throw new IOException("Parent's accessible queue is not ANY(*), "
            + "but child's accessible queue is *");
      } else {
        Set<String> diff =
            Sets.difference(this.getAccessibleNodeLabels(),
                parent.getAccessibleNodeLabels());
        if (!diff.isEmpty()) {
          throw new IOException("Some labels of child queue is not a subset "
              + "of parent queue, these labels=["
              + StringUtils.join(diff, ",") + "]");
        }
      }
    }
  }

  this.reservationsContinueLooking = csContext.getConfiguration()
      .getReservationContinueLook();

  this.preemptionDisabled = isQueueHierarchyPreemptionDisabled(this);
  this.cr = clusterResource;
}
 
Example 13
Project: atlas   File: ManifestHelper.java   View Source Code Vote up 4 votes
public static boolean checkManifest(AppVariantContext appVariantContext, File fullManifest,
                                    AtlasDependencyTree dependencyTree,
                                    AtlasExtension atlasExtension) throws DocumentException {

    Set<String> notMergedArtifacts = getNotMergedBundles(atlasExtension);

    BundleInfo mainBundleInfo = new BundleInfo();
    collectBundleInfo(appVariantContext, mainBundleInfo, fullManifest, null);

    List<String> errors = new ArrayList<>();
    for (AwbBundle awbBundle : dependencyTree.getAwbBundles()) {
        String cord = String.format("%s:%s",
                                    awbBundle.getResolvedCoordinates().getGroupId(),
                                    awbBundle.getResolvedCoordinates().getArtifactId());

        if (null != notMergedArtifacts && notMergedArtifacts.contains(cord)) {
            continue;
        }

        for (String activity : awbBundle.bundleInfo.getActivities()) {
            if (StringUtils.isNotEmpty(activity) && !mainBundleInfo.getActivities().contains(activity)) {
                errors.add("miss activity:" + activity);
            }
        }

        for (String service : awbBundle.bundleInfo.getServices()) {
            if (StringUtils.isNotEmpty(service) && !mainBundleInfo.getServices().contains(service)) {
                errors.add("miss service:" + service);
            }
        }

        if (!atlasExtension.getManifestOptions().isRemoveProvider()) {
            for (String provider : awbBundle.bundleInfo.getContentProviders()) {
                if (StringUtils.isNotEmpty(provider) && !mainBundleInfo.getContentProviders().contains(provider)) {
                    errors.add("miss provider:" + provider);
                }
            }
        }

        for (String receiver : awbBundle.bundleInfo.getReceivers()) {
            if (StringUtils.isNotEmpty(receiver) && !mainBundleInfo.getReceivers().contains(receiver)) {
                errors.add("miss receiver:" + receiver);
            }
        }

    }

    if (errors.isEmpty()) {
        return true;
    }

    for (String err : errors) {
        sLogger.error(err);
    }

    throw new GradleException("manifest merge error :" + StringUtils.join(errors, ","));
}
 
Example 14
Project: database-transform-tool   File: ManageTable.java   View Source Code Vote up 4 votes
/**
 * @decription 数据同步(MongoDB-->Greenplum)
 * @author yi.zhang
 * @time 2017年8月4日 下午5:26:59
 * @param source	数据源
 * @param target	目标库
 * @param mapper	表映射
 * @param filter_columns	字段过滤
 */
protected void mongodb2greenplum(Config source,Config target,Map<String,String> mapper,List<String> filter_columns){
	if(source==null||target==null){
		return;
	}
	MongoDBFactory factory = new MongoDBFactory();
	factory.init(source.getServers(), source.getDatabase(), source.getSchema(), source.getUsername(), source.getPassword());
	Map<String,String> mapping = new HashMap<String,String>();
	if(mapper==null||mapper.size()==0){
		List<String> tables = factory.queryTables();
		for (String table : tables) {
			mapping.put(table, table);
		}
	}else{
		mapping = mapper;
	}
	GreenplumFactory tfactory = new GreenplumFactory();
	tfactory.init(target.getServers(), target.getDatabase(), target.getSchema(), target.getUsername(), target.getPassword(), true, 100, 10);
	List<String> stables = factory.queryTables();
	List<String> ttables = tfactory.queryTables();
	for(String stable : mapping.keySet()){
		String ttable = mapping.get(stable);
		if(!(stables.contains(stable)&&ttables.contains(ttable))){
			System.out.println("--数据表["+stable+"]或目标表["+ttable+"]不存在--");
			continue;
		}
		Map<String,String> reflect = new LinkedHashMap<String,String>();
		Map<String, String> scolumns = factory.queryColumns(stable);
		Map<String, String> tcolumns = tfactory.queryColumns(ttable);
		if(scolumns==null||scolumns.isEmpty()||tcolumns==null||tcolumns.isEmpty()){
			System.out.println("--数据表["+stable+"]或目标表["+ttable+"]无合适字段--");
			continue;
		}
		for(String scolumn:scolumns.keySet()){
			String s_column = scolumn.trim().toLowerCase().replaceAll("(_+?|-+?)", "");
			if(filter_columns!=null&&(filter_columns.contains(scolumn)||filter_columns.contains(s_column))){
				continue;
			}
			for(String tcolumn:tcolumns.keySet()){
				String t_column = tcolumn.trim().toLowerCase().replaceAll("(_+?|-+?)", "");
				if(filter_columns!=null&&(filter_columns.contains(tcolumn)||filter_columns.contains(t_column))){
					continue;
				}
				if(scolumn.equalsIgnoreCase(tcolumn)||scolumn.equalsIgnoreCase(t_column)||s_column.equalsIgnoreCase(tcolumn)||s_column.equalsIgnoreCase(t_column)){
					reflect.put(scolumn, tcolumn);
				}
			}
		}
		if(reflect.isEmpty()){
			System.out.println("--数据表["+stable+"]或目标表["+ttable+"]无对应字段--");
			continue;
		}
		List<?> datas = factory.executeQuery(stable, null, null);
		System.out.println("--数据表["+stable+"]数据量:"+datas.size());
		for (Object data : datas) {
			Map<String,Object> tdata = new LinkedHashMap<String,Object>();
			JSONObject json = (JSONObject)data;
			for(String key:json.keySet()){
				Object value = json.get(key);
				if(value instanceof Date){
					value = DateUtil.formatDateTimeStr((Date)value);
				}
				if(value instanceof String){
					value = "\""+json.getString(key)+"\"";
				}
				tdata.replace(reflect.get(key), value);
			}
			String sql = "insert into "+ttable+"("+StringUtils.join(tdata.keySet(), ",")+")values("+StringUtils.join(tdata.values(), ",")+")";
			tfactory.executeUpdate(sql);
		}
	}
}
 
Example 15
Project: kaltura-ce-sakai-extension   File: KalturaAPIServiceStub.java   View Source Code Vote up 4 votes
@Override
protected boolean removeItemFromKalturaPlaylist(KalturaPlaylist playlist, String kalturaId) {
    if (playlist == null) {
        throw new IllegalArgumentException("playlist is not set");
    }
    if (StringUtils.isEmpty(kalturaId)) {
        throw new IllegalArgumentException("kaltura entry id is not set");
    }
    boolean removed = false;
    if (playlist.playlistContent != null) {
        // must create a mutable ArrayList in order to remove item here
        List<String> entries = new ArrayList<String>(Arrays.asList(StringUtils.splitByWholeSeparator(playlist.playlistContent, ",")));
        boolean changed = entries.remove(kalturaId);
        if (changed) {
            MediaCollection mc = null;
            if (entries.isEmpty()) {
                entries.add(KalturaAPIService.DEFAULT_PLAYLIST_EMPTY);
            } else {
                KalturaPlaylist newPlaylist = new KalturaPlaylist();
                newPlaylist.playlistContent = StringUtils.join(entries, ",");
                // get the collection
                for (Iterator<MediaCollection> mci = mockCollections.iterator();mci.hasNext();) {
                    MediaCollection mediaCollection = mci.next();
                    if (StringUtils.equals(mediaCollection.getIdStr(), playlist.id)) {
                        mc = mediaCollection;
                        break;
                    }
                }
            }
            // add the items to the collection
            if (mc != null) {
                // create list of media items to add to collection
                List<MediaItem> mediaItems = new ArrayList<MediaItem>();
                for (String entry : entries) {
                    for (MediaItem mi : mockItems) {
                        if (StringUtils.equals(mi.getIdStr(), entry)) {
                            mediaItems.add(mi);
                            break;
                        }
                    }
                }
                mc.setItems(mediaItems);
            }
            removed = true;
        }
    }
    return removed;
}
 
Example 16
Project: hadoop-oss   File: CrossOriginFilter.java   View Source Code Vote up 4 votes
@VisibleForTesting
String getAllowedMethodsHeader() {
  return StringUtils.join(allowedMethods, ',');
}
 
Example 17
Project: hadoop   File: TestLogAggregationService.java   View Source Code Vote up 4 votes
@Test
public void testFailedDirsLocalFileDeletionAfterUpload() throws Exception {

  // setup conf and services
  DeletionService mockDelService = mock(DeletionService.class);
  File[] localLogDirs =
      TestNonAggregatingLogHandler.getLocalLogDirFiles(this.getClass()
        .getName(), 7);
  final List<String> localLogDirPaths =
      new ArrayList<String>(localLogDirs.length);
  for (int i = 0; i < localLogDirs.length; i++) {
    localLogDirPaths.add(localLogDirs[i].getAbsolutePath());
  }

  String localLogDirsString = StringUtils.join(localLogDirPaths, ",");

  this.conf.set(YarnConfiguration.NM_LOG_DIRS, localLogDirsString);
  this.conf.set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR,
    this.remoteRootLogDir.getAbsolutePath());
  this.conf.setLong(YarnConfiguration.NM_DISK_HEALTH_CHECK_INTERVAL_MS, 500);

  ApplicationId application1 = BuilderUtils.newApplicationId(1234, 1);
  ApplicationAttemptId appAttemptId =
      BuilderUtils.newApplicationAttemptId(application1, 1);

  this.dirsHandler = new LocalDirsHandlerService();
  LocalDirsHandlerService mockDirsHandler = mock(LocalDirsHandlerService.class);

  LogAggregationService logAggregationService =
      spy(new LogAggregationService(dispatcher, this.context, mockDelService,
        mockDirsHandler));
  AbstractFileSystem spylfs =
      spy(FileContext.getLocalFSFileContext().getDefaultFileSystem());
  FileContext lfs = FileContext.getFileContext(spylfs, conf);
  doReturn(lfs).when(logAggregationService).getLocalFileContext(
    isA(Configuration.class));

  logAggregationService.init(this.conf);
  logAggregationService.start();

  TestNonAggregatingLogHandler.runMockedFailedDirs(logAggregationService,
    application1, user, mockDelService, mockDirsHandler, conf, spylfs, lfs,
    localLogDirs);

  logAggregationService.stop();
  assertEquals(0, logAggregationService.getNumAggregators());
  verify(logAggregationService).closeFileSystems(
    any(UserGroupInformation.class));

  ApplicationEvent expectedEvents[] =
      new ApplicationEvent[] {
          new ApplicationEvent(appAttemptId.getApplicationId(),
            ApplicationEventType.APPLICATION_LOG_HANDLING_INITED),
          new ApplicationEvent(appAttemptId.getApplicationId(),
            ApplicationEventType.APPLICATION_LOG_HANDLING_FINISHED) };

  checkEvents(appEventHandler, expectedEvents, true, "getType",
    "getApplicationID");
}
 
Example 18
Project: morf   File: Function.java   View Source Code Vote up 4 votes
/**
 * @see java.lang.Object#toString()
 */
@Override
public String toString() {
  return type.toString() + "(" + StringUtils.join(arguments, ", ") + ")" + super.toString();
}
 
Example 19
Project: VASSAL-src   File: LOS_Thread.java   View Source Code Vote up 4 votes
protected String getLosCheckList() {
  return StringUtils.join(checkList, ", ");
}
 
Example 20
Project: argument-reasoning-comprehension-task   File: Step0bTextSegmenterA.java   View Source Code Vote up 4 votes
private static void annotate(StandaloneArgument argument, PrintWriter outputTXTFile,
        Map<String, List<List<String>>> segmentedEDUs)
        throws IOException
{
    try {
        // original jcas, for automatic segmenting with tokens and sentences
        JCas originalJCas = initializeJCas(argument);

        SimplePipeline.runPipeline(originalJCas, getPipeline());

        // for re-annotation with manual sentences, paragraph, and tokens
        JCas segmentedJCas = initializeJCas(argument);
        copyParagraphAndTokenAnnotations(originalJCas, segmentedJCas);

        // now for each sentence collect tokens and run EDU segmenter
        for (Sentence sentence : JCasUtil.select(originalJCas, Sentence.class)) {

            List<Token> tokens = JCasUtil.selectCovered(Token.class, sentence);
            List<String> tokenWords = new ArrayList<>();

            for (Token token : tokens) {
                tokenWords.add(token.getCoveredText());
            }

            String text = StringUtils.join(tokenWords, " ");
            String sentenceID = argument.getId() + "_" + sentence.getBegin();

            // either output for external segmenting or annotate
            if (outputTXTFile != null && segmentedEDUs == null) {
                outputTXTFile.println(sentenceID + "\t" + text);
                System.out.println("Writing " + sentenceID);
            }
            else if (outputTXTFile == null && segmentedEDUs != null) {

                List<List<String>> collectedEDUs = segmentedEDUs.get(sentenceID);

                if (collectedEDUs == null) {
                    throw new IllegalStateException(
                            "Cannot find EDUs for sentence " + sentenceID);
                }

                reAnnotatedSentencesFromEDUs(segmentedJCas, collectedEDUs, tokenWords, tokens);
            }
            else {
                throw new IllegalStateException();
            }
        }

        // save back
        argument.setJCas(segmentedJCas);
    }
    catch (UIMAException | IOException e) {
        throw new IOException(e);
    }
}