Example usage for java.lang Runtime freeMemory

List of usage examples for java.lang Runtime freeMemory

Introduction

In this page you can find the example usage for java.lang Runtime freeMemory.

Prototype

public native long freeMemory();

Source Link

Document

Returns the amount of free memory in the Java Virtual Machine.

Usage

From source file:com.github.lpezet.antiope.metrics.aws.MachineMetricFactory.java

private void addMemoryMetrics(List<MetricDatum> pTargetList, Set<MachineMetric> pCustomSet) {
    Runtime rt = Runtime.getRuntime();
    long oTotalMem = rt.totalMemory();
    long oFreeMem = rt.freeMemory();
    long oUsedMem = oTotalMem - oFreeMem;
    long oSpareMem = rt.maxMemory() - oUsedMem;
    List<Long> oValues = Arrays.asList(oTotalMem, oFreeMem, oUsedMem, oSpareMem);
    MetricValues oMetricValues = memoryMetricValues(pCustomSet, oValues);
    addMetrics(pTargetList, oMetricValues, StandardUnit.Bytes);
}

From source file:ffx.HeadlessMain.java

/**
 * Complete initializations./* w  w w.  j  ava 2 s.com*/
 *
 * @param commandLineFile a {@link java.io.File} object.
 * @param argList a {@link java.util.List} object.
 * @param logHandler a {@link ffx.ui.LogHandler} object.
 */
public HeadlessMain(File commandLineFile, List<String> argList, LogHandler logHandler) {
    // Start a timer.
    stopWatch.start();

    // Construct the MainPanel, set it's LogHandler, and initialize then it.
    mainPanel = new MainPanel();
    logHandler.setMainPanel(mainPanel);
    mainPanel.initialize();

    // Open the supplied script file.
    if (commandLineFile != null) {
        if (!commandLineFile.exists()) {
            /**
             * See if the commandLineFile is an embedded script.
             */
            String name = commandLineFile.getName();
            name = name.replace('.', '/');
            String pathName = "ffx/scripts/" + name;
            ClassLoader loader = getClass().getClassLoader();
            URL embeddedScript = loader.getResource(pathName + ".ffx");
            if (embeddedScript == null) {
                embeddedScript = loader.getResource(pathName + ".groovy");
            }
            if (embeddedScript != null) {
                try {
                    commandLineFile = new File(FFXClassLoader.copyInputStreamToTmpFile(
                            embeddedScript.openStream(), commandLineFile.getName(), ".ffx"));
                } catch (Exception e) {
                    logger.warning("Exception extracting embedded script " + embeddedScript.toString() + "\n"
                            + e.toString());
                }
            }
        }
        if (commandLineFile.exists()) {
            mainPanel.getModelingShell().setArgList(argList);
            mainPanel.open(commandLineFile, null);
        } else {
            logger.warning(format("%s was not found.", commandLineFile.toString()));
        }
    }

    /**
     * Print start-up information.
     */
    if (logger.isLoggable(Level.FINE)) {
        StringBuilder sb = new StringBuilder();
        sb.append(format("\n Start-up Time (msec): %s.", stopWatch.getTime()));
        Runtime runtime = Runtime.getRuntime();
        runtime.runFinalization();
        runtime.gc();
        long occupiedMemory = runtime.totalMemory() - runtime.freeMemory();
        long KB = 1024;
        sb.append(format("\n In-Use Memory   (Kb): %d", occupiedMemory / KB));
        sb.append(format("\n Free Memory     (Kb): %d", runtime.freeMemory() / KB));
        sb.append(format("\n Total Memory    (Kb): %d", runtime.totalMemory() / KB));
        logger.fine(sb.toString());
    }
}

From source file:org.apache.shindig.social.opensocial.util.JsonConverterPerformancePerf.java

public void testToJsonLibOnInheritedClassInput() throws Exception {
    SpecialPerson[] spa = new SpecialPerson[TEST_SIZE];
    SpecialPerson[] sparesult = new SpecialPerson[TEST_SIZE];
    Runtime r = Runtime.getRuntime();
    r.gc();//w  w  w.ja va2 s .  c  o  m
    long personStart = r.totalMemory() - r.freeMemory();
    for (int i = 0; i < TEST_SIZE; i++) {
        spa[i] = new SpecialPerson(String.valueOf(i), "robot", "nonsense");
    }
    long personEnd = r.totalMemory() - r.freeMemory();

    String[] serializeOutput = new String[TEST_SIZE];
    r.gc();
    for (int i = 0; i < TEST_SIZE; i++) {

        serializeOutput[i] = beanJsonLibConverter.convertToString(spa[i]);
    }

    r.gc();
    long memstart = r.totalMemory() - r.freeMemory();
    long startInput = System.currentTimeMillis();
    for (int i = 0; i < TEST_SIZE; i++) {
        sparesult[i] = beanJsonLibConverter.convertToObject(serializeOutput[i], SpecialPerson.class);
    }
    long endInput = System.currentTimeMillis();
    long memend = r.totalMemory() - r.freeMemory();

    log.info("SF JSON Lib Input " + average(startInput, endInput, TEST_SIZE) + " ms/conversion, "
            + (average(memstart, memend, TEST_SIZE) - average(personStart, personEnd, TEST_SIZE))
            + " heap bytes/conversion, person object consumed on average "
            + average(personStart, personEnd, TEST_SIZE));
}

From source file:org.apache.shindig.social.opensocial.util.JsonConverterPerformancePerf.java

public void XtestToJsonOnInheritedClassInput() throws Exception {
    SpecialPerson[] spa = new SpecialPerson[TEST_SIZE];
    SpecialPerson[] sparesult = new SpecialPerson[TEST_SIZE];
    Runtime r = Runtime.getRuntime();
    r.gc();//from w  ww  .  jav a2s .c o  m
    long personStart = r.totalMemory() - r.freeMemory();
    for (int i = 0; i < TEST_SIZE; i++) {
        spa[i] = new SpecialPerson(String.valueOf(i), "robot", "nonsense");
    }
    long personEnd = r.totalMemory() - r.freeMemory();

    String[] serializeOutput = new String[TEST_SIZE];
    r.gc();
    for (int i = 0; i < TEST_SIZE; i++) {

        serializeOutput[i] = beanJsonConverter.convertToString(spa[i]);
    }

    r.gc();
    long memstart = r.totalMemory() - r.freeMemory();
    long startInput = System.currentTimeMillis();

    for (int i = 0; i < TEST_SIZE; i++) {
        sparesult[i] = beanJsonConverter.convertToObject(serializeOutput[i], SpecialPerson.class);
    }
    long endInput = System.currentTimeMillis();
    long memend = r.totalMemory() - r.freeMemory();

    log.info("SF JSON Lib Input " + average(startInput, endInput, TEST_SIZE) + " ms/conversion, "
            + (average(memstart, memend, TEST_SIZE) - average(personStart, personEnd, TEST_SIZE))
            + " heap bytes/conversion, person object consumed on average "
            + average(personStart, personEnd, TEST_SIZE));
}

From source file:org.apache.shindig.social.opensocial.util.JsonConverterPerformancePerf.java

public void testToJsonLibOnInheritedClassOutput() throws Exception {
    SpecialPerson[] spa = new SpecialPerson[TEST_SIZE];
    for (int i = 0; i < TEST_SIZE; i++) {
        spa[i] = new SpecialPerson(String.valueOf(i), "robot", "nonsense");
    }//from  w w w. j a  v  a  2 s .  c o  m
    Runtime r = Runtime.getRuntime();
    r.gc();
    long memstart = r.totalMemory() - r.freeMemory();
    long startOutput = System.currentTimeMillis();
    String[] output = new String[TEST_SIZE];
    for (int i = 0; i < TEST_SIZE; i++) {
        output[i] = beanJsonLibConverter.convertToString(spa[i]);
    }
    long endOutput = System.currentTimeMillis();
    long memend = r.totalMemory() - r.freeMemory();

    String[] serializeOutput = new String[TEST_SIZE];
    char[] source = output[0].toCharArray();
    r.gc();

    long stringsizeStart = r.totalMemory() - r.freeMemory();
    for (int i = 0; i < TEST_SIZE; i++) {
        serializeOutput[i] = new String(source);
    }
    long stringsizeEnd = r.totalMemory() - r.freeMemory();

    /*
     * Output the time per conversion and the memory usage - the output per
     * conversion.
     *
     */

    log.info("SF JSON Lib Output " + average(startOutput, endOutput, TEST_SIZE) + " ms/conversion, "
            + (average(memstart, memend, TEST_SIZE) - average(stringsizeStart, stringsizeEnd, TEST_SIZE))
            + " heap bytes/conversion, output packet consumed on average "
            + average(stringsizeStart, stringsizeEnd, TEST_SIZE) + " for a string length of "
            + output[0].length());
    log.info("Output Was [" + output[0] + ']');
}

From source file:org.openmrs.module.emrmonitor.metric.JavaRuntimeMetricProducer.java

/**
 * @return a list of produced metrics/*from w  w w  .  j  av a  2  s  . co m*/
 */
@Override
public Map<String, String> produceMetrics() {

    Map<String, String> metrics = new LinkedHashMap<String, String>();

    // Memory
    Runtime runtime = Runtime.getRuntime();
    metrics.put("memory.total", FormatUtil.formatBytes(runtime.totalMemory()));
    metrics.put("memory.total.bytes", Long.toString(runtime.totalMemory()));
    metrics.put("memory.free", FormatUtil.formatBytes(runtime.freeMemory()));
    metrics.put("memory.free.bytes", Long.toString(runtime.freeMemory()));
    metrics.put("memory.maximum", FormatUtil.formatBytes(runtime.maxMemory()));
    metrics.put("memory.maximum.bytes", Long.toString(runtime.maxMemory()));

    // Date/time
    Calendar cal = Calendar.getInstance();
    metrics.put("datetime.display", DateFormat.getDateTimeInstance().format(cal.getTime()));
    metrics.put("datetime.date", DateFormatUtils.ISO_DATE_FORMAT.format(cal));
    metrics.put("datetime.time", DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(cal));
    metrics.put("datetime.timezone", cal.getTimeZone().getDisplayName());

    // Java
    Properties sp = System.getProperties();
    metrics.put("version", sp.getProperty("java.version"));
    metrics.put("vendor", sp.getProperty("java.vendor"));
    metrics.put("jvmVersion", sp.getProperty("java.vm.version"));
    metrics.put("jvmVendor", sp.getProperty("java.vm.vendor"));
    metrics.put("runtimeName", sp.getProperty("java.runtime.name"));
    metrics.put("runtimeVersion", sp.getProperty("java.runtime.version"));
    metrics.put("user.name", sp.getProperty("user.name"));
    metrics.put("user.language", sp.getProperty("user.language"));
    metrics.put("user.timezone", sp.getProperty("user.timezone"));
    metrics.put("user.directory", sp.getProperty("user.dir"));
    metrics.put("encoding", sp.getProperty("sun.jnu.encoding"));
    metrics.put("tempDirectory", sp.getProperty("java.io.tmpdir"));

    return metrics;
}

From source file:com.aurel.track.prop.LoginBL.java

/**
 *
 * @param username/*from w  w w.j av  a 2 s  .  com*/
 * @param userPwd
 * @param nonce
 * @param request
 * @param anonymousLogin
 * @return Map with two entries: 1. "errors": ArrayList<LabelValueBean>; 2.
 *         "mappingEnum": Integer with 2: bad credentials, 6: license
 *         problems, 7: forward to URL, 8: first time admin user, 18:
 *         request license, 9: standard login
 *
 */
public static Map<String, Object> setEnvironment(String username, String userPwd, String nonce,
        HttpServletRequest request, Map<String, Object> sessionMap, boolean anonymousLogin,
        boolean usingContainerBasedAuthentication, boolean springAuthenticated) {
    HttpSession httpSession = request.getSession();
    ArrayList<LabelValueBean> errors = new ArrayList<LabelValueBean>();
    HashMap<String, Object> result = new HashMap<String, Object>();
    Integer mappingEnum = 0;

    // Make things robust
    if (username == null) {
        username = "x";
    }
    if (userPwd == null) {
        userPwd = "x";
    }
    // Move locale to one that we actually have, in case there
    // was a request for a locale that we do not have
    Locale locale = LocaleHandler.getExistingLocale(request.getLocales());
    LocaleHandler.exportLocaleToSession(sessionMap, locale);
    Support support = new Support();
    support.setURIs(request);
    if (username != null) {
        ACCESSLOGGER.info("LOGON: User '" + username.trim() + "' trying to log on" + " at "
                + new Date().toString() + " from " + request.getRemoteAddr());
    }
    ServletContext servletContext = org.apache.struts2.ServletActionContext.getServletContext();
    try {
        if (!Torque.isInit()) {
            Torque.init(HandleHome.getTorqueProperties(servletContext, true));
            LOGGER.debug("Database is " + Torque.getDefaultDB());
            LOGGER.info("Torque was re-initialized.");
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
        LOGGER.error("Could not initialize Torque (1)");
        LOGGER.error(ExceptionUtils.getStackTrace(e));
        errors.add(new LabelValueBean("errGeneralError",
                getText("logon.err.noDataBase", locale) + ":" + e.getMessage()));
        mappingEnum = 1;
        result.put("errors", errors);
        result.put("mappingEnum", mappingEnum);
        return result;
    }
    TPersonBean personBean = null;
    if (anonymousLogin) {
        personBean = PersonBL.getAnonymousIfActive();
    } else {
        try {
            String pwd = "";
            if (nonce == null || nonce.length() == 0) {
                pwd = userPwd; // clear text
            } else {
                pwd = decrypt(nonce.charAt(0), userPwd); // key is first
                // character of
                // nonce
            }
            personBean = PersonBL.loadByLoginNameWithRights(username);

            if (personBean != null) {
                personBean.setPlainPwd(pwd);

                if (personBean.isDisabled()) {
                    errors.add(
                            new LabelValueBean("errCredentials", getText("logon.err.user.disabled", locale)));
                    ACCESSLOGGER
                            .warn("LOGON: User " + personBean.getLoginName() + " is disabled, login refused!");
                } else if (usingContainerBasedAuthentication == false && springAuthenticated == false
                        && !personBean.authenticate(pwd)) {
                    ACCESSLOGGER.warn("LOGON: Wrong password given for user " + personBean.getFullName()
                            + " at " + new Date().toString() + " from " + request.getRemoteAddr());
                    errors.add(new LabelValueBean("errCredentials",
                            getText("logon.err.password.mismatch", locale)));
                }
            } else {
                ACCESSLOGGER.warn("LOGON: No such user: " + username + " at " + new Date().toString() + " from "
                        + request.getRemoteAddr());
                errors.add(
                        new LabelValueBean("errCredentials", getText("logon.err.password.mismatch", locale)));
                LOGGER.debug("User '" + username + "' is not in database...");
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            LOGGER.error("Could not initialize Torque (2)");
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            errors.add(new LabelValueBean("errGeneralError", getText("logon.err.noDataBase", locale)));
        }
    }

    if (errors.size() > 0 || personBean == null) {
        mappingEnum = 2;
        result.put("errors", errors);
        result.put("mappingEnum", mappingEnum);
        return result;
    }

    // At this point, we have successfully identified the user.
    // Try to set the users preferred locale
    if (personBean.getPrefLocale() != null && !"".equals(personBean.getPrefLocale())) {
        // get as stored in user profile
        locale = LocaleHandler.getExistingLocale(LocaleHandler.getLocaleFromString(personBean.getPrefLocale()));
    }
    if (locale == null) {
        // rely on browser settings
        locale = LocaleHandler.getExistingLocale(request.getLocales());
    }
    personBean.setLocale(locale);

    // set the bean with the last saved login date and save the actual date
    // as
    // last login date in the database
    personBean.setLastButOneLogin(personBean.getLastLogin());
    personBean.setLastLogin(new Date());
    PersonBL.saveSimple(personBean);
    LocaleHandler.exportLocaleToSession(sessionMap, locale);

    // -----------------------------------------------------

    // check if opState
    // (reject users, but not admin, in maintenance state)
    ApplicationBean appBean = ApplicationBean.getInstance();

    if (appBean == null) {
        LOGGER.error("appBean == null: this should never happen");
        mappingEnum = 3;
        result.put("errors", errors);
        result.put("mappingEnum", mappingEnum);
        return result;
    }

    httpSession.setAttribute(Constants.APPLICATION_BEAN, appBean);

    TSiteBean siteBean = DAOFactory.getFactory().getSiteDAO().load1();

    if (ApplicationBean.OPSTATE_MAINTENNANCE.equals(siteBean.getOpState()) && !personBean.getIsSysAdmin()) {
        // print error, refuse login
        errors.add(new LabelValueBean("errGeneralError", getText("logon.err.maintenance", locale)));
        mappingEnum = 4;
        result.put("errors", errors);
        result.put("mappingEnum", mappingEnum);
        return result;
    }

    Runtime rt = Runtime.getRuntime();
    long mbyte = 1024 * 1024;
    long freeMemoryMB = rt.freeMemory() / mbyte;
    if (freeMemoryMB < 50 && !personBean.getIsSysAdmin()) {
        rt.gc();
        freeMemoryMB = rt.freeMemory() / mbyte;
        if (freeMemoryMB < 50) {
            errors.add(new LabelValueBean("errGeneralError", getText("logon.err.freeMemory", locale)));
            mappingEnum = 19;
            result.put("errors", errors);
            result.put("mappingEnum", mappingEnum);
            return result;
        }
    }

    // Save our logged-in user in the session
    // and set a cookie so she can conveniently point
    // directly to issues without having to log on for
    // the next CookieTimeout seconds

    httpSession.setAttribute(Constants.USER_KEY, personBean);

    int maxItemsProUser = GeneralSettings.getMaxItems();
    FilterUpperTO filterUpperTO = new FilterUpperTO();
    TreeFilterExecuterFacade.prepareFilterUpperTO(filterUpperTO, personBean, locale, null, null);
    int noOfProjectRoleItemsProUser = LoadTreeFilterItemCounts.countTreeFilterProjectRoleItems(filterUpperTO,
            personBean, locale, maxItemsProUser);
    int noOfRACIRoleItemsProUser = LoadTreeFilterItemCounts.countTreeFilterRACIRoleItems(filterUpperTO,
            personBean, locale, maxItemsProUser);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Maximum number of items per user " + maxItemsProUser);
        LOGGER.debug(
                "Number of project role items accessible by " + username + ": " + noOfProjectRoleItemsProUser);
        LOGGER.debug("Number of RACI role items accessible by " + username + ": " + noOfRACIRoleItemsProUser);
    }
    boolean projectRoleItemsAboveLimit = noOfProjectRoleItemsProUser >= maxItemsProUser;
    boolean raciRoleItemsAboveLimit = noOfRACIRoleItemsProUser >= maxItemsProUser;
    personBean.setProjectRoleItemsAboveLimit(Boolean.valueOf(projectRoleItemsAboveLimit));
    personBean.setRaciRoleItemsAboveLimit(Boolean.valueOf(raciRoleItemsAboveLimit));
    PersonBL.setLicensedFeatures(personBean);

    List<TListTypeBean> issueTypes = IssueTypeBL.loadAllByPerson(personBean.getObjectID(), locale);
    httpSession.setAttribute("issueTypesJSON", JSONUtility.encodeIssueTypes(issueTypes));
    Integer sessionTimeoutMinutes = personBean.getSessionTimeoutMinutes();
    if (sessionTimeoutMinutes != null && sessionTimeoutMinutes.intValue() != 0) {
        httpSession.setMaxInactiveInterval(sessionTimeoutMinutes * 60);
    }
    // load the my filters in the menu
    List<FilterInMenuTO> myFilters = FilterBL.loadMyMenuFiltersWithTooltip(personBean, locale);

    httpSession.setAttribute(FilterBL.MY_MENU_FILTERS_JSON, FilterInMenuJSON.encodeFiltersInMenu(myFilters));

    List<FilterInMenuTO> lastQueries = FilterInMenuBL.getLastExecutedQueries(personBean, locale);

    httpSession.setAttribute(FilterBL.LAST_EXECUTED_FILTERS_JSON,
            FilterInMenuJSON.encodeFiltersInMenu(lastQueries));
    httpSession.setAttribute(ShortcutBL.SHORTCUTS_JSON, ShortcutBL.encodeShortcutsJSON());

    // modules
    List modules = getModuleDescriptors(personBean);
    httpSession.setAttribute("usedModules", modules);
    httpSession.setAttribute("usedModulesJSON", MasterHomeJSON.encodeModules(modules, personBean));
    httpSession.setAttribute("loggedInPersonUserLevel", personBean.getUserLevel());
    httpSession.setAttribute("clientUserLevelID", TPersonBean.USERLEVEL.CLIENT);

    // maxFileSize
    int maxFileSize = AttachBL.getMaxFileSize(siteBean);
    httpSession.setAttribute("MAXFILESIZE", maxFileSize);

    // ------------------------------------------------------
    // Create a new SessionBean for this session and bind it to the session

    SessionBean sBean = new SessionBean();
    httpSession.setAttribute(Constants.SESSION_BEAN, sBean);

    ItemLockBL.removeLockedIssuesByUser(personBean.getObjectID());

    ACCESSLOGGER.info("LOGON: User '" + personBean.getLoginName().trim() + "' (" + personBean.getFullName()
            + ")" + " logged in at " + new Date().toString() + " from " + request.getRemoteAddr());

    LicenseManager lm = appBean.getLicenseManager();
    if (lm != null) {
        int rf = lm.getErrorCode();
        boolean haveLicenseErrors = false;
        switch (rf) {
        case 1:
            haveLicenseErrors = true;
            errors.add(
                    new LabelValueBean("errLicenseError", getText("logon.err.license.needCommercial", locale)));
            break;
        case 2:
            haveLicenseErrors = true;
            errors.add(new LabelValueBean("errLicenseError", getText("logon.err.license.expired", locale)));
            break;
        case 3:
            haveLicenseErrors = true;
            errors.add(
                    new LabelValueBean("errLicenseError", getText("logon.err.license.full.exceeded", locale)));
            break;
        case 4:
            haveLicenseErrors = true;
            errors.add(new LabelValueBean("errLicenseError", getText("logon.err.license.invalid",
                    new String[] { ApplicationBean.getIpNumbersString() }, locale)));
            break;
        case 7:
            haveLicenseErrors = true;
            errors.add(new LabelValueBean("errLicenseError",
                    getText("logon.err.license.limited.exceeded", locale)));
            break;
        case 8:
            haveLicenseErrors = true;
            errors.add(
                    new LabelValueBean("errLicenseError", getText("logon.err.license.gantt.exceeded", locale)));
            break;
        default:
            break;
        }

        if (haveLicenseErrors == true) {
            mappingEnum = 6;
            result.put("errors", errors);
            result.put("mappingEnum", mappingEnum);
            return result;
        }
    }

    result.put("errors", errors);

    httpSession.setAttribute("DESIGNPATH", personBean.getDesignPath());

    Boolean isMobileDevice = LogoffBL.isThisAMobileDevice(request);
    httpSession.setAttribute("mobile", isMobileDevice);

    LOGGER.debug("Mobile is " + httpSession.getAttribute("mobile"));

    // check for post-login forward
    String forwardUrl = (String) httpSession.getAttribute(Constants.POSTLOGINFORWARD);
    if (forwardUrl != null) {
        LOGGER.debug("Forward URL found :" + forwardUrl);
        mappingEnum = 7;
        result.put("mappingEnum", mappingEnum);
        return result;

    }

    Map ret = new GroovyScriptExecuter().handleEvent(IEventSubscriber.EVENT_POST_USER_LOGGED_IN, new HashMap());
    if (ret.get(BINDING_PARAMS.CONTINUE).equals(Boolean.FALSE)) {
        mappingEnum = 10;
        result.put("mappingEnum", mappingEnum);
        return result;
    }

    String extendedKey = ApplicationBean.getInstance().getExtendedKey();

    if (extendedKey == null || extendedKey.length() < 10) { // no empty keys
        // allowed
        mappingEnum = 18;
        result.put("mappingEnum", mappingEnum);
        return result;

    }

    String firstTime = (String) servletContext.getAttribute("FirstTime");

    result.put("user", personBean);

    if (personBean.getIsSysAdmin() && firstTime != null && firstTime.equals("FT")) {

        servletContext.removeAttribute("FirstTime");
        mappingEnum = 8;
        result.put("mappingEnum", mappingEnum);
        return result;

    } else {
        // Forward control to the specified success URI
        mappingEnum = 9;
        result.put("mappingEnum", mappingEnum);
        return result;
    }
}

From source file:org.ambraproject.action.debug.DebugInfoAction.java

@Override
public String execute() throws Exception {
    if (!checkAccess()) {
        return ERROR;
    }//ww w .ja  va 2 s . c o m
    timestamp = new Date(System.currentTimeMillis());
    Runtime rt = Runtime.getRuntime();
    jvmFreeMemory = (double) rt.freeMemory() / (1024.0 * 1024.0);
    jvmTotalMemory = (double) rt.totalMemory() / (1024.0 * 1024.0);
    jvmMaxMemory = (double) rt.maxMemory() / (1024.0 * 1024.0);
    HttpServletRequest req = ServletActionContext.getRequest();
    tomcatVersion = ServletActionContext.getServletContext().getServerInfo();
    sessionCount = SessionCounter.getSessionCount();
    host = req.getLocalName();
    hostIp = req.getLocalAddr();
    buildInfo = generateBuildInfo();

    // The easiest way I found to get the URL and username for the DB.
    // It's not that easy and involves opening a connection...
    Context initialContext = new InitialContext();
    Context context = (Context) initialContext.lookup("java:comp/env");
    DataSource ds = (DataSource) context.lookup("jdbc/AmbraDS");
    Connection conn = null;
    try {
        conn = ds.getConnection();
        DatabaseMetaData metadata = conn.getMetaData();
        dbUrl = metadata.getURL();
        dbUser = metadata.getUserName();
    } finally {
        conn.close();
    }

    Configuration config = ConfigurationStore.getInstance().getConfiguration();
    FileStoreService filestoreService = (FileStoreService) context.lookup("ambra/FileStore");
    filestore = filestoreService.toString();
    solrUrl = (String) config.getProperty("ambra.services.search.server.url");
    configuration = dumpConfig(config);
    cmdLine = IOUtils.toString(new FileInputStream("/proc/self/cmdline"));

    return SUCCESS;
}

From source file:com.betfair.tornjak.monitor.FreeMemoryMonitor.java

/**
 * Answers the amount of free memory in this runtime environment, as a percentage.
 */// ww  w. j a  v  a  2  s .  co m
@Override
@ManagedAttribute()
public int getFreeMemoryPercentage() {
    Runtime runtime = Runtime.getRuntime();
    // 'totalMemory' is how much heap we have *currently*
    // - this may increase up to 'maxMemory' (and can decrease)
    long totalMemory = runtime.totalMemory();
    // 'freeMemory' is 'totalMemory' - allocated)
    long freeMemory = runtime.freeMemory();
    // Work out how much we have used
    long allocatedMemory = totalMemory - freeMemory;
    // 'maxMemory' is equivalent to the JVM option '-Xmx'
    long maxMemory = runtime.maxMemory();
    // Work out the percentage used
    return (int) (100 - (allocatedMemory * 100 / maxMemory));
}

From source file:org.loklak.api.susi.StatusService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization rights,
        JSONObjectWithDefault permissions) throws APIException {

    post.setResponse(response, "application/javascript");

    // generate json
    Runtime runtime = Runtime.getRuntime();
    JSONObject json = new JSONObject(true);
    JSONObject system = new JSONObject(true);
    system.put("assigned_memory", runtime.maxMemory());
    system.put("used_memory", runtime.totalMemory() - runtime.freeMemory());
    system.put("available_memory", runtime.maxMemory() - runtime.totalMemory() + runtime.freeMemory());
    system.put("cores", runtime.availableProcessors());
    system.put("threads", Thread.activeCount());
    system.put("runtime", System.currentTimeMillis() - Caretaker.startupTime);
    system.put("load_system_average", OS.getSystemLoadAverage());
    system.put("load_system_cpu", OS.getSystemCpuLoad());
    system.put("load_process_cpu", OS.getProcessCpuLoad());
    system.put("server_threads", SusiServer.getServerThreads());
    system.put("server_uri", SusiServer.getServerURI());

    JSONObject index = new JSONObject(true);
    JSONObject messages = new JSONObject(true);
    JSONObject queue = new JSONObject(true);
    messages.put("queue", queue);
    JSONObject users = new JSONObject(true);
    JSONObject queries = new JSONObject(true);
    JSONObject accounts = new JSONObject(true);
    JSONObject user = new JSONObject(true);
    index.put("messages", messages);
    index.put("users", users);
    index.put("queries", queries);
    index.put("accounts", accounts);
    index.put("user", user);

    JSONObject client_info = new JSONObject(true);
    client_info.put("RemoteHost", post.getClientHost());
    client_info.put("IsLocalhost", post.isLocalhostAccess() ? "true" : "false");

    JSONObject request_header = new JSONObject(true);
    Enumeration<String> he = post.getRequest().getHeaderNames();
    while (he.hasMoreElements()) {
        String h = he.nextElement();
        request_header.put(h, post.getRequest().getHeader(h));
    }//from   w ww .  j  a v  a2s .co  m
    client_info.put("request_header", request_header);

    json.put("system", system);
    json.put("index", index);
    json.put("client_info", client_info);

    return json;
}