Example usage for org.apache.commons.lang RandomStringUtils randomAlphanumeric

List of usage examples for org.apache.commons.lang RandomStringUtils randomAlphanumeric

Introduction

In this page you can find the example usage for org.apache.commons.lang RandomStringUtils randomAlphanumeric.

Prototype

public static String randomAlphanumeric(int count) 

Source Link

Document

Creates a random string whose length is the number of characters specified.

Characters will be chosen from the set of alpha-numeric characters.

Usage

From source file:com.xpn.xwiki.plugin.collection.CollectionPlugin.java

/**
 * Returns a pdf of the transcluded view of the given xwiki 2.0 document.
 *
 * @return the transcluded result in xhtml syntax.
 *//*ww w. java2 s.  c  o m*/
public void exportWithLinks(String packageName, XWikiDocument doc, List<String> selectlist,
        boolean ignoreInitialPage, String type, String pdftemplatepage, XWikiContext context) throws Exception {
    // XWikiContext context2 = context.getContext();
    // Preparing the PDF Exporter and PDF URL Factory (this last one is
    // necessary for images includes)
    PdfExportImpl pdfexport = new PdfExportImpl();
    XWikiURLFactory urlf = context.getWiki().getURLFactoryService().createURLFactory(XWikiContext.MODE_PDF,
            context);
    context.setURLFactory(urlf);
    // Preparing the PDF http headers to have the browser recognize the file
    // as PDF
    context.getResponse().setContentType("application/" + type);
    if (doc == null) {
        context.getResponse().addHeader("Content-disposition", "inline; filename=" + packageName + "." + type);
    } else {
        context.getResponse().addHeader("Content-disposition",
                "inline; filename=" + Utils.encode(doc.getSpace(), context) + "_"
                        + Utils.encode(doc.getName(), context) + "." + type);
    }
    // Preparing temporary directories for the PDF URL Factory
    File dir = context.getWiki().getTempDirectory(context);
    File tempdir = new File(dir, RandomStringUtils.randomAlphanumeric(8));
    // We should call this but we cannot do it. It might not be a problem
    // but if we have an encoding issue we should look into it
    // this.tidy.setOutputEncoding(context2.getWiki().getEncoding());
    // this.tidy.setInputEncoding(context2.getWiki().getEncoding());
    try {
        // we need to prepare the pdf export directory before running the
        // transclusion
        tempdir.mkdirs();
        context.put("pdfexportdir", tempdir);
        context.put("pdfexport-file-mapping", new HashMap<String, File>());
        // running the transclusion and the final rendering to HTML
        String content = getRenderedContentWithLinks(doc, selectlist, ignoreInitialPage, context);
        addDebug("Content: " + content);
        // preparing velocity context for the adding of the headers and
        // footers
        VelocityContext vcontext = (VelocityContext) context.get("vcontext");
        vcontext.put("content", content);
        Document vdoc = new Document(doc, context);
        vcontext.put("doc", vdoc);
        vcontext.put("cdoc", vdoc);
        vcontext.put("tdoc", vdoc);

        String tcontent = null;
        // pdfmulti.vm should be declared  in the skin
        if (pdftemplatepage != null) {
        }
        if (tcontent == null) {
            tcontent = context.getWiki().parseTemplate("pdfmulti.vm", context);
        }
        // launching the export
        pdfexport.exportHtml(tcontent, context.getResponse().getOutputStream(),
                (type.equals("rtf")) ? PdfExportImpl.RTF : PdfExportImpl.PDF, context);
    } finally {
        // cleaning temporary directories
        File[] filelist = tempdir.listFiles();
        for (int i = 0; i < filelist.length; i++) {
            filelist[i].delete();
        }
        tempdir.delete();
    }
}

From source file:com.haulmont.cuba.security.app.UserManagementServiceBean.java

@Override
public String generateRememberMeToken(UUID userId) {
    String token = RandomStringUtils.randomAlphanumeric(RememberMeToken.TOKEN_LENGTH);

    Transaction tx = persistence.createTransaction();
    try {/*www .  j av  a 2 s  . c om*/
        EntityManager em = persistence.getEntityManager();

        RememberMeToken rememberMeToken = metadata.create(RememberMeToken.class);
        rememberMeToken.setToken(token);
        rememberMeToken.setUser(em.getReference(User.class, userId));

        em.persist(rememberMeToken);

        tx.commit();
    } finally {
        tx.end();
    }

    return token;
}

From source file:com.kixeye.chassis.transport.WebSocketTransportTest.java

@Test
public void testWebSocketServiceWithJson() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    properties.put("http.enabled", "false");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    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);

    WebSocketClient wsClient = new WebSocketClient();

    try {/*from w ww  .  ja v  a2s  .co  m*/
        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(
                "ws://localhost:" + properties.get("websocket.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.cws.esolutions.core.processors.impl.ServerManagementProcessorImplTest.java

@Test
public void addServerAsQaAppServer() {
    Server dmgrServer = new Server();
    dmgrServer.setServerGuid("dac2e765-109e-4385-8563-aab66d6713f9");

    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.QA);
        server.setServerStatus(ServerStatus.ONLINE);
        server.setServerType(ServerType.APPSERVER);
        server.setServerComments("app server");
        server.setAssignedEngineer(userAccount);
        server.setCpuType("AMD 1.0 GHz");
        server.setCpuCount(1);//from w  w  w  .  j a  v  a2  s  . c o m
        server.setServerModel("Virtual Server");
        server.setSerialNumber("1YU391");
        server.setInstalledMemory(4096);
        server.setOwningDmgr(dmgrServer);
        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.xtructure.xutil.valid.UTestValidateUtils.java

public void assertThatWithOnePredicateBehavesAsExpected() {
    String assertionName = RandomStringUtils.randomAlphanumeric(10);
    boolean valid = assertThat(assertionName, new Object(), isNotNull());
    if (!valid) {
        throw new AssertionError();
    }//from   w ww . j a  v a  2s.c o m
    try {
        assertThat(assertionName, null, isNotNull());
    } catch (AssertionError e) {
        if (!String.format("%s (%s): %s", assertionName, null, isNotNull()).equals(e.getMessage())) {
            throw new AssertionError();
        }
    }
}

From source file:eu.abc4trust.abce.pertubationtests.tud.section2.PA_II_2_2_1malformedCEuri.java

public static URI randomURI() throws URISyntaxException {//generates a random URI
    //urn:abc4trust:1.0:algorithm:idemix
    String uriString = "urn:";
    uriString += RandomStringUtils.randomAlphanumeric(5) + ":";
    uriString += RandomStringUtils.randomAlphanumeric(10) + ":";
    uriString += RandomStringUtils.randomAlphanumeric(10) + ":";
    uriString += RandomStringUtils.randomAlphanumeric(10);

    URI randomUri = new URI(uriString);
    return randomUri;
}

From source file:eu.abc4trust.abce.pertubationtests.tud.section2.PA_II_2_2_7randomUID.java

public static URI randomURI() throws URISyntaxException {//generates a random URI
    String uriString = "urn:";
    uriString += RandomStringUtils.randomAlphanumeric(5) + ":";
    uriString += RandomStringUtils.randomAlphanumeric(10) + ":";
    uriString += RandomStringUtils.randomAlphanumeric(10) + ":";
    uriString += RandomStringUtils.randomAlphanumeric(10);

    URI randomUri = new URI(uriString);
    return randomUri;
}

From source file:com.itdhq.contentLoader.ContentLoaderComponent.java

/**
 * Plain Text generator/* w  ww.  j  a v  a 2s . c  o  m*/
 * TODO find normal human-like text generator
 *
 * @param size in chars
 * @return plain text (letters and numbers)
 */
private String genPlainText(int size) {
    return RandomStringUtils.randomAlphanumeric(size);
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.servlet.MMXUserResourceTest.java

private String getUserJsonString() {
    MMXUserInfo userInfo = new MMXUserInfo();
    userInfo.setAppId(RandomStringUtils.randomAlphabetic(10));
    userInfo.setEmail(RandomStringUtils.randomAlphabetic(5) + "@magnet.com");
    userInfo.setName(RandomStringUtils.randomAlphabetic(5) + " " + RandomStringUtils.randomAlphabetic(5));
    userInfo.setUsername(RandomStringUtils.randomAlphabetic(10));
    userInfo.setPassword(RandomStringUtils.randomAlphanumeric(4 + RandomUtils.nextInt(6)));
    return new GsonBuilder().setPrettyPrinting().create().toJson(userInfo);
}

From source file:de.thm.arsnova.services.UserService.java

@Override
public DbUser createDbUser(String username, String password) {
    if (null == keygen) {
        keygen = KeyGenerators.secureRandom(32);
    }/*from ww  w .  j  a  v  a  2 s. com*/

    if (null == mailPattern) {
        parseMailAddressPattern();
    }

    if (null == mailPattern || !mailPattern.matcher(username).matches()) {
        return null;
    }

    if (null != databaseDao.getUser(username)) {
        return null;
    }

    DbUser dbUser = new DbUser();
    dbUser.setUsername(username);
    dbUser.setPassword(encodePassword(password));
    dbUser.setActivationKey(RandomStringUtils.randomAlphanumeric(32));
    dbUser.setCreation(System.currentTimeMillis());

    DbUser result = databaseDao.createOrUpdateUser(dbUser);
    if (null != result) {
        sendActivationEmail(result);
    }

    return result;
}