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.buddycloud.mediaserver.business.dao.MediaDAO.java
protected Media storeMedia(String fileName, String title, String description, String author, String entityId, String mimeType, byte[] data, final boolean isAvatar) throws FileUploadException { String directory = getDirectory(entityId); mkdir(directory);/* ww w. j ava 2s .co m*/ // TODO assert id uniqueness String mediaId = RandomStringUtils.randomAlphanumeric(20); String filePath = directory + File.separator + mediaId; File file = new File(filePath); LOGGER.debug("Storing new media: " + file.getAbsolutePath()); try { FileOutputStream out = FileUtils.openOutputStream(file); out.write(data); out.close(); } catch (IOException e) { LOGGER.error("Error while storing file: " + filePath, e); throw new FileUploadException(e.getMessage()); } final Media media = createMedia(mediaId, fileName, title, description, author, entityId, mimeType, file, isAvatar); // store media's metadata new Thread() { public void start() { try { dataSource.storeMedia(media); if (isAvatar) { if (dataSource.getEntityAvatarId(media.getEntityId()) != null) { dataSource.updateEntityAvatar(media.getEntityId(), media.getId()); } else { dataSource.storeAvatar(media); } } } catch (MetadataSourceException e) { // do nothing LOGGER.error("Database error", e); } } }.start(); return media; }
From source file:com.kixeye.chassis.transport.WebSocketTransportTest.java
@Test public void testWebSocketServiceWithJsonWithWss() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("secureWebsocket.enabled", "true"); properties.put("secureWebsocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("secureWebsocket.hostname", "localhost"); properties.put("secureWebsocket.selfSigned", "true"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestWebSocketService.class); SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setTrustAll(true); WebSocketClient wsClient = new WebSocketClient(sslContextFactory); try {/* w ww .j a v a2 s. c om*/ context.refresh(); final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class); final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class); messageRegistry.registerType("stuff", TestObject.class); wsClient.start(); QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, null); Session session = wsClient.connect(webSocket, new URI("wss://localhost:" + properties.get("secureWebsocket.port") + "/" + serDe.getMessageFormatName())) .get(5000, TimeUnit.MILLISECONDS); Envelope envelope = new Envelope("getStuff", null, null, Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), null); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); byte[] rawStuff = serDe.serialize(new TestObject("more stuff")); envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff)); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); envelope = new Envelope("getStuff", null, null, null); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100))); envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff)); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(error); Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code); envelope = new Envelope("expectedError", null, null, null); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); error = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(error); Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code); Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description); envelope = new Envelope("unexpectedError", null, null, null); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); error = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(error); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code); } finally { try { wsClient.stop(); } finally { context.close(); } } }
From source file:com.tasktop.c2c.server.profile.tests.service.BaseProfileServiceTest.java
@Test(expected = ValidationException.class) public void testCreateProjectDescriptionTooLong() throws ValidationException, EntityNotFoundException { Profile profile = createMockProfile(entityManager); Project project = createMockProject(null); String string256 = RandomStringUtils.randomAlphanumeric(256); project.setDescription(string256);/*from ww w .j a v a2 s. c o m*/ try { profileService.createProject(profile.getId(), project); } catch (ValidationException e) { // expected assertHaveValidationError(e, "Description is too long (Maximum of 255 characters)"); throw e; } }
From source file:com.cws.esolutions.core.processors.impl.ServerManagementProcessorImplTest.java
@Test public void addServerAsQaMasterDnsServer() { 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.QA); server.setServerStatus(ServerStatus.ONLINE); server.setServerType(ServerType.DNSMASTER); server.setServerComments("app server"); server.setAssignedEngineer(userAccount); server.setCpuType("AMD 1.0 GHz"); server.setCpuCount(1);// www.j a v a2 s . c om 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:alluxio.cli.fs.command.CpCommand.java
/** * Copies a file specified by argv from the filesystem to the local filesystem. This is the * utility function./*from ww w . j a va 2s . c o m*/ * * @param srcPath The source {@link AlluxioURI} (has to be a file) * @param dstPath The {@link AlluxioURI} of the destination in the local filesystem */ private void copyFileToLocal(AlluxioURI srcPath, AlluxioURI dstPath) throws AlluxioException, IOException { File dstFile = new File(dstPath.getPath()); String randomSuffix = String.format(".%s_copyToLocal_", RandomStringUtils.randomAlphanumeric(8)); File outputFile; if (dstFile.isDirectory()) { outputFile = new File(PathUtils.concatPath(dstFile.getAbsolutePath(), srcPath.getName())); } else { outputFile = dstFile; } File tmpDst = new File(outputFile.getPath() + randomSuffix); try (Closer closer = Closer.create()) { OpenFileOptions options = OpenFileOptions.defaults(); FileInStream is = closer.register(mFileSystem.openFile(srcPath, options)); FileOutputStream out = closer.register(new FileOutputStream(tmpDst)); byte[] buf = new byte[64 * Constants.MB]; int t = is.read(buf); while (t != -1) { out.write(buf, 0, t); t = is.read(buf); } if (!tmpDst.renameTo(outputFile)) { throw new IOException( "Failed to rename " + tmpDst.getPath() + " to destination " + outputFile.getPath()); } System.out.println("Copied " + srcPath + " to " + "file://" + outputFile.getPath()); } finally { tmpDst.delete(); } }
From source file:alluxio.shell.command.CpCommand.java
/** * Copies a file specified by argv from the filesystem to the local filesystem. This is the * utility function.//from w w w . j a va2s.com * * @param srcPath The source {@link AlluxioURI} (has to be a file) * @param dstPath The {@link AlluxioURI} of the destination in the local filesystem * @throws AlluxioException when Alluxio exception occurs * @throws IOException when non-Alluxio exception occurs */ private void copyFileToLocal(AlluxioURI srcPath, AlluxioURI dstPath) throws AlluxioException, IOException { File dstFile = new File(dstPath.getPath()); String randomSuffix = String.format(".%s_copyToLocal_", RandomStringUtils.randomAlphanumeric(8)); File outputFile; if (dstFile.isDirectory()) { outputFile = new File(PathUtils.concatPath(dstFile.getAbsolutePath(), srcPath.getName())); } else { outputFile = dstFile; } File tmpDst = new File(outputFile.getPath() + randomSuffix); try (Closer closer = Closer.create()) { OpenFileOptions options = OpenFileOptions.defaults().setReadType(ReadType.NO_CACHE); FileInStream is = closer.register(mFileSystem.openFile(srcPath, options)); FileOutputStream out = closer.register(new FileOutputStream(tmpDst)); byte[] buf = new byte[64 * Constants.MB]; int t = is.read(buf); while (t != -1) { out.write(buf, 0, t); t = is.read(buf); } if (!tmpDst.renameTo(outputFile)) { throw new IOException( "Failed to rename " + tmpDst.getPath() + " to destination " + outputFile.getPath()); } System.out.println("Copied " + srcPath + " to " + "file://" + outputFile.getPath()); } finally { tmpDst.delete(); } }
From source file:com.buddycloud.mediaserver.business.dao.MediaDAO.java
protected Thumbnail getPreview(String entityId, String mediaId, Integer maxHeight, Integer maxWidth, String mediaDirectory)/*from www . j a v a 2 s.co m*/ throws MetadataSourceException, IOException, InvalidPreviewFormatException, MediaNotFoundException { File media = new File(mediaDirectory + File.separator + mediaId); if (!media.exists()) { throw new MediaNotFoundException(mediaId, entityId); } String previewId = dataSource.getPreviewId(mediaId, maxHeight, maxWidth); if (previewId != null) { File preview = new File(mediaDirectory + File.separator + previewId); if (!preview.exists()) { dataSource.deletePreview(previewId); } else { return new Thumbnail(dataSource.getPreviewMimeType(previewId), IOUtils.toByteArray(FileUtils.openInputStream(preview))); } } else { // generate random id previewId = RandomStringUtils.randomAlphanumeric(20); } return buildNewPreview(media, mediaId, previewId, mediaDirectory, maxHeight, maxWidth); }
From source file:com.cws.esolutions.core.processors.impl.ServerManagementProcessorImplTest.java
@Test public void addServerAsPrdMasterDnsServer() { 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.PRD); server.setServerStatus(ServerStatus.ONLINE); server.setServerType(ServerType.DNSMASTER); server.setServerComments("app server"); server.setAssignedEngineer(userAccount); server.setCpuType("AMD 1.0 GHz"); server.setCpuCount(1);/*www.j ava 2s .c o 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:com.flexive.ejb.beans.AccountEngineBean.java
private long create(String userName, String loginName, String password, String email, long lang, long mandatorId, boolean isActive, boolean isConfirmed, Date validFrom, Date validTo, long defaultNode, String description, boolean allowMultiLogin, boolean checkUserRoles, boolean hashPassword) throws FxApplicationException { final UserTicket ticket = FxContext.getUserTicket(); // Security//from w w w . j a v a 2 s . co m if (checkUserRoles && !ticket.isGlobalSupervisor()) { if (!ticket.isInRole(Role.MandatorSupervisor)) FxPermissionUtils.checkRole(ticket, Role.AccountManagement); if (ticket.getMandatorId() != mandatorId) throw new FxNoAccessException(LOG, "ex.account.create.wrongMandator"); } // Parameter checks try { CacheAdmin.getEnvironment().getMandator(mandatorId); loginName = checkLoginName(loginName); userName = checkUserName(userName); checkDates(validFrom, validTo); if (description == null) description = ""; email = FxFormatUtils.checkEmail(email); if (!language.isValid(lang)) throw new FxInvalidParameterException("LANGUAGE", "ex.account.languageInvalid", lang); } catch (FxInvalidParameterException pe) { if (LOG.isInfoEnabled()) LOG.info(pe); throw pe; } Connection con = null; PreparedStatement stmt = null; String curSql; FxPK contactDataPK; try { final FxContext ri = FxContext.get(); final FxContent contactData; try { if (!checkUserRoles) { // we're probably running in unprivileged code, but application logic // already determined that a user account should be created ri.runAsSystem(); } contactData = co.initialize(CacheAdmin.getEnvironment().getType(FxType.CONTACTDATA).getId()); } finally { if (!checkUserRoles) { ri.stopRunAsSystem(); } } contactData.setAclId(ACL.ACL_CONTACTDATA); contactData.setValue("/SURNAME", new FxString(false, userName)); contactData.setValue("/EMAIL", new FxString(false, email)); try { FxContext.get().runAsSystem(); contactDataPK = co.save(contactData); } finally { FxContext.get().stopRunAsSystem(); } // Obtain a database connection con = Database.getDbConnection(); // Get a new Id long newId = seq.getId(FxSystemSequencer.ACCOUNT); if (hashPassword) { password = password == null ? "" : FxFormatUtils.encodePassword(newId, userName, password); } curSql = "INSERT INTO " + TBL_ACCOUNTS + "(" + //1 2 3 4 5 6 7 8 9 "ID,MANDATOR,USERNAME,LOGIN_NAME,PASSWORD,EMAIL,CONTACT_ID,LANG,VALID_FROM," + //10 11 12 13 14 "VALID_TO,DESCRIPTION,CREATED_BY,CREATED_AT,MODIFIED_BY," + //15 16 17 18 19 20 "MODIFIED_AT,IS_ACTIVE,IS_VALIDATED,DEFAULT_NODE,ALLOW_MULTILOGIN,UPDATETOKEN) values " + //1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; final long NOW = System.currentTimeMillis(); stmt = con.prepareStatement(curSql); stmt.setLong(1, newId); stmt.setLong(2, mandatorId); stmt.setString(3, userName); stmt.setString(4, loginName); stmt.setString(5, password); stmt.setString(6, email); stmt.setLong(7, contactDataPK.getId()); stmt.setInt(8, (int) lang); //subtract a second to prevent login-after-immediatly-create problems with databases truncating milliseconds stmt.setLong(9, validFrom.getTime() - 1000); stmt.setLong(10, validTo.getTime()); stmt.setString(11, description); stmt.setLong(12, ticket.getUserId()); stmt.setLong(13, NOW); stmt.setLong(14, ticket.getUserId()); stmt.setLong(15, NOW); stmt.setBoolean(16, isActive); stmt.setBoolean(17, isConfirmed); stmt.setLong(18, (defaultNode < 0) ? 0 : defaultNode); stmt.setBoolean(19, allowMultiLogin); stmt.setString(20, RandomStringUtils.randomAlphanumeric(64)); stmt.executeUpdate(); //make sure the user is the owner of his contact data stmt.close(); stmt = con.prepareStatement("UPDATE " + TBL_CONTENT + " SET CREATED_BY=?, MANDATOR=? WHERE ID=?"); stmt.setLong(1, newId); stmt.setLong(2, mandatorId); stmt.setLong(3, contactDataPK.getId()); stmt.executeUpdate(); CacheAdmin.expireCachedContent(contactDataPK.getId()); // call scripts final List<Long> scriptIds = scripting.getByScriptEvent(FxScriptEvent.AfterAccountCreate); final FxScriptBinding binding = new FxScriptBinding(); binding.setVariable("accountId", newId); binding.setVariable("pk", contactDataPK); for (long scriptId : scriptIds) scripting.runScript(scriptId, binding); StringBuilder sbHistory = new StringBuilder(1000); sbHistory.append("<account action=\"create\">\n").append(" <id>").append(newId).append("</id>\n") .append(" <mandator>").append(CacheAdmin.getEnvironment().getMandator(mandatorId).getName()) .append("</mandator>\n").append(" <username>").append(userName).append("</username>\n") .append(" <loginname>").append(loginName).append("</loginname>\n").append(" <email>") .append(email).append("</email>\n").append(" <validfrom>") .append(FxFormatUtils.toString(validFrom)).append("</validfrom>\n").append(" <validto>") .append(FxFormatUtils.toString(validTo)).append("</validto>\n") .append(" <description><![CDATA[").append(description).append("]]></description>\n") .append(" <active>").append(isActive).append("</active>\n").append(" <confirmed>") .append(isConfirmed).append("</confirmed>\n").append(" <multilogin>").append(allowMultiLogin) .append("</multilogin>\n").append("</account>"); EJBLookup.getHistoryTrackerEngine().trackData(sbHistory.toString(), "history.account.create", loginName); StructureLoader.updateUserGroups(FxContext.get().getDivisionId(), group.loadAll(-1)); // EVERY users is a member of group EVERYONE and his mandator final long[] groups = { UserGroup.GROUP_EVERYONE, group.loadMandatorGroup(mandatorId).getId() }; ri.runAsSystem(); try { setGroups(newId, groups); } catch (Exception exc) { throw new FxCreateException(exc, "ex.account.create.everyoneAssignFailed", exc.getMessage()); } finally { ri.stopRunAsSystem(); } // Return the id return newId; } catch (SQLException exc) { final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(exc); EJBUtils.rollback(ctx); if (uniqueConstraintViolation) { throw new FxEntryExistsException(LOG, exc, "ex.account.userExists", loginName, userName); } else { throw new FxCreateException(LOG, exc, "ex.account.createFailed.sql", loginName, exc.getMessage()); } } finally { Database.closeObjects(AccountEngineBean.class, con, stmt); } }
From source file:edu.duke.cabig.c3pr.webservice.integration.SubjectManagementWebServiceTest.java
private void executeCreateSubjectTest() throws DataSetException, IOException, SQLException, DatabaseUnitException, Exception { SubjectManagement service = getService(); // successful subject creation. final CreateSubjectRequest request = new CreateSubjectRequest(); Subject subject = createSubject(false, true); request.setSubject(subject);// w ww .j a v a2 s. c o m Subject createdSubject = service.createSubject(request).getSubject(); assertNotNull(createdSubject); // If the default c3pr generated system identifier is sent in the request, there is no need to strip it from the created subject //system identifiers in response, otherwise we need to remove the default system identifier from response before doing deep compare. if (!ifC3PRDefaultSystemIdentifierSent(subject)) { stripC3PRDefaultSystemIdentifier(createdSubject); } assertTrue(BeanUtils.deepCompare(subject, createdSubject)); verifySubjectDatabaseData(createdSubject, ""); // duplicate subject try { service.createSubject(request); fail(); } catch (SubjectAlreadyExistsExceptionFaultMessage e) { logger.info("Duplicate subject creation passed."); } //missing primary identifier subject.getEntity().getBiologicEntityIdentifier().clear(); subject.getEntity().getBiologicEntityIdentifier().add(createSecondaryBioEntityOrgId(false)); try { service.createSubject(request); fail(); } catch (InvalidSubjectDataExceptionFaultMessage e) { logger.info("missing primary identifier passed."); } // duplicate secondary identifier subject = createSubject(false, true); subject.getEntity().getBiologicEntityIdentifier().get(1).getIdentifier() .setExtension(RandomStringUtils.randomAlphanumeric(16)); request.setSubject(subject); createdSubject = service.createSubject(request).getSubject(); assertNotNull(createdSubject); // If the default c3pr generated system identifier is sent in the request, there is no need to strip it from the created subject //system identifiers in response, otherwise we need to remove the default system identifier from response before doing deep compare. if (!ifC3PRDefaultSystemIdentifierSent(subject)) { stripC3PRDefaultSystemIdentifier(createdSubject); } assertTrue(BeanUtils.deepCompare(subject, createdSubject)); // bad subject data subject.getEntity().getBirthDate().setValue(BAD_ISO_DATE); try { service.createSubject(request); fail(); } catch (InvalidSubjectDataExceptionFaultMessage e) { logger.info("Bad subject data test passed."); } // missing identifiers subject = createSubject(false, true); request.setSubject(subject); subject.getEntity().getBiologicEntityIdentifier().clear(); try { service.createSubject(request); fail(); } catch (InvalidSubjectDataExceptionFaultMessage e) { logger.info("Missing test identifiers passed."); } // Bad subject data, XSD validation. subject.getEntity().setAdministrativeGenderCode(null); try { service.createSubject(request); fail(); } catch (SOAPFaultException e) { logger.info("Bad test subject data, XSD validation passed."); } }