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.shelfmap.simplequery.domain.BlobReferenceTest.java

@When("putting a object as the content of a BlobReference")
public void putImageToS3() throws Exception {
    testKeyName = "testUpload" + RandomStringUtils.randomAlphanumeric(10);

    ByteArrayOutputStream byteOutput = null;
    ByteArrayInputStream byteInput = null;
    InputStream source = null;/*  www.j  ava 2s . com*/
    try {
        //First, we must write testImage to byteArray with ImageIO.
        //Then we must create an image for assertion from the byteArray.
        //Because the data from getResourceStream() and the data create ImageIO.write() are not same binary data.
        byteOutput = new ByteArrayOutputStream();
        ImageIO.write(testImage, "jpeg", byteOutput);
        byteOutput.close();

        byte[] data = byteOutput.toByteArray();
        byteInput = new ByteArrayInputStream(data);

        //This is the image which will be used at assertion-time.
        sourceImage = ImageIO.read(byteInput);

        Map<String, Object> conversionInfo = createConversionInfo();
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.addUserMetadata("format", "jpeg");
        metadata.setContentType("image/jpeg");

        BlobReference<BufferedImage> imageReference = new DefaultBlobReference<BufferedImage>(ctx.getContext(),
                new S3Resource(BUCKET_NAME, testKeyName), BufferedImage.class,
                new ImageContentConverter(conversionInfo));

        //Here we use testImage (not sourceImage) for setContent().
        //setContent() will create binary stream with ImageIO.write().
        //so the data is same with the source binary data of sourceImage.
        imageReference.setContent(testImage, metadata);
    } finally {
        IO.close(source, this);
        IO.close(byteInput, this);
        IO.close(byteOutput, this);
    }
}

From source file:com.infosupport.ellison.core.archive.ApplicationArchiveTest.java

@Test(expected = FileNotFoundException.class)
public void testGetFile_FileNotFound() throws Exception {
    String randomFileName = null;
    do {/* w w w  . j ava  2s  .com*/
        randomFileName = RandomStringUtils.randomAlphanumeric(10);
    } while (inputJarContents.contains(randomFileName));

    applicationArchive.getFile(randomFileName);
}

From source file:com.third.rent.user.controller.LoginController.java

@RequestMapping(value = "/user/userseachpwd.do")
public String userseachpwd(@RequestParam String userId, @RequestParam String userEmail, Model model) {
    logger.info("?   ? userId={}, userEmail={}", userId, userEmail);
    UserVO userVo = new UserVO();
    userVo.setUserId(userId);//from w  w w .j a v  a2 s.c  o m
    userVo.setUserEmail(userEmail);

    /* String result = userService.selectSearchpwd(userVo); */

    // id, email ? ?  ?2
    int count = userService.returnUserCount(userVo);
    logger.info("id, email ? ?    count={}", count);

    String url = "/user/index.do", msg = "";

    if (count > 0) {

        // ? 8?  ?
        // char  33(!)~122(z) ? 8
        String ramdomPwd = RandomStringUtils.randomAlphanumeric(8);
        logger.info(" ??   ramdomPwd={}", ramdomPwd);
        userVo.setUserPwd(ramdomPwd);

        userService.updateNewRandomPwd(userVo);

        String subject = "[3 ]" + userId + "?  ??  .";
        String content = "  [ " + ramdomPwd
                + " ] - ?  ";
        String receiver = userEmail;
        String sender = "admin@herbmall.com";

        try {
            emailSender.sendEmail(subject, content, receiver, sender);
            logger.info("??  ");
            msg = "  ?? ?.";
        } catch (MessagingException e) {
            logger.info("??  ");
            e.printStackTrace();
            msg = "  ??  .";
        }
    } else {
        msg = " ID Email?  ?  .";
    }

    model.addAttribute("msg", msg);
    model.addAttribute("url", url);

    return "common/message";
}

From source file:eu.vital.vitalcep.restApp.filteringApi.StaticFiltering.java

/**
 * Creates a filter.//from   ww  w  .ja  v  a  2 s  . c  om
 *
 * @param info
 * @return the filter id 
 * @throws java.io.IOException 
 */
@POST
@Path("filterstaticdata")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response filterstaticdata(String info, @Context HttpServletRequest req)
        throws IOException, UnsupportedEncodingException, NoSuchAlgorithmException {

    JSONObject jo = new JSONObject(info);

    if (jo.has("dolceSpecification") && jo.has("data")) { // && jo.has("data") for demo

        MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL));
        MongoDatabase db = mongo.getDatabase(mongoDB);

        try {
            db.getCollection("staticdatafilters");
        } catch (Exception e) {
            //System.out.println("Mongo is down");
            db = null;
            if (mongo != null) {
                mongo.close();
                mongo = null;
            }
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();

        }

        if (jo.has("dolceSpecification")) {

            //Filter oFilter = new Filter(filter);
            JSONObject dsjo = jo.getJSONObject("dolceSpecification");
            String str = dsjo.toString();//"{\"dolceSpecification\": "+ dsjo.toString()+"}";

            try {

                DolceSpecification ds = new DolceSpecification(str);

                if (!(ds instanceof DolceSpecification)) {
                    return Response.status(Response.Status.BAD_REQUEST).build();
                }

                String mqin = RandomStringUtils.randomAlphanumeric(8);
                String mqout = RandomStringUtils.randomAlphanumeric(8);

                JSONArray aData = jo.getJSONArray("data");

                CEP cepProcess = new CEP();

                if (!(cepProcess.CEPStart(CEP.CEPType.DATA, ds, mqin, mqout, confFile, aData.toString(),
                        null))) {
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
                }

                String clientName = "collector_" + RandomStringUtils.randomAlphanumeric(4);

                if (cepProcess.PID < 1) {
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
                }

                UUID uuid = UUID.randomUUID();
                String randomUUIDString = uuid.toString();

                DBObject dbObject = createCEPFilterStaticSensorJsonld(info, randomUUIDString, jo, dsjo,
                        "vital:CEPFilterStaticDataSensor");
                Document doc = new Document(dbObject.toMap());

                try {
                    db.getCollection("staticdatafilters").insertOne(doc);
                    String id = doc.get("_id").toString();

                } catch (MongoException ex) {
                    db = null;
                    if (mongo != null) {
                        mongo.close();
                        mongo = null;
                    }
                    return Response.status(Response.Status.BAD_REQUEST).build();
                }

                JSONObject opState = createOperationalStateObservation(randomUUIDString);

                DBObject oPut = (DBObject) JSON.parse(opState.toString());
                Document doc1 = new Document(oPut.toMap());

                try {
                    db.getCollection("staticdatafiltersobservations").insertOne(doc1);
                    String id = doc1.get("_id").toString();

                } catch (MongoException ex) {
                    db = null;
                    if (mongo != null) {
                        mongo.close();
                        mongo = null;
                    }
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
                }

                /////////////////////////////////////////////////////
                // creates client and messages process
                //
                MqttAllInOne oMqtt = new MqttAllInOne();
                TMessageProc MsgProcc = new TMessageProc();

                /////////////////////////////////////////////////////////////////////////
                // PREPARING DOLCE INPUT
                Decoder decoder = new Decoder();
                ArrayList<String> simpleEventAL = decoder.JsonldArray2DolceInput(aData);

                String sal = simpleEventAL.toString();
                /////////////////////////////////////////////////////////////////////////////
                // SENDING TO MOSQUITTO
                oMqtt.sendMsg(MsgProcc, clientName, simpleEventAL, mqin, mqout, false);

                /////////////////////////////////////////////////////////////////////////////
                //RECEIVING FROM MOSQUITO               
                ArrayList<MqttMsg> mesagges = MsgProcc.getMsgs();

                ArrayList<Document> outputL;
                outputL = new ArrayList<>();

                Encoder encoder = new Encoder();

                outputL = encoder.dolceOutputList2ListDBObject(mesagges, host, randomUUIDString);

                String sOutput = "[";
                for (int i = 0; i < outputL.size(); i++) {
                    Document element = outputL.get(i);

                    if (i == 0) {
                        sOutput = sOutput + element.toJson();
                    }
                    sOutput = sOutput + "," + element.toJson();
                }

                sOutput = sOutput + "]";

                StringBuilder ck = new StringBuilder();

                try {
                    Security slogin = new Security();

                    Boolean token = slogin.login(req.getHeader("name"), req.getHeader("password"), false, ck);
                    if (!token) {
                        return Response.status(Response.Status.UNAUTHORIZED).build();
                    }
                    cookie = ck.toString();

                    DMSManager oDMS = new DMSManager(dmsURL, cookie);

                    MongoCollection<Document> collection = db.getCollection("staticdatafiltersobservations");

                    if (outputL.size() > 0) {
                        collection.insertMany(outputL);
                        if (!oDMS.pushObservations(sOutput)) {
                            java.util.logging.Logger.getLogger(StaticFiltering.class.getName())
                                    .log(Level.SEVERE, "couldn't save to the DMS");
                        }
                    }

                } catch (KeyManagementException | KeyStoreException ex) {
                    db = null;
                    if (mongo != null) {
                        mongo.close();
                        mongo = null;
                    }
                    java.util.logging.Logger.getLogger(MessageProcessor_publisher.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
                //cepProcess.
                try {
                    CepContainer.deleteCepProcess(cepProcess.PID);

                    if (!cepProcess.cepDispose()) {
                        java.util.logging.Logger.getLogger(StaticFiltering.class.getName()).log(Level.SEVERE,
                                "couldn't terminate ucep");
                    }
                } catch (Exception e) {
                    java.util.logging.Logger.getLogger(StaticFiltering.class.getName()).log(Level.SEVERE, null,
                            e);
                }
                db = null;
                if (mongo != null) {
                    mongo.close();
                    mongo = null;
                }
                return Response.status(Response.Status.OK).entity(sOutput).build();

            } catch (IOException | JSONException | java.text.ParseException e) {
                db = null;
                if (mongo != null) {
                    mongo.close();
                    mongo = null;
                }
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
            }
        }

        return Response.status(Response.Status.BAD_REQUEST).build();

    }

    return Response.status(Response.Status.BAD_REQUEST).build();

}

From source file:gov.nih.nci.firebird.test.ValueGenerator.java

public static String getUniqueString(int length) {
    return RandomStringUtils.randomAlphanumeric(length);
}

From source file:net.nelz.simplesm.aop.ReadThroughMultiCacheTest.java

@Test
public void testGenerateResultsException() {
    final List<Object> keyObjects = new ArrayList<Object>();
    final Map<Object, String> obj2key = new HashMap<Object, String>();
    final String keyObject = RandomStringUtils.randomAlphanumeric(8);
    final String key = keyObject + "-" + RandomStringUtils.randomAlphanumeric(4);
    keyObjects.add(keyObject);/* w  w  w.  j a v a2 s  . co  m*/
    obj2key.put(keyObject, key);
    coord.setKeyObjects(keyObjects);
    coord.getObj2Key().putAll(obj2key);

    try {
        coord.generateResultList();
        fail("Expected Exception");
    } catch (RuntimeException ex) {
    }

}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.api.topics.MMXTopicsItemsResourceTest.java

public static void generatePubsubItems() {
    for (int i = 1; i <= 10; i++) {
        TopicItemEntity entity = new TopicItemEntity();
        entity.setServiceId(SERVICE_ID);
        entity.setNodeId(getNodeId());/*from  w ww  .j  a  v  a 2 s.c  o m*/
        entity.setId(RandomStringUtils.randomAlphanumeric(10));
        entity.setJid(JID);
        Date creationDate = new DateTime(testStartTime).minusDays(i).toDate();
        entity.setPayload(getRandomPublishedItemPayload(creationDate));
        String dateStr = StringUtils.dateToMillis(creationDate);
        LOGGER.trace("generatePubsubItems : persisting with date={}", creationDate);
        entity.setCreationDate(dateStr);
        topicItemEntityList.add(entity);
        DBTestUtil.getTopicItemDAO().persist(entity);
    }
}

From source file:gov.nih.cadsr.transform.FilesTransformation.java

public static String transformToCSV(String xmlFile, String xsltFile) {

    StringBuffer sb = null;//w w  w.j a  v  a 2  s .co  m

    try {

        String path = "/local/content/cadsrapi/transform/data/";
        String ext = "txt";
        File dir = new File(path);
        String name = String.format("%s.%s", RandomStringUtils.randomAlphanumeric(8), ext);
        File rf = new File(dir, name);

        long startTime = System.currentTimeMillis();

        //Obtain a new instance of a TransformerFactory. 
        TransformerFactory f = TransformerFactory.newInstance();
        // Process the Source into a Transformer Object...Construct a StreamSource from a File.
        Transformer t = f.newTransformer(new StreamSource(xsltFile));

        //Construct a StreamSource from input and output
        Source s;
        try {
            s = new StreamSource((new ByteArrayInputStream(xmlFile.getBytes("utf-8"))));
            Result r = new StreamResult(rf);

            //Transform the XML Source to a Result.
            t.transform(s, r);
            System.out.println("Tranformation completed ...");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            System.out.println(e1.toString());
        }

        //convert output file to string                                       
        try {
            BufferedReader bf = new BufferedReader(new FileReader(rf));
            sb = new StringBuffer();
            try {

                while ((bf.readLine()) != null) {
                    sb.append(bf.readLine());
                    System.out.println(bf.readLine());

                }
            } catch (IOException e) {

                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis();
        System.out.println("Transformation took " + (endTime - startTime) + " milliseconds");
        System.out.println("Transformation took " + (endTime - startTime) / 1000 + " seconds");
    }

    catch (TransformerConfigurationException e) {
        System.out.println(e.toString());

    } catch (TransformerException e) {
        System.out.println(e.toString());

    }

    return sb.toString();
}

From source file:com.cws.esolutions.security.processors.impl.AccountChangeProcessorImplTest.java

@Test
public void changeUserSecurity() {
    AccountChangeProcessorImplTest.userSecurity.setPassword("Ariana21*");
    AccountChangeProcessorImplTest.userSecurity.setSecQuestionOne(RandomStringUtils.randomAlphanumeric(64));
    AccountChangeProcessorImplTest.userSecurity.setSecQuestionTwo(RandomStringUtils.randomAlphanumeric(64));
    AccountChangeProcessorImplTest.userSecurity.setSecAnswerOne(RandomStringUtils.randomAlphanumeric(64));
    AccountChangeProcessorImplTest.userSecurity.setSecAnswerTwo(RandomStringUtils.randomAlphanumeric(64));

    AccountChangeRequest request = new AccountChangeRequest();
    request.setApplicationId("6236B840-88B0-4230-BCBC-8EC33EE837D9");
    request.setApplicationName("eSolutions");
    request.setHostInfo(AccountChangeProcessorImplTest.hostInfo);
    request.setIsReset(false);/* w  w w .ja v  a 2  s. com*/
    request.setUserAccount(AccountChangeProcessorImplTest.userAccount);
    request.setRequestor(AccountChangeProcessorImplTest.userAccount);
    request.setUserSecurity(AccountChangeProcessorImplTest.userSecurity);

    try {
        AccountChangeResponse response = processor.changeUserSecurity(request);

        Assert.assertEquals(SecurityRequestStatus.SUCCESS, response.getRequestStatus());
    } catch (AccountChangeException acx) {
        Assert.fail(acx.getMessage());
    }
}

From source file:com.cws.esolutions.security.dao.usermgmt.impl.SQLUserManagerTest.java

@Test
public void modifyUserPassword() {
    try {// w w  w.j  a v a  2s . c o  m
        Assert.assertTrue(
                manager.modifyUserPassword(SQLUserManagerTest.GUID, RandomStringUtils.randomAlphanumeric(64)));
    } catch (UserManagementException umx) {
        Assert.fail(umx.getMessage());
    }
}