List of usage examples for org.apache.commons.lang RandomStringUtils randomAlphanumeric
public static String randomAlphanumeric(int count)
Creates a random string whose length is the number of characters specified.
Characters will be chosen from the set of alpha-numeric characters.
From source file:com.magnet.mmx.server.plugin.mmxmgmt.db.TagDAOImplTest.java
private static AppEntity createRandomApp(int index) throws Exception { String serverUserId = "serverUser"; String appName = APP_NAME_PREFIX + index; String appId = RandomStringUtils.randomAlphanumeric(10); String apiKey = UUID.randomUUID().toString(); String googleApiKey = UUID.randomUUID().toString(); String googleProjectId = RandomStringUtils.randomAlphanumeric(8); String apnsPwd = RandomStringUtils.randomAlphanumeric(10); String ownerId = RandomStringUtils.randomAlphabetic(10); String ownerEmail = RandomStringUtils.randomAlphabetic(4) + "@magnet.com"; String guestSecret = RandomStringUtils.randomAlphabetic(10); boolean apnsProductionEnvironment = false; AppEntity appEntity = new AppEntity(); appEntity.setServerUserId(serverUserId); appEntity.setName(appName);/*w w w .ja v a2 s .com*/ appEntity.setAppId(appId); appEntity.setAppAPIKey(apiKey); appEntity.setGoogleAPIKey(googleApiKey); appEntity.setGoogleProjectId(googleProjectId); appEntity.setApnsCertPassword(apnsPwd); appEntity.setOwnerId(ownerId); appEntity.setOwnerEmail(ownerEmail); appEntity.setGuestSecret(guestSecret); appEntity.setApnsCertProduction(apnsProductionEnvironment); DBTestUtil.getAppDAO().persist(appEntity); return appEntity; }
From source file:com.xtructure.xutil.valid.UTestValidateUtils.java
public void validateArgWithValidationStrategyBehavesAsExpected() { String argName = RandomStringUtils.randomAlphanumeric(10); ArgumentValidationStrategy<Object> validationStrategy = new ArgumentValidationStrategy<Object>(isNotNull()); boolean valid = validateArg(argName, new Object(), validationStrategy); if (!valid) { throw new AssertionError(); }//from www . ja v a2s .c o m try { validateArg(argName, null, validationStrategy); } catch (IllegalArgumentException e) { if (!String.format("%s (%s): %s", argName, null, isNotNull()).equals(e.getMessage())) { throw new AssertionError(); } } }
From source file:com.google.cloud.bigtable.hbase.TestIncrement.java
/** * Requirement 6.3 - Test that increment uses the current time as the default timestamp for new * versions./*from w w w . ja va 2 s.co m*/ */ @Test public void testDefaultTimestamp() throws IOException { long now = System.currentTimeMillis(); long oneMinute = 60 * 1000; long fifteenMinutes = 15 * 60 * 1000; Table table = getConnection().getTable(TABLE_NAME); byte[] rowKey = Bytes.toBytes("testrow-" + RandomStringUtils.randomAlphanumeric(8)); byte[] qualifier = Bytes.toBytes("testQualifier-" + RandomStringUtils.randomAlphanumeric(8)); Put put = new Put(rowKey); put.addColumn(COLUMN_FAMILY, qualifier, 1L, Bytes.toBytes(100L)); table.put(put); Increment increment = new Increment(rowKey).addColumn(COLUMN_FAMILY, qualifier, 1L); table.increment(increment); Get get = new Get(rowKey).addColumn(COLUMN_FAMILY, qualifier); Result result = table.get(get); long timestamp1 = result.getColumnLatestCell(COLUMN_FAMILY, qualifier).getTimestamp(); Assert.assertTrue(Math.abs(timestamp1 - now) < fifteenMinutes); try { TimeUnit.MILLISECONDS.sleep(10); // Make sure the clock has a chance to move } catch (InterruptedException e) { Thread.currentThread().interrupt(); } table.increment(increment); result = table.get(get); long timestamp2 = result.getColumnLatestCell(COLUMN_FAMILY, qualifier).getTimestamp(); Assert.assertTrue("Time increases strictly", timestamp2 > timestamp1); Assert.assertTrue("Time doesn't move too fast", (timestamp2 - timestamp1) < oneMinute); table.close(); }
From source file:elaborate.editor.model.orm.service.UserService.java
void composeAndSendEmail(Configuration config, Emailer emailer, User user) { String from_email = config.getSetting(Configuration.FROM_EMAIL); String from_name = config.getSetting(Configuration.FROM_NAME); String to_email = user.getEmail(); String subject = "Elaborate4 Password reset"; Map<String, Object> map = Maps.newHashMap(); map.put("user", user.getUsername()); String token = RandomStringUtils.randomAlphanumeric(20); Log.info("token={}", token); tokenMap.put(user.getId(), token);// w w w . j a va 2 s . co m map.put("url", MessageFormat.format("{0}/resetpassword?emailaddress={1}&token={2}", // config.getSetting(Configuration.WORK_URL), // user.getEmail(), // token// )); String body = FreeMarker.templateToString("email.ftl", map, getClass()); try { emailer.sendMail(from_email, from_name, to_email, subject, body); } catch (MessagingException e) { e.printStackTrace(); } }
From source file:com.cws.esolutions.core.processors.impl.ServerManagementProcessorImplTest.java
@Test public void addServerAsDevWebServer() { for (int x = 0; x < 4; x++) { String name = RandomStringUtils.randomAlphanumeric(8).toLowerCase(); Service service = new Service(); service.setGuid("1fe90f9d-0ead-4caf-92f6-a64be1dcc6aa"); Server server = new Server(); server.setOsName("CentOS"); server.setDomainName("caspersbox.corp"); server.setOperIpAddress("192.168.10.55"); server.setOperHostName(RandomStringUtils.randomAlphanumeric(8).toLowerCase()); server.setMgmtIpAddress("192.168.10.155"); server.setMgmtHostName(name + "-mgt"); server.setBkIpAddress("172.16.10.55"); server.setBkHostName(name + "-bak"); server.setNasIpAddress("172.15.10.55"); server.setNasHostName(name + "-nas"); server.setServerRegion(ServiceRegion.DEV); server.setServerStatus(ServerStatus.ONLINE); server.setServerType(ServerType.WEBSERVER); server.setServerComments("app server"); server.setAssignedEngineer(userAccount); server.setCpuType("AMD 1.0 GHz"); server.setCpuCount(1);/*w w w . j a va 2 s . co m*/ server.setServerModel("Virtual Server"); server.setSerialNumber("1YU391"); server.setInstalledMemory(4096); server.setNetworkPartition(NetworkPartition.DRN); server.setService(service); ServerManagementRequest request = new ServerManagementRequest(); request.setRequestInfo(hostInfo); request.setUserAccount(userAccount); request.setServiceId("45F6BC9E-F45C-4E2E-B5BF-04F93C8F512E"); request.setTargetServer(server); request.setApplicationId("6236B840-88B0-4230-BCBC-8EC33EE837D9"); request.setApplicationName("eSolutions"); try { ServerManagementResponse response = processor.addNewServer(request); Assert.assertEquals(CoreServicesStatus.SUCCESS, response.getRequestStatus()); } catch (ServerManagementException smx) { Assert.fail(smx.getMessage()); } } }
From source file:de.ingrid.portal.portlets.myportal.MyPortalLoginPortlet.java
/** * @see org.apache.portals.bridges.velocity.GenericVelocityPortlet#processAction(javax.portlet.ActionRequest, * javax.portlet.ActionResponse)//from w w w . j av a2 s.c om */ public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException { LoginForm frm = (LoginForm) Utils.getActionForm(request, LoginForm.SESSION_KEY, LoginForm.class); frm.clearErrors(); String cmd = request.getParameter("cmd"); boolean isLoggedInExternally = request.getAttribute(Settings.USER_AUTH_INFO) != null; if (cmd != null && cmd.equals("doLogin")) { HttpSession session = ((RequestContext) request.getAttribute(RequestContext.REQUEST_PORTALENV)) .getRequest().getSession(true); frm.populate(request); if (!frm.validate()) { return; } if (frm.getInput(LoginConstants.DESTINATION) != null) session.setAttribute(LoginConstants.DESTINATION, frm.getInput(LoginConstants.DESTINATION)); else session.removeAttribute(LoginConstants.DESTINATION); if (frm.getInput(LoginConstants.USERNAME) != null) session.setAttribute(LoginConstants.USERNAME, frm.getInput(LoginConstants.USERNAME)); else session.removeAttribute(LoginConstants.USERNAME); if (frm.getInput(LoginConstants.PASSWORD) != null) session.setAttribute(LoginConstants.PASSWORD, frm.getInput(LoginConstants.PASSWORD)); else session.removeAttribute(LoginConstants.PASSWORD); // signalize that the user is about to log in // see MyPortalOverviewPortlet::doView() session.setAttribute(Settings.SESSION_LOGIN_STARTED, "1"); response.sendRedirect( response.encodeURL(((RequestContext) request.getAttribute(RequestContext.REQUEST_PORTALENV)) .getRequest().getContextPath() + "/login/redirector")); } else if (cmd != null && cmd.equals("doCreateProfile") && isLoggedInExternally) { PortalAdministration admin = (PortalAdministration) getPortletContext() .getAttribute(CommonPortletServices.CPS_PORTAL_ADMINISTRATION); List<String> roles = getInitialParameterFromOtherPortlet("roles"); List<String> groups = getInitialParameterFromOtherPortlet("groups"); List<String> rulesNames = getInitialParameterFromOtherPortlet("rulesNames"); List<String> rulesValues = getInitialParameterFromOtherPortlet("rulesValues"); Map<String, String> rules = new HashMap<String, String>(); for (int ix = 0; ix < ((rulesNames.size() < rulesValues.size()) ? rulesNames.size() : rulesValues.size()); ix++) { rules.put(rulesNames.get(ix), rulesValues.get(ix)); } Map<String, String> userAttributes = getUserAttributes(request); String username = (String) request.getAttribute(Settings.USER_AUTH_INFO); String password = RandomStringUtils.randomAlphanumeric(8); Boolean isAdminPortalUser = (Boolean) request.getAttribute(Settings.USER_AUTH_INFO_IS_ADMIN); // generate login id String confirmId = Utils .getMD5Hash(username.concat(password).concat(Long.toString(System.currentTimeMillis()))); userAttributes.put("user.custom.ingrid.user.confirmid", confirmId); // add admin-portal role if (isAdminPortalUser) { roles.add("user"); roles.add(IngridRole.ROLE_ADMIN_PORTAL); } try { log.debug("username: " + username + ", roles: " + roles + ", groups: " + groups + ", userAttr: " + userAttributes + ", rules: " + rules); admin.registerUser(username, password, roles, groups, userAttributes, rules, null); //UserManager userManager = (UserManager) getPortletContext().getAttribute(CommonPortletServices.CPS_USER_MANAGER_COMPONENT); //userManager.setPasswordEnabled(username, false); if (isAdminPortalUser) { addAdminSystemRole(username); } } catch (RegistrationException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } else { Integer errorCode = (Integer) ((RequestContext) request.getAttribute(RequestContext.REQUEST_PORTALENV)) .getSessionAttribute(LoginConstants.ERRORCODE); if (errorCode != null) { response.setRenderParameter("errorCode", errorCode.toString()); } else if (request.getUserPrincipal() == null) { response.setRenderParameter("errorCode", "login.error.principal.null"); } else { frm.clearErrors(); } } }
From source file:com.streamreduce.core.model.ConnectionTest.java
@Test public void testConnectionMergeWithJson_CopiesAllConnectionCredentialFields() { String expectedIdentity = RandomStringUtils.randomAlphanumeric(10); String expectedCredential = RandomStringUtils.randomAlphanumeric(10); String expectedApiKey = RandomStringUtils.randomAlphanumeric(10); String expectedOAuthToken = RandomStringUtils.randomAlphanumeric(10); String expectedOAuthTokenSecret = RandomStringUtils.randomAlphanumeric(10); Connection connection = TestUtils.createCloudConnection(); JSONObject jsonObject = new JSONObjectBuilder().add("credentials", new JSONObjectBuilder().add("identity", expectedIdentity).add("credential", expectedCredential) .add("api_key", expectedApiKey).add("oauthToken", expectedOAuthToken) .add("oauthTokenSecret", expectedOAuthTokenSecret).build()) .build();//from w w w. j av a 2 s. c om connection.mergeWithJSON(jsonObject); ConnectionCredentials mergedCredentials = connection.getCredentials(); Assert.assertEquals(expectedIdentity, mergedCredentials.getIdentity()); Assert.assertEquals(expectedCredential, mergedCredentials.getCredential()); Assert.assertEquals(expectedApiKey, mergedCredentials.getApiKey()); Assert.assertEquals(expectedOAuthToken, mergedCredentials.getOauthToken()); Assert.assertEquals(expectedOAuthTokenSecret, mergedCredentials.getOauthTokenSecret()); }
From source file:com.ofbizcn.securityext.login.LoginEvents.java
/** * Email the password for the userLoginId specified in the request object. * * @param request The HTTPRequest object for the current request * @param response The HTTPResponse object for the current request * @return String specifying the exit status of this event *//*from ww w .ja v a2 s.c om*/ public static String emailPassword(HttpServletRequest request, HttpServletResponse response) { String defaultScreenLocation = "component://securityext/widget/EmailSecurityScreens.xml#PasswordEmail"; Delegator delegator = (Delegator) request.getAttribute("delegator"); LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); String productStoreId = "";//ProductStoreWorker.getProductStoreId(request); String errMsg = null; boolean useEncryption = "true".equals( EntityUtilProperties.getPropertyValue("security.properties", "password.encrypt", delegator)); String userLoginId = request.getParameter("USERNAME"); if ((userLoginId != null) && ("true".equals( EntityUtilProperties.getPropertyValue("security.properties", "username.lowercase", delegator)))) { userLoginId = userLoginId.toLowerCase(); } if (!UtilValidate.isNotEmpty(userLoginId)) { // the password was incomplete errMsg = UtilProperties.getMessage(resource, "loginevents.username_was_empty_reenter", UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } GenericValue supposedUserLogin = null; String passwordToSend = null; try { supposedUserLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId) .queryOne(); if (supposedUserLogin == null) { // the Username was not found errMsg = UtilProperties.getMessage(resource, "loginevents.username_not_found_reenter", UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } if (useEncryption) { // password encrypted, can't send, generate new password and email to user passwordToSend = RandomStringUtils.randomAlphanumeric(Integer.parseInt( EntityUtilProperties.getPropertyValue("security", "password.length.min", "5", delegator))); if ("true".equals(EntityUtilProperties.getPropertyValue("security.properties", "password.lowercase", delegator))) { passwordToSend = passwordToSend.toLowerCase(); } supposedUserLogin.set("currentPassword", HashCrypt.cryptUTF8(LoginServices.getHashType(), null, passwordToSend)); supposedUserLogin.set("passwordHint", "Auto-Generated Password"); if ("true".equals(EntityUtilProperties.getPropertyValue("security.properties", "password.email_password.require_password_change", delegator))) { supposedUserLogin.set("requirePasswordChange", "Y"); } } else { passwordToSend = supposedUserLogin.getString("currentPassword"); } } catch (GenericEntityException e) { Debug.logWarning(e, "", module); Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.toString()); errMsg = UtilProperties.getMessage(resource, "loginevents.error_accessing_password", messageMap, UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } StringBuilder emails = new StringBuilder(); GenericValue party = null; try { party = supposedUserLogin.getRelatedOne("Party", false); } catch (GenericEntityException e) { Debug.logWarning(e, "", module); party = null; } if (party != null) { Iterator<GenericValue> emailIter = UtilMisc .toIterator(ContactHelper.getContactMechByPurpose(party, "PRIMARY_EMAIL", false)); while (emailIter != null && emailIter.hasNext()) { GenericValue email = emailIter.next(); emails.append(emails.length() > 0 ? "," : "").append(email.getString("infoString")); } } if (!UtilValidate.isNotEmpty(emails.toString())) { // the Username was not found errMsg = UtilProperties.getMessage(resource, "loginevents.no_primary_email_address_set_contact_customer_service", UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } // get the ProductStore email settings GenericValue productStoreEmail = null; try { productStoreEmail = EntityQuery.use(delegator).from("ProductStoreEmailSetting") .where("productStoreId", productStoreId, "emailType", "PRDS_PWD_RETRIEVE").queryOne(); } catch (GenericEntityException e) { Debug.logError(e, "Problem getting ProductStoreEmailSetting", module); } String bodyScreenLocation = null; if (productStoreEmail != null) { bodyScreenLocation = productStoreEmail.getString("bodyScreenLocation"); } if (UtilValidate.isEmpty(bodyScreenLocation)) { bodyScreenLocation = defaultScreenLocation; } // set the needed variables in new context Map<String, Object> bodyParameters = FastMap.newInstance(); bodyParameters.put("useEncryption", Boolean.valueOf(useEncryption)); bodyParameters.put("password", UtilFormatOut.checkNull(passwordToSend)); bodyParameters.put("locale", UtilHttp.getLocale(request)); bodyParameters.put("userLogin", supposedUserLogin); bodyParameters.put("productStoreId", productStoreId); Map<String, Object> serviceContext = FastMap.newInstance(); serviceContext.put("bodyScreenUri", bodyScreenLocation); serviceContext.put("bodyParameters", bodyParameters); if (productStoreEmail != null) { serviceContext.put("subject", productStoreEmail.getString("subject")); serviceContext.put("sendFrom", productStoreEmail.get("fromAddress")); serviceContext.put("sendCc", productStoreEmail.get("ccAddress")); serviceContext.put("sendBcc", productStoreEmail.get("bccAddress")); serviceContext.put("contentType", productStoreEmail.get("contentType")); } else { GenericValue emailTemplateSetting = null; try { emailTemplateSetting = EntityQuery.use(delegator).from("EmailTemplateSetting") .where("emailTemplateSettingId", "EMAIL_PASSWORD").cache().queryOne(); } catch (GenericEntityException e) { Debug.logError(e, module); } if (emailTemplateSetting != null) { String subject = emailTemplateSetting.getString("subject"); subject = FlexibleStringExpander.expandString(subject, UtilMisc.toMap("userLoginId", userLoginId)); serviceContext.put("subject", subject); serviceContext.put("sendFrom", emailTemplateSetting.get("fromAddress")); } else { serviceContext.put("subject", UtilProperties.getMessage(resource, "loginservices.password_reminder_subject", UtilMisc.toMap("userLoginId", userLoginId), UtilHttp.getLocale(request))); serviceContext.put("sendFrom", EntityUtilProperties.getPropertyValue("general.properties", "defaultFromEmailAddress", delegator)); } } serviceContext.put("sendTo", emails.toString()); serviceContext.put("partyId", party.getString("partyId")); try { Map<String, Object> result = dispatcher.runSync("sendMailHiddenInLogFromScreen", serviceContext); if (ModelService.RESPOND_ERROR.equals(result.get(ModelService.RESPONSE_MESSAGE))) { Map<String, Object> messageMap = UtilMisc.toMap("errorMessage", result.get(ModelService.ERROR_MESSAGE)); errMsg = UtilProperties.getMessage(resource, "loginevents.error_unable_email_password_contact_customer_service_errorwas", messageMap, UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } } catch (GenericServiceException e) { Debug.logWarning(e, "", module); errMsg = UtilProperties.getMessage(resource, "loginevents.error_unable_email_password_contact_customer_service", UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } // don't save password until after it has been sent if (useEncryption) { try { supposedUserLogin.store(); } catch (GenericEntityException e) { Debug.logWarning(e, "", module); Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.toString()); errMsg = UtilProperties.getMessage(resource, "loginevents.error_saving_new_password_email_not_correct_password", messageMap, UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } } if (useEncryption) { errMsg = UtilProperties.getMessage(resource, "loginevents.new_password_createdandsent_check_email", UtilHttp.getLocale(request)); request.setAttribute("_EVENT_MESSAGE_", errMsg); } else { errMsg = UtilProperties.getMessage(resource, "loginevents.new_password_sent_check_email", UtilHttp.getLocale(request)); request.setAttribute("_EVENT_MESSAGE_", errMsg); } return "success"; }
From source file:com.blackberry.logtools.logmultisearch.java
@SuppressWarnings("static-access") public int run(String[] argv) throws Exception { //Configuring configuration and filesystem to work on HDFS final Configuration conf = getConf(); //Configuration processed by ToolRunner FileSystem fs = FileSystem.get(conf); //Initiate tools used for running search LogTools tools = new LogTools(); //Other options String date_format = "RFC5424"; String field_separator = ""; ArrayList<String> D_options = new ArrayList<String>(); boolean quiet = true; boolean silent = false; boolean log = false; boolean forcelocal = false; boolean forceremote = false; //The arguments are // - strings/*from www . ja va2 s.c o m*/ // - dc number // - service // - component // - startTime (Something 'date' can parse, or just a time in ms from epoch) // - endTime (Same as start) // - outputDir //Indexing for arguments to be passed for Mapreduce int stringsNum = 0; int dcNum = 1; int svcNum = 2; int compNum = 3; int startNum = 4; int endNum = 5; int outNum = 6; //Parsing through user arguments String[] args = new String[7]; int count = 0; //Count created to track the parse of all arguments int argcount = 0; //Count created to track number of arguments to be passed on while (count < argv.length) { String arg = argv[count]; count++; if (arg.equals("--")) { break; } else if (arg.startsWith("-")) { if (arg.equals("--v")) { quiet = tools.parseV(silent); } else if (arg.equals("--i")) { conf.set("logdriver.search.case.insensitive", "true"); } else if (arg.equals("--a")) { LogTools.logConsole(quiet, silent, warn, "AND searching selected"); conf.set("logdriver.search.and", "true"); } else if (arg.startsWith("--dateFormat=")) { arg = arg.replace("--dateFormat=", ""); date_format = arg; } else if (arg.startsWith("--fieldSeparator=")) { arg = arg.replace("--fieldSeparator=", ""); field_separator = arg; } else if (arg.startsWith("-strings=")) { arg = arg.replace("-strings=", ""); args[stringsNum] = arg; argcount++; } else if (arg.startsWith("-dc=")) { arg = arg.replace("-dc=", ""); args[dcNum] = arg; argcount++; } else if (arg.startsWith("-svc=")) { arg = arg.replace("-svc=", ""); args[svcNum] = arg; argcount++; } else if (arg.startsWith("-comp=")) { arg = arg.replace("-comp=", ""); args[compNum] = arg; argcount++; } else if (arg.startsWith("-start=")) { arg = arg.replace("-start=", ""); args[startNum] = arg; argcount++; } else if (arg.startsWith("-end=")) { arg = arg.replace("-end=", ""); args[endNum] = arg; argcount++; } //User inputs output directory that is to be created //Check to see if parent directory exists && output directory does not exist else if (arg.startsWith("--out=")) { args[outNum] = tools.parseOut(arg, fs); argcount++; } else if (arg.startsWith("-D")) { D_options.add(arg); } else if (arg.equals("--silent")) { silent = tools.parseSilent(quiet); } else if (arg.equals("--log")) { log = true; } else if (arg.equals("--l")) { forcelocal = tools.parsePigMode(forceremote); } else if (arg.equals("--r")) { forceremote = tools.parsePigMode(forcelocal); } else { LogTools.logConsole(quiet, silent, error, "Unrecognized option: " + arg); System.exit(1); } } else { LogTools.logConsole(quiet, silent, error, "Unrecognized option: " + arg); System.exit(1); } } //Default output should be stdout represented by "-" if (args[outNum] == null) { args[outNum] = "-"; argcount++; LogTools.logConsole(quiet, silent, info, "Output set to default stdout."); } if (argcount < 7) { System.err.println(";****************************************" + "\n\t\t\t NOT ENOUGH ARGUMENTS\n" + "\n\tUSAGE: logmultisearch [REQUIRED ARGUMENTS] [OPTIONS] (Order does not matter)" + "\n\tREQUIRED ARGUMENTS:" + "\n\t\t-strings=[STRINGS_DIR|STRINGS_FILE|STRING] String/file/directory of strings to search." + "\n\t\t-dc=[DATACENTER] Data Center." + "\n\t\t-svc=[SERVICE] Service." + "\n\t\t-comp=[COMPONENT] Component." + "\n\t\t-start=[START] Start time." + "\n\t\t-end=[END] End time." + "\n\tOptions:" + "\n\t\t--out=[DIRECTORY] Desired output directory. If not defined, output to stdout." + "\n\t\t--v Verbose output." + "\n\t\t--r Force remote sort." + "\n\t\t--l Force local sort." + "\n\t\t--dateFormat=[FORMAT] Valid formats are RFC822, RFC3164 (zero padded day)," + "\n\t RFC5424 (default), or any valid format string for FastDateFormat." + "\n\t\t--fieldSeparator=X The separator to use to separate fields in intermediate" + "\n\t files. Defaults to 'INFORMATION SEPARATOR ONE' (U+001F)." + "\n\t\t--silent Output only the data." + "\n\t\t--i Make search case insensitive." + "\n\t\t--a Enable AND searching." + "\n\t\t--log Save all the logs.\n" + ";****************************************"); System.exit(1); } //Parse time inputs for start and end of search args[startNum] = tools.parseDate(args[startNum]); args[endNum] = tools.parseDate(args[endNum]); tools.checkTime(args[startNum], args[endNum]); //Retrieve 'strings' argument to be able to pass search strings to HDFS //Retrieve 'out' argument to determine where output of results should be sent String strings = args[stringsNum]; String out = args[outNum]; //Generate files to temporarily store output of mapreduce jobs and pig logs locally File local_output = File.createTempFile("tmp.", RandomStringUtils.randomAlphanumeric(10)); if (log != true) { local_output.deleteOnExit(); } File pig_tmp = File.createTempFile("tmp.", RandomStringUtils.randomAlphanumeric(10)); if (log != true) { pig_tmp.deleteOnExit(); } //Name the temp directory for storing results in HDFS String tmp = "tmp/logmultisearch-" + RandomStringUtils.randomAlphanumeric(10); //Set args[stringsNum] to be location of search strings to be used for the Multisearch args[stringsNum] = (StringEscapeUtils.escapeJava(tmp) + "/strings"); //Set args[outNum] to be temp output directory to be passed onto MultiSearchByTime instead of UserInput argument args[outNum] = (StringEscapeUtils.escapeJava(tmp) + "/rawlines"); //Managing console output - deal with --v/--silent Logger LOG = LoggerFactory.getLogger(logmultisearch.class); tools.setConsoleOutput(local_output, quiet, silent); //Create temp directory in HDFS to store logsearch logs before sorting tools.tmpDirHDFS(quiet, silent, fs, conf, tmp, log); //If the strings argument is the path of a file, copy the file to HDFS. //If the strings argument is the path of a directory, copy all files in the directory to HDFS. //If the strings argument is not a path to a file/directory, write to a newly created file in HDFS. try { File f = new File(strings); if (f.isFile()) { LogTools.logConsole(quiet, silent, warn, "Strings input is a File..."); //dos2unix file conversion File dos2unix = File.createTempFile("tmp.", RandomStringUtils.randomAlphanumeric(10)); dos2unix.deleteOnExit(); tools.dosTounix(f, dos2unix); //Copy over temp directory into a new directory in HDFS to be used for logmultisearch fs.copyFromLocalFile(new Path(dos2unix.getAbsolutePath()), new Path(tmp + "/strings")); } else if (f.isDirectory()) { LogTools.logConsole(quiet, silent, warn, "Strings input is a Directory..."); //Get list of all files in directory to convert from dos2unix String[] fileList = f.list(); //Create temp directory to store all converted files File tempDir = Files.createTempDir(); tempDir.deleteOnExit(); //Convert all files from dos2unix and write to temp directory for (int i = 0; i < fileList.length; i++) { File dos2unix = File.createTempFile("unix", fileList[i], tempDir); dos2unix.deleteOnExit(); tools.dosTounix(new File(f.getAbsolutePath() + "/" + fileList[i]), dos2unix); } //Copy over temp directory into a new directory in HDFS to be used for logmultisearch fs.copyFromLocalFile(new Path(tempDir.getAbsolutePath()), new Path(tmp + "/strings")); } else { LogTools.logConsole(quiet, silent, warn, "Strings input is a search string..."); //Make directory and file for strings fs.mkdirs(new Path(tmp + "/strings")); fs.createNewFile(new Path(tmp + "/strings/strings")); //Write search strings to file FSDataOutputStream hdfsOut = fs.create(new Path(tmp + "/strings/strings")); hdfsOut.writeUTF(strings); hdfsOut.close(); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } LogTools.logConsole(quiet, silent, warn, "Searching..."); LogTools.logConsole(quiet, silent, warn, "Passing Arguments: SearchStrings=" + strings + " DC=" + args[dcNum] + " Service=" + args[svcNum] + " Component=" + args[compNum] + " StartTime=" + args[startNum] + " EndTime=" + args[endNum] + " Output=" + out); //Set standard configuration for running Mapreduce and PIG String queue_name = "logsearch"; //Start Mapreduce job tools.runMRJob(quiet, silent, conf, D_options, out, LOG, field_separator, queue_name, args, "MultiSearchByTime", new MultiSearchByTime()); //Before sorting, determine the number of records and size of the results found long foundresults = tools.getResults(local_output); long size = tools.getSize(foundresults, tmp, fs); //Run PIG job if results found tools.runPig(silent, quiet, foundresults, size, tmp, out, D_options, queue_name, date_format, field_separator, pig_tmp, fs, conf, forcelocal, forceremote); //Display location of tmp files if log enabled tools.logs(log, local_output, pig_tmp, tmp); return 0; }
From source file:fr.xebia.demo.amazon.aws.AmazonAwsIamAccountCreatorV2.java
/** * Create an Amazon IAM account with a password, a secret key and member of * "Admins". The password, access key and secret key are sent by email. * // w w w .j a v a 2 s.c o m * @param userName * valid email used as userName of the created account. */ public void createUsers(String userName) { CreateUserRequest createUserRequest = new CreateUserRequest(userName); CreateUserResult createUserResult = iam.createUser(createUserRequest); User user = createUserResult.getUser(); String password = RandomStringUtils.randomAlphanumeric(8); iam.createLoginProfile(new CreateLoginProfileRequest(user.getUserName(), password)); iam.addUserToGroup(new AddUserToGroupRequest("Admins", user.getUserName())); CreateAccessKeyResult createAccessKeyResult = iam .createAccessKey(new CreateAccessKeyRequest().withUserName(user.getUserName())); AccessKey accessKey = createAccessKeyResult.getAccessKey(); // SSH KeyPair sshKeyPair = createOrOverWriteSshKeyPair(userName); // X509 java.security.KeyPair x509KeyPair = createRsaKeyPair(); X509Certificate x509Certificate = createX509Certificate(userName, x509KeyPair); SigningCertificate signingCertificate; try { UploadSigningCertificateResult uploadSigningCertificateResult = iam .uploadSigningCertificate(new UploadSigningCertificateRequest(Pems.pem(x509Certificate)) .withUserName(user.getUserName())); signingCertificate = uploadSigningCertificateResult.getCertificate(); } catch (CertificateEncodingException e) { throw Throwables.propagate(e); } System.out.println("CREATED userName=" + user.getUserName() + "\tpassword=" + password + "\taccessKeyId=" + accessKey.getAccessKeyId() + "\tsecretAccessKey=" + accessKey.getSecretAccessKey() + "\tsshKeyPair=" + sshKeyPair.getKeyName() + "\tx509Certificate=" + signingCertificate.getCertificateId()); String subject = "Xebia France Amazon EC2 Credentials"; String body = "Hello,\n"; body += "\n"; body += "Here are the credentials to connect to Xebia Amazon AWS/EC2 training infrastructure:\n"; body += "\n"; body += "User Name: " + user.getUserName() + "\n"; body += "Password: " + password + "\n"; body += "\n"; body += "Access Key Id: " + accessKey.getAccessKeyId() + "\n"; body += "Secret Access Key: " + accessKey.getSecretAccessKey() + "\n"; body += "\n"; body += "SSH private key pair '" + sshKeyPair.getKeyName() + "' attached, rename it as '" + sshKeyPair.getKeyName() + ".pem" + "'n"; body += "\n"; body += "The authentication page is https://xebia-france.signin.aws.amazon.com/console"; body += "\n"; body += "Don't hesitate to connect to Amazon AWS, to play with it but please DO NOT FORGET TO STOP INSTANCES OR IF POSSIBLE TERMINATE THEM AFTER USING THEM.\n"; body += "Letting instances started would cost unnecessary money to Xebia.\n"; body += "\n"; body += "\n"; body += "Thanks,\n"; body += "\n"; body += "Cyrille"; try { sendEmail(subject, body, accessKey, sshKeyPair, x509KeyPair, x509Certificate, signingCertificate, "cyrille@cyrilleleclerc.com", user.getUserName()); } catch (Exception e) { e.printStackTrace(); } }