Java Code Examples for com.google.common.collect.Lists#transform()

The following examples show how to use com.google.common.collect.Lists#transform() . 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: SimpleUserService.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<? extends User> searchUsers(String searchTerm, String sortColumn, SortOrder order,
                                            Integer limit) throws IOException {
  limit = limit == null ? 10000 : limit;

  if (searchTerm == null || searchTerm.isEmpty()) {
    return getAllUsers(limit);
  }

  final SearchQuery query = SearchQueryUtils.or(
    SearchQueryUtils.newContainsTerm(UserIndexKeys.NAME, searchTerm),
    SearchQueryUtils.newContainsTerm(UserIndexKeys.FIRST_NAME, searchTerm),
    SearchQueryUtils.newContainsTerm(UserIndexKeys.LAST_NAME, searchTerm),
    SearchQueryUtils.newContainsTerm(UserIndexKeys.EMAIL, searchTerm));

  final LegacyFindByCondition conditon = new LegacyFindByCondition()
    .setCondition(query)
    .setLimit(limit)
    .addSorting(buildSorter(sortColumn, order));

  return Lists.transform(Lists.newArrayList(KVUtil.values(userStore.find(conditon))), infoConfigTransformer);
}
 
Example 2
Source File: PullFileLoader.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Find and load all pull files under a base {@link Path} recursively in an order sorted by last modified date.
 * @param path base {@link Path} where pull files should be found recursively.
 * @param sysProps A {@link Config} used as fallback.
 * @param loadGlobalProperties if true, will also load at most one *.properties file per directory from the
 *          {@link #rootDirectory} to the pull file {@link Path} for each pull file.
 * @return The loaded {@link Config}s.
 */
public List<Config> loadPullFilesRecursively(Path path, Config sysProps, boolean loadGlobalProperties) {
  return Lists.transform(this.fetchJobFilesRecursively(path), new Function<Path, Config>() {
    @Nullable
    @Override
    public Config apply(@Nullable Path jobFile) {
      if (jobFile == null) {
        return null;
      }

      try {
        return PullFileLoader.this.loadPullFile(jobFile,
            sysProps, loadGlobalProperties);
      } catch (IOException e) {
        log.error("Cannot load job from {} due to {}", jobFile, ExceptionUtils.getFullStackTrace(e));
        return null;
      }
    }
  });
}
 
Example 3
Source File: SolrQuestionIndex.java    From mamute with Apache License 2.0 5 votes vote down vote up
private SolrInputDocument toDoc(Question q) {
	List<String> tagNames = Lists.transform(q.getTags(), new Function<Tag, String>() {
		@Nullable
		@Override
		public String apply(@Nullable Tag tag) {
			return tag.getName();
		}
	});

	SolrInputDocument doc = new SolrInputDocument();
	doc.addField("id", q.getId());
	doc.addField("title", q.getTitle());
	doc.addField("description", q.getMarkedDescription());
	doc.addField("tags", join(tagNames));

	String solution = null;
	List<String> answers = new ArrayList<>();
	for (Answer a : q.getAnswers()) {
		if (a.isSolution()) {
			solution = a.getDescription();
		} else {
			answers.add(a.getDescription());
		}
	}

	if (solution != null) {
		doc.addField("solution", solution);
	}
	if (answers.size() > 0) {
		doc.addField("answers", join(answers));
	}

	return doc;
}
 
Example 4
Source File: LdapSecurityProvider.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the LDAP path for the user
 *
 * @param user
 * @return String
 */
protected String getUserDN(String user) {
    List<String> domain = Lists.transform(Arrays.asList(ldapRealm.split("\\.")), new Function<String, String>() {
        @Override
        public String apply(String input) {
            return "dc=" + input;
        }
    });

    String dc = Joiner.on(",").join(domain).toLowerCase();
    return "cn=" + user + ",ou=" + organizationUnit + "," + dc;
}
 
Example 5
Source File: SoyFunctions.java    From deploymentmanager-autogen with Apache License 2.0 5 votes vote down vote up
private static List<VmTierSpec> extractTierList(SoyValue tiersArg) {
  if (tiersArg instanceof SoyList) {
    List<? extends SoyValue> list = ((SoyList) tiersArg).asResolvedJavaList();
    return Lists.transform(list, new Function<SoyValue, VmTierSpec>() {
      @Override
      public VmTierSpec apply(SoyValue soyValue) {
        return (VmTierSpec) ((SoyProtoValue) soyValue).getProto();
      }
    });
  } else if (tiersArg instanceof SoyProtoValue) {
    return ((MultiVmDeploymentPackageSpec) ((SoyProtoValue) tiersArg).getProto()).getTiersList();
  } else {
    throw new IllegalArgumentException("Unable to extract tier list from argument");
  }
}
 
Example 6
Source File: AssertionView.java    From hifive-pitalium with Apache License 2.0 5 votes vote down vote up
/**
 * スクリーンショット比較の前準備として、除外領域をマスクし、座標情報とペアにして返します。
 *
 * @param target スクリーンショット撮影結果
 * @return マスク済の画像と座標情報のペア
 */
private ImageRectanglePair prepareScreenshotImageForCompare(TargetResult target) {
	BufferedImage image = target.getImage().get();

	// Mask
	List<ScreenAreaResult> excludes = target.getExcludes();
	if (!excludes.isEmpty()) {
		List<Rectangle> maskAreas = Lists.transform(toExcludesForJson(excludes),
				SCREEN_AREA_RESULT_TO_RECTANGLE_FUNCTION);
		image = ImageUtils.getMaskedImage(image, maskAreas);
	}

	return new ImageRectanglePair(image, target.getTarget().getRectangle().toRectangle());
}
 
Example 7
Source File: Lease.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Programmatic
public LeaseStatus getEffectiveStatus() {
    List<LeaseItem> all = Lists.newArrayList(getItems());
    int itemCount = getItems().size();
    List<LeaseItemStatus> statusList = Lists.transform(all, leaseItem -> leaseItem.getStatus());
    int suspensionCount = Collections.frequency(statusList, LeaseItemStatus.SUSPENDED);
    if (suspensionCount > 0) {
        if (itemCount == suspensionCount) {
            return LeaseStatus.SUSPENDED;
        } else {
            return LeaseStatus.SUSPENDED_PARTIALLY;
        }
    }
    return null;
}
 
Example 8
Source File: RecentColorsOption.java    From ganttproject with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getPersistentValue() {
  if (myColors.isEmpty()) {
    return null;
  }
  List<String> values = Lists.transform(myColors, new Function<Color, String>() {
    @Override
    public String apply(Color c) {
      return Util.getColor(c);
    }
  });
  return Joiner.on(' ').join(values);
}
 
Example 9
Source File: ScanUtilTest.java    From phoenix with Apache License 2.0 5 votes vote down vote up
private static Collection<?> foreach(KeyRange[][] ranges, int[] widths, byte[] expectedKey,
        Bound bound) {
    List<List<KeyRange>> slots = Lists.transform(Lists.newArrayList(ranges), ARRAY_TO_LIST);
    List<Object> ret = Lists.newArrayList();
    ret.add(new Object[] { slots, widths, expectedKey, bound });
    return ret;
}
 
Example 10
Source File: GraphBackedTypeStore.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
/**
 * Finds or creates type vertices with the information specified.
 *
 * @param infoList
 * @return list with the vertices corresponding to the types in the list.
 * @throws AtlasException
 */
private List<AtlasVertex> createVertices(List<TypeVertexInfo> infoList) throws AtlasException {

    List<AtlasVertex> result = new ArrayList<>(infoList.size());
    List<String> typeNames = Lists.transform(infoList, new Function<TypeVertexInfo,String>() {
        @Override
        public String apply(TypeVertexInfo input) {
            return input.getTypeName();
        }
    });
    Map<String, AtlasVertex> vertices = findVertices(typeNames);

    for(TypeVertexInfo info : infoList) {
        AtlasVertex vertex = vertices.get(info.getTypeName());
        if (! GraphHelper.elementExists(vertex)) {
            LOG.debug("Adding vertex {}{}", PROPERTY_PREFIX, info.getTypeName());
            vertex = graph.addVertex();
            setProperty(vertex, Constants.VERTEX_TYPE_PROPERTY_KEY, VERTEX_TYPE); // Mark as type AtlasVertex
            setProperty(vertex, Constants.TYPE_CATEGORY_PROPERTY_KEY, info.getCategory());
            setProperty(vertex, Constants.TYPENAME_PROPERTY_KEY, info.getTypeName());
        }
        String newDescription = info.getTypeDescription();
        if (newDescription != null) {
            String oldDescription = getPropertyKey(Constants.TYPEDESCRIPTION_PROPERTY_KEY);
            if (!newDescription.equals(oldDescription)) {
                setProperty(vertex, Constants.TYPEDESCRIPTION_PROPERTY_KEY, newDescription);
            }
        } else {
            LOG.debug(" type description is null ");
        }
        result.add(vertex);
    }
    return result;
}
 
Example 11
Source File: Pql.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the values in a row of the result set in the form of a string list.
 *
 * @param row the row to get the values for
 * @return the string list of the row values
 */
public static List<String> getRowStringValues(Row row) {
  return Lists.transform(
      Lists.newArrayList(row.getValues()),
      new Function<Value, String>() {
        public String apply(Value input) {
          return Pql.toString(input);
        }
      });
}
 
Example 12
Source File: AbstractBundleSubmissionServiceImpl.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
public List<BundleSubmission> getBundleSubmissionsWithGradingsByContainerJidAndProblemJidAndUserJid(String containerJid, String problemJid, String userJid) {
    List<SM> submissionModels = bundleSubmissionDao.findSortedByFiltersEq("id", "asc", "", ImmutableMap.<SingularAttribute<? super SM, ? extends Object>, String>of(AbstractBundleSubmissionModel_.containerJid, containerJid, AbstractBundleSubmissionModel_.problemJid, problemJid, AbstractBundleSubmissionModel_.createdBy, userJid), 0, -1);
    Map<String, List<GM>> gradingModelsMap = bundleGradingDao.getBySubmissionJids(Lists.transform(submissionModels, m -> m.jid));

    return Lists.transform(submissionModels, m -> BundleSubmissionServiceUtils.createSubmissionFromModels(m, gradingModelsMap.get(m.jid)));
}
 
Example 13
Source File: CopyWithCluster.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private RelNode copyOf(LogicalWindow window) {
  final RelNode input = window.getInput().accept(this);
  return new LogicalWindow(
    cluster,
    copyOf(window.getTraitSet()),
    input,
    Lists.transform(window.constants, COPY_REX_LITERAL),
    copyOf(window.getRowType()),
    window.groups
  );
}
 
Example 14
Source File: ResourceDescriptionDeltaTest.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
@SuppressWarnings("PMD.CyclomaticComplexity")
private IResourceDescription createDescriptionWithFingerprints(final String... fragmentsAndFingerprints) {
  final URI resourceURI = URI.createURI("foo:/foo.foo");
  return new AbstractResourceDescription() {

    public Iterable<QualifiedName> getImportedNames() {
      return ImmutableSet.of();
    }

    public Iterable<IReferenceDescription> getReferenceDescriptions() {
      return ImmutableSet.of();
    }

    public URI getURI() {
      return resourceURI;
    }

    @Override
    protected List<IEObjectDescription> computeExportedObjects() {
      return Lists.transform(Lists.newArrayList(fragmentsAndFingerprints), new Function<String, IEObjectDescription>() {
        public IEObjectDescription apply(final String from) {
          final String fragment = from.split(":")[0];
          final String fingerprint = from.indexOf(':') != -1 ? from.split(":")[1] : from;
          return new AbstractEObjectDescription() {

            public QualifiedName getQualifiedName() {
              return QualifiedName.create(fragment);
            }

            public QualifiedName getName() {
              return getQualifiedName();
            }

            public URI getEObjectURI() {
              return resourceURI.appendFragment(fragment);
            }

            public EObject getEObjectOrProxy() {
              return null;
            }

            public EClass getEClass() {
              return null;
            }

            @Override
            public String[] getUserDataKeys() {
              return new String[] {IFingerprintComputer.OBJECT_FINGERPRINT};
            }

            @Override
            public String getUserData(final String name) {
              return name.equals(IFingerprintComputer.OBJECT_FINGERPRINT) ? Integer.toString(fingerprint.hashCode()) : null; // NOPMD
            }
          };
        }
      });
    }
  };
}
 
Example 15
Source File: XmlElement.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Compares this element with another {@link XmlElement} ignoring all attributes belonging to
 * the {@link SdkConstants#TOOLS_URI} namespace.
 *
 * @param other the other element to compare against.
 * @return a {@link String} describing the differences between the two XML elements or
 * {@link Optional#absent()} if they are equals.
 */
@NonNull
public Optional<String> compareTo(Object other) {

    if (!(other instanceof XmlElement)) {
        return Optional.of("Wrong type");
    }
    XmlElement otherNode = (XmlElement) other;

    // compare element names
    if (getXml().getNamespaceURI() != null) {
        if (!getXml().getLocalName().equals(otherNode.getXml().getLocalName())) {
            return Optional.of(
                    String.format("Element names do not match: %1$s versus %2$s",
                            getXml().getLocalName(),
                            otherNode.getXml().getLocalName()));
        }
        // compare element ns
        String thisNS = getXml().getNamespaceURI();
        String otherNS = otherNode.getXml().getNamespaceURI();
        if ((thisNS == null && otherNS != null)
                || (thisNS != null && !thisNS.equals(otherNS))) {
            return Optional.of(
                    String.format("Element namespaces names do not match: %1$s versus %2$s",
                            thisNS, otherNS));
        }
    } else {
        if (!getXml().getNodeName().equals(otherNode.getXml().getNodeName())) {
            return Optional.of(String.format("Element names do not match: %1$s versus %2$s",
                    getXml().getNodeName(),
                    otherNode.getXml().getNodeName()));
        }
    }

    // compare attributes, we do it twice to identify added/missing elements in both lists.
    Optional<String> message = checkAttributes(this, otherNode);
    if (message.isPresent()) {
        return message;
    }
    message = checkAttributes(otherNode, this);
    if (message.isPresent()) {
        return message;
    }

    // compare children
    @NonNull List<Node> expectedChildren = filterUninterestingNodes(getXml().getChildNodes());
    @NonNull List<Node> actualChildren = filterUninterestingNodes(otherNode.getXml().getChildNodes());
    if (expectedChildren.size() != actualChildren.size()) {

        if (expectedChildren.size() > actualChildren.size()) {
            // missing some.
            @NonNull List<String> missingChildrenNames =
                    Lists.transform(expectedChildren, NODE_TO_NAME);
            missingChildrenNames.removeAll(Lists.transform(actualChildren, NODE_TO_NAME));
            return Optional.of(String.format(
                    "%1$s: Number of children do not match up: "
                            + "expected %2$d versus %3$d at %4$s, missing %5$s",
                    getId(),
                    expectedChildren.size(),
                    actualChildren.size(),
                    otherNode.printPosition(),
                    Joiner.on(",").join(missingChildrenNames)));
        } else {
            // extra ones.
            @NonNull List<String> extraChildrenNames = Lists.transform(actualChildren, NODE_TO_NAME);
            extraChildrenNames.removeAll(Lists.transform(expectedChildren, NODE_TO_NAME));
            return Optional.of(String.format(
                    "%1$s: Number of children do not match up: "
                            + "expected %2$d versus %3$d at %4$s, extra elements found : %5$s",
                    getId(),
                    expectedChildren.size(),
                    actualChildren.size(),
                    otherNode.printPosition(),
                    Joiner.on(",").join(expectedChildren)));
        }
    }
    for (Node expectedChild : expectedChildren) {
        if (expectedChild.getNodeType() == Node.ELEMENT_NODE) {
            @NonNull XmlElement expectedChildNode = new XmlElement((Element) expectedChild, mDocument);
            message = findAndCompareNode(otherNode, actualChildren, expectedChildNode);
            if (message.isPresent()) {
                return message;
            }
        }
    }
    return Optional.absent();
}
 
Example 16
Source File: SkipScanFilterTest.java    From phoenix with Apache License 2.0 4 votes vote down vote up
private static Collection<?> foreach(KeyRange[][] ranges, int[] widths, int[] slotSpans, Expectation... expectations) {
    List<List<KeyRange>> cnf = Lists.transform(Lists.newArrayList(ranges), ARRAY_TO_LIST);
    List<Object> ret = Lists.newArrayList();
    ret.add(new Object[] {cnf, widths, slotSpans, Arrays.asList(expectations)} );
    return ret;
}
 
Example 17
Source File: Lattice.java    From Bats with Apache License 2.0 4 votes vote down vote up
public List<String> uniqueColumnNames() {
  return Lists.transform(columns, column -> column.alias);
}
 
Example 18
Source File: PrettyProtobuf.java    From storm with Apache License 2.0 4 votes vote down vote up
/**
 * Pretty-print List of mesos protobuf Offers.
 */
public static String offerListToString(List<Offer> offers) {
  List<String> offersAsStrings = Lists.transform(offers, offerToStringTransform);
  return String.format("[\n%s]", StringUtils.join(offersAsStrings, ",\n"));
}
 
Example 19
Source File: OLogRawDataContent.java    From c5-replicator with Apache License 2.0 4 votes vote down vote up
private static List<ByteBuffer> sliceAll(List<ByteBuffer> buffers) {
  return Lists.transform(buffers, ByteBuffer::slice);
}
 
Example 20
Source File: XmlElement.java    From java-n-IDE-for-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Compares this element with another {@link XmlElement} ignoring all attributes belonging to
 * the {@link SdkConstants#TOOLS_URI} namespace.
 *
 * @param other the other element to compare against.
 * @return a {@link String} describing the differences between the two XML elements or
 * {@link Optional#absent()} if they are equals.
 */
public Optional<String> compareTo(Object other) {

    if (!(other instanceof XmlElement)) {
        return Optional.of("Wrong type");
    }
    XmlElement otherNode = (XmlElement) other;

    // compare element names
    if (getXml().getNamespaceURI() != null) {
        if (!getXml().getLocalName().equals(otherNode.getXml().getLocalName())) {
            return Optional.of(
                    String.format("Element names do not match: %1$s versus %2$s",
                            getXml().getLocalName(),
                            otherNode.getXml().getLocalName()));
        }
        // compare element ns
        String thisNS = getXml().getNamespaceURI();
        String otherNS = otherNode.getXml().getNamespaceURI();
        if ((thisNS == null && otherNS != null)
                || (thisNS != null && !thisNS.equals(otherNS))) {
            return Optional.of(
                    String.format("Element namespaces names do not match: %1$s versus %2$s",
                            thisNS, otherNS));
        }
    } else {
        if (!getXml().getNodeName().equals(otherNode.getXml().getNodeName())) {
            return Optional.of(String.format("Element names do not match: %1$s versus %2$s",
                    getXml().getNodeName(),
                    otherNode.getXml().getNodeName()));
        }
    }

    // compare attributes, we do it twice to identify added/missing elements in both lists.
    Optional<String> message = checkAttributes(this, otherNode);
    if (message.isPresent()) {
        return message;
    }
    message = checkAttributes(otherNode, this);
    if (message.isPresent()) {
        return message;
    }

    // compare children
    List<Node> expectedChildren = filterUninterestingNodes(getXml().getChildNodes());
    List<Node> actualChildren = filterUninterestingNodes(otherNode.getXml().getChildNodes());
    if (expectedChildren.size() != actualChildren.size()) {

        if (expectedChildren.size() > actualChildren.size()) {
            // missing some.
            List<String> missingChildrenNames =
                    Lists.transform(expectedChildren, NODE_TO_NAME);
            missingChildrenNames.removeAll(Lists.transform(actualChildren, NODE_TO_NAME));
            return Optional.of(String.format(
                    "%1$s: Number of children do not match up: "
                            + "expected %2$d versus %3$d at %4$s, missing %5$s",
                    getId(),
                    expectedChildren.size(),
                    actualChildren.size(),
                    otherNode.printPosition(),
                    Joiner.on(",").join(missingChildrenNames)));
        } else {
            // extra ones.
            List<String> extraChildrenNames = Lists.transform(actualChildren, NODE_TO_NAME);
            extraChildrenNames.removeAll(Lists.transform(expectedChildren, NODE_TO_NAME));
            return Optional.of(String.format(
                    "%1$s: Number of children do not match up: "
                            + "expected %2$d versus %3$d at %4$s, extra elements found : %5$s",
                    getId(),
                    expectedChildren.size(),
                    actualChildren.size(),
                    otherNode.printPosition(),
                    Joiner.on(",").join(expectedChildren)));
        }
    }
    for (Node expectedChild : expectedChildren) {
        if (expectedChild.getNodeType() == Node.ELEMENT_NODE) {
            XmlElement expectedChildNode = new XmlElement((Element) expectedChild, mDocument);
            message = findAndCompareNode(otherNode, actualChildren, expectedChildNode);
            if (message.isPresent()) {
                return message;
            }
        }
    }
    return Optional.absent();
}