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

The following examples show how to use org.apache.commons.lang.StringUtils#join() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StringCodec.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public String toString(Collection<T> pojo)
{
  if (pojo == null) {
    return null;
  }

  if (pojo.isEmpty()) {
    return "";
  }

  String[] parts = new String[pojo.size()];

  int i = 0;
  for (T o : pojo) {
    parts[i++] = codec.toString(o);
  }

  return StringUtils.join(parts, separator);
}
 
Example 2
Source File: FixTableComparer.java    From celos with Apache License 2.0 6 votes vote down vote up
private FixObjectCompareResult compareFixRows(List<String> columnNames, FixTable.FixRow expRow, FixTable.FixRow actRow) {
    if (expRow.equals(actRow)) {
        return FixObjectCompareResult.SUCCESS;
    }

    List<String> expDesc = Lists.newArrayList();
    List<String> actDesc = Lists.newArrayList();

    for (String key: columnNames) {
        String expValue = expRow.getCells().get(key);
        String actValue = actRow.getCells().get(key);
        if (!expValue.equals(actValue)) {
            expDesc.add(key + "=" + expValue);
            actDesc.add(key + "=" + actValue);
        }
    }

    String differenctDescription =
            "Cells in expected data set: [" + StringUtils.join(expDesc, ", ") + "], " +
            "cells in actual data set: [" + StringUtils.join(actDesc, ", ") + "]";

    return FixObjectCompareResult.failed(differenctDescription);
}
 
Example 3
Source File: ParseMailInputTest.java    From hop with Apache License 2.0 6 votes vote down vote up
/**
 * Test message recipients can be parsed
 *
 * @throws Exception
 */
@Test
@Ignore
public void testMessageRecipientsIsParsed() throws Exception {
  int[] fields = { MailInputField.COLUMN_RECIPIENTS };
  MailInputField[] farr = this.getDefaultInputFields( fields );
  this.mockMailInputMeta( farr );
  try {
    mailInput.init();
  } catch ( Exception e ) {
    // don't worry about it
  }
  MessageParser underTest = mailInput.new MessageParser();
  Object[] r = RowDataUtil.allocateRowData( data.nrFields );
  underTest.parseToArray( r, message );

  // is concatenated with ';'
  String expected = StringUtils.join( new String[] { REC1, REC2 }, ";" );
  Assert.assertEquals( "Message Recipients is correct", expected, String.class.cast( r[ 0 ] ) );
}
 
Example 4
Source File: CelosSchedulerWorker.java    From celos with Apache License 2.0 6 votes vote down vote up
private void startScheduler(TestCase testCase, Set<WorkflowID> workflowList, ScheduledTime actualTime, ScheduledTime endTime) throws Exception {
    System.out.println(testCase.getName() + ": Starting scheduler for: " + StringUtils.join(workflowList, ", "));
    client.iterateScheduler(actualTime, testCase.getTargetWorkflows());

    while (!actualTime.getDateTime().isAfter(endTime.getDateTime())) {
        String workflowStatuses = StringUtils.join(getWorkflowStatusesInfo(workflowList, actualTime), " ");
        if (!workflowStatuses.trim().isEmpty()) {
            System.out.println(testCase.getName() + ": Workflow statuses: " + workflowStatuses);
        }
        if (!isThereAnyRunningWorkflows(workflowList, actualTime)) {
            actualTime = new ScheduledTime(actualTime.getDateTime().plusHours(1));
        } else {
            Thread.sleep(2000);
        }
        client.iterateScheduler(actualTime, testCase.getTargetWorkflows());
    }
}
 
Example 5
Source File: AviaterRegexFilter.java    From canal with Apache License 2.0 6 votes vote down vote up
public AviaterRegexFilter(String pattern, boolean defaultEmptyValue){
    this.defaultEmptyValue = defaultEmptyValue;
    List<String> list = null;
    if (StringUtils.isEmpty(pattern)) {
        list = new ArrayList<String>();
    } else {
        String[] ss = StringUtils.split(pattern, SPLIT);
        list = Arrays.asList(ss);
    }

    // 对pattern按照从长到短的排序
    // 因为 foo|foot 匹配 foot 会出错,原因是 foot 匹配了 foo 之后,会返回 foo,但是 foo 的长度和 foot
    // 的长度不一样
    Collections.sort(list, COMPARATOR);
    // 对pattern进行头尾完全匹配
    list = completionPattern(list);
    this.pattern = StringUtils.join(list, PATTERN_SPLIT);
}
 
Example 6
Source File: TestGlobPaths.java    From hadoop with Apache License 2.0 5 votes vote down vote up
private void checkStatus(FileStatus[] status, Path ... expectedMatches) {
  assertNotNull(status);
  String[] paths = new String[status.length];
  for (int i=0; i < status.length; i++) {
    paths[i] = getPathFromStatus(status[i]);
  }
  String got = StringUtils.join(paths, "\n");
  String expected = StringUtils.join(expectedMatches, "\n");
  assertEquals(expected, got);
}
 
Example 7
Source File: ReasonGistSelectorAllConcatenated.java    From argument-reasoning-comprehension-task with Apache License 2.0 5 votes vote down vote up
@Override
public String selectFinalReasonGist(SortedSet<SingleWorkerAssignment<String>> value)
{
    List<String> values = new ArrayList<>();
    for (SingleWorkerAssignment<String> assignment : value) {
        values.add(assignment.getLabel());
    }

    return StringUtils.join(values, " *** ");
}
 
Example 8
Source File: TddlRuleConfig.java    From tddl with Apache License 2.0 5 votes vote down vote up
/**
 * 基于文件创建rule的spring容器
 * 
 * @param file
 * @return
 */
private ApplicationContext buildRuleByFile(String version, String file) {
    try {
        Resource resource = new PathMatchingResourcePatternResolver().getResource(file);
        String ruleStr = StringUtils.join(IOUtils.readLines(resource.getInputStream()), SystemUtils.LINE_SEPARATOR);
        return buildRuleByStr(version, ruleStr);
    } catch (IOException e) {
        throw new TddlRuleException(e);
    }
}
 
Example 9
Source File: StatsdMetricsReporterService.java    From kafka-monitor with Apache License 2.0 5 votes vote down vote up
private String generateStatsdMetricName(String bean, String attribute) {
  String service = bean.split(":")[1];
  String serviceName = service.split(",")[0].split("=")[1];
  String serviceType = service.split(",")[1].split("=")[1];
  String[] segs = {serviceType, serviceName, attribute};
  return StringUtils.join(segs, ".");
}
 
Example 10
Source File: ReflectUtil.java    From sofa-acts with Apache License 2.0 5 votes vote down vote up
public static String genModelForSpeciMethod(String csvModelRootPath, ClassLoader classLoader,
                                            String className, String methodName,
                                            boolean isResultOnly) {
    try {
        Set<String> setWarnMsg = CSVApis.genCsvFromSpeciMethodByRootPath(csvModelRootPath,
            classLoader, className, methodName, isResultOnly);

        return StringUtils.join(setWarnMsg, ";");
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Class not found:" + className, e);
    } catch (Exception exp) {
        throw new ActsException("Failed to generate template:" + exp.getMessage());
    }

}
 
Example 11
Source File: LinkisJobConverter.java    From DataSphereStudio with Apache License 2.0 5 votes vote down vote up
public String conversion(LinkisAzkabanReadNode schedulerNode){
    String tmpConversion = baseConversion(schedulerNode);
    String[] shareNodeArray =  schedulerNode.getShareNodeIds();
    String readNodePrefix = "read.nodes = ";
    String shareNodeIds = StringUtils.join(shareNodeArray, ",");
    return tmpConversion + readNodePrefix + shareNodeIds + "\n";
}
 
Example 12
Source File: NormalizationFunctions.java    From datawave with Apache License 2.0 5 votes vote down vote up
public static String ipv4(Object ipField) throws NormalizationException {
    String ip = ValueTuple.getNormalizedStringValue(ipField);
    
    int index = ip.indexOf("..*");
    // is it a wildcard?
    if (index != -1) {
        String temp = ip.substring(0, index);
        if (log.isDebugEnabled()) {
            log.debug("wildcard ip: " + temp);
        }
        
        // zero padd temp and return with the .* on the end
        
        String[] octets = StringUtils.split(temp, ".");
        for (int i = 0; i < octets.length; i++) {
            int oct = Integer.parseInt(octets[i]);
            octets[i] = String.format("%03d", oct);
            if (log.isDebugEnabled()) {
                log.debug("octets[i]: " + octets[i] + "  oct: " + oct);
            }
        }
        
        ip = StringUtils.join(octets, ".") + "..*";
        
    } else {
        IpAddressType normalizer = new IpAddressType();
        ip = normalizer.normalize(ip);
    }
    return ip;
}
 
Example 13
Source File: TestDAGImpl.java    From tez with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test(timeout = 5000)
public void testEdgeManager_RouteDataMovementEventToDestinationWithLegacyRouting() {
  // Remove after legacy routing is removed
  setupDAGWithCustomEdge(ExceptionLocation.RouteDataMovementEventToDestination, true);
  dispatcher.getEventHandler().handle(
      new DAGEvent(dagWithCustomEdge.getID(), DAGEventType.DAG_INIT));
  dispatcher.getEventHandler().handle(new DAGEventStartDag(dagWithCustomEdge.getID(),
      null));
  dispatcher.await();
  Assert.assertEquals(DAGState.RUNNING, dagWithCustomEdge.getState());

  VertexImpl v1 = (VertexImpl)dagWithCustomEdge.getVertex("vertex1");
  VertexImpl v2 = (VertexImpl)dagWithCustomEdge.getVertex("vertex2");

  dispatcher.await();
  Task t1= v2.getTask(0);
  TaskAttemptImpl ta1= (TaskAttemptImpl)t1.getAttempt(TezTaskAttemptID.getInstance(t1.getTaskId(), 0));

  DataMovementEvent daEvent = DataMovementEvent.create(ByteBuffer.wrap(new byte[0]));
  TezEvent tezEvent = new TezEvent(daEvent, 
      new EventMetaData(EventProducerConsumerType.INPUT, "vertex1", "vertex2", ta1.getID()));
  dispatcher.getEventHandler().handle(
      new VertexEventRouteEvent(v2.getVertexId(), Lists.newArrayList(tezEvent)));
  dispatcher.await();

  Assert.assertEquals(VertexState.FAILED, v2.getState());
  Assert.assertEquals(VertexState.KILLED, v1.getState());
  String diag = StringUtils.join(v2.getDiagnostics(), ",");
  Assert.assertTrue(diag.contains(ExceptionLocation.RouteDataMovementEventToDestination.name()));
}
 
Example 14
Source File: MutantTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void exploratoryTest() {
    List<Integer> mutatedLines = new ArrayList<>();
    String s = StringUtils.join(mutatedLines, ",");
    System.out.println("MutantTest.exploratoryTest() " + s);

}
 
Example 15
Source File: Header.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Builds the HTML class attribute string by combining the headerStyleClasses list
 * with a space delimiter
 *
 * @return class attribute string
 */
public String getHeaderStyleClassesAsString() {
    if (headerTagCssClasses != null) {
        return StringUtils.join(headerTagCssClasses, " ");
    }

    return "";
}
 
Example 16
Source File: CommonRepositoryHandler.java    From sqoop-on-spark with Apache License 2.0 4 votes vote down vote up
/**
 * @param inputId
 * @param conn
 * @return
 */
private String getOverrides(long inputId, Connection conn) {

  PreparedStatement overridesStmt = null;
  PreparedStatement inputStmt = null;

  ResultSet rsOverride = null;
  ResultSet rsInput = null;

  List<String> overrides = new ArrayList<String>();
  try {
    overridesStmt = conn.prepareStatement(crudQueries.getStmtSelectInputOverrides());
    inputStmt = conn.prepareStatement(crudQueries.getStmtSelectInputById());
    overridesStmt.setLong(1, inputId);
    rsOverride = overridesStmt.executeQuery();

    while (rsOverride.next()) {
      long overrideId = rsOverride.getLong(1);
      inputStmt.setLong(1, overrideId);
      rsInput = inputStmt.executeQuery();
      if(rsInput.next()) {
       overrides.add(rsInput.getString(2));
      }
    }
    if (overrides != null && overrides.size() > 0) {
      return StringUtils.join(overrides, ",");
    } else {
      return StringUtils.EMPTY;

    }
  } catch (SQLException ex) {
    logException(ex, inputId);
    throw new SqoopException(CommonRepositoryError.COMMON_0048, ex);
  } finally {
    if (rsOverride != null) {
      closeResultSets(rsOverride);
    }
    if (rsInput != null) {
      closeResultSets(rsInput);
    }

    if (overridesStmt != null) {
      closeStatements(overridesStmt);
    }
    if (inputStmt != null) {
      closeStatements(inputStmt);
    }
  }
}
 
Example 17
Source File: MFPredictionUDF.java    From incubator-hivemall with Apache License 2.0 4 votes vote down vote up
@Override
public String getDisplayString(String[] args) {
    return "mf_predict(" + StringUtils.join(args, ',') + ')';
}
 
Example 18
Source File: ReferenceSearch.java    From rebuild with GNU General Public License v3.0 4 votes vote down vote up
@RequestMapping({ "reference", "quick" })
public void referenceSearch(HttpServletRequest request, HttpServletResponse response) {
	final ID user = getRequestUser(request);
	final String entity = getParameterNotNull(request, "entity");
	final String field = getParameterNotNull(request, "field");
	
	Entity metaEntity = MetadataHelper.getEntity(entity);
	Field referenceField = metaEntity.getField(field);
	if (referenceField.getType() != FieldType.REFERENCE) {
		writeSuccess(response, JSONUtils.EMPTY_ARRAY);
		return;
	}
	
	Entity referenceEntity = referenceField.getReferenceEntity();
	Field referenceNameField = MetadataHelper.getNameField(referenceEntity);
	if (referenceNameField == null) {
		LOG.warn("No name-field found : " + referenceEntity.getName());
		writeSuccess(response, JSONUtils.EMPTY_ARRAY);
		return;
	}

	// 引用字段数据过滤仅在搜索时有效
	// 启用数据过滤后最近搜索将不可用
	final String protocolFilter = new ProtocolFilterParser(null).parseRef(field + "." + entity);

	String q = getParameter(request, "q");
	// 为空则加载最近使用的
	if (StringUtils.isBlank(q)) {
		ID[] recently = null;
		if (protocolFilter == null) {
			String type = getParameter(request, "type");
			recently = Application.getRecentlyUsedCache().gets(user, referenceEntity.getName(), type);
		}

		if (recently == null || recently.length == 0) {
			writeSuccess(response, JSONUtils.EMPTY_ARRAY);
		} else {
			writeSuccess(response, RecentlyUsedSearch.formatSelect2(recently, null));
		}
		return;
	}
	q = StringEscapeUtils.escapeSql(q);
	
	// 可搜索字符
	Set<String> searchFields = new HashSet<>();
	DisplayType referenceNameFieldType = EasyMeta.getDisplayType(referenceNameField);
	if (!(referenceNameFieldType == DisplayType.DATETIME || referenceNameFieldType == DisplayType.DATE
			|| referenceNameFieldType == DisplayType.NUMBER || referenceNameFieldType == DisplayType.DECIMAL
			|| referenceNameFieldType == DisplayType.ID)) {
		searchFields.add(referenceNameField.getName());
	}
	if (referenceEntity.containsField(EntityHelper.QuickCode) && StringUtils.isAlphanumericSpace(q)) {
		searchFields.add(EntityHelper.QuickCode);
	}
	for (Field seriesField : MetadataSorter.sortFields(referenceEntity, DisplayType.SERIES)) {
		searchFields.add(seriesField.getName());
	}

	if (searchFields.isEmpty()) {
		LOG.warn("No fields of search found : " + referenceEntity);
		writeSuccess(response, JSONUtils.EMPTY_ARRAY);
		return;
	}

	String like = " like '%" + q + "%'";
	String searchWhere = StringUtils.join(searchFields.iterator(), like + " or ") + like;
	if (protocolFilter != null) {
		searchWhere = "(" + searchWhere + ") and (" + protocolFilter + ')';
	}

	String sql = MessageFormat.format("select {0},{1} from {2} where ( {3} )",
			referenceEntity.getPrimaryField().getName(), referenceNameField.getName(), referenceEntity.getName(), searchWhere);
	if (referenceEntity.containsField(EntityHelper.ModifiedOn)) {
		sql += " order by modifiedOn desc";
	}

	List<Object> result = resultSearch(sql, metaEntity, referenceNameField);
	writeSuccess(response, result);
}
 
Example 19
Source File: Or.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public String toString(){
  return "("+ StringUtils.join(expressions, " | ")+")";
}
 
Example 20
Source File: RowSet.java    From antsdb with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public String toString() {
    return StringUtils.join(this.conditions, ';');
}