List of usage examples for javax.servlet.http HttpServletRequest getRemoteUser
public String getRemoteUser();
null
if the user has not been authenticated. From source file:com.krawler.spring.authHandler.authHandlerController.java
public JSONObject verifyUserLogin(HttpServletRequest request, HttpServletResponse response, String user, String pass, String login, String subdomain) throws ServletException { JSONObject jobj = new JSONObject(); JSONObject rjobj = new JSONObject(); JSONObject ujobj = new JSONObject(); KwlReturnObject kmsg = null;//from w w w .j ava 2s . c om String result = ""; String userid = ""; String companyid = ""; HashMap<String, Object> requestParams2 = null; JSONObject obj = null, jret = new JSONObject(); boolean isvalid = false; try { boolean isValidUser = false; HashMap<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("user", StringUtil.checkForNull(user)); requestParams.put("pass", StringUtil.checkForNull(pass)); requestParams.put("subdomain", StringUtil.checkForNull(subdomain)); if (StringUtil.isNullOrEmpty(login)) { kmsg = authHandlerDAOObj.verifyLogin(requestParams); jobj = authHandler.getVerifyLoginJson(kmsg.getEntityList(), request); if (jobj.has("success") && (jobj.get("success").equals(true))) { User userObject = null; UserLogin userLogin = null; Company company = null; if (kmsg.getEntityList() != null && !kmsg.getEntityList().isEmpty()) { Object[] row = (Object[]) kmsg.getEntityList().get(0); userObject = (User) row[0]; userLogin = (UserLogin) row[1]; company = (Company) row[2]; } obj = new JSONObject(); companyid = jobj.getString("companyid"); userid = jobj.getString("lid"); kmsg = permissionHandlerDAOObj.getRoleofUser(userid); Iterator ite3 = kmsg.getEntityList().iterator(); while (ite3.hasNext()) { Object[] row = (Object[]) ite3.next(); String roleid = row[0].toString(); jobj.put("roleid", roleid); } CompanyPreferences cmpPref = (CompanyPreferences) kwlCommonTablesDAOObj .getClassObject("com.krawler.crm.database.tables.CompanyPreferences", companyid); obj = crmManagerCommon.getCompanyPreferencesJSON(cmpPref, obj); jobj.put("companyPreferences", obj); //company = company == null ? (Company) kwlCommonTablesDAOObj.getClassObject("com.krawler.common.admin.Company", companyid) : company; company = (Company) kwlCommonTablesDAOObj.getClassObject("com.krawler.common.admin.Company", companyid); jobj.put("notifyon", company.getNotificationtype() > 0 ? true : false); userObject = (User) kwlCommonTablesDAOObj.getClassObject("com.krawler.common.admin.User", userid); jobj.put("helpFlag", userObject.getHelpflag()); requestParams2 = new HashMap<String, Object>(); requestParams2.put("userid", userid); kmsg = permissionHandlerDAOObj.getUserPermission(requestParams2); Iterator ite = kmsg.getEntityList().iterator(); JSONArray jarr = new JSONArray(); while (ite.hasNext()) { JSONObject jo = new JSONObject(); Object[] roww = (Object[]) ite.next(); jo.put(roww[0].toString(), roww[1]); jarr.put(jo); if (roww[0].toString().equals(Constants.Crm_Case_modulename)) {// Case jo = new JSONObject(); jo.put(roww[0].toString() + "s", roww[1]);// Cases jarr.put(jo); } } jobj.put("perms", jarr); // store company info in session, store user hierarchy in session StringBuffer usersList = getManagerDAO().recursiveUsers(userid); sessionHandlerImplObj.createUserSession(request, jobj, userObject, company, userLogin, usersList); sessionHandlerImplObj.setAttribute(Constants.SESSION_SYS_EMAILID, StringUtil.getSysEmailIdByCompanyID(company)); setLocale(request, response, jobj.optString("language", null)); requestParams.put("userloginid", StringUtil.checkForNull(userid)); profileHandlerDAOObj.saveUserLogin(requestParams); isvalid = true; } else { jobj = new JSONObject(); jobj.put("success", false); jobj.put("reason", "noaccess"); jobj.put("message", "Authentication failed"); isvalid = false; } } else { String username = request.getRemoteUser(); if (!StringUtil.isNullOrEmpty(username)) { // jbj = DBCon.AuthUser(username, subdomain); boolean toContinue = true; if (sessionHandlerImplObj.validateSession(request, response)) { String companyid_session = sessionHandlerImplObj.getCompanyid(request); String subdomainFromSession = companyDetailsDAOObj.getSubDomain(companyid_session); if (!subdomain.equalsIgnoreCase(subdomainFromSession)) { result = "alreadyloggedin"; toContinue = false; } } if (toContinue) { requestParams = new HashMap<String, Object>(); requestParams.put("user", username); requestParams.put("subdomain", subdomain); kmsg = authHandlerDAOObj.verifyLogin(requestParams); jobj = authHandler.getVerifyLoginJson(kmsg.getEntityList(), request); if (jobj.has("success") && (jobj.get("success").equals(true))) { User userObject = null; UserLogin userLogin = null; Company company = null; if (kmsg.getEntityList() != null && !kmsg.getEntityList().isEmpty()) { Object[] row = (Object[]) kmsg.getEntityList().get(0); userObject = (User) row[0]; userLogin = (UserLogin) row[1]; company = (Company) row[2]; } // sessionbean.createUserSession(request, jbj); obj = new JSONObject(); userid = jobj.getString("lid"); kmsg = permissionHandlerDAOObj.getRoleofUser(userid); Iterator ite3 = kmsg.getEntityList().iterator(); while (ite3.hasNext()) { Object[] row = (Object[]) ite3.next(); String roleid = row[0].toString(); jobj.put("roleid", roleid); } CompanyPreferences cmpPref = (CompanyPreferences) kwlCommonTablesDAOObj.getClassObject( "com.krawler.crm.database.tables.CompanyPreferences", jobj.getString("companyid")); obj = crmManagerCommon.getCompanyPreferencesJSON(cmpPref, obj); jobj.put("companyPreferences", obj); //company = company == null ? (Company) kwlCommonTablesDAOObj.getClassObject("com.krawler.common.admin.Company", companyid) : company; company = (Company) kwlCommonTablesDAOObj.getClassObject( "com.krawler.common.admin.Company", jobj.getString("companyid")); jobj.put("notifyon", company.getNotificationtype() > 0 ? true : false); //userObject = userObject == null ? (User) kwlCommonTablesDAOObj.getClassObject("com.krawler.common.admin.User", userid): userObject; userObject = (User) kwlCommonTablesDAOObj .getClassObject("com.krawler.common.admin.User", userid); jobj.put("helpFlag", userObject.getHelpflag()); requestParams2 = new HashMap<String, Object>(); requestParams2.put("userid", userid); kmsg = permissionHandlerDAOObj.getUserPermission(requestParams2); Iterator ite = kmsg.getEntityList().iterator(); JSONArray jarr = new JSONArray(); while (ite.hasNext()) { JSONObject jo = new JSONObject(); Object[] roww = (Object[]) ite.next(); jo.put(roww[0].toString(), roww[1]); jarr.put(jo); if (roww[0].toString().equals(Constants.Crm_Case_modulename)) {// Case jo = new JSONObject(); jo.put(roww[0].toString() + "s", roww[1]);// Cases jarr.put(jo); } } jobj.put("perms", jarr); // store company info in session, store user hierarchy in session StringBuffer usersList = getManagerDAO().recursiveUsers(userid); sessionHandlerImplObj.createUserSession(request, jobj, userObject, company, userLogin, usersList); sessionHandlerImplObj.setAttribute(Constants.SESSION_SYS_EMAILID, StringUtil.getSysEmailIdByCompanyID(company)); setLocale(request, response, jobj.optString("language", null)); isValidUser = true; } else { result = "noaccess"; } } } else { if (sessionHandlerImpl.isValidSession(request, response)) { isValidUser = true; } else { result = "timeout"; } } if (isValidUser) { JSONObject temp = new JSONObject(); companyid = sessionHandlerImpl.getCompanyid(request); String companyName = sessionHandlerImplObj.getCompanyName(request); temp.put("companyid", companyid); String platformUrl = ConfigReader.getinstance().get("platformURL"); //getServletContext().getInitParameter("platformUrl"); sessionHandlerImplObj.setAttribute(Constants.SESSION_PARTNERNAME, companyName); if (platformUrl != null) { apiCallHandlerService.callApp(platformUrl, temp, companyid, "7", false, getReceiver()); apiCallHandlerService.callApp(platformUrl, temp, companyid, "13", false, new Receiver() { String companyName = Constants.DESKERA; public Receiver setCompany(String companyName) { this.companyName = companyName; return this; } @Override public void receive(Object obj) { JSONObject jobj = null; if (obj instanceof JSONObject) jobj = (JSONObject) obj; try { sessionHandlerImplObj.setAttribute(Constants.SESSION_PARTNERNAME, jobj.optString(Constants.SESSION_PARTNERNAME, this.companyName)); if (jobj.optString(Constants.SESSION_PARTNERNAME, this.companyName) .equals(Constants.DESKERA)) { sessionHandlerImplObj.setAttribute(Constants.SESSION_PARTNERNAME, this.companyName); } } catch (Exception ex) { logger.warn("Cannot store partnername: " + ex.toString()); } } }.setCompany(companyName)); } userid = sessionHandlerImpl.getUserid(request); User userObj = (User) kwlCommonTablesDAOObj.getClassObject("com.krawler.common.admin.User", userid); String userName = sessionHandlerImplObj.getUserName(request); jobj.put("fullname", profileHandlerDAOObj.getUserFullName(userid)); jobj.put("lid", userid); jobj.put("companyid", companyid); jobj.put("company", companyName); jobj.put("username", userName); jobj.put("email", userObj.getEmailID()); jobj.put("timeformat", userObj.getTimeformat()); jobj.put("callwith", sessionHandlerImplObj.getUserCallWith(request)); CompanyPreferences cmpPref = (CompanyPreferences) kwlCommonTablesDAOObj .getClassObject("com.krawler.crm.database.tables.CompanyPreferences", companyid); obj = new JSONObject(); obj = crmManagerCommon.getCompanyPreferencesJSON(cmpPref, obj); jobj.put("companyPreferences", obj); jobj.put("helpFlag", userObj.getHelpflag()); if (!permissionHandlerDAOObj.isSuperAdmin(userid, companyid)) { JSONObject permJobj = new JSONObject(); kmsg = permissionHandlerDAOObj.getActivityFeature(); permJobj = permissionHandler.getAllPermissionJson(kmsg.getEntityList(), request, kmsg.getRecordTotalCount()); requestParams2 = new HashMap<String, Object>(); requestParams2.put("userid", userid); kmsg = permissionHandlerDAOObj.getUserPermission(requestParams2); permJobj = permissionHandler.getRolePermissionJson(kmsg.getEntityList(), permJobj); jobj.put("perm", permJobj); } else { jobj.put("deskeraadmin", true); } requestParams2 = new HashMap<String, Object>(); requestParams2.put("timezoneid", sessionHandlerImplObj.getTimeZoneID(request)); requestParams2.put("dateformatid", sessionHandlerImpl.getDateFormatID(request)); requestParams2.put("currencyid", sessionHandlerImpl.getCurrencyID(request)); JSONObject prefJson = new JSONObject(); kmsg = authHandlerDAOObj.getPreferences(requestParams2); prefJson = getPreferencesJson(kmsg.getEntityList(), request); jobj.put("preferences", prefJson.getJSONArray("data").get(0)); JSONObject roleJson = new JSONObject(); kmsg = permissionHandlerDAOObj.getRoleList(); Iterator ite = kmsg.getEntityList().iterator(); int inc = 0; while (ite.hasNext()) { Object row = (Object) ite.next(); String rname = ((Rolelist) row).getRolename(); rjobj.put(rname, (int) Math.pow(2, inc)); inc++; } kmsg = permissionHandlerDAOObj.getRoleofUser(userid); ite = kmsg.getEntityList().iterator(); if (ite.hasNext()) { Object[] row = (Object[]) ite.next(); ujobj.put("roleid", row[0].toString()); } roleJson.put("Role", rjobj); roleJson.put("URole", ujobj); jobj.put("role", roleJson); jobj.put("subdomain", subdomain); jobj.put("base_url", URLUtil.getRequestPageURL(request, Links.UnprotectedLoginPageFull)); createAccountingSession(request); jobj.put("subscribedAccounting", crmManagerCommon.hasSyncAccountingPerm(request)); createProjectSession(request); jobj.put("createProject", crmManagerCommon.hasCreateProjPerm(request)); jobj.put("viewProject", crmManagerCommon.hasViewProjPerm(request)); Iterator ite5 = spreadSheetDAOObj.getSpreadsheetConfig(userid).iterator(); JSONObject obj5 = new JSONObject(); while (ite5.hasNext()) { SpreadSheetConfig cm = (SpreadSheetConfig) ite5.next(); if (cm.getState() != null && !StringUtil.isNullOrEmpty(cm.getState())) { JSONObject state = new JSONObject(cm.getState()); if (state.has("sort")) { obj5.put(cm.getModule(), state.get("sort")); } } } jobj.put("modulestates", obj5); jobj.put("tzdiff", sessionHandlerImplObj.getTimeZoneDifference(request)); cometManagementService.initBayeuxVariable(getServletContext()); isvalid = true; } else { jobj.put("success", false); jobj.put("reason", result); jobj.put("message", "Authentication failed"); isvalid = false; } } } catch (Exception e) { LOG.info(e.getMessage(), e); e.printStackTrace(); } finally { try { jret.put("valid", isvalid); jret.put("data", jobj); } catch (JSONException ex) { Logger.getLogger(authHandlerController.class.getName()).log(Level.SEVERE, null, ex); } } return jret; }
From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java
public RelationField addRelation(HttpServletRequest request, Connection conn, TableInfo tableToAddTo, String internalFieldName, String fieldName, String fieldDesc, TableInfo relatedTable, BaseField relatedField) throws SQLException, DisallowedException, CantDoThatException, ObjectNotFoundException, CodingErrorException { if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.MANAGE_TABLE, tableToAddTo))) {/*from w w w.j a va2 s. co m*/ throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.MANAGE_TABLE, tableToAddTo); } String listValueFieldInternalName = request .getParameter(PossibleListOptions.LISTVALUEFIELD.getFormInputName()); String mandatoryString = request.getParameter(PossibleBooleanOptions.MANDATORY.getFormInputName()); boolean notNull = Helpers.valueRepresentsBooleanTrue(mandatoryString); String defaultToNullString = request.getParameter(PossibleBooleanOptions.DEFAULTTONULL.getFormInputName()); boolean defaultToNull = Helpers.valueRepresentsBooleanTrue(defaultToNullString); FieldPrintoutSetting printoutSetting = FieldPrintoutSetting.NAME_AND_VALUE; String oneToOneString = request.getParameter(PossibleBooleanOptions.ONETOONE.getFormInputName()); boolean oneToOne = Helpers.valueRepresentsBooleanTrue(oneToOneString); String printoutSettingString = HttpRequestUtil.getStringValue(request, PossibleListOptions.PRINTFORMAT.getFormInputName()); if (printoutSettingString != null) { if (!printoutSettingString.equals("")) { printoutSetting = FieldPrintoutSetting.valueOf(printoutSettingString.toUpperCase()); } } // Create the relation object RelationFieldOptions fieldOptions = new RelationFieldOptions(); fieldOptions.setDefaultToNull(defaultToNull); fieldOptions.setNotNull(notNull); fieldOptions.setPrintoutSetting(printoutSetting); fieldOptions.setOneToOne(oneToOne); if (oneToOne) { fieldOptions.setUnique(false); } else { fieldOptions.setUnique(true); } RelationField relationToAdd = new RelationFieldDefn(this.relationalDataSource, tableToAddTo, internalFieldName, relatedTable, relatedField, fieldOptions); relationToAdd.setFieldDescription(fieldDesc); relationToAdd.setFieldName(fieldName); if (listValueFieldInternalName == null) { // if no other field was specified for display purposes // use the field on which the relation is based relationToAdd.setDisplayField(relationToAdd.getRelatedField()); } else { BaseField valueField = relatedTable.getField(listValueFieldInternalName); relationToAdd.setDisplayField(valueField); } // Add it to the databases and in-memory cache addField(conn, tableToAddTo, relationToAdd, request); this.dataManagement.logLastSchemaChangeTime(request); UsageLogger usageLogger = new UsageLogger(this.relationalDataSource); AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser()); usageLogger.logTableSchemaChange(user, tableToAddTo, AppAction.ADD_FIELD, "relation: " + relationToAdd); UsageLogger.startLoggingThread(usageLogger); return relationToAdd; }
From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java
public void removeTable(SessionDataInfo sessionData, HttpServletRequest request, TableInfo tableToRemove, Connection conn) throws SQLException, DisallowedException, CantDoThatException, TableDependencyException, CodingErrorException, ObjectNotFoundException { if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.ADMINISTRATE))) { throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.ADMINISTRATE); }/*w w w . j ava 2s.co m*/ // Check the table doesn't have any user-added fields for (BaseField field : tableToRemove.getFields()) { if (!(field.equals(tableToRemove.getPrimaryKey()) || field.getHidden())) { throw new CantDoThatException("Please remove all fields before removing the table"); } } // Check that it doesn't have any reports if (tableToRemove.getReports().size() > 1) { throw new CantDoThatException( "Please remove reports " + tableToRemove.getReports() + " before removing the table"); } // Get a set of dependent tables. If empty proceed with the deletion of // the table, otherwise, raise an exception LinkedHashSet<TableInfo> dependentTables = new LinkedHashSet<TableInfo>(); this.getDependentTables(tableToRemove, dependentTables, request); if (dependentTables.size() > 0) { LinkedHashSet<BaseReportInfo> dependentReports = new LinkedHashSet<BaseReportInfo>(); for (TableInfo dependentTable : dependentTables) { dependentReports.addAll(dependentTable.getReports()); } throw new TableDependencyException( "Unable to remove table - other tables are linked to it, that need to be removed first", dependentTables, dependentReports); } // No dependencies exist so remove the table & its default report: BaseReportInfo defaultReport = tableToRemove.getDefaultReport(); this.removeReportWithoutChecks(sessionData, request, defaultReport, conn); // Remove any privileges on the table this.getAuthManager().removePrivilegesOnTable(request, tableToRemove); this.tableCache.remove(tableToRemove.getInternalTableName()); // Delete from persistent store HibernateUtil.currentSession().delete(tableToRemove); try { // Delete the table from the relational database. // The CASCADE is to drop the related sequence. // TODO: replace this with a specific sequence drop PreparedStatement statement = conn .prepareStatement("DROP TABLE " + tableToRemove.getInternalTableName() + " CASCADE"); statement.execute(); statement.close(); } catch (SQLException sqlex) { String errorCode = sqlex.getSQLState(); if (errorCode.equals("42P01")) { logger.warn("Can't delete table " + tableToRemove + " from relational database, it's not there"); // TODO: review why we're swallowing this error } else { throw new SQLException(sqlex + ": error code " + errorCode, sqlex); } } this.authManager.getCompanyForLoggedInUser(request).removeTable(tableToRemove); UsageLogger usageLogger = new UsageLogger(this.relationalDataSource); AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser()); usageLogger.logTableSchemaChange(user, tableToRemove, AppAction.REMOVE_TABLE, ""); UsageLogger.startLoggingThread(usageLogger); }
From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java
public TableInfo addTable(SessionDataInfo sessionData, HttpServletRequest request, Connection conn, String internalTableName, String internalDefaultReportName, String tableName, String internalPrimaryKeyName, String tableDesc) throws SQLException, DisallowedException, CantDoThatException, ObjectNotFoundException, CodingErrorException { if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.ADMINISTRATE))) { throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.ADMINISTRATE); }/*from w ww. j a va 2 s. c om*/ TableInfo newTable = new TableDefn(internalTableName, tableName, tableDesc); HibernateUtil.currentSession().save(newTable); try { String SQLCode = "CREATE TABLE " + newTable.getInternalTableName() + " ()"; PreparedStatement statement = conn.prepareStatement(SQLCode); statement.execute(); statement.close(); // Create an initial report for the table SimpleReportInfo defaultReport = new SimpleReportDefn(newTable, internalDefaultReportName, "Default report", "A simple report of all items in the '" + tableName + "' data store", null); // The true passed means it is the default report newTable.addReport(defaultReport, true); // Add an auto-generated primary key to act as a row identifier SequenceField primaryKeyField = new SequenceFieldDefn(newTable, internalPrimaryKeyName, "ID:" + tableName, PRIMARY_KEY_DESCRIPTION, FieldPrintoutSetting.NO_PRINTOUT); HibernateUtil.currentSession().save(primaryKeyField); newTable.addField(primaryKeyField); newTable.setPrimaryKey(primaryKeyField); this.addFieldToRelationalDb(conn, newTable, primaryKeyField); setPrimaryKeyDbAction(conn, newTable); // Update the default report to add the primary key ReportFieldInfo primaryKeyReportField = defaultReport.addTableField(primaryKeyField); // Sort the default report by primary key descending, i.e. show new // records at the top defaultReport.addSort(primaryKeyReportField, false); // Save default report definition to the database this.updateViewDbAction(conn, defaultReport, request); // Add hidden table fields this.addDateCreatedFieldToTable(conn, newTable); this.addCreatedByFieldToTable(conn, newTable); this.addLastModifiedFieldToTable(conn, newTable); this.addModifiedByFieldToTable(conn, newTable); this.addRecordLockedFieldToTable(conn, newTable); this.addViewCountFieldToTable(conn, newTable); this.addCommentsFeedFieldToTable(conn, newTable); } catch (SQLException sqlex) { // Reformat the error message to be more user friendly. // Use SQLState as an error identifier because it is standard across // databases String errorCode = sqlex.getSQLState(); if (errorCode.equals("42P07")) { // A table with that name already exists throw new SQLException( "The internal table name '" + newTable.getInternalTableName() + "' already exists", errorCode); } else if (errorCode.equals("42601")) { throw new SQLException("Table couldn't be created", sqlex); } else { throw new SQLException(sqlex + ": error code " + errorCode, sqlex); } } // Cache the table in the company object this.authManager.getCompanyForLoggedInUser(request).addTable(newTable); UsageLogger usageLogger = new UsageLogger(this.relationalDataSource); AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser()); usageLogger.logTableSchemaChange(user, newTable, AppAction.ADD_TABLE, ""); UsageLogger.startLoggingThread(usageLogger); return newTable; // this.dataManagement.logLastSchemaChangeTime(request); }
From source file:net.lightbody.bmp.proxy.jetty.servlet.Dump.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("Dump", this); request.setCharacterEncoding("ISO_8859_1"); getServletContext().setAttribute("Dump", this); String info = request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try {/* ww w .j av a2 s. c om*/ throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance()); } catch (Throwable th) { throw new ServletException(th); } } String redirect = request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(redirect); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String error = request.getParameter("error"); if (error != null && error.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String length = request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } String buffer = request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name = info.substring(info.indexOf("Locale/") + 7); Field f = java.util.Locale.class.getField(locale_name); response.setLocale((Locale) f.get(null)); } catch (Exception e) { LogSupport.ignore(log, e); response.setLocale(Locale.getDefault()); } } String cn = request.getParameter("cookie"); String cv = request.getParameter("value"); String v = request.getParameter("version"); if (cn != null && cv != null) { Cookie cookie = new Cookie(cn, cv); cookie.setComment("Cookie from dump servlet"); if (v != null) { cookie.setMaxAge(300); cookie.setPath("/"); cookie.setVersion(Integer.parseInt(v)); } response.addCookie(cookie); } String pi = request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out = response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); if ("/ex1".equals(pi)) throw new IOException("test ex1"); if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); if ("/ex3".equals(pi)) throw new HttpException(501); } PrintWriter pout = response.getWriter(); Page page = null; try { page = new Page(); page.title("Dump Servlet"); page.add(new Heading(1, "Dump Servlet")); Table table = new Table(0).cellPadding(0).cellSpacing(0); page.add(table); table.newRow(); table.addHeading("getMethod: ").cell().right(); table.addCell("" + request.getMethod()); table.newRow(); table.addHeading("getContentLength: ").cell().right(); table.addCell(Integer.toString(request.getContentLength())); table.newRow(); table.addHeading("getContentType: ").cell().right(); table.addCell("" + request.getContentType()); table.newRow(); table.addHeading("getCharacterEncoding: ").cell().right(); table.addCell("" + request.getCharacterEncoding()); table.newRow(); table.addHeading("getRequestURI: ").cell().right(); table.addCell("" + request.getRequestURI()); table.newRow(); table.addHeading("getRequestURL: ").cell().right(); table.addCell("" + request.getRequestURL()); table.newRow(); table.addHeading("getContextPath: ").cell().right(); table.addCell("" + request.getContextPath()); table.newRow(); table.addHeading("getServletPath: ").cell().right(); table.addCell("" + request.getServletPath()); table.newRow(); table.addHeading("getPathInfo: ").cell().right(); table.addCell("" + request.getPathInfo()); table.newRow(); table.addHeading("getPathTranslated: ").cell().right(); table.addCell("" + request.getPathTranslated()); table.newRow(); table.addHeading("getQueryString: ").cell().right(); table.addCell("" + request.getQueryString()); table.newRow(); table.addHeading("getProtocol: ").cell().right(); table.addCell("" + request.getProtocol()); table.newRow(); table.addHeading("getScheme: ").cell().right(); table.addCell("" + request.getScheme()); table.newRow(); table.addHeading("getServerName: ").cell().right(); table.addCell("" + request.getServerName()); table.newRow(); table.addHeading("getServerPort: ").cell().right(); table.addCell("" + Integer.toString(request.getServerPort())); table.newRow(); table.addHeading("getLocalName: ").cell().right(); table.addCell("" + request.getLocalName()); table.newRow(); table.addHeading("getLocalAddr: ").cell().right(); table.addCell("" + request.getLocalAddr()); table.newRow(); table.addHeading("getLocalPort: ").cell().right(); table.addCell("" + Integer.toString(request.getLocalPort())); table.newRow(); table.addHeading("getRemoteUser: ").cell().right(); table.addCell("" + request.getRemoteUser()); table.newRow(); table.addHeading("getRemoteAddr: ").cell().right(); table.addCell("" + request.getRemoteAddr()); table.newRow(); table.addHeading("getRemoteHost: ").cell().right(); table.addCell("" + request.getRemoteHost()); table.newRow(); table.addHeading("getRemotePort: ").cell().right(); table.addCell("" + request.getRemotePort()); table.newRow(); table.addHeading("getRequestedSessionId: ").cell().right(); table.addCell("" + request.getRequestedSessionId()); table.newRow(); table.addHeading("isSecure(): ").cell().right(); table.addCell("" + request.isSecure()); table.newRow(); table.addHeading("isUserInRole(admin): ").cell().right(); table.addCell("" + request.isUserInRole("admin")); table.newRow(); table.addHeading("getLocale: ").cell().right(); table.addCell("" + request.getLocale()); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { table.newRow(); table.addHeading("getLocales: ").cell().right(); table.addCell(locales.nextElement()); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers") .attribute("COLSPAN", "2").left(); Enumeration h = request.getHeaderNames(); String name; while (h.hasMoreElements()) { name = (String) h.nextElement(); Enumeration h2 = request.getHeaders(name); while (h2.hasMoreElements()) { String hv = (String) h2.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(hv); } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters") .attribute("COLSPAN", "2").left(); h = request.getParameterNames(); while (h.hasMoreElements()) { name = (String) h.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(request.getParameter(name)); String[] values = request.getParameterValues(name); if (values == null) { table.newRow(); table.addHeading(name + " Values: ").cell().right(); table.addCell("NULL!!!!!!!!!"); } else if (values.length > 1) { for (int i = 0; i < values.length; i++) { table.newRow(); table.addHeading(name + "[" + i + "]: ").cell().right(); table.addCell(values[i]); } } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left(); Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; table.newRow(); table.addHeading(cookie.getName() + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell(cookie.getValue()); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes") .attribute("COLSPAN", "2").left(); Enumeration a = request.getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>"); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters") .attribute("COLSPAN", "2").left(); a = getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters") .attribute("COLSPAN", "2").left(); a = getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes") .attribute("COLSPAN", "2").left(); a = getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"); } if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data") && request.getContentLength() < 1000000) { MultiPartRequest multi = new MultiPartRequest(request); String[] parts = multi.getPartNames(); table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content") .attribute("COLSPAN", "2").left(); for (int p = 0; p < parts.length; p++) { name = parts[p]; table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>"); } } String res = request.getParameter("resource"); if (res != null && res.length() > 0) { table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res) .attribute("COLSPAN", "2").left(); table.newRow(); table.addHeading("this.getClass(): ").cell().right(); table.addCell("" + this.getClass().getResource(res)); table.newRow(); table.addHeading("this.getClass().getClassLoader(): ").cell().right(); table.addCell("" + this.getClass().getClassLoader().getResource(res)); table.newRow(); table.addHeading("Thread.currentThread().getContextClassLoader(): ").cell().right(); table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res)); table.newRow(); table.addHeading("getServletContext(): ").cell().right(); try { table.addCell("" + getServletContext().getResource(res)); } catch (Exception e) { table.addCell("" + e); } } /* ------------------------------------------------------------ */ page.add(Break.para); page.add(new Heading(1, "Request Wrappers")); ServletRequest rw = request; int w = 0; while (rw != null) { page.add((w++) + ": " + rw.getClass().getName() + "<br/>"); if (rw instanceof HttpServletRequestWrapper) rw = ((HttpServletRequestWrapper) rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw = ((ServletRequestWrapper) rw).getRequest(); else rw = null; } page.add(Break.para); page.add(new Heading(1, "International Characters")); page.add("Directly encoced: Drst<br/>"); page.add("HTML reference: Dürst<br/>"); page.add("Decimal (252) 8859-1: Dürst<br/>"); page.add("Hex (xFC) 8859-1: Dürst<br/>"); page.add( "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>"); page.add(Break.para); page.add(new Heading(1, "Form to generate GET content")); TableForm tf = new TableForm(response.encodeURL(getURI(request))); tf.method("GET"); tf.addTextField("TextField", "TextField", 20, "value"); tf.addButton("Action", "Submit"); page.add(tf); page.add(Break.para); page.add(new Heading(1, "Form to generate POST content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("TextField", "TextField", 20, "value"); Select select = tf.addSelect("Select", "Select", true, 3); select.add("ValueA"); select.add("ValueB1,ValueB2"); select.add("ValueC"); tf.addButton("Action", "Submit"); page.add(tf); page.add(new Heading(1, "Form to upload content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.attribute("enctype", "multipart/form-data"); tf.addFileField("file", "file"); tf.addButton("Upload", "Upload"); page.add(tf); page.add(new Heading(1, "Form to get Resource")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("resource", "resource", 20, ""); tf.addButton("Action", "getResource"); page.add(tf); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } page.write(pout); String data = request.getParameter("data"); if (data != null && data.length() > 0) { int d = Integer.parseInt(data); while (d > 0) { pout.println("1234567890123456789012345678901234567890123456789\n"); d = d - 50; } } pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); if ("/ex7".equals(pi)) throw new HttpException(501); } request.getInputStream().close(); }
From source file:com.openkm.servlet.admin.BenchmarkServlet.java
/** * Generate documents into repository (OpenKM RAW) */// w w w.ja v a2s . co m private void okmRawGenerate(HttpServletRequest request, HttpServletResponse response, String base) throws IOException { log.debug("okmRawGenerate({}, {}, {})", new Object[] { request, response, base }); int maxDocuments = WebUtils.getInt(request, "param1"); int maxFolder = WebUtils.getInt(request, "param2"); int maxDepth = WebUtils.getInt(request, "param3"); int maxIterations = WebUtils.getInt(request, "param4"); PrintWriter out = response.getWriter(); PrintWriter results = new PrintWriter(Config.HOME_DIR + File.separator + base + ".csv"); long tBegin = 0, tEnd = 0, pBegin = 0, pEnd = 0; Benchmark bm = null; Session session = null; response.setContentType(MimeTypeConfig.MIME_HTML); header(out, "OpenKM generate documents (RAW)", breadcrumb); out.flush(); try { session = JCRUtils.getSession(); bm = new Benchmark(maxDocuments, maxFolder, maxDepth); out.println("<b>- Documents:</b> " + bm.getMaxDocuments() + "<br/>"); out.println("<b>- Folders:</b> " + bm.getMaxFolders() + "<br/>"); out.println("<b>- Depth:</b> " + bm.getMaxDepth() + "<br/>"); out.println("<b>- Calibration:</b> " + bm.runCalibration() + " ms<br/>"); out.println("<b>- Calculated foldes:</b> " + bm.calculateFolders() + "<br/>"); out.println("<b>- Calculated documents:</b> " + bm.calculateDocuments() + "<br/><br/>"); results.print("\"Date\","); results.print("\"Time\","); results.print("\"Seconds\","); results.print("\"Folders\","); results.print("\"Documents\","); results.print("\"Size\"\n"); results.flush(); tBegin = System.currentTimeMillis(); for (int i = 0; i < maxIterations; i++) { out.println("<h2>Iteration " + i + "</h2>"); out.println("<table class=\"results\" width=\"80%\">"); out.println( "<tr><th>Date</th><th>Partial time</th><th>Partial miliseconds</th><th>Total folders</th><th>Total documents</th><th>Total size</th></tr>"); out.flush(); Node rootNode = session.getRootNode().getNode(Repository.ROOT); Node baseNode = null; if (rootNode.hasNode(base)) { baseNode = rootNode.getNode(base); } else { baseNode = BaseFolderModule.create(session, rootNode, base); } PrintWriter pResults = new PrintWriter(Config.HOME_DIR + File.separator + base + "_" + i + ".csv"); pResults.print("\"Date\","); pResults.print("\"Time\","); pResults.print("\"Seconds\","); pResults.print("\"Folders\","); pResults.print("\"Documents\","); pResults.print("\"Size\"\n"); pResults.flush(); pBegin = System.currentTimeMillis(); bm.okmRawPopulate(session, baseNode, out, pResults); pEnd = System.currentTimeMillis(); pResults.close(); out.println("</table>"); results.print("\"" + FormatUtil.formatDate(Calendar.getInstance()) + "\","); results.print("\"" + FormatUtil.formatSeconds(pEnd - pBegin) + "\","); results.print("\"" + (pEnd - pBegin) + "\","); results.print("\"" + bm.getTotalFolders() + "\","); results.print("\"" + bm.getTotalDocuments() + "\","); results.print("\"" + FormatUtil.formatSize(bm.getTotalSize()) + "\"\n"); results.flush(); out.println("<table class=\"results\" width=\"80%\">"); out.println( "<tr><th>Date</th><th>Partial time</th><th>Total folders</th><th>Total documents</th><th>Total size</th></tr>"); out.println("<td>" + FormatUtil.formatDate(Calendar.getInstance()) + "</td>"); out.println("<td>" + FormatUtil.formatSeconds(pEnd - pBegin) + "</td>"); out.println("<td>" + bm.getTotalFolders() + "</td>"); out.println("<td>" + bm.getTotalDocuments() + "</td>"); out.println("<td>" + FormatUtil.formatSize(bm.getTotalSize()) + "</td>"); out.println("</tr>"); out.println("</table>"); out.flush(); } tEnd = System.currentTimeMillis(); } catch (FileNotFoundException e) { out.println("<div class=\"warn\">FileNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.PathNotFoundException e) { out.println("<div class=\"warn\">PathNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.ItemExistsException e) { out.println("<div class=\"warn\">ItemExistsException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.AccessDeniedException e) { out.println("<div class=\"warn\">AccessDeniedException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.RepositoryException e) { out.println("<div class=\"warn\">RepositoryException: " + e.getMessage() + "</div>"); out.flush(); } catch (InputMismatchException e) { out.println("<div class=\"warn\">InputMismatchException: " + e.getMessage() + "</div>"); out.flush(); } catch (DatabaseException e) { out.println("<div class=\"warn\">DatabaseException: " + e.getMessage() + "</div>"); out.flush(); } finally { JCRUtils.logout(session); } long elapse = tEnd - tBegin; out.println("<hr/>"); out.println("<b>Total size:</b> " + FormatUtil.formatSize(bm.getTotalSize()) + "<br/>"); out.println("<b>Total folders:</b> " + bm.getTotalFolders() + "<br/>"); out.println("<b>Total documents:</b> " + bm.getTotalDocuments() + "<br/>"); out.println("<b>Total time:</b> " + FormatUtil.formatSeconds(elapse) + "<br/>"); out.println("<b>Documents per second:</b> " + bm.getTotalDocuments() / (elapse / 1000) + "<br/>"); footer(out); out.flush(); out.close(); results.close(); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_BENCHMARK_OKM_RAW", null, null, "Size: " + FormatUtil.formatSize(bm.getTotalSize()) + ", Folders: " + bm.getTotalFolders() + ", Documents: " + bm.getTotalDocuments() + ", Time: " + FormatUtil.formatSeconds(elapse)); log.debug("okmRawGenerate: void"); }
From source file:org.openqa.jetty.servlet.Dump.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("Dump", this); request.setCharacterEncoding("ISO_8859_1"); getServletContext().setAttribute("Dump", this); String info = request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try {// w w w . j a v a2 s . c om throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance()); } catch (Throwable th) { throw new ServletException(th); } } String redirect = request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(redirect); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String error = request.getParameter("error"); if (error != null && error.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String length = request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } String buffer = request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name = info.substring(info.indexOf("Locale/") + 7); Field f = java.util.Locale.class.getField(locale_name); response.setLocale((Locale) f.get(null)); } catch (Exception e) { LogSupport.ignore(log, e); response.setLocale(Locale.getDefault()); } } String cn = request.getParameter("cookie"); String cv = request.getParameter("value"); String v = request.getParameter("version"); if (cn != null && cv != null) { Cookie cookie = new Cookie(cn, cv); cookie.setComment("Cookie from dump servlet"); if (v != null) { cookie.setMaxAge(300); cookie.setPath("/"); cookie.setVersion(Integer.parseInt(v)); } response.addCookie(cookie); } String pi = request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out = response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); if ("/ex1".equals(pi)) throw new IOException("test ex1"); if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); if ("/ex3".equals(pi)) throw new HttpException(501); } PrintWriter pout = response.getWriter(); Page page = null; try { page = new Page(); page.title("Dump Servlet"); page.add(new Heading(1, "Dump Servlet")); Table table = new Table(0).cellPadding(0).cellSpacing(0); page.add(table); table.newRow(); table.addHeading("getMethod: ").cell().right(); table.addCell("" + request.getMethod()); table.newRow(); table.addHeading("getContentLength: ").cell().right(); table.addCell(Integer.toString(request.getContentLength())); table.newRow(); table.addHeading("getContentType: ").cell().right(); table.addCell("" + request.getContentType()); table.newRow(); table.addHeading("getCharacterEncoding: ").cell().right(); table.addCell("" + request.getCharacterEncoding()); table.newRow(); table.addHeading("getRequestURI: ").cell().right(); table.addCell("" + request.getRequestURI()); table.newRow(); table.addHeading("getRequestURL: ").cell().right(); table.addCell("" + request.getRequestURL()); table.newRow(); table.addHeading("getContextPath: ").cell().right(); table.addCell("" + request.getContextPath()); table.newRow(); table.addHeading("getServletPath: ").cell().right(); table.addCell("" + request.getServletPath()); table.newRow(); table.addHeading("getPathInfo: ").cell().right(); table.addCell("" + request.getPathInfo()); table.newRow(); table.addHeading("getPathTranslated: ").cell().right(); table.addCell("" + request.getPathTranslated()); table.newRow(); table.addHeading("getQueryString: ").cell().right(); table.addCell("" + request.getQueryString()); table.newRow(); table.addHeading("getProtocol: ").cell().right(); table.addCell("" + request.getProtocol()); table.newRow(); table.addHeading("getScheme: ").cell().right(); table.addCell("" + request.getScheme()); table.newRow(); table.addHeading("getServerName: ").cell().right(); table.addCell("" + request.getServerName()); table.newRow(); table.addHeading("getServerPort: ").cell().right(); table.addCell("" + Integer.toString(request.getServerPort())); table.newRow(); table.addHeading("getLocalName: ").cell().right(); table.addCell("" + request.getLocalName()); table.newRow(); table.addHeading("getLocalAddr: ").cell().right(); table.addCell("" + request.getLocalAddr()); table.newRow(); table.addHeading("getLocalPort: ").cell().right(); table.addCell("" + Integer.toString(request.getLocalPort())); table.newRow(); table.addHeading("getRemoteUser: ").cell().right(); table.addCell("" + request.getRemoteUser()); table.newRow(); table.addHeading("getRemoteAddr: ").cell().right(); table.addCell("" + request.getRemoteAddr()); table.newRow(); table.addHeading("getRemoteHost: ").cell().right(); table.addCell("" + request.getRemoteHost()); table.newRow(); table.addHeading("getRemotePort: ").cell().right(); table.addCell("" + request.getRemotePort()); table.newRow(); table.addHeading("getRequestedSessionId: ").cell().right(); table.addCell("" + request.getRequestedSessionId()); table.newRow(); table.addHeading("isSecure(): ").cell().right(); table.addCell("" + request.isSecure()); table.newRow(); table.addHeading("isUserInRole(admin): ").cell().right(); table.addCell("" + request.isUserInRole("admin")); table.newRow(); table.addHeading("getLocale: ").cell().right(); table.addCell("" + request.getLocale()); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { table.newRow(); table.addHeading("getLocales: ").cell().right(); table.addCell(locales.nextElement()); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers") .attribute("COLSPAN", "2").left(); Enumeration h = request.getHeaderNames(); String name; while (h.hasMoreElements()) { name = (String) h.nextElement(); Enumeration h2 = request.getHeaders(name); while (h2.hasMoreElements()) { String hv = (String) h2.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(hv); } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters") .attribute("COLSPAN", "2").left(); h = request.getParameterNames(); while (h.hasMoreElements()) { name = (String) h.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(request.getParameter(name)); String[] values = request.getParameterValues(name); if (values == null) { table.newRow(); table.addHeading(name + " Values: ").cell().right(); table.addCell("NULL!!!!!!!!!"); } else if (values.length > 1) { for (int i = 0; i < values.length; i++) { table.newRow(); table.addHeading(name + "[" + i + "]: ").cell().right(); table.addCell(values[i]); } } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left(); Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; table.newRow(); table.addHeading(cookie.getName() + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell(cookie.getValue()); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes") .attribute("COLSPAN", "2").left(); Enumeration a = request.getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>"); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters") .attribute("COLSPAN", "2").left(); a = getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters") .attribute("COLSPAN", "2").left(); a = getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes") .attribute("COLSPAN", "2").left(); a = getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"); } if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data") && request.getContentLength() < 1000000) { MultiPartRequest multi = new MultiPartRequest(request); String[] parts = multi.getPartNames(); table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content") .attribute("COLSPAN", "2").left(); for (int p = 0; p < parts.length; p++) { name = parts[p]; table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>"); } } String res = request.getParameter("resource"); if (res != null && res.length() > 0) { table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res) .attribute("COLSPAN", "2").left(); table.newRow(); table.addHeading("this.getClass(): ").cell().right(); table.addCell("" + this.getClass().getResource(res)); table.newRow(); table.addHeading("this.getClass().getClassLoader(): ").cell().right(); table.addCell("" + this.getClass().getClassLoader().getResource(res)); table.newRow(); table.addHeading("Thread.currentThread().getContextClassLoader(): ").cell().right(); table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res)); table.newRow(); table.addHeading("getServletContext(): ").cell().right(); try { table.addCell("" + getServletContext().getResource(res)); } catch (Exception e) { table.addCell("" + e); } } /* ------------------------------------------------------------ */ page.add(Break.para); page.add(new Heading(1, "Request Wrappers")); ServletRequest rw = request; int w = 0; while (rw != null) { page.add((w++) + ": " + rw.getClass().getName() + "<br/>"); if (rw instanceof HttpServletRequestWrapper) rw = ((HttpServletRequestWrapper) rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw = ((ServletRequestWrapper) rw).getRequest(); else rw = null; } page.add(Break.para); page.add(new Heading(1, "International Characters")); page.add("Directly encoced: Drst<br/>"); page.add("HTML reference: Dürst<br/>"); page.add("Decimal (252) 8859-1: Dürst<br/>"); page.add("Hex (xFC) 8859-1: Dürst<br/>"); page.add( "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>"); page.add(Break.para); page.add(new Heading(1, "Form to generate GET content")); TableForm tf = new TableForm(response.encodeURL(getURI(request))); tf.method("GET"); tf.addTextField("TextField", "TextField", 20, "value"); tf.addButton("Action", "Submit"); page.add(tf); page.add(Break.para); page.add(new Heading(1, "Form to generate POST content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("TextField", "TextField", 20, "value"); Select select = tf.addSelect("Select", "Select", true, 3); select.add("ValueA"); select.add("ValueB1,ValueB2"); select.add("ValueC"); tf.addButton("Action", "Submit"); page.add(tf); page.add(new Heading(1, "Form to upload content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.attribute("enctype", "multipart/form-data"); tf.addFileField("file", "file"); tf.addButton("Upload", "Upload"); page.add(tf); page.add(new Heading(1, "Form to get Resource")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("resource", "resource", 20, ""); tf.addButton("Action", "getResource"); page.add(tf); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } page.write(pout); String data = request.getParameter("data"); if (data != null && data.length() > 0) { int d = Integer.parseInt(data); while (d > 0) { pout.println("1234567890123456789012345678901234567890123456789\n"); d = d - 50; } } pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); if ("/ex7".equals(pi)) throw new HttpException(501); } request.getInputStream().close(); }
From source file:com.openkm.servlet.admin.BenchmarkServlet.java
/** * Generate documents into repository (Jackrabbit) */// ww w .j a va 2s .com private void jcrGenerate(HttpServletRequest request, HttpServletResponse response, String base) throws IOException { log.debug("jcrGenerate({}, {}, {})", new Object[] { request, response, base }); int maxDocuments = WebUtils.getInt(request, "param1"); int maxFolder = WebUtils.getInt(request, "param2"); int maxDepth = WebUtils.getInt(request, "param3"); int maxIterations = WebUtils.getInt(request, "param4"); PrintWriter out = response.getWriter(); PrintWriter results = new PrintWriter(Config.HOME_DIR + File.separator + base + ".csv"); long tBegin = 0, tEnd = 0, pBegin = 0, pEnd = 0; Benchmark bm = null; Session session = null; response.setContentType(MimeTypeConfig.MIME_HTML); header(out, "Jackrabbit generate documents", breadcrumb); out.flush(); try { session = JCRUtils.getSession(); bm = new Benchmark(maxDocuments, maxFolder, maxDepth); out.println("<b>- Documents:</b> " + bm.getMaxDocuments() + "<br/>"); out.println("<b>- Folders:</b> " + bm.getMaxFolders() + "<br/>"); out.println("<b>- Depth:</b> " + bm.getMaxDepth() + "<br/>"); out.println("<b>- Calibration:</b> " + bm.runCalibration() + " ms<br/>"); out.println("<b>- Calculated foldes:</b> " + bm.calculateFolders() + "<br/>"); out.println("<b>- Calculated documents:</b> " + bm.calculateDocuments() + "<br/><br/>"); results.print("\"Date\","); results.print("\"Time\","); results.print("\"Seconds\","); results.print("\"Folders\","); results.print("\"Documents\","); results.print("\"Size\"\n"); results.flush(); tBegin = System.currentTimeMillis(); for (int i = 0; i < maxIterations; i++) { out.println("<h2>Iteration " + i + "</h2>"); out.println("<table class=\"results\" width=\"80%\">"); out.println( "<tr><th>Date</th><th>Partial time</th><th>Partial miliseconds</th><th>Total folders</th><th>Total documents</th><th>Total size</th></tr>"); out.flush(); Node rootNode = session.getRootNode().getNode(Repository.ROOT); Node baseNode = null; if (rootNode.hasNode(base)) { baseNode = rootNode.getNode(base); } else { baseNode = rootNode.addNode(base, JcrConstants.NT_FOLDER); rootNode.save(); } PrintWriter pResults = new PrintWriter(Config.HOME_DIR + File.separator + base + "_" + i + ".csv"); pResults.print("\"Date\","); pResults.print("\"Time\","); pResults.print("\"Seconds\","); pResults.print("\"Folders\","); pResults.print("\"Documents\","); pResults.print("\"Size\"\n"); pResults.flush(); pBegin = System.currentTimeMillis(); bm.jcrPopulate(session, baseNode, out, pResults); pEnd = System.currentTimeMillis(); pResults.close(); out.println("</table>"); results.print("\"" + FormatUtil.formatDate(Calendar.getInstance()) + "\","); results.print("\"" + FormatUtil.formatSeconds(pEnd - pBegin) + "\","); results.print("\"" + (pEnd - pBegin) + "\","); results.print("\"" + bm.getTotalFolders() + "\","); results.print("\"" + bm.getTotalDocuments() + "\","); results.print("\"" + FormatUtil.formatSize(bm.getTotalSize()) + "\"\n"); results.flush(); out.println("<table class=\"results\" width=\"80%\">"); out.println( "<tr><th>Date</th><th>Partial time</th><th>Total folders</th><th>Total documents</th><th>Total size</th></tr>"); out.println("<td>" + FormatUtil.formatDate(Calendar.getInstance()) + "</td>"); out.println("<td>" + FormatUtil.formatSeconds(pEnd - pBegin) + "</td>"); out.println("<td>" + bm.getTotalFolders() + "</td>"); out.println("<td>" + bm.getTotalDocuments() + "</td>"); out.println("<td>" + FormatUtil.formatSize(bm.getTotalSize()) + "</td>"); out.println("</tr>"); out.println("</table>"); out.flush(); } tEnd = System.currentTimeMillis(); } catch (FileNotFoundException e) { out.println("<div class=\"warn\">FileNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.PathNotFoundException e) { out.println("<div class=\"warn\">PathNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.ItemExistsException e) { out.println("<div class=\"warn\">ItemExistsException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.AccessDeniedException e) { out.println("<div class=\"warn\">AccessDeniedException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.RepositoryException e) { out.println("<div class=\"warn\">RepositoryException: " + e.getMessage() + "</div>"); out.flush(); } catch (InputMismatchException e) { out.println("<div class=\"warn\">InputMismatchException: " + e.getMessage() + "</div>"); out.flush(); } catch (DatabaseException e) { out.println("<div class=\"warn\">DatabaseException: " + e.getMessage() + "</div>"); out.flush(); } finally { JCRUtils.logout(session); } long elapse = tEnd - tBegin; out.println("<hr/>"); out.println("<b>Total size:</b> " + FormatUtil.formatSize(bm.getTotalSize()) + "<br/>"); out.println("<b>Total folders:</b> " + bm.getTotalFolders() + "<br/>"); out.println("<b>Total documents:</b> " + bm.getTotalDocuments() + "<br/>"); out.println("<b>Total time:</b> " + FormatUtil.formatSeconds(elapse) + "<br/>"); out.println("<b>Documents per second:</b> " + bm.getTotalDocuments() / (elapse / 1000) + "<br/>"); footer(out); out.flush(); out.close(); results.close(); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_BENCHMARK_JCR", null, null, "Size: " + FormatUtil.formatSize(bm.getTotalSize()) + ", Folders: " + bm.getTotalFolders() + ", Documents: " + bm.getTotalDocuments() + ", Time: " + FormatUtil.formatSeconds(elapse)); log.debug("jcrGenerate: void"); }
From source file:org.opennms.web.controller.GraphResultsController.java
/** {@inheritDoc} */ @Override// w w w .j a v a 2 s . c o m protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { String[] requiredParameters = new String[] { "resourceId", "reports" }; for (String requiredParameter : requiredParameters) { if (request.getParameter(requiredParameter) == null) { throw new MissingParameterException(requiredParameter, requiredParameters); } } String[] resourceIds = request.getParameterValues("resourceId"); String[] reports = request.getParameterValues("reports"); // see if the start and end time were explicitly set as params String start = request.getParameter("start"); String end = request.getParameter("end"); String relativeTime = request.getParameter("relativetime"); final String startMonth = request.getParameter("startMonth"); final String startDate = request.getParameter("startDate"); final String startYear = request.getParameter("startYear"); final String startHour = request.getParameter("startHour"); final String endMonth = request.getParameter("endMonth"); final String endDate = request.getParameter("endDate"); final String endYear = request.getParameter("endYear"); final String endHour = request.getParameter("endHour"); long startLong = 0; long endLong = 0; if (start != null || end != null) { String[] ourRequiredParameters = new String[] { "start", "end" }; if (start == null) { throw new MissingParameterException("start", ourRequiredParameters); } if (end == null) { throw new MissingParameterException("end", ourRequiredParameters); } //The following is very similar to RrdGraphController.parseTimes, but modified for the local context a bit // There's merging possibilities, but I don't know how (common parent class seems wrong; service bean for a single // method isn't much better. Ideas? //Try a simple 'long' parsing. If either fails, do a full parse. If one is a straight 'long' but the other isn't // that's fine, the TimeParser code will handle it fine (as long as we convert milliseconds to seconds) // Indeed, we *have* to use TimeParse for both to ensure any relative references (using "start" or "end") work correctly. // NB: can't do a "safe" parsing using the WebSecurityUtils; if we did, it would filter out all the possible rrdfetch // format text and always work :) boolean startIsInteger = false; boolean endIsInteger = false; //If either of start/end *is* a long, convert from the incoming milliseconds to seconds that // is expected for epoch times by TimeParser try { startLong = Long.valueOf(start); startIsInteger = true; start = "" + (startLong / 1000); } catch (NumberFormatException e) { } try { endLong = Long.valueOf(end); endIsInteger = true; end = "" + (endLong / 1000); } catch (NumberFormatException e) { } if (!endIsInteger || !startIsInteger) { //One or both of start/end aren't integers, so we need to do full parsing using TimeParser TimeParser startParser = new TimeParser(start); TimeParser endParser = new TimeParser(end); try { TimeSpec specStart = startParser.parse(); TimeSpec specEnd = endParser.parse(); long[] results = TimeSpec.getTimestamps(specStart, specEnd); //Multiply by 1000. TimeSpec returns timestamps in Seconds, not Milliseconds. startLong = results[0] * 1000; endLong = results[1] * 1000; } catch (RrdException e1) { throw new IllegalArgumentException("Could not parse start '" + start + "' and end '" + end + "' as valid time specifications", e1); } } } else if (startMonth != null || startDate != null || startYear != null || startHour != null || endMonth != null || endDate != null || endYear != null || endHour != null) { String[] ourRequiredParameters = new String[] { "startMonth", "startDate", "startYear", "startHour", "endMonth", "endDate", "endYear", "endHour" }; for (String requiredParameter : ourRequiredParameters) { if (request.getParameter(requiredParameter) == null) { throw new MissingParameterException(requiredParameter, ourRequiredParameters); } } Calendar startCal = Calendar.getInstance(); startCal.set(Calendar.MONTH, WebSecurityUtils.safeParseInt(startMonth)); startCal.set(Calendar.DATE, WebSecurityUtils.safeParseInt(startDate)); startCal.set(Calendar.YEAR, WebSecurityUtils.safeParseInt(startYear)); startCal.set(Calendar.HOUR_OF_DAY, WebSecurityUtils.safeParseInt(startHour)); startCal.set(Calendar.MINUTE, 0); startCal.set(Calendar.SECOND, 0); startCal.set(Calendar.MILLISECOND, 0); Calendar endCal = Calendar.getInstance(); endCal.set(Calendar.MONTH, WebSecurityUtils.safeParseInt(endMonth)); endCal.set(Calendar.DATE, WebSecurityUtils.safeParseInt(endDate)); endCal.set(Calendar.YEAR, WebSecurityUtils.safeParseInt(endYear)); endCal.set(Calendar.HOUR_OF_DAY, WebSecurityUtils.safeParseInt(endHour)); endCal.set(Calendar.MINUTE, 0); endCal.set(Calendar.SECOND, 0); endCal.set(Calendar.MILLISECOND, 0); startLong = startCal.getTime().getTime(); endLong = endCal.getTime().getTime(); } else { if (relativeTime == null) { relativeTime = s_periods[0].getId(); } RelativeTimePeriod period = RelativeTimePeriod.getPeriodByIdOrDefault(s_periods, relativeTime, s_periods[0]); long[] times = period.getStartAndEndTimes(); startLong = times[0]; endLong = times[1]; } // The 'matching' parameter is going to work only for one resource. String matching = request.getParameter("matching"); if (matching != null) { reports = getSuggestedReports(resourceIds[0], matching); } ModelAndView modelAndView = null; try { GraphResults model = m_graphResultsService.findResults(resourceIds, reports, startLong, endLong, relativeTime); modelAndView = new ModelAndView("/graph/results", "results", model); } catch (Exception e) { LOG.warn("Can't get graph results", e); modelAndView = new ModelAndView("/graph/results-error"); } modelAndView.addObject("loggedIn", request.getRemoteUser() != null); return modelAndView; }
From source file:com.openkm.servlet.admin.BenchmarkServlet.java
/** * Generate documents into repository (OpenKM RAW) */// www. ja v a 2 s. co m private void okmApiLowGenerate(HttpServletRequest request, HttpServletResponse response, String base) throws IOException { log.debug("okmApiLowGenerate({}, {}, {})", new Object[] { request, response, base }); int maxDocuments = WebUtils.getInt(request, "param1"); int maxFolder = WebUtils.getInt(request, "param2"); int maxDepth = WebUtils.getInt(request, "param3"); int maxIterations = WebUtils.getInt(request, "param4"); PrintWriter out = response.getWriter(); PrintWriter results = new PrintWriter(Config.HOME_DIR + File.separator + base + ".csv"); long tBegin = 0, tEnd = 0, pBegin = 0, pEnd = 0; Benchmark bm = null; Session session = null; response.setContentType(MimeTypeConfig.MIME_HTML); header(out, "OpenKM generate documents (API LOW)", breadcrumb); out.flush(); try { session = JCRUtils.getSession(); bm = new Benchmark(maxDocuments, maxFolder, maxDepth); out.println("<b>- Documents:</b> " + bm.getMaxDocuments() + "<br/>"); out.println("<b>- Folders:</b> " + bm.getMaxFolders() + "<br/>"); out.println("<b>- Depth:</b> " + bm.getMaxDepth() + "<br/>"); out.println("<b>- Calibration:</b> " + bm.runCalibration() + " ms<br/>"); out.println("<b>- Calculated foldes:</b> " + bm.calculateFolders() + "<br/>"); out.println("<b>- Calculated documents:</b> " + bm.calculateDocuments() + "<br/><br/>"); results.print("\"Date\","); results.print("\"Time\","); results.print("\"Seconds\","); results.print("\"Folders\","); results.print("\"Documents\","); results.print("\"Size\"\n"); results.flush(); tBegin = System.currentTimeMillis(); for (int i = 0; i < maxIterations; i++) { out.println("<h2>Iteration " + i + "</h2>"); out.println("<table class=\"results\" width=\"80%\">"); out.println( "<tr><th>Date</th><th>Partial time</th><th>Partial miliseconds</th><th>Total folders</th><th>Total documents</th><th>Total size</th></tr>"); out.flush(); Node rootNode = session.getRootNode().getNode(Repository.ROOT); Node baseNode = null; if (rootNode.hasNode(base)) { baseNode = rootNode.getNode(base); } else { baseNode = BaseFolderModule.create(session, rootNode, base); } PrintWriter pResults = new PrintWriter(Config.HOME_DIR + File.separator + base + "_" + i + ".csv"); pResults.print("\"Date\","); pResults.print("\"Time\","); pResults.print("\"Seconds\","); pResults.print("\"Folders\","); pResults.print("\"Documents\","); pResults.print("\"Size\"\n"); pResults.flush(); pBegin = System.currentTimeMillis(); bm.okmApiLowPopulate(session, baseNode, out, pResults); pEnd = System.currentTimeMillis(); pResults.close(); out.println("</table>"); results.print("\"" + FormatUtil.formatDate(Calendar.getInstance()) + "\","); results.print("\"" + FormatUtil.formatSeconds(pEnd - pBegin) + "\","); results.print("\"" + (pEnd - pBegin) + "\","); results.print("\"" + bm.getTotalFolders() + "\","); results.print("\"" + bm.getTotalDocuments() + "\","); results.print("\"" + FormatUtil.formatSize(bm.getTotalSize()) + "\"\n"); results.flush(); out.println("<table class=\"results\" width=\"80%\">"); out.println( "<tr><th>Date</th><th>Partial time</th><th>Total folders</th><th>Total documents</th><th>Total size</th></tr>"); out.println("<td>" + FormatUtil.formatDate(Calendar.getInstance()) + "</td>"); out.println("<td>" + FormatUtil.formatSeconds(pEnd - pBegin) + "</td>"); out.println("<td>" + bm.getTotalFolders() + "</td>"); out.println("<td>" + bm.getTotalDocuments() + "</td>"); out.println("<td>" + FormatUtil.formatSize(bm.getTotalSize()) + "</td>"); out.println("</tr>"); out.println("</table>"); out.flush(); } tEnd = System.currentTimeMillis(); } catch (FileNotFoundException e) { out.println("<div class=\"warn\">FileNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.PathNotFoundException e) { out.println("<div class=\"warn\">PathNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.ItemExistsException e) { out.println("<div class=\"warn\">ItemExistsException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.AccessDeniedException e) { out.println("<div class=\"warn\">AccessDeniedException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.RepositoryException e) { out.println("<div class=\"warn\">RepositoryException: " + e.getMessage() + "</div>"); out.flush(); } catch (InputMismatchException e) { out.println("<div class=\"warn\">InputMismatchException: " + e.getMessage() + "</div>"); out.flush(); } catch (UserQuotaExceededException e) { out.println("<div class=\"warn\">UserQuotaExceededException: " + e.getMessage() + "</div>"); out.flush(); } catch (DatabaseException e) { out.println("<div class=\"warn\">DatabaseException: " + e.getMessage() + "</div>"); out.flush(); } finally { JCRUtils.logout(session); } long elapse = tEnd - tBegin; out.println("<hr/>"); out.println("<b>Total size:</b> " + FormatUtil.formatSize(bm.getTotalSize()) + "<br/>"); out.println("<b>Total folders:</b> " + bm.getTotalFolders() + "<br/>"); out.println("<b>Total documents:</b> " + bm.getTotalDocuments() + "<br/>"); out.println("<b>Total time:</b> " + FormatUtil.formatSeconds(elapse) + "<br/>"); out.println("<b>Documents per second:</b> " + bm.getTotalDocuments() / (elapse / 1000) + "<br/>"); footer(out); out.flush(); out.close(); results.close(); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_BENCHMARK_OKM_API_LOW", null, null, "Size: " + FormatUtil.formatSize(bm.getTotalSize()) + ", Folders: " + bm.getTotalFolders() + ", Documents: " + bm.getTotalDocuments() + ", Time: " + FormatUtil.formatSeconds(elapse)); log.debug("okmApiLowGenerate: void"); }