List of usage examples for com.google.common.base Function Function
Function
From source file:com.himanshu.utilities.guava.ListTransformDemo.java
public static void main(String[] args) { List<WrapperA> wrapperAList = new ArrayList<WrapperA>(); wrapperAList.add(new WrapperA("test 1")); wrapperAList.add(new WrapperA("test 2")); wrapperAList.add(new WrapperA("test 3")); Collection<WrapperB> wrapperBList = Collections2.transform(wrapperAList, new Function<WrapperA, WrapperB>() { @Override/* w w w .j a va 2 s . c om*/ public WrapperB apply(WrapperA arg0) { return new WrapperB(arg0.getName(), UUID.randomUUID().toString()); } }); System.out.println("WrapperA : " + wrapperAList); System.out.println("WrapperB : " + wrapperBList); }
From source file:org.example.guava.ListGroupExample.java
public static void main(String[] args) { List list = new ArrayList(); list.add(new Entry(20, "xiaosan1")); list.add(new Entry(18, "xiaosan2")); list.add(new Entry(18, "xiaosan3")); list.add(new Entry(20, "xiaosan4")); list.add(new Entry(18, "xiaosan5")); list.add(new Entry(20, "xiaosan6")); /*//from w ww . j av a 2s. c o m :?? */ Map<Integer, Entry> map = Multimaps.index(list, new Function<Entry, Integer>() { @Override public Integer apply(Entry input) { return input.getAge(); } }).asMap(); /* output: {20=[Entry{age=20,name=xiaosan1}, Entry{age=20,name=xiaosan4}, Entry{age=20,name=xiaosan6}], 18=[Entry{age=18,name=xiaosan2}, Entry{age=18,name=xiaosan3}, Entry{age=18,name=xiaosan5}]} */ System.out.println(map); }
From source file:kn.uni.gis.dataimport.FormatStrangeFlickrFormat.java
License:asdf
public static void main(String[] args) throws IOException { Iterable<String> readLines = filterNulls(concatLines(Files.readLines(new File(INPUT), Charsets.UTF_8))); // BufferedReader reader = Files // .newReader(new File(INPUT), Charsets.UTF_8); // 1,20,12/*from www.j a v a2 s. c o m*/ Files.write(Joiner.on("\n").skipNulls().join(Iterables.transform(readLines, new Function<String, String>() { @Override public String apply(String input) { // System.out.println(input); String[] split = input.split(";"); if (equalss(split[0], "524", "567", "2284", "2720")) { return null; } assertNumbers(split); String asdf = Joiner.on("\t").join(split[0], split[19], split[20], "Z", "M", split[3], ""); System.out.println(asdf); return asdf; } private void assertNumbers(String[] split) { if (!!!split[0].equals("Field1")) { Preconditions.checkArgument(Double.valueOf(split[19].replace(',', '.')) > 13, split[19] + Arrays.toString(split)); Preconditions.checkArgument(Double.valueOf(split[20].replace(',', '.')) > 52, split[20] + Arrays.toString(split)); } } })).replaceAll(",", "."), new File(OUTPUT), Charsets.UTF_8); }
From source file:net.sourceforge.docfetcher.enums.MsgMigrator.java
public static void main(String[] args) throws Exception { File oldTransDir = new File("dev/old-translations-from-1.0.3"); final String enPropName = "Resource.properties"; Properties oldEnProp = CharsetDetectorHelper.load(new File(oldTransDir, enPropName)); List<File> oldPropFiles = Arrays.asList(Util.listFiles(oldTransDir, new FilenameFilter() { public boolean accept(File dir, String name) { return !name.equals(enPropName); }// www.j av a 2 s .c o m })); final Map<Properties, File> propToFileMap = Maps.newHashMap(); List<Properties> oldProps = Lists.transform(oldPropFiles, new Function<File, Properties>() { public Properties apply(File file) { try { Properties prop = CharsetDetectorHelper.load(file); propToFileMap.put(prop, file); return prop; } catch (IOException e) { throw new RuntimeException(e); } }; }); StringBuilder sb0 = new StringBuilder(); for (Msg msg : Msg.values()) { String key = ConfLoader.convert(msg.name(), true); String value = ConfLoader.convert(msg.get(), false); String comments = msg.getComment(); if (!comments.isEmpty()) sb0.append("# " + comments + Util.LS); sb0.append(key + "=" + value); sb0.append(Util.LS); } File enOutFile = new File(Util.TEMP_DIR, enPropName); Files.write(sb0.toString(), enOutFile, Charsets.UTF_8); Util.println("File written: " + enOutFile.getPath()); for (Properties oldProp : oldProps) { StringBuilder sb = new StringBuilder(); for (Msg msg : Msg.values()) { String key = msg.name(); String enOldValue = oldEnProp.getProperty(key); if (enOldValue == null) // New key? continue; else if (!enOldValue.equals(msg.get())) // Changed value? continue; String value = oldProp.getProperty(key); if (value == null) value = enOldValue; else if (value.equals("$TODO$")) continue; key = ConfLoader.convert(key, true); value = ConfLoader.convert(value, false); sb.append(key + "=" + value); sb.append(Util.LS); } String filename = propToFileMap.get(oldProp).getName(); File outFile = new File(Util.TEMP_DIR, filename); Files.write(sb.toString(), outFile, Charsets.UTF_8); Util.println("File written: " + outFile.getPath()); } }
From source file:com.ondeck.datapipes.examples.SimpleFlowExample.java
public static void main(String[] args) throws FlowException { /**/* ww w . j ava2 s . c o m*/ * A Dataprovider step is required to provide input to a Flow */ DataProviderStep<String> dataProviderStep = new DataProviderStep<>(TypeToken.of(String.class)); /** * Step one is a FunctionStep that takes a String argument and converts it into an Integer. * The parent of this step is the dataProviderStep. */ FunctionStep<String, Integer> stepOne = new FunctionStep<>(new Function<String, Integer>() { @Override public Integer apply(String sourceValue) { List<Integer> list = Lists.newArrayList(); list.add(Integer.valueOf(sourceValue)); System.out.println("Step One : Input string is " + sourceValue + ". Converting to int."); return Integer.valueOf(sourceValue); } }, dataProviderStep, TypeToken.of(Integer.class)); /** * Step two is a FunctionStep that takes the result of step one and multiplies it by two. */ FunctionStep<Integer, Integer> stepTwo = new FunctionStep<>(new Function<Integer, Integer>() { @Override public Integer apply(Integer sourceValue) { System.out.println("Step Two : Multiplying input by 2"); return sourceValue * 2; } }, stepOne, TypeToken.of(Integer.class)); /** * Finally use an executor to execute the flow. */ String[] inputs = new String[] { "1", "50", "12" }; for (String i : inputs) { SimpleExecuteVisitor<Integer> executeVisitor = new SimpleExecuteVisitor<>(); executeVisitor.addInput(new TypeToken<String>() { }, i); Integer result = executeVisitor.execute(stepTwo); System.out.println("Result is " + result); System.out.println(); } }
From source file:com.ondeck.datapipes.examples.SimpleFlowMultiStepExample.java
public static void main(String[] args) throws FlowException { DataProviderStep<List<String>> dataProvider = new DataProviderStep<>(new TypeToken<List<String>>() { });//from w ww . j av a2 s. c o m /** * A MultiStep allow to apply the same treatment to all element of a collection. The step named sub defined below * converts a String to an Integer. Notice how the parent step of sub is null. */ FunctionStep<String, Integer> sub = new FunctionStep<>(new Function<String, Integer>() { @Override public Integer apply(String input) { System.out.println(Thread.currentThread().getName() + " executing multi step sub step"); return Integer.valueOf(input); } }, null, TypeToken.of(Integer.class)); /** * multi applies the treatment defined by sub to each element provided by the output of the parent step dataProvider. */ MultiStep<String, Integer, List<String>, ArrayList<Integer>> multi = new MultiStep<>(sub, dataProvider, new TypeToken<ArrayList<Integer>>() { }); /** * Finally use an ExecuteVisitor to execute the flow. Using a ParallelExecuteVisitor allows for parallel execution * of each substep of the multi step. */ ExecuteVisitor<ArrayList<Integer>> executeVisitor = new ParallelExecuteVisitor<>( Executors.newCachedThreadPool()); executeVisitor.addInput(new TypeToken<List<String>>() { }, Arrays.asList("1", "2", "3")); List<Integer> result = executeVisitor.execute(multi); System.out.println(result); }
From source file:com.cloudbees.api.Main.java
public static void main(String[] args) throws Exception { File beesCredentialsFile = new File(System.getProperty("user.home"), ".bees/bees.config"); Preconditions.checkArgument(beesCredentialsFile.exists(), "File %s not found", beesCredentialsFile); Properties beesCredentials = new Properties(); beesCredentials.load(new FileInputStream(beesCredentialsFile)); String apiUrl = "https://api.cloudbees.com/api"; String apiKey = beesCredentials.getProperty("bees.api.key"); String secret = beesCredentials.getProperty("bees.api.secret"); BeesClient client = new BeesClient(apiUrl, apiKey, secret, "xml", "1.0"); client.setVerbose(false);/*from w ww . j a va 2 s . c o m*/ URL databasesUrl = Thread.currentThread().getContextClassLoader().getResource("databases.txt"); Preconditions.checkNotNull(databasesUrl, "File 'databases.txt' NOT found in the classpath"); Collection<String> databaseNames; try { databaseNames = Sets.newTreeSet(Resources.readLines(databasesUrl, Charsets.ISO_8859_1)); } catch (Exception e) { throw Throwables.propagate(e); } databaseNames = Collections2.transform(databaseNames, new Function<String, String>() { @Nullable @Override public String apply(@Nullable String input) { // {host_db_create,<<"tco_q5rm">>,<<"TCO_q5rm">>, if (input == null) return null; if (input.startsWith("#")) return null; if (input.indexOf('"') == -1) { logger.warn("Skip invalid line {}", input); return null; } input = input.substring(input.indexOf('"') + 1); if (input.indexOf('"') == -1) { logger.warn("Skip invalid line {}", input); return null; } return input.substring(0, input.indexOf('"')); } }); databaseNames = Collections2.filter(databaseNames, new Predicate<String>() { @Override public boolean apply(@Nullable String s) { return !Strings.isNullOrEmpty(s); } }); Multimap<String, String> databasesByAccount = ArrayListMultimap.create(); Class.forName("com.mysql.jdbc.Driver"); for (String databaseName : databaseNames) { try { DatabaseInfo databaseInfo = client.databaseInfo(databaseName, true); databasesByAccount.put(databaseInfo.getOwner(), databaseInfo.getName()); logger.debug("Evaluate " + databaseInfo.getName()); if (true == false) { // Hibernate logger.info("Hibernate {}", databaseName); Map<String, String> params = new HashMap<String, String>(); params.put("database_id", databaseName); String url = client.getRequestURL("database.hibernate", params); String response = client.executeRequest(url); DatabaseInfoResponse apiResponse = (DatabaseInfoResponse) client.readResponse(response); logger.info("DB {} status: {}", apiResponse.getDatabaseInfo().getName(), apiResponse.getDatabaseInfo().getStatus()); } if (true == false) { // Hibernate logger.info("Activate {}", databaseName); Map<String, String> params = new HashMap<String, String>(); params.put("database_id", databaseName); String url = client.getRequestURL("database.activate", params); String response = client.executeRequest(url); DatabaseInfoResponse apiResponse = (DatabaseInfoResponse) client.readResponse(response); logger.info("DB {} status: {}", apiResponse.getDatabaseInfo().getName(), apiResponse.getDatabaseInfo().getStatus()); } String dbUrl = "jdbc:mysql://" + databaseInfo.getMaster() + "/" + databaseInfo.getName(); logger.info("Connect to {} user={}", dbUrl, databaseInfo.getUsername()); Connection cnn = DriverManager.getConnection(dbUrl, databaseInfo.getUsername(), databaseInfo.getPassword()); cnn.setAutoCommit(false); cnn.close(); } catch (Exception e) { logger.warn("Exception for {}", databaseName, e); } } System.out.println("OWNERS"); for (String account : databasesByAccount.keySet()) { System.out.println(account + ": " + Joiner.on(", ").join(databasesByAccount.get(account))); } }
From source file:samples.ExampleCreateIssuesAsynchronous.java
public static void main(String[] args) throws IOException { final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory(); final JiraRestClient restClient = factory.createWithBasicHttpAuthentication(jiraServerUri, "admin", "admin"); try {//w w w . j a v a2 s . co m final List<Promise<BasicIssue>> promises = Lists.newArrayList(); final IssueRestClient issueClient = restClient.getIssueClient(); System.out.println("Sending issue creation requests..."); for (int i = 0; i < 100; i++) { final String summary = "NewIssue#" + i; final IssueInput newIssue = new IssueInputBuilder("TST", 1L, summary).build(); System.out.println("\tCreating: " + summary); promises.add(issueClient.createIssue(newIssue)); } System.out.println("Collecting responses..."); final Iterable<BasicIssue> createdIssues = transform(promises, new Function<Promise<BasicIssue>, BasicIssue>() { @Override public BasicIssue apply(Promise<BasicIssue> promise) { return promise.claim(); } }); System.out.println("Created issues:\n" + Joiner.on("\n").join(createdIssues)); } finally { restClient.close(); } }
From source file:com.github.jsdossier.tools.WriteDeps.java
public static void main(String[] args) throws CmdLineException, IOException { Flags flags = new Flags(); CmdLineParser parser = new CmdLineParser(flags); parser.setUsageWidth(79);//from w ww .j a va2s . c o m parser.parseArgument(args); FileSystem fs = FileSystems.getDefault(); Path closure = fs.getPath(flags.closure); Path output = fs.getPath(flags.output); ImmutableList<SourceFile> depsFile = ImmutableList .of(SourceFile.fromFile(closure.resolve("deps.js").toString())); ImmutableList<SourceFile> sourceFiles = FluentIterable.from(flags.inputs) .transform(new Function<String, SourceFile>() { @Override public SourceFile apply(String input) { return SourceFile.fromFile(input); } }).toList(); DepsGenerator generator = new DepsGenerator(depsFile, sourceFiles, DepsGenerator.InclusionStrategy.DO_NOT_DUPLICATE, closure.toAbsolutePath().toString(), new PrintStreamErrorManager(System.err)); try (BufferedWriter writer = Files.newBufferedWriter(output, UTF_8)) { writer.write(generator.computeDependencyCalls()); writer.flush(); } }
From source file:com.spotify.folsom.LoadTestRunner.java
public static void main(final String[] args) throws Throwable { final BinaryMemcacheClient<String> client = new MemcacheClientBuilder<>(StringTranscoder.UTF8_INSTANCE) .withAddress("127.0.0.1").withMaxOutstandingRequests(100000).connectBinary(); final String[] keys = new String[10]; for (int i = 0; i < 10; i++) { keys[i] = "key" + i; }// www . j a va2 s .c o m final List<ListenableFuture<Boolean>> futures = Lists.newArrayList(); for (int r = 0; r < 100; r++) { for (final String keyProto : keys) { final String key = keyProto + ":" + r; final ListenableFuture<MemcacheStatus> setFuture = client.set(key, "value" + key, 100000); final ListenableFuture<String> getFuture = Utils.transform(setFuture, new AsyncFunction<MemcacheStatus, String>() { @Override public ListenableFuture<String> apply(final MemcacheStatus input) throws Exception { return client.get(key); } }); final ListenableFuture<String> deleteFuture = Utils.transform(getFuture, new AsyncFunction<String, String>() { @Override public ListenableFuture<String> apply(final String value) throws Exception { return Utils.transform(client.delete(key), new Function<MemcacheStatus, String>() { @Override public String apply(final MemcacheStatus input) { return value; } }); } }); final ListenableFuture<Boolean> assertFuture = Utils.transform(deleteFuture, new Function<String, Boolean>() { @Override public Boolean apply(final String input) { return ("value" + key).equals(input); } }); futures.add(assertFuture); } } final List<Boolean> asserts = Futures.allAsList(futures).get(); int failed = 0; for (final boolean b : asserts) { if (!b) { failed++; } } System.out.println(failed + " failed of " + asserts.size()); client.shutdown(); }