com.github.javafaker.Faker Java Examples

The following examples show how to use com.github.javafaker.Faker. 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: Fixtures.java    From uphold-sdk-android with MIT License 8 votes vote down vote up
public static Account loadAccount(HashMap<String, String> fields) {
    final Faker faker = new Faker();
    final HashMap<String, String> fakerFields = new HashMap<String, String>() {{
        put("currency", faker.lorem().fixedString(3));
        put("id", faker.lorem().fixedString(20));
        put("label", faker.lorem().fixedString(10));
        put("status", faker.lorem().fixedString(8));
        put("type", faker.lorem().fixedString(8));
    }};

    if (fields != null) {
        fakerFields.putAll(fields);
    }

    return new Account(fakerFields.get("currency"), fakerFields.get("id"), fakerFields.get("label"), fakerFields.get("status"), fakerFields.get("type"));
}
 
Example #2
Source File: DataGenerator.java    From kafka-streams-in-action with Apache License 2.0 7 votes vote down vote up
public static List<Purchase> generatePurchases(int number, int numberCustomers) {
    List<Purchase> purchases = new ArrayList<>();

    Faker faker = new Faker();
    List<Customer> customers = generateCustomers(numberCustomers);
    List<Store> stores = generateStores();

    Random random = new Random();
    for (int i = 0; i < number; i++) {
        String itemPurchased = faker.commerce().productName();
        int quantity = faker.number().numberBetween(1, 5);
        double price = Double.parseDouble(faker.commerce().price(4.00, 295.00));
        Date purchaseDate = timestampGenerator.get();

        Customer customer = customers.get(random.nextInt(numberCustomers));
        Store store = stores.get(random.nextInt(NUMBER_UNIQUE_STORES));

        Purchase purchase = Purchase.builder().creditCardNumber(customer.creditCardNumber).customerId(customer.customerId)
                .department(store.department).employeeId(store.employeeId).firstName(customer.firstName)
                .lastName(customer.lastName).itemPurchased(itemPurchased).quanity(quantity).price(price).purchaseDate(purchaseDate)
                .zipCode(store.zipCode).storeId(store.storeId).build();


        if (purchase.getDepartment().toLowerCase().contains("electronics")) {
            Purchase cafePurchase = generateCafePurchase(purchase, faker);
            purchases.add(cafePurchase);
        }
        purchases.add(purchase);
    }

    return purchases;

}
 
Example #3
Source File: Fixtures.java    From uphold-sdk-android with MIT License 6 votes vote down vote up
public static TransactionCardDepositRequest loadTransactionCardDepositRequest(HashMap<String, String> fields){
    final Faker faker = new Faker();
    final HashMap<String, String> fakerFields = new HashMap<String, String>() {{
        put("amount", faker.numerify("123456789"));
        put("currency", faker.lorem().fixedString(3));
        put("origin", faker.lorem().fixedString(8));
        put("securityCode", String.valueOf(faker.numerify("1234")));
    }};

    if (fields != null) {
        fakerFields.putAll(fields);
    }

    TransactionDenominationRequest transactionDenominationRequest = new TransactionDenominationRequest(fakerFields.get("amount"), fakerFields.get("currency"));

    return new TransactionCardDepositRequest(transactionDenominationRequest, fakerFields.get("origin"), fakerFields.get("securityCode"));
}
 
Example #4
Source File: BookInitializer.java    From blog-tutorials with MIT License 6 votes vote down vote up
@Override
public void run(String... args) throws Exception {
  log.info("Initializing books ...");
  Faker faker = new Faker();

  for (int i = 0; i < 42; i++) {

    Book book = new Book();
    book.setAuthor(faker.book().author());
    book.setIsbn(UUID.randomUUID().toString());
    book.setTitle(faker.book().title());

    bookRepository.save(book);
  }
  log.info("... finished initialization");
}
 
Example #5
Source File: GenerateRequestCommand.java    From jobson with Apache License 2.0 6 votes vote down vote up
@Override
protected void run(Bootstrap<ApplicationConfig> bootstrap, Namespace namespace, ApplicationConfig applicationConfig) throws Exception {
    final String specId = namespace.get(SPEC_NAME_ARG);
    final Path specsDir = Paths.get(applicationConfig.getJobSpecConfiguration().getDir());
    final Path specFile = specsDir.resolve(specId).resolve(SPEC_DIR_SPEC_FILENAME);

    if (specFile.toFile().exists()) {
        final JobSpec jobSpec = readYAML(specFile, JobSpec.class);
        final JobSpecId jobSpecId = new JobSpecId(specId);
        final String jobName = new Faker().lorem().sentence(5);
        final Map<JobExpectedInputId, JsonNode> generatedInputs = generateInputs(jobSpec);
        final APIJobRequest jobRequest =
                new APIJobRequest(jobSpecId, jobName, generatedInputs);

        System.out.println(toJSON(jobRequest));
        System.exit(0);
    } else {
        System.err.println(specFile + ": No such file");
        System.exit(1);
    }
}
 
Example #6
Source File: RandomDataEndpoint.java    From blog-tutorials with MIT License 6 votes vote down vote up
@GetMapping("/books")
public JsonNode getRandomBook() {

  Faker faker = new Faker(new Locale("en-US"));
  ArrayNode books = objectMapper.createArrayNode();

  for (int i = 0; i < 10; i++) {
    books.add(objectMapper.createObjectNode()
      .put("author", faker.book().author())
      .put("genre", faker.book().genre())
      .put("publisher", faker.book().publisher())
      .put("title", faker.book().title()));
  }

  return books;
}
 
Example #7
Source File: RandomDataEndpoint.java    From blog-tutorials with MIT License 6 votes vote down vote up
@GetMapping("/persons")
public JsonNode getRandomPersons() {

  Faker faker = new Faker();
  ArrayNode persons = objectMapper.createArrayNode();

  for (int i = 0; i < 10; i++) {
    persons.add(objectMapper.createObjectNode()
      .put("firstName", faker.name().firstName())
      .put("lastName", faker.name().lastName())
      .put("title", faker.name().title())
      .put("suffix", faker.name().suffix())
      .put("address", faker.address().streetAddress())
      .put("city", faker.address().cityName())
      .put("country", faker.address().country()));
  }

  return persons;
}
 
Example #8
Source File: DataGenerator.java    From kafka-streams-in-action with Apache License 2.0 6 votes vote down vote up
private static List<Store> generateStores() {
    List<Store> stores = new ArrayList<>(NUMBER_UNIQUE_STORES);
    Faker faker = new Faker();
    for (int i = 0; i < NUMBER_UNIQUE_STORES; i++) {
        String department = (i % 5 == 0) ? "Electronics" : faker.commerce().department();
        String employeeId = Long.toString(faker.number().randomNumber(5, false));
        String zipCode = faker.options().option("47197-9482", "97666", "113469", "334457");
        String storeId = Long.toString(faker.number().randomNumber(6, true));
        if (i + 1 == NUMBER_UNIQUE_STORES) {
            employeeId = "000000"; //Seeding id for employee security check
        }
        stores.add(new Store(employeeId, zipCode, storeId, department));
    }

    return stores;
}
 
Example #9
Source File: Fixtures.java    From uphold-sdk-android with MIT License 6 votes vote down vote up
public static ContactRequest loadContactRequest(HashMap<String, String> fields) {
    final Faker faker = new Faker();
    final HashMap<String, String> fakerFields = new HashMap<String, String>() {{
        put("addresses", String.format("%s,%s,%s", faker.numerify("123456789"), faker.numerify("123456789"), faker.numerify("123456789")));
        put("company", faker.name().name());
        put("emails", String.format("%s,%s,%s", faker.internet().emailAddress(), faker.internet().emailAddress(), faker.internet().emailAddress()));
        put("firstName", faker.name().firstName());
        put("lastName", faker.name().lastName());
    }};

    if (fields != null) {
        fakerFields.putAll(fields);
    }

    ArrayList<String> addresses = new ArrayList<>(Arrays.asList(fakerFields.get("addresses").split(",")));
    ArrayList<String> emails = new ArrayList<>(Arrays.asList(fakerFields.get("emails").split(",")));

    return new ContactRequest(addresses, fakerFields.get("company"), emails, fakerFields.get("firstName"), fakerFields.get("lastName"));
}
 
Example #10
Source File: DataGenerator.java    From kafka-streams-in-action with Apache License 2.0 6 votes vote down vote up
public static List<PublicTradedCompany> generatePublicTradedCompanies(int numberCompanies) {
    List<PublicTradedCompany> companies = new ArrayList<>();
    Faker faker = new Faker();
    Random random = new Random();
    for (int i = 0; i < numberCompanies; i++) {
        String name = faker.company().name();
        String stripped = name.replaceAll("[^A-Za-z]", "");
        int start = random.nextInt(stripped.length() - 4);
        String symbol = stripped.substring(start, start + 4);
        double volatility = Double.parseDouble(faker.options().option("0.01", "0.02", "0.03", "0.04", "0.05", "0.06", "0.07", "0.08", "0.09"));
        double lastSold = faker.number().randomDouble(2, 15, 150);
        String sector = faker.options().option("Energy", "Finance", "Technology", "Transportation", "Health Care");
        String industry = faker.options().option("Oil & Gas Production", "Coal Mining", "Commercial Banks", "Finance/Investors Services", "Computer Communications Equipment", "Software Consulting", "Aerospace", "Railroads", "Major Pharmaceuticals");
        companies.add(new PublicTradedCompany(volatility, lastSold, symbol, name, sector, industry));
    }

    return companies;

}
 
Example #11
Source File: Fixtures.java    From uphold-sdk-android with MIT License 6 votes vote down vote up
public static TransactionDepositRequest loadTransactionDepositRequest(HashMap<String, String> fields){
    final Faker faker = new Faker();
    final HashMap<String, String> fakerFields = new HashMap<String, String>() {{
        put("amount", faker.numerify("123456789"));
        put("currency", faker.lorem().fixedString(3));
        put("origin", faker.lorem().fixedString(8));
    }};

    if (fields != null) {
        fakerFields.putAll(fields);
    }

    TransactionDenominationRequest transactionDenominationRequest = new TransactionDenominationRequest(fakerFields.get("amount"), fakerFields.get("currency"));

    return new TransactionDepositRequest(transactionDenominationRequest, fakerFields.get("origin"));
}
 
Example #12
Source File: Fixtures.java    From uphold-sdk-android with MIT License 6 votes vote down vote up
public static TransactionTransferRequest loadTransactionTransferRequest(HashMap<String, String> fields){
    final Faker faker = new Faker();
    final HashMap<String, String> fakerFields = new HashMap<String, String>() {{
        put("amount", faker.numerify("123456789"));
        put("currency", faker.lorem().fixedString(3));
        put("destination", faker.internet().emailAddress());
        put("reference", faker.numerify("123456789"));
    }};

    if (fields != null) {
        fakerFields.putAll(fields);
    }

    TransactionDenominationRequest transactionDenominationRequest = new TransactionDenominationRequest(fakerFields.get("amount"), fakerFields.get("currency"));

    return new TransactionTransferRequest(transactionDenominationRequest, fakerFields.get("destination"), fakerFields.get("reference"));
}
 
Example #13
Source File: DataGenerator.java    From kafka-streams-in-action with Apache License 2.0 6 votes vote down vote up
public static List<String> generateRandomText() {
    List<String> phrases = new ArrayList<>(NUMBER_TEXT_STATEMENTS);
    Faker faker = new Faker();

    for (int i = 0; i < NUMBER_TEXT_STATEMENTS; i++) {
        ChuckNorris chuckNorris = faker.chuckNorris();
        phrases.add(chuckNorris.fact());
    }
    return phrases;
}
 
Example #14
Source File: LoadDataResource.java    From microservice-with-jwt-and-microprofile with Apache License 2.0 6 votes vote down vote up
@POST
public void load() {
    final Faker faker = new Faker(Locale.ENGLISH);
    final Random random = new Random(System.nanoTime());

    for (int i = 0 ; i < (5 + random.nextInt(20)) ; i++) {
        addComments(
                moviesBean.addMovie(
                        new Movie(
                                faker.book().title(),
                                faker.book().author(),
                                faker.book().genre(),
                                random.nextInt(10),
                                1960 + random.nextInt(50))),random.nextInt(100));
    }

}
 
Example #15
Source File: JavaFakerUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenJavaFaker_whenAddressObjectCalled_checkValidAddressInfoGiven() throws Exception {

    Faker faker = new Faker();

    String streetName = faker.address()
        .streetName();
    String number = faker.address()
        .buildingNumber();
    String city = faker.address()
        .city();
    String country = faker.address()
        .country();

    System.out.println(String.format("%s\n%s\n%s\n%s", number, streetName, city, country));

}
 
Example #16
Source File: JavaFakerUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenJavaFakersWithDifferentLocals_checkZipCodesMatchRegex() throws Exception {

    Faker ukFaker = new Faker(new Locale("en-GB"));
    Faker usFaker = new Faker(new Locale("en-US"));

    System.out.println(String.format("American zipcode: %s", usFaker.address()
        .zipCode()));
    System.out.println(String.format("British postcode: %s", ukFaker.address()
        .zipCode()));

    Pattern ukPattern = Pattern.compile("([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\\s?[0-9][A-Za-z]{2})");
    Matcher ukMatcher = ukPattern.matcher(ukFaker.address()
        .zipCode());

    assertTrue(ukMatcher.find());

    Matcher usMatcher = Pattern.compile("^\\d{5}(?:[-\\s]\\d{4})?$")
        .matcher(usFaker.address()
            .zipCode());

    assertTrue(usMatcher.find());

}
 
Example #17
Source File: WanServer.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
private void createCustomers(CustomerRepository repository) {
	Faker faker = new Faker();
	Name fakerName = faker.name();
	Internet fakerInternet = faker.internet();
	LongStream.range(0, 300).forEach(index -> repository.save(new Customer(index,
			new EmailAddress(fakerInternet.emailAddress()), fakerName.firstName(), fakerName.lastName())));
}
 
Example #18
Source File: StringArrayExpectedInput.java    From jobson with Apache License 2.0 5 votes vote down vote up
@Override
public StringArrayInput generateExampleInput() {
    final Faker f = new Faker();

    final List<String> items =
            Stream.generate(() -> f.lorem().fixedString(7))
                    .limit(4)
                    .collect(toList());

    return new StringArrayInput(items);
}
 
Example #19
Source File: Fixtures.java    From uphold-sdk-android with MIT License 5 votes vote down vote up
public static DocumentRequest loadDocumentRequest(HashMap<String, String> fields) {
    final Faker faker = new Faker();
    final HashMap<String, String> fakerFields = new HashMap<String, String>() {{
        put("type", faker.lorem().fixedString(5));
        put("value", faker.lorem().fixedString(5));
    }};

    if (fields != null) {
        fakerFields.putAll(fields);
    }

    return new DocumentRequest(fakerFields.get("type"), fakerFields.get("value"));
}
 
Example #20
Source File: WanServerConfig.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
@Bean(name = "DiskStore")
DiskStoreFactoryBean diskStore(GemFireCache gemFireCache, Faker faker) throws IOException {
	DiskStoreFactoryBean diskStoreFactoryBean = new DiskStoreFactoryBean();
	File tempDirectory = File.createTempFile(faker.name().firstName(), faker.name().firstName());
	tempDirectory.delete();
	tempDirectory.mkdirs();
	tempDirectory.deleteOnExit();
	DiskStoreFactoryBean.DiskDir[] diskDirs = { new DiskStoreFactoryBean.DiskDir(tempDirectory.getAbsolutePath()) };
	diskStoreFactoryBean.setDiskDirs(Arrays.asList(diskDirs));
	diskStoreFactoryBean.setCache(gemFireCache);
	return diskStoreFactoryBean;
}
 
Example #21
Source File: RedisCacheTest.java    From shiro-redis with MIT License 5 votes vote down vote up
private void scaffold() {
    RedisManager redisManager = scaffoldStandaloneRedisManager();
    prefix = scaffoldPrefix();
    redisCache = scaffoldRedisCache(redisManager, new StringSerializer(), new ObjectSerializer(), prefix, NumberUtils.toInt(properties.getProperty("cacheManager.expire")), RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME);
    redisCacheWithPrincipalIdFieldName = scaffoldRedisCache(redisManager, new StringSerializer(), new ObjectSerializer(), prefix, NumberUtils.toInt(properties.getProperty("cacheManager.expire")), properties.getProperty("cacheManager.principalIdFieldName"));
    redisCacheWithEmptyPrincipalIdFieldName = scaffoldRedisCache(redisManager, new StringSerializer(), new ObjectSerializer(), prefix, NumberUtils.toInt(properties.getProperty("cacheManager.expire")), "");
    redisCacheWithStrings = scaffoldRedisCache(redisManager, new StringSerializer(), new ObjectSerializer(), prefix, NumberUtils.toInt(properties.getProperty("cacheManager.expire")), properties.getProperty("cacheManager.principalIdFieldName"));
    user1 = scaffoldAuthKey(scaffoldUser());
    user2 = scaffoldAuthKey(scaffoldUser());
    user3 = scaffoldAuthKey(scaffoldUser());
    user4 = new SimplePrincipalCollection(Faker.instance().gameOfThrones().character(), Faker.instance().gameOfThrones().city());
    users1_2_3 = scaffoldKeys(user1, user2, user3);
}
 
Example #22
Source File: token-generation-server.7.x.java    From api-snippets with MIT License 5 votes vote down vote up
public static void main(String[] args) {
  // Serve static files from src/main/resources/public
  staticFileLocation("/public");

  String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
  String API_KEY = System.getenv("TWILIO_API_KEY");
  String API_SECRET = System.getenv("TWILIO_API_SECRET");

  String TWILIO_CONFIGURATION_SID = System.getenv("TWILIO_CONFIGURATION_SID");

  // Create a Faker instance to generate a random username for the connecting user
  Faker faker = new Faker();

  // Create an access token using our Twilio credentials
  get("/token", "application/json", (request, response) -> {
    // Generate a random username for the connecting client
    String identity =
        faker.name().firstName() + faker.name().lastName() + faker.address().zipCode();

    // Create Video grant
    VideoGrant grant =
        new VideoGrant().setConfigurationProfileSid(TWILIO_CONFIGURATION_SID);

    // Create access token
    AccessToken token = new AccessToken.Builder(ACCOUNT_SID, API_KEY, API_SECRET)
        .identity(identity)
        .grant(grant)
        .build();

    // create JSON response payload
    HashMap<String, String> json = new HashMap<String, String>();
    json.put("identity", identity);
    json.put("token", token.toJwt());

    // Render JSON response
    Gson gson = new Gson();
    return gson.toJson(json);
  });
}
 
Example #23
Source File: token-generation-server.7.x.java    From api-snippets with MIT License 5 votes vote down vote up
public static void main(String[] args) {
  // Serve static files from src/main/resources/public
  staticFileLocation("/public");

  final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
  final String API_KEY = System.getenv("TWILIO_API_KEY");
  final String API_SECRET = System.getenv("TWILIO_API_SECRET");

  final String TWILIO_CONFIGURATION_SID = System.getenv("TWILIO_CONFIGURATION_SID");

  // Create a Faker instance to generate a random username for the connecting user
  final Faker faker = new Faker();

  // Create an access token using our Twilio credentials
  get("/token", "application/json", (request, response) -> {
    // Generate a random username for the connecting client
    final String identity = faker.name().firstName() + faker.name().lastName() + faker.address().zipCode();

    // Create Twilio Video grant
    final VideoGrant grant = new VideoGrant().setConfigurationProfileSid(TWILIO_CONFIGURATION_SID);

    // Create access token
    final AccessToken token = new AccessToken.Builder(ACCOUNT_SID, API_KEY, API_SECRET)
        .identity(identity)
        .grant(grant)
        .build();

    // create JSON response payload
    final HashMap<String, String> json = new HashMap<String, String>();
    json.put("identity", identity);
    json.put("token", token.toJwt());

    // Render JSON response
    final Gson gson = new Gson();
    return gson.toJson(json);
  });
}
 
Example #24
Source File: LoadData.java    From janusgraph_tutorial with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the graph connection.
 *
 * @param configFile
 */
public LoadData(String configFile) {
  graph = JanusGraphFactory.open(configFile);
  faker = new Faker();

  Calendar cal = Calendar.getInstance();
  cal.add(Calendar.MONTH, -1);
  oneMonthAgo = cal.getTime();
}
 
Example #25
Source File: CreateSupernodes.java    From janusgraph_tutorial with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the graph connection.
 *
 * @param configFile
 */
public CreateSupernodes(String configFile) throws Exception {
  graph = JanusGraphFactory.open(configFile);
  faker = new Faker();
  queryRunner = new QueryRunner(graph.traversal(), "test");

  Calendar cal = Calendar.getInstance();
  cal.add(Calendar.YEAR, -1);
  oneYearAgo = cal.getTime();
}
 
Example #26
Source File: JavaFakerUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenJavaFakersWithSameSeed_whenNameCalled_CheckSameName() throws Exception {

    Faker faker1 = new Faker(new Random(24));
    Faker faker2 = new Faker(new Random(24));

    assertEquals(faker1.name()
        .firstName(),
        faker2.name()
            .firstName());
}
 
Example #27
Source File: BookRepository.java    From tutorials with MIT License 5 votes vote down vote up
@PostConstruct
public void init() {
    Faker faker = new Faker(Locale.ENGLISH);
    final com.github.javafaker.Book book = faker.book();
    this.items = IntStream.range(1, faker.random()
        .nextInt(10, 20))
        .mapToObj(i -> new Book(i, book.title(), book.author(), book.genre()))
        .collect(Collectors.toList());

}
 
Example #28
Source File: DataGenerator.java    From kafka-streams-in-action with Apache License 2.0 5 votes vote down vote up
private static Purchase generateCafePurchase(Purchase purchase, Faker faker) {
    Date date = purchase.getPurchaseDate();
    Instant adjusted = date.toInstant().minus(faker.number().numberBetween(5, 18), ChronoUnit.MINUTES);
    Date cafeDate = Date.from(adjusted);

    return Purchase.builder(purchase).department("Coffee")
            .itemPurchased(faker.options().option("Mocha", "Mild Roast", "Red-Eye", "Dark Roast"))
            .price(Double.parseDouble(faker.commerce().price(3.00, 6.00))).quanity(1).purchaseDate(cafeDate).build();

}
 
Example #29
Source File: LoadDataResource.java    From microservice-with-jwt-and-microprofile with Apache License 2.0 5 votes vote down vote up
private void addComments(final Movie movie, final int nbComments) {

        final Faker faker = new Faker(Locale.ENGLISH);

        for (int i = 0; i < nbComments; i++) {
            final Comment comment = new Comment();
            comment.setTimestamp(faker.date().past(300, TimeUnit.DAYS));
            comment.setAuthor(faker.name().fullName());
            comment.setEmail(faker.internet().emailAddress());
            comment.setComment(faker.chuckNorris().fact());

            moviesBean.addCommentToMovie(movie.getId(), comment);
        }
    }
 
Example #30
Source File: DataGenerator.java    From kafka-streams-in-action with Apache License 2.0 5 votes vote down vote up
public static List<String> generateFinancialNews() {
    List<String> news = new ArrayList<>(9);
    Faker faker = new Faker();
    for (int i = 0; i < 9; i++) {
        news.add(faker.company().bs());
    }
    return news;
}