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

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 agit, under directory /agit/src/main/java/com/madgag/agit/diff/.

Source file: CommitDiffer.java

  30 
vote

public List<FileDiff> calculateCommitDiffs(Repository repo,RevCommit beforeCommit,RevCommit afterCommit) throws IOException {
  Log.d(TAG,"calculateCommitDiffs");
  RevWalk revWalk=new RevWalk(repo);
  final TreeWalk tw=new TreeWalk(revWalk.getObjectReader());
  tw.setRecursive(true);
  tw.reset();
  addTree(tw,revWalk,beforeCommit);
  addTree(tw,revWalk,afterCommit);
  tw.setFilter(TreeFilter.ANY_DIFF);
  List<DiffEntry> files=detectRenames(repo,DiffEntry.scan(tw));
  final LineContextDiffer lineContextDiffer=new LineContextDiffer(revWalk.getObjectReader());
  return newArrayList(transform(files,new Function<DiffEntry,FileDiff>(){
    public FileDiff apply(    DiffEntry d){
      return new FileDiff(lineContextDiffer,d);
    }
  }
));
}
 

Example 2

From project arquillian-extension-drone, under directory /drone-webdriver/src/test/java/org/jboss/arquillian/drone/webdriver/example/.

Source file: LoginPage.java

  30 
vote

@Override public <V>V until(Function<? super WebDriver,V> isTrue){
  if (message == null) {
    return super.until(isTrue);
  }
 else {
    try {
      return super.until(isTrue);
    }
 catch (    TimeoutException e) {
      throw new TimeoutException(message,e);
    }
  }
}
 

Example 3

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

Source file: SessionAdapter.java

  29 
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 4

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

Source file: ConfigurationFactory.java

  29 
vote

ConfigurationFactory(Map<String,String> properties,final Problems.Monitor monitor){
  this.monitor=monitor;
  this.properties=ImmutableMap.copyOf(properties);
  metadataCache=new MapMaker().weakKeys().weakValues().makeComputingMap(new Function<Class<?>,ConfigurationMetadata<?>>(){
    @Override public ConfigurationMetadata<?> apply(    Class<?> configClass){
      return ConfigurationMetadata.getConfigurationMetadata(configClass,monitor);
    }
  }
);
}
 

Example 5

From project akubra, under directory /akubra-map/src/main/java/org/akubraproject/map/.

Source file: IdMappingBlobStoreConnection.java

  29 
vote

@Override public Iterator<URI> listBlobIds(final String filterPrefix) throws IOException {
  String intPrefix=null;
  Iterator<URI> intIterator;
  if (filterPrefix == null) {
    intIterator=delegate.listBlobIds(null);
  }
 else {
    intPrefix=mapper.getInternalPrefix(filterPrefix);
    intIterator=delegate.listBlobIds(intPrefix);
  }
  Iterator<URI> extIterator=Iterators.transform(intIterator,new Function<URI,URI>(){
    public URI apply(    URI uri){
      return mapper.getExternalId(uri);
    }
  }
);
  if (filterPrefix != null && intPrefix == null) {
    return Iterators.filter(extIterator,new Predicate<URI>(){
      public boolean apply(      URI uri){
        return uri.toString().startsWith(filterPrefix);
      }
    }
);
  }
 else {
    return extIterator;
  }
}
 

Example 6

From project android-rackspacecloud, under directory /extensions/httpnio/src/main/java/org/jclouds/http/pool/.

Source file: ConnectionPoolTransformingHttpCommandExecutorService.java

  29 
vote

@Inject public ConnectionPoolTransformingHttpCommandExecutorService(ExecutorService executor,HttpCommandConnectionPool.Factory<C> pf,BlockingQueue<HttpCommandRendezvous<?>> commandQueue){
  super(executor);
  this.poolFactory=pf;
  poolMap=new MapMaker().makeComputingMap(new Function<URI,HttpCommandConnectionPool<C>>(){
    public HttpCommandConnectionPool<C> apply(    URI endPoint){
      checkArgument(endPoint.getHost() != null,String.format("endPoint.getHost() is null for %s",endPoint));
      try {
        HttpCommandConnectionPool<C> pool=poolFactory.create(endPoint);
        addDependency(pool);
        return pool;
      }
 catch (      RuntimeException e) {
        logger.error(e,"error creating entry for %s",endPoint);
        throw e;
      }
    }
  }
);
  this.commandQueue=commandQueue;
}
 

Example 7

From project android_external_guava, under directory /src/com/google/common/collect/.

Source file: CustomConcurrentHashMap.java

  29 
vote

/** 
 * Creates a  {@link ConcurrentMap}, backed by the given strategy, that supports atomic, on-demand computation of values.  {@link Map#get}returns the value corresponding to the given key, atomically computes it using the computer function passed to this builder, or waits for another thread to compute the value if necessary. Only one value will be computed for each key at a given time. <p>If an entry's value has not finished computing yet, query methods besides  {@link java.util.Map#get} return immediately as if an entrydoesn't exist. In other words, an entry isn't externally visible until the value's computation completes. <p> {@link Map#get} in the returned map implementation throws:<ul> <li> {@link NullPointerException} if the key is null or thecomputer returns null</li> <li>or  {@link ComputationException} wrapping an exception thrown by thecomputation</li> </ul> <p><b>Note:</b> Callers of  {@code get()} <i>must</i> ensure that the keyargument is of type  {@code K}.  {@code Map.get()} takes {@code Object}, so the key type is not checked at compile time. Passing an object of a type other than  {@code K} can result in that object being unsafelypassed to the computer function as type  {@code K} not to mention theunsafe key being stored in the map.
 * @param strategy used to implement and manipulate the entries
 * @param computer used to compute values for keys
 * @param < K > the type of keys to be stored in the returned map
 * @param < V > the type of values to be stored in the returned map
 * @param < E > the type of internal entry to be stored in the returned map
 * @throws NullPointerException if strategy or computer is null
 */
public <K,V,E>ConcurrentMap<K,V> buildComputingMap(ComputingStrategy<K,V,E> strategy,Function<? super K,? extends V> computer){
  if (strategy == null) {
    throw new NullPointerException("strategy");
  }
  if (computer == null) {
    throw new NullPointerException("computer");
  }
  return new ComputingImpl<K,V,E>(strategy,this,computer);
}
 

Example 8

From project annotare2, under directory /app/magetab/src/test/java/uk/ac/ebi/fg/annotare2/magetab/base/.

Source file: TableTest.java

  29 
vote

private void assertTableEqualsTo(Table table,ArrayList<ArrayList<String>> rows){
  if (rows.isEmpty()) {
    assertEquals("An empty table should correspond to the empty set of input rows",0,table.getHeight());
    return;
  }
  int trimmedWidth=Collections.max(transform(rows,new Function<List<String>,Integer>(){
    public Integer apply(    @Nullable List<String> input){
      int size=0;
      for (      String s : input) {
        if (!isNullOrEmpty(s)) {
          size++;
        }
      }
      return size;
    }
  }
));
  assertEquals("The height of the table should be equal to the number of input rows",rows.size(),table.getHeight());
  assertEquals("The trimmed width of the table should be equal to the max trimmed width of the input rows",trimmedWidth,table.getTrimmedWidth());
  for (int i=0; i < rows.size(); i++) {
    List<String> row=rows.get(i);
    int rowSize=0;
    for (int j=0; j < row.size(); j++) {
      String value=table.getValueAt(i,j);
      if (!isNullOrEmpty(row.get(j))) {
        assertNotNull("Not empty values should be added to the table",value);
        assertEquals("Not empty values should be equal to the corresponding values in the input",row.get(j),value);
        rowSize++;
      }
 else {
        assertNull("Empty or null values should be ignored in the table (until you set it intentionally)",value);
      }
    }
    assertEquals("Untrimmed width of a row should be exactly equal to the size of corresponding input row",row.size(),table.getRow(i).getSize());
    assertEquals("Table should be able to trim out empty values",rowSize,table.getRow(i).getTrimmedSize());
  }
}
 

Example 9

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

Source file: AndroidNativeDriver.java

  29 
vote

/** 
 * Creates a  {@code Function} to get screen rotation information. This{@code Function} should always be run on the main application thread.
 */
private Function<Void,Integer> doGetOrientation(){
  return new Function<Void,Integer>(){
    @Override public Integer apply(    Void ignoredArgument){
      Display display=checkHasCurrentActivity().getWindowManager().getDefaultDisplay();
      return display.getOrientation();
    }
  }
;
}
 

Example 10

From project Arecibo, under directory /collector/src/main/java/com/ning/arecibo/collector/persistent/.

Source file: EventReplayingLoadGenerator.java

  29 
vote

public void generateEventStream(){
  resetSecondCounter();
  replayIterationStartTime=new DateTime();
  for (int i=0; i < REPLAY_REPEAT_COUNT; i++) {
    final Collection<File> files=FileUtils.listFiles(new File(REPLAY_FILE_DIRECTORY),new String[]{"bin"},false);
    firstReplayEventTimestamp=null;
    resetSecondCounter();
    for (    final File file : Replayer.FILE_ORDERING.sortedCopy(files)) {
      try {
        log.info("About to read file %s",file.getAbsolutePath());
        replayer.read(file,new Function<HostSamplesForTimestamp,Void>(){
          @Override public Void apply(          HostSamplesForTimestamp hostSamples){
            if (shuttingDown.get()) {
              return null;
            }
            processSamples(hostSamples);
            return null;
          }
        }
);
      }
 catch (      IOException e) {
        log.warn(e,"Exception replaying file: %s",file.getAbsolutePath());
      }
      if (shuttingDown.get()) {
        log.info("Exiting generateEventStream() because shutdown is true");
      }
    }
    latestHostTimes.clear();
    replayIterationStartTime=lastEndTime.plusSeconds(30);
  }
}
 

Example 11

From project arquillian-graphene, under directory /graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/.

Source file: JSTarget.java

  29 
vote

@SuppressWarnings("unchecked") public Collection<JSTarget> getJSInterfaceDependencies(){
  if (dependecyAnnotation == null) {
    return (Collection<JSTarget>)Collections.EMPTY_LIST;
  }
  return Collections2.transform(Arrays.asList(dependecyAnnotation.interfaces()),new Function<Class<?>,JSTarget>(){
    @Override public JSTarget apply(    Class<?> input){
      return new JSTarget(input);
    }
  }
);
}
 

Example 12

From project artifactory-plugin, under directory /src/main/java/org/jfrog/hudson/.

Source file: ArtifactoryServer.java

  29 
vote

public List<VirtualRepository> getVirtualRepositoryKeys(){
  Credentials resolvingCredentials=getResolvingCredentials();
  ArtifactoryBuildInfoClient client=createArtifactoryClient(resolvingCredentials.getUsername(),resolvingCredentials.getPassword(),createProxyConfiguration(Jenkins.getInstance().proxy));
  try {
    List<String> keys=client.getVirtualRepositoryKeys();
    virtualRepositories=Lists.newArrayList(Lists.transform(keys,new Function<String,VirtualRepository>(){
      public VirtualRepository apply(      String from){
        return new VirtualRepository(from,from);
      }
    }
));
  }
 catch (  IOException e) {
    if (log.isLoggable(Level.FINE)) {
      log.log(Level.WARNING,"Could not obtain virtual repositories list from '" + url + "'",e);
    }
 else {
      log.log(Level.WARNING,"Could not obtain virtual repositories list from '" + url + "': "+ e.getMessage());
    }
    return Lists.newArrayList();
  }
 finally {
    client.shutdown();
  }
  virtualRepositories.add(0,new VirtualRepository("-- To use Artifactory for resolution select a virtual repository --",""));
  return virtualRepositories;
}
 

Example 13

From project astyanax, under directory /src/main/java/com/netflix/astyanax/connectionpool/.

Source file: JmxConnectionPoolMonitor.java

  29 
vote

@Override public String getActiveHosts(){
  return StringUtils.join(Lists.transform(pool.getActivePools(),new Function<HostConnectionPool<?>,String>(){
    @Override public String apply(    HostConnectionPool<?> host){
      return host.getHost().getName();
    }
  }
),",");
}
 

Example 14

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

Source file: ELBProvisioner.java

  29 
vote

private String ensureLbExists(ELBApi aws,AWSEC2Client ec2,String name,int from_port,int to_port,String protocol){
  LoadBalancer lb=aws.getLoadBalancerApi().get(name);
  if (lb != null) {
    return lb.getDnsName();
  }
 else {
    Set<AvailabilityZoneInfo> avail_zones=ec2.getAvailabilityZoneAndRegionServices().describeAvailabilityZonesInRegion(null);
    Listener listener=Listener.builder().protocol(Protocol.valueOf(protocol)).port(from_port).instancePort(to_port).build();
    Iterable<String> avail_zones_s=Iterables.transform(avail_zones,new Function<AvailabilityZoneInfo,String>(){
      @Override public String apply(      AvailabilityZoneInfo input){
        return input.getZone();
      }
    }
);
    return aws.getLoadBalancerApi().createLoadBalancerListeningInAvailabilityZones(name,listener,avail_zones_s);
  }
}
 

Example 15

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

Source file: ScriptRunner.java

  29 
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 16

From project azkaban, under directory /azkaban/src/java/azkaban/flow/.

Source file: GroupedFlow.java

  29 
vote

@Override public String getName(){
  return StringUtils.join(Iterables.transform(Arrays.asList(flows),new Function<Flow,String>(){
    @Override public String apply(    Flow flow){
      return flow.getName();
    }
  }
).iterator()," + ");
}
 

Example 17

From project BHT-FPA, under directory /mailer-common/de.bht.fpa.mail.common/src/de/bht/fpa/mail/s000000/common/mail/testdata/.

Source file: FileSystemTestDataProvider.java

  29 
vote

private Function<File,Message> toParsedXMLMessages(){
  return new Function<File,Message>(){
    @Override public Message apply(    File file){
      try {
        return JAXB.unmarshal(file,Message.class);
      }
 catch (      Exception e) {
        return null;
      }
    }
  }
;
}
 

Example 18

From project build-info, under directory /build-info-extractor-gradle/src/main/groovy/org/jfrog/gradle/plugin/artifactory/extractor/.

Source file: GradleBuildInfoExtractor.java

  29 
vote

private List<Artifact> calculateArtifacts(final Project project) throws Exception {
  Iterable<GradleDeployDetails> deployDetails=getProjectDeployDetails(project);
  List<Artifact> artifacts=newArrayList(transform(deployDetails,new Function<GradleDeployDetails,Artifact>(){
    public Artifact apply(    GradleDeployDetails from){
      PublishArtifactInfo publishArtifact=from.getPublishArtifact();
      DeployDetails deployDetails=from.getDeployDetails();
      String artifactPath=deployDetails.getArtifactPath();
      int index=artifactPath.lastIndexOf('/');
      return new ArtifactBuilder(artifactPath.substring(index + 1)).type(getTypeString(publishArtifact.getType(),publishArtifact.getClassifier(),publishArtifact.getExtension())).md5(deployDetails.getMd5()).sha1(deployDetails.getSha1()).build();
    }
  }
));
  return artifacts;
}
 

Example 19

From project c10n, under directory /core/src/ext/guice/java/c10n/guice/.

Source file: C10NModule.java

  29 
vote

private Set<URL> getPackageURLs(){
  Iterable<URL> packages=Iterables.concat(Iterables.transform(Arrays.asList(packagePrefixes),new Function<String,Set<URL>>(){
    @Override public Set<URL> apply(    String prefix){
      return ClasspathHelper.forPackage(prefix);
    }
  }
));
  return Sets.newHashSet(packages);
}
 

Example 20

From project candlepin, under directory /src/main/java/org/candlepin/service/impl/.

Source file: DefaultIdentityCertServiceAdapter.java

  29 
vote

@SuppressWarnings("unchecked") @Inject public DefaultIdentityCertServiceAdapter(PKIUtility pki,IdentityCertificateCurator identityCertCurator,KeyPairCurator keyPairCurator,CertificateSerialCurator serialCurator,@Named("endDateGenerator") Function endDtGen){
  this.pki=pki;
  this.idCertCurator=identityCertCurator;
  this.keyPairCurator=keyPairCurator;
  this.serialCurator=serialCurator;
  this.endDateGenerator=endDtGen;
}
 

Example 21

From project cdk, under directory /generator/src/test/java/org/richfaces/cdk/apt/.

Source file: TaskFactoryTest.java

  29 
vote

@Test public void testTask() throws Exception {
  expect(output.getFolders()).andReturn(null);
  processor.init((ProcessingEnvironment)anyObject());
  expectLastCall();
  expect(processor.getSupportedSourceVersion()).andReturn(SourceVersion.RELEASE_6);
  expect(processor.getSupportedAnnotationTypes()).andReturn(Collections.singleton("*"));
  expect(processor.getSupportedOptions()).andReturn(Collections.<String>emptySet());
  Capture<Set<? extends TypeElement>> capturedTypes=new Capture<Set<? extends TypeElement>>(CaptureType.FIRST);
  expect(processor.process(capture(capturedTypes),EasyMock.<RoundEnvironment>anyObject())).andReturn(true).times(2);
  replay(processor,output);
  CompilationTask task=factory.get();
  assertTrue(task.call());
  Set<? extends TypeElement> elements=capturedTypes.getValue();
  assertFalse(elements.isEmpty());
  Collection<String> typeNames=Collections2.transform(elements,new Function<TypeElement,String>(){
    @Override public String apply(    TypeElement e){
      return e.getSimpleName().toString();
    }
  }
);
  assertTrue(typeNames.contains("TestAnnotation2"));
  assertTrue(typeNames.contains("TestMethodAnnotation"));
  verify(processor,output);
}
 

Example 22

From project Cinch, under directory /src/com/palantir/ptoss/cinch/core/.

Source file: BindingContext.java

  29 
vote

private Map<String,ObjectFieldMethod> indexBindableProperties(Function<PropertyDescriptor,Method> methodFn) throws IntrospectionException {
  final Map<ObjectFieldMethod,String> getterOfms=Maps.newHashMap();
  for (  Field field : Sets.newHashSet(bindableModels.values())) {
    BeanInfo beanInfo=Introspector.getBeanInfo(field.getType());
    PropertyDescriptor[] props=beanInfo.getPropertyDescriptors();
    for (    PropertyDescriptor descriptor : props) {
      Method method=methodFn.apply(descriptor);
      if (method == null) {
        continue;
      }
      BindableModel model=getFieldObject(field,BindableModel.class);
      getterOfms.put(new ObjectFieldMethod(model,field,method),descriptor.getName());
    }
  }
  return dotIndex(getterOfms.keySet(),ObjectFieldMethod.TO_FIELD_NAME,Functions.forMap(getterOfms));
}
 

Example 23

From project closure-templates, under directory /java/tests/com/google/template/soy/shared/restricted/.

Source file: EscapingConventionsTest.java

  29 
vote

/** 
 * Create a lexer used by unittests to check that maliciously injected values can't violate the boundaries of string literals, comments, identifiers, etc. in template code.
 */
private static Function<String,List<String>> makeLexer(final String... regexParts){
  return new Function<String,List<String>>(){
    @Override public List<String> apply(    String src){
      ImmutableList.Builder<String> tokens=ImmutableList.builder();
      Pattern token=Pattern.compile(Joiner.on("").join(regexParts),Pattern.DOTALL);
      while (src.length() != 0) {
        Matcher m=token.matcher(src);
        if (m.find()) {
          tokens.add(m.group());
          src=src.substring(m.end());
        }
 else {
          throw new IllegalArgumentException("Cannot lex `" + src + "`");
        }
      }
      return tokens.build();
    }
  }
;
}
 

Example 24

From project cloud-management, under directory /src/main/java/com/proofpoint/cloudmanagement/service/.

Source file: JCloudsInstanceConnector.java

  29 
vote

public JCloudsInstanceConnector(final JCloudsConfig config){
  Preconditions.checkNotNull(config);
  this.name=config.getName();
  this.awsVpcSubnetId=config.getAwsVpcSubnetId();
  Properties overrides=new Properties();
  if (config.getLocation() != null) {
    overrides.setProperty(Constants.PROPERTY_ENDPOINT,config.getLocation());
  }
  overrides.setProperty(KeystoneProperties.CREDENTIAL_TYPE,CredentialType.PASSWORD_CREDENTIALS.toString());
  overrides.setProperty(KeystoneProperties.VERSION,"2.0");
  Set<Module> moduleOverrides=ImmutableSet.<Module>of(new JCloudsLoggingAdapterModule());
  ComputeServiceContext context=new ComputeServiceContextFactory().createContext(config.getApi(),config.getUser(),config.getSecret(),moduleOverrides,overrides);
  computeService=context.getComputeService();
  if (!config.getApi().equals("aws-ec2")) {
    Preconditions.checkState(any(computeService.listImages(),new Predicate<org.jclouds.compute.domain.Image>(){
      @Override public boolean apply(      @Nullable org.jclouds.compute.domain.Image image){
        return image.getId().endsWith(config.getDefaultImageId());
      }
    }
),"No image found for default image id [" + config.getDefaultImageId() + "] please verify that this image exists");
  }
  defaultImageId=config.getDefaultImageId();
  hardwareMap=Maps.uniqueIndex(computeService.listHardwareProfiles(),new Function<Hardware,String>(){
    @Override public String apply(    @Nullable Hardware hardware){
      return firstNonNull(hardware.getName(),hardware.getId());
    }
  }
);
  locationMap=Maps.uniqueIndex(computeService.listAssignableLocations(),new Function<Location,String>(){
    @Override public String apply(    @Nullable Location location){
      return location.getId();
    }
  }
);
  getAllInstances();
}
 

Example 25

From project clustermeister, under directory /api/src/main/java/com/github/nethad/clustermeister/api/impl/.

Source file: ConfigurationUtil.java

  29 
vote

/** 
 * This helps reading lists form the configuration that consist of  'named objects', e.g. (YAML): <pre> list: - name1: key1: value key2: value2 - name2: key1: value3 key3: value4 ... </pre> More specifically it reduces a List&lt;Map&lt;String, Map&lt;String,  String&gt;&gt;&gt; as produced by above example to a Map&lt;String,  Map&lt;String, String&gt;&gt; like this (Java syntax, referring to above  example): <pre> [ name1 => [  key1 => value, key2 => value2  ], name2 => [ key1 => value3, key3 => value4 ], ... ] </pre>
 * @param list the list to reduce.
 * @param errorMessage  Custom error message to add to exception in case of the  list not being convertible.
 * @return A map reduced as described above.
 * @throws IllegalArgumentException if the list can not be converted in this manner.
 */
public static Map<String,Map<String,String>> reduceObjectList(List<Object> list,String errorMessage){
  try {
    Map<String,Map<String,String>> result=Maps.newLinkedHashMap();
    List<Map<String,Map<String,String>>> mapList=Lists.transform(list,new Function<Object,Map<String,Map<String,String>>>(){
      @Override public Map apply(      Object input){
        return (Map<String,Map<String,String>>)input;
      }
    }
);
    for (    Map<String,Map<String,String>> map : mapList) {
      for (      Map.Entry<String,Map<String,String>> entry : map.entrySet()) {
        String key=entry.getKey();
        Map<String,String> value=entry.getValue();
        for (        Map.Entry<String,String> valueEntry : value.entrySet()) {
          Object valueValue=valueEntry.getValue();
          valueEntry.setValue(String.valueOf(valueValue));
        }
        result.put(key,value);
      }
    }
    return result;
  }
 catch (  ClassCastException ex) {
    throw new IllegalArgumentException(errorMessage,ex);
  }
}
 

Example 26

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

Source file: Tag.java

  29 
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 27

From project commons-j, under directory /src/main/java/nerds/antelax/commons/base/.

Source file: DecisionFunction.java

  29 
vote

/** 
 * Constructs a new  {@link Function} that delegates to other {@link Function}s based on the results of a  {@link Predicate}.
 * @param predicate the  {@link Predicate} on which to base the decision
 * @param successFunction the  {@link Function} to invoke if {@link #predicate} returns <code>true</code>
 * @param failureFunction the  {@link Function} to invoke if {@link #predicate} returns <code>false</code>
 */
DecisionFunction(final Predicate<F> predicate,final Function<F,T> successFunction,final Function<F,T> failureFunction){
  Preconditions.checkNotNull(predicate);
  Preconditions.checkNotNull(successFunction);
  Preconditions.checkNotNull(failureFunction);
  this.predicate=predicate;
  this.successFunction=successFunction;
  this.failureFunction=failureFunction;
}
 

Example 28

From project community-plugins, under directory /deployit-cli-plugins/dar-manifest-exporter/src/main/java/ext/deployit/community/cli/manifestexport/collect/.

Source file: Maps2.java

  29 
vote

/** 
 * Constructs a map with the given keys where values are generated by the given function. Supports duplicate and  {@code null} values, but{@code null} keys are <em>not</em> allowed.
 * @param < K > the type of the keys
 * @param < V > the type of the values
 * @param keys the keys to be included in the map. Keys must be non- <code>null</code>
 * @param valueFunction the function that produces values for the keys
 * @return a map containing the keys from the given set with values whichare generated from the keys
 * @see Maps#uniqueIndex(Iterable,Function)
 */
public static @Nonnull <K,V>Map<K,V> fromKeys(@Nonnull Set<K> keys,@Nonnull Function<? super K,V> valueFunction){
  Map<K,V> result=newHashMapWithExpectedSize(keys.size());
  for (  K key : keys) {
    result.put(checkNotNull(key),valueFunction.apply(key));
  }
  return result;
}
 

Example 29

From project components-ness-jackson, under directory /src/main/java/com/nesscomputing/jackson/.

Source file: SerializerBinderBuilderImpl.java

  29 
vote

private void buildSerializer(){
  binder.install(new AbstractModule(){
    @Override protected void configure(){
      if (String.class != type.getType()) {
        bindSerializers(Json.class,Smile.class);
      }
      bindSerializers(JsonSerializer.class,SmileSerializer.class);
    }
    @SuppressWarnings("unchecked") private void bindSerializers(    Class<? extends Annotation> jsonSerializerAnnotation,    Class<? extends Annotation> smileSerializerAnnotation){
      SerializerProvider<T,String> stringProvider=new StringSerializerProvider<T>(action);
      SerializerProvider<T,byte[]> bytesProviderSmile=new SmileSerializerProvider<T>(action);
      SerializerProvider<T,byte[]> bytesProviderJson=new JsonBytesSerializerProvider<T>(action);
      bind(keyFor(type,STRING_TYPE,jsonSerializerAnnotation)).toProvider(stringProvider).in(Scopes.SINGLETON);
      bind((Key<Function<? super T,String>>)Key.get(Types.newParameterizedType(Function.class,Types.supertypeOf(type.getType()),String.class),jsonSerializerAnnotation)).toProvider(stringProvider).in(Scopes.SINGLETON);
      bind(keyFor(type,BYTEA_TYPE,jsonSerializerAnnotation)).toProvider(bytesProviderJson).in(Scopes.SINGLETON);
      bind((Key<Function<? super T,byte[]>>)Key.get(Types.newParameterizedType(Function.class,Types.supertypeOf(type.getType()),byte[].class),jsonSerializerAnnotation)).toProvider(bytesProviderJson).in(Scopes.SINGLETON);
      bind(keyFor(type,BYTEA_TYPE,smileSerializerAnnotation)).toProvider(bytesProviderSmile).in(Scopes.SINGLETON);
      bind((Key<Function<? super T,byte[]>>)Key.get(Types.newParameterizedType(Function.class,Types.supertypeOf(type.getType()),byte[].class),smileSerializerAnnotation)).toProvider(bytesProviderSmile).in(Scopes.SINGLETON);
    }
  }
);
}
 

Example 30

From project core_4, under directory /impl/src/main/java/org/richfaces/resource/.

Source file: ResourceUtils.java

  29 
vote

static <V>Map<ResourceKey,V> readMappings(Function<Entry<String,String>,V> producer,String mappingFileName){
  Map<ResourceKey,V> result=Maps.newHashMap();
  for (  Entry<String,String> entry : PropertiesUtil.loadProperties(mappingFileName).entrySet()) {
    result.put(ResourceKey.create(entry.getKey()),producer.apply(entry));
  }
  result=Collections.unmodifiableMap(result);
  return result;
}
 

Example 31

From project cp-common-utils, under directory /src/com/clarkparsia/common/collect/.

Source file: Iterables2.java

  29 
vote

/** 
 * Returns an iterable that applies  {@code function} to each element of {@code fromIterable}. <p>The returned iterable's iterator supports  {@code remove()} if the provided iterator does. After a successful {@code remove()} call,{@code fromIterable} no longer contains the corresponding element.
 * @param fromIterable the iterable to transform
 * @param function the function to tranforms the iterable
 * @return the transformed iterable
 */
public static <F,T>Iterable<T> transform(final Iterable<F> fromIterable,final Function<? super F,? extends T> function){
  return new Iterable<T>(){
    public Iterator<T> iterator(){
      return Iterators2.transform(fromIterable.iterator(),function);
    }
  }
;
}
 

Example 32

From project cp-openrdf-utils, under directory /core/src/com/clarkparsia/openrdf/.

Source file: ExtRepository.java

  29 
vote

/** 
 * Return the superclasses of the given resource
 * @param theRes the resource
 * @return the resource's superclasses
 */
public Iterable<Resource> getSuperclasses(final Resource theRes){
  return Iterables.transform(new IterationIterable<Statement>(new Supplier<RepositoryResult<Statement>>(){
    public RepositoryResult<Statement> get(){
      return getStatements(theRes,RDFS.SUBCLASSOF,null);
    }
  }
),new Function<Statement,Resource>(){
    public Resource apply(    Statement theStmt){
      return (Resource)theStmt.getObject();
    }
  }
);
}
 

Example 33

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

Source file: Sort.java

  29 
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 34

From project culvert, under directory /culvert-accumulo/src/test/java/com/bah/culvert/accumulo/database/.

Source file: ITAccumuloAdapter.java

  29 
vote

/** 
 * Test all the adapters
 * @throws Throwable
 */
@Test public void testAdapters() throws Throwable {
  AccumuloDatabaseAdapter db=new AccumuloDatabaseAdapter();
  db.setConf(conf);
  DatabaseAdapterTestingUtility.testDatabaseAdapter(db);
  Function<String,Void> cleanup=new Function<String,Void>(){
    @Override public Void apply(    String input){
      ITAccumuloAdapter.this.cleanTable(input);
      return null;
    }
  }
;
  TableAdapterTestingUtility.testTableAdapter(db,cleanup);
  TableAdapterTestingUtility.testRemoteExecTableAdapter(db,1,cleanup);
}
 

Example 35

From project curator, under directory /curator-framework/src/main/java/com/netflix/curator/framework/imps/.

Source file: CuratorFrameworkImpl.java

  29 
vote

@Override public void close(){
  log.debug("Closing");
  if (state.compareAndSet(State.STARTED,State.STOPPED)) {
    listeners.forEach(new Function<CuratorListener,Void>(){
      @Override public Void apply(      CuratorListener listener){
        CuratorEvent event=new CuratorEventImpl(CuratorFrameworkImpl.this,CuratorEventType.CLOSING,0,null,null,null,null,null,null,null,null);
        try {
          listener.eventReceived(CuratorFrameworkImpl.this,event);
        }
 catch (        Exception e) {
          log.error("Exception while sending Closing event",e);
        }
        return null;
      }
    }
);
    listeners.clear();
    unhandledErrorListeners.clear();
    connectionStateManager.close();
    client.close();
    executorService.shutdownNow();
  }
}
 

Example 36

From project daleq, under directory /daleq-core/src/main/java/de/brands4friends/daleq/core/internal/builder/.

Source file: ImmutableRowData.java

  29 
vote

public ImmutableRowData(final List<FieldData> fields){
  this.fields=ImmutableList.copyOf(Preconditions.checkNotNull(fields));
  this.index=Maps.uniqueIndex(this.fields,new Function<FieldData,String>(){
    @Override public String apply(    @Nullable final FieldData field){
      if (field == null) {
        return null;
      }
      return field.getName();
    }
  }
);
}
 

Example 37

From project ddd-cqrs-sample, under directory /src/test/java/pl/com/bottega/acceptance/commons/agents/browser/.

Source file: BrowserAgentDriver.java

  29 
vote

private Function<WebDriver,WebElement> elementAppears(final String cssSelector){
  return new Function<WebDriver,WebElement>(){
    @Override public WebElement apply(    WebDriver driver){
      WebElement element=driver.findElement(By.cssSelector(cssSelector));
      if (element.isDisplayed()) {
        return element;
      }
      throw new NotFoundException();
    }
  }
;
}
 

Example 38

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

Source file: RF10888.java

  29 
vote

public Object getFilteredData(){
  @SuppressWarnings("unchecked") List<Person> resultList=(List<Person>)persistenceService.getEntityManager().createQuery("SELECT p from Person as p").getResultList();
  List<Predicate<Person>> predicates=Lists.newArrayList();
  if (!Strings.isNullOrEmpty(name)) {
    predicates.add(contains(name,new Function<Person,CharSequence>(){
      public CharSequence apply(      Person input){
        return input.getName();
      }
    }
));
  }
  if (!Strings.isNullOrEmpty(surname)) {
    predicates.add(contains(surname,new Function<Person,CharSequence>(){
      public CharSequence apply(      Person input){
        return input.getSurname();
      }
    }
));
  }
  if (!Strings.isNullOrEmpty(email)) {
    predicates.add(contains(email,new Function<Person,CharSequence>(){
      public CharSequence apply(      Person input){
        return input.getEmail();
      }
    }
));
  }
  return Lists.newArrayList(Collections2.filter(resultList,Predicates.and(predicates)));
}
 

Example 39

From project droid-fu, under directory /src/main/java/com/google/common/collect/.

Source file: CustomConcurrentHashMap.java

  29 
vote

/** 
 * Creates a  {@link ConcurrentMap}, backed by the given strategy, that supports atomic, on-demand computation of values.  {@link Map#get}returns the value corresponding to the given key, atomically computes it using the computer function passed to this builder, or waits for another thread to compute the value if necessary. Only one value will be computed for each key at a given time. <p> If an entry's value has not finished computing yet, query methods besides  {@link java.util.Map#get} return immediately as if an entrydoesn't exist. In other words, an entry isn't externally visible until the value's computation completes. <p> {@link Map#get} in the returned map implementation throws:<ul> <li> {@link NullPointerException} if the key is null or the computerreturns null</li> <li>or  {@link ComputationException} wrapping an exception thrown bythe computation</li> </ul> <p> <b>Note:</b> Callers of  {@code get()} <i>must</i> ensure that the keyargument is of type  {@code K}.  {@code Map.get()} takes {@code Object}, so the key type is not checked at compile time. Passing an object of a type other than  {@code K} can result in that object beingunsafely passed to the computer function as type  {@code K} not tomention the unsafe key being stored in the map.
 * @param strategy used to implement and manipulate the entries
 * @param computer used to compute values for keys
 * @param < K > the type of keys to be stored in the returned map
 * @param < V > the type of values to be stored in the returned map
 * @param < E > the type of internal entry to be stored in the returned map
 * @throws NullPointerException if strategy or computer is null
 */
public <K,V,E>ConcurrentMap<K,V> buildComputingMap(ComputingStrategy<K,V,E> strategy,Function<? super K,? extends V> computer){
  if (strategy == null) {
    throw new NullPointerException("strategy");
  }
  if (computer == null) {
    throw new NullPointerException("computer");
  }
  return new ComputingImpl<K,V,E>(strategy,this,computer);
}
 

Example 40

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

Source file: BrushTest.java

  29 
vote

private Iterable<String> styles(String... styles){
  return newArrayList(transform(asList(styles),new Function<String,String>(){
    public String apply(    String from){
      return style(from);
    }
  }
));
}