Example usage for java.util.concurrent TimeUnit DAYS

List of usage examples for java.util.concurrent TimeUnit DAYS

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit DAYS.

Prototype

TimeUnit DAYS

To view the source code for java.util.concurrent TimeUnit DAYS.

Click Source Link

Document

Time unit representing twenty four hours.

Usage

From source file:cloudeventbus.cli.Certs.java

private static String formatTime(long seconds) {
    final long days = seconds / TimeUnit.DAYS.toSeconds(1);
    seconds -= TimeUnit.DAYS.toSeconds(days);
    final long hours = seconds / TimeUnit.HOURS.toSeconds(1);
    seconds -= TimeUnit.HOURS.toSeconds(hours);
    final long minutes = seconds / TimeUnit.MINUTES.toSeconds(1);
    seconds -= TimeUnit.MINUTES.toSeconds(minutes);
    return String.format("%dd:%dh:%dm:%ds", days, hours, minutes, seconds);
}

From source file:com.sangupta.httptools.DownloadUrlCommand.java

/**
 * Terminate the thread pool/*from w w w  .  j  a v a  2s  .  c om*/
 * 
 * @param pool
 *            the thread pool to terminate
 */
private void shutdownAndAwaitTermination(ExecutorService pool) {
    pool.shutdown(); // Disable new tasks from being submitted
    try {
        // Wait a while for existing tasks to terminate
        if (!pool.awaitTermination(1, TimeUnit.DAYS)) {
            pool.shutdownNow(); // Cancel currently executing tasks

            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(60, TimeUnit.SECONDS))
                System.err.println("Pool did not terminate");
        }
    } catch (InterruptedException ie) {
        // (Re-)Cancel if current thread also interrupted
        pool.shutdownNow();
        // Preserve interrupt status
        Thread.currentThread().interrupt();
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.scheduler.quota.TestQuotaService.java

public void CheckProjectDailyCost(float used) throws IOException {

    Map<String, YarnProjectsDailyCost> hopYarnProjectsDailyCostList;

    LightWeightRequestHandler bomb;//from   w  w  w  .j a  v  a 2s  . c  o m
    bomb = new LightWeightRequestHandler(YARNOperationType.TEST) {
        @Override
        public Object performTask() throws IOException {
            connector.beginTransaction();
            connector.writeLock();

            YarnProjectsDailyCostDataAccess _pdcDA = (YarnProjectsDailyCostDataAccess) RMStorageFactory
                    .getDataAccess(YarnProjectsDailyCostDataAccess.class);
            Map<String, YarnProjectsDailyCost> hopYarnProjectsDailyCostList = _pdcDA.getAll();

            connector.commit();
            return hopYarnProjectsDailyCostList;
        }
    };

    hopYarnProjectsDailyCostList = (Map<String, YarnProjectsDailyCost>) bomb.handle();
    long _miliSec = System.currentTimeMillis();
    final long _day = TimeUnit.DAYS.convert(_miliSec, TimeUnit.MILLISECONDS);

    for (Map.Entry<String, YarnProjectsDailyCost> _ypdc : hopYarnProjectsDailyCostList.entrySet()) {
        Assert.assertTrue(_ypdc.getValue().getProjectName().equalsIgnoreCase("Project07"));
        Assert.assertTrue(_ypdc.getValue().getProjectUser().equalsIgnoreCase("rizvi"));
        Assert.assertEquals(_day, _ypdc.getValue().getDay());
        Assert.assertEquals(used, _ypdc.getValue().getCreditsUsed());

    }
}

From source file:uk.ac.cam.cl.dtg.segue.api.UsersFacade.java

/**
 * Construct an instance of the UsersFacade.
 *
 * @param properties/*from  w w  w .  jav a2 s .  co m*/
 *            - properties loader for the application
 * @param userManager
 *            - user manager for the application
 * @param logManager
 *            - so we can log interesting events.
 * @param statsManager
 *            - so we can view stats on interesting events.
 * @param userAssociationManager
 *            - so we can check permissions..
 * @param misuseMonitor
 *            - so we can check for misuse
 * @param emailPreferenceManager
 *            - so we can provide email preferences
 */
@Inject
public UsersFacade(final PropertiesLoader properties, final UserAccountManager userManager,
        final ILogManager logManager, final StatisticsManager statsManager,
        final UserAssociationManager userAssociationManager, final IMisuseMonitor misuseMonitor,
        final AbstractEmailPreferenceManager emailPreferenceManager,
        final AbstractUserPreferenceManager userPreferenceManager, final SchoolListReader schoolListReader) {
    super(properties, logManager);
    this.userManager = userManager;
    this.statsManager = statsManager;
    this.userAssociationManager = userAssociationManager;
    this.misuseMonitor = misuseMonitor;
    this.emailPreferenceManager = emailPreferenceManager;
    this.userPreferenceManager = userPreferenceManager;
    this.schoolListReader = schoolListReader;

    this.schoolOtherSupplier = Suppliers.memoizeWithExpiration(new Supplier<Set<School>>() {
        @Override
        public Set<School> get() {
            try {
                List<RegisteredUserDTO> users = userManager.findUsers(new RegisteredUserDTO());

                Set<School> schoolOthers = Sets.newHashSet();

                for (RegisteredUserDTO user : users) {
                    if (user.getSchoolOther() != null) {
                        School pseudoSchool = new School();
                        pseudoSchool.setUrn(Integer.toString(user.getSchoolOther().hashCode()));
                        pseudoSchool.setName(user.getSchoolOther());
                        pseudoSchool.setDataSource(School.SchoolDataSource.USER_ENTERED);
                        schoolOthers.add(pseudoSchool);
                    }
                }
                return schoolOthers;
            } catch (SegueDatabaseException e) {
                return null;
            }
        }
    }, 1, TimeUnit.DAYS);
}

From source file:org.codice.ddf.commands.catalog.CqlCommands.java

protected long getFilterStartTime() {
    if (lastSeconds > 0) {
        return filterCurrentTime - TimeUnit.SECONDS.toMillis(lastSeconds);
    } else if (lastMinutes > 0) {
        return filterCurrentTime - TimeUnit.MINUTES.toMillis(lastMinutes);
    } else if (lastHours > 0) {
        return filterCurrentTime - TimeUnit.HOURS.toMillis(lastHours);
    } else if (lastDays > 0) {
        return filterCurrentTime - TimeUnit.DAYS.toMillis(lastDays);
    } else if (lastWeeks > 0) {
        Calendar weeks = GregorianCalendar.getInstance();
        weeks.setTimeInMillis(filterCurrentTime);
        weeks.add(Calendar.WEEK_OF_YEAR, -1 * lastWeeks);
        return weeks.getTimeInMillis();
    } else if (lastMonths > 0) {
        Calendar months = GregorianCalendar.getInstance();
        months.setTimeInMillis(filterCurrentTime);
        months.add(Calendar.MONTH, -1 * lastMonths);
        return months.getTimeInMillis();
    } else {//from  ww w .  j  a v a2 s . com
        return 0;
    }
}

From source file:com.cloud.agent.Agent.java

public Agent(final IAgentShell shell, final int localAgentId, final ServerResource resource)
        throws ConfigurationException {
    _shell = shell;// w w w .j a v  a2s .  c o m
    _resource = resource;
    _link = null;

    resource.setAgentControl(this);

    final String value = _shell.getPersistentProperty(getResourceName(), "id");
    _id = value != null ? Long.parseLong(value) : null;
    s_logger.info("id is " + (_id != null ? _id : ""));

    final Map<String, Object> params = PropertiesUtil.toMap(_shell.getProperties());

    // merge with properties from command line to let resource access command line parameters
    for (final Map.Entry<String, Object> cmdLineProp : _shell.getCmdLineProperties().entrySet()) {
        params.put(cmdLineProp.getKey(), cmdLineProp.getValue());
    }

    if (!_resource.configure(getResourceName(), params)) {
        throw new ConfigurationException("Unable to configure " + _resource.getName());
    }

    final String host = _shell.getHost();
    _connection = new NioClient("Agent", host, _shell.getPort(), _shell.getWorkers(), this);

    // ((NioClient)_connection).setBindAddress(_shell.getPrivateIp());

    s_logger.debug("Adding shutdown hook");
    Runtime.getRuntime().addShutdownHook(new ShutdownThread(this));

    _ugentTaskPool = new ThreadPoolExecutor(shell.getPingRetries(), 2 * shell.getPingRetries(), 10,
            TimeUnit.MINUTES, new SynchronousQueue<Runnable>(), new NamedThreadFactory("UgentTask"));

    _executor = new ThreadPoolExecutor(_shell.getWorkers(), 5 * _shell.getWorkers(), 1, TimeUnit.DAYS,
            new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("agentRequest-Handler"));

    s_logger.info("Agent [id = " + (_id != null ? _id : "new") + " : type = " + getResourceName() + " : zone = "
            + _shell.getZone() + " : pod = " + _shell.getPod() + " : workers = " + _shell.getWorkers()
            + " : host = " + host + " : port = " + _shell.getPort());
}

From source file:com.techno.jay.codingcontests.Home.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    FirebaseApp.initializeApp(this);

    FontChangeCrawler fontChanger = new FontChangeCrawler(getAssets(), "fonts/ProductSans-Regular.ttf");
    fontChanger.replaceFonts((ViewGroup) this.findViewById(android.R.id.content));
    //==2) for fragment hoy to====
    //== fontChanger.replaceFonts((ViewGroup) this.getView());
    //===3) for adepterview and handlerview na use mate====
    //==convertView = inflater.inflate(R.layout.listitem, null);
    //==fontChanger.replaceFonts((ViewGroup)convertView);

    bp = new BillingProcessor(Home.this, Const.LICENSE_KEY, Home.this);
    /*bp.consumeAsync(inventory.getPurchase(SKU_GAS),
        mConsumeFinishedListener);*/
    bp.consumePurchase(Const.Product_Plan_Unlimitedversion);

    Toolbar toolbar = (Toolbar) this.findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*www.  jav a2  s.com*/

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setIcon(R.drawable.appicon);

    /*     if (Build.VERSION.SDK_INT >= 21) {
    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    window.setStatusBarColor(Color.parseColor("#1976D2"));
    window.setNavigationBarColor(Color.parseColor("#1976D2"));
         }*/

    sharepref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);

    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(
                android.Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[] { android.Manifest.permission.READ_PHONE_STATE },
                    PERMISSIONS_REQUEST_READ_PHONE_STATE);
        } else {
            getDeviceImei();
        }
    } else {
        getDeviceImei();
    }

    databaseReferenceUser = FirebaseDatabase.getInstance().getReference("Users");
    //databaseReferenceUser.keepSynced(true);

    token = FirebaseInstanceId.getInstance().getToken();

    SimpleDateFormat format_diffrent = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    Date now = new Date();
    date = format_diffrent.format(now);

    // creating connection detector class instance
    ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
    // get Internet status
    isInternetPresent = cd.isConnectingToInternet();
    if (isInternetPresent) {
        // Internet Connection is Present
        // make HTTP requests
        //refreshedToken = FirebaseInstanceId.getInstance().getToken();
        databaseReferenceUser.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // Get user value

                if (dataSnapshot.hasChild(str_IMEI)) {
                    String IMEI_no = dataSnapshot.child("IMEI").getValue(String.class);
                    String date_got = dataSnapshot.child("date").getValue(String.class);
                    Log.d("date got", date_got);
                    String status_got = dataSnapshot.child("status").getValue(String.class);

                    Toast.makeText(Home.this, "  Already registered. !   ", Toast.LENGTH_LONG).show();
                    SimpleDateFormat myFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

                    try {
                        Date date1 = myFormat.parse(date_got);
                        Date date2 = myFormat.parse(date);
                        long diff = date2.getTime() - date1.getTime();
                        System.out.println("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));

                        long days_count = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);

                        if (days_count > 10 && status_got.equalsIgnoreCase("inactive")) {
                            promptForUpgrade();
                        }

                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                //  Log.w("TAG", "getUser:onCancelled", databaseError.toException());
                // new Signup_async().execute();
            }
        });

    } else {

        Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), " Sorry! No Internet!!!",
                Snackbar.LENGTH_LONG);

        // Changing message text color
        snackbar.setActionTextColor(Color.BLUE);

        // Changing action button text color
        View sbView = snackbar.getView();
        TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
        textView.setTextColor(Color.YELLOW);
        snackbar.show();

        Toast.makeText(Home.this, "  No Internet Connection!!!.  ", Toast.LENGTH_LONG).show();

    }

    Set<String> set = sharepref.getStringSet("arraylist", null);
    List<String> sposers = new ArrayList<String>(set);

    String[] apossor_arry = new String[sposers.size()];
    apossor_arry = sposers.toArray(apossor_arry);

    FragmentTransaction tx;
    tx = getSupportFragmentManager().beginTransaction();
    tx.replace(R.id.frame, new MainHomeFragmentFirebase());
    tx.commit();

    searchView = (MaterialSearchView) findViewById(R.id.search_view);
    searchView.setVoiceSearch(false);
    searchView.setHint("Enter Coding website/technology");
    searchView.setCursorDrawable(R.drawable.custome_cursor);
    searchView.setSuggestions(apossor_arry);
    searchView.setEllipsize(true);

    searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            Snackbar.make(findViewById(android.R.id.content), "Query: " + query, Snackbar.LENGTH_LONG).show();
            Intent result = new Intent(Home.this, ResultContestLink.class);
            result.putExtra("query", query);

            startActivity(result);
            overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            //Do some magic
            return false;
        }
    });

    searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
        @Override
        public void onSearchViewShown() {
            //Do some magic
        }

        @Override
        public void onSearchViewClosed() {
            //Do some magic
        }
    });

    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle Toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close) {

        @Override
        public void onDrawerClosed(View drawerView) {
            // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
            super.onDrawerClosed(drawerView);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank

            super.onDrawerOpened(drawerView);
        }
    };
    //Setting the actionbarToggle to drawer layout
    drawer.setDrawerListener(Toggle);
    //calling sync state is necessay or else your hamburger icon wont show up
    Toggle.syncState();

    databaseReferenceEventData = FirebaseDatabase.getInstance().getReference("Contest").child("objects");
    databaseReferenceEventData.keepSynced(true);

    //Initializing NavigationView
    navigationView = (NavigationView) findViewById(R.id.nav_view);

    Menu m = navigationView.getMenu();
    for (int i = 0; i < m.size(); i++) {
        MenuItem mi = m.getItem(i);

        //for aapplying a font to subMenu ...
        SubMenu subMenu = mi.getSubMenu();
        if (subMenu != null && subMenu.size() > 0) {
            for (int j = 0; j < subMenu.size(); j++) {
                MenuItem subMenuItem = subMenu.getItem(j);
                applyFontToMenuItem(subMenuItem);
            }
        }

        //the method we have create in activity
        applyFontToMenuItem(mi);
    }

    View header = navigationView.getHeaderView(0);
    tv_total_sponsers = (TextView) header.findViewById(R.id.tv_total_sponsers);
    tv_total_contests = (TextView) header.findViewById(R.id.tv_total_contests);

    tv_total_sponsers.setText("Total Contests websites : " + sharepref.getString("totalsposor", "NA"));

    // navigationView.setNavigationItemSelectedListener(this);

    //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
    assert navigationView != null;
    navigationView.setCheckedItem(R.id.nav_home);
    navigationView.getMenu().getItem(0).setChecked(true);
    navigationView.setItemIconTintList(null);

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        // This method will trigger on item Click of navigation menu
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            navigationView.getMenu().getItem(0).setChecked(false);

            //Checking if the item is in checked state or not, if not make it in checked state
            if (activeMenuItem != null)
                activeMenuItem.setChecked(false);
            activeMenuItem = menuItem;
            menuItem.setChecked(true);
            //else menuItem.setChecked(true);

            //Closing drawer on item click
            drawer.closeDrawers();
            Fragment fragment = null;
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

            //Check to see which item was being clicked and perform appropriate action
            switch (menuItem.getItemId()) {

            //Replacing the main content with ContentFragment Which is our Inbox View;
            case R.id.nav_home:
                // Toast.makeText(getApplicationContext(),"Shop",Toast.LENGTH_SHORT).show();
                fragment = new MainHomeFragmentFirebase();
                break;

            case R.id.nav_longcompetition:

                fragment = new LongtermCompetition();
                break;
            case R.id.nav_exit:
                System.exit(0);
                getIntent().setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                break;
            case R.id.nav_running:
                // Toast.makeText(getApplicationContext(),"Shop",Toast.LENGTH_SHORT).show();
                fragment = new LiveContests();
                break;

            case R.id.nav_past:
                // Toast.makeText(getApplicationContext(),"Shop",Toast.LENGTH_SHORT).show();
                fragment = new CompletedContest();
                break;

            case R.id.nav_share:
                // Toast.makeText(getApplicationContext(),"Shop",Toast.LENGTH_SHORT).show();

                Intent intentshare = new Intent(Intent.ACTION_SEND);
                intentshare.setType("text/plain");
                intentshare.putExtra(Intent.EXTRA_TEXT,
                        "Best Competitive Programming news/reminder app for Coders.World wide coding competitions and hiring challenges.Solve the challenges and get chance to win awesome prizes and also hired by world famous MNCs(i.e AMAZON , IBM , intel , google , SAP many more...).\n\n\n"
                                + "https://play.google.com/store/apps/details?id=com.techno.jay.codingcontests&hl=en"
                                + "\n\n-developed by Technocrats Appware");
                startActivity(Intent.createChooser(intentshare, "Share"));

                break;
            case R.id.nav_feedback:
                final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
                try {
                    startActivity(
                            new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
                } catch (Exception e) {
                    // Log.d("TAG","Message ="+e);
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                            "https://play.google.com/store/apps/details?id=com.techno.jay.codingcontests&hl=en")));
                }
                break;

            case R.id.nav_hiring:
                // Toast.makeText(getApplicationContext(),"Shop",Toast.LENGTH_SHORT).show();
                Intent result = new Intent(Home.this, ResultContestLink.class);
                result.putExtra("query", "hiring");

                startActivity(result);
                overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                break;

            case R.id.nav_setting:
                Intent seting = new Intent(Home.this, Setting_app.class);
                startActivity(seting);
                overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                break;

            case R.id.nav_aboutus:
                // Toast.makeText(getApplicationContext(),"Shop",Toast.LENGTH_SHORT).show();
                fragment = new Aboutus();
                break;

            /*case R.id.nav_aboutus:
                // Toast.makeText(getApplicationContext(),"Shop",Toast.LENGTH_SHORT).show();
                fragment= new Aboutus_fragment();
                break;
                    
            case R.id.spam:
                Toast.makeText(getApplicationContext(),"Spam Selected",Toast.LENGTH_SHORT).show();
                return true;*/
            default:
                Toast.makeText(getApplicationContext(), "Coming Soon...", Toast.LENGTH_SHORT).show();

                break;

            }

            if (fragment != null) {

                fragmentTransaction.replace(R.id.frame, fragment);
                //getSupportFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();
                fragmentTransaction.addToBackStack(null).commit();

                getSupportActionBar().setTitle("Coding Contests");

            } else {
                menuItem.setChecked(false);
            }

            return true;
        }
    });

}

From source file:dk.dbc.opensearch.datadock.DatadockPool.java

/**
 * Shuts down the datadockPool. it waits for all current jobs to
 * finish before exiting./*from w  ww. j av a2 s .  c  o m*/
 *
 * @throws InterruptedException if the checkJobs or sleep call is interrupted (by kill or otherwise).
 */
public void shutdown() throws InterruptedException {
    log.trace("shutdown() called");

    threadpool.shutdown();
    threadpool.awaitTermination(1, TimeUnit.DAYS);

    // courtesy checkJobs - must be called in order to make sure that 
    // all jobs are finished correctly.
    this.checkJobs();

    log.trace("shutdown() called - leaving");
}

From source file:com.linkedin.pinot.core.startree.BaseStarTreeIndexTest.java

/**
 * Helper method to build the segment./*www. ja va 2  s .  c  om*/
 *
 * @param segmentDirName
 * @param segmentName
 * @throws Exception
 */
Schema buildSegment(String segmentDirName, String segmentName) throws Exception {
    int ROWS = (int) MathUtils.factorial(NUM_DIMENSIONS);
    Schema schema = new Schema();

    for (int i = 0; i < NUM_DIMENSIONS; i++) {
        String dimName = "d" + (i + 1);
        DimensionFieldSpec dimensionFieldSpec = new DimensionFieldSpec(dimName, FieldSpec.DataType.STRING,
                true);
        schema.addField(dimName, dimensionFieldSpec);
    }

    schema.setTimeFieldSpec(new TimeFieldSpec(TIME_COLUMN_NAME, FieldSpec.DataType.INT, TimeUnit.DAYS));
    for (int i = 0; i < NUM_METRICS; i++) {
        String metricName = "m" + (i + 1);
        MetricFieldSpec metricFieldSpec = new MetricFieldSpec(metricName, FieldSpec.DataType.INT);
        schema.addField(metricName, metricFieldSpec);
    }

    SegmentGeneratorConfig config = new SegmentGeneratorConfig(schema);
    config.setEnableStarTreeIndex(true);
    config.setOutDir(segmentDirName);
    config.setFormat(FileFormat.AVRO);
    config.setSegmentName(segmentName);

    final List<GenericRow> data = new ArrayList<>();
    for (int row = 0; row < ROWS; row++) {
        HashMap<String, Object> map = new HashMap<>();
        for (int i = 0; i < NUM_DIMENSIONS; i++) {
            String dimName = schema.getDimensionFieldSpecs().get(i).getName();
            map.put(dimName, dimName + "-v" + row % (NUM_DIMENSIONS - i));
        }

        Random random = new Random(_randomSeed);
        for (int i = 0; i < NUM_METRICS; i++) {
            String metName = schema.getMetricFieldSpecs().get(i).getName();
            map.put(metName, random.nextInt(METRIC_MAX_VALUE));
        }

        // Time column.
        map.put("daysSinceEpoch", row % 7);

        GenericRow genericRow = new GenericRow();
        genericRow.init(map);
        data.add(genericRow);
    }

    SegmentIndexCreationDriverImpl driver = new SegmentIndexCreationDriverImpl();
    RecordReader reader = createReader(schema, data);
    driver.init(config, reader);
    driver.build();

    LOGGER.info("Built segment {} at {}", segmentName, segmentDirName);
    return schema;
}

From source file:org.zenoss.zep.dao.impl.EventArchiveDaoImplIT.java

@Test
public void testIncomingFirstSeen() throws ZepException {
    long yesterday = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1);
    Event event = Event.newBuilder(createEvent()).setFirstSeenTime(yesterday).build();
    EventSummary summary = createArchive(event);
    assertEquals(yesterday, summary.getFirstSeenTime());
}