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:edu.duke.cabig.c3pr.webservice.integration.SecurityWebServiceTest.java

/**
 * @throws InterruptedException/*from ww w.  j a  v  a 2 s.c o m*/
 * @throws IOException
 * @throws SecurityExceptionFaultMessage
 * @throws InvalidSubjectDataExceptionFaultMessage
 * 
 */
public void testSecurity() throws InterruptedException, IOException, InvalidSubjectDataExceptionFaultMessage,
        SecurityExceptionFaultMessage {

    // prepare a request that just needs to go through; does not need to
    // return any subjects actually
    final AdvancedQuerySubjectRequest request = new AdvancedQuerySubjectRequest();
    DSETAdvanceSearchCriterionParameter params = new DSETAdvanceSearchCriterionParameter();
    request.setParameters(params);

    AdvanceSearchCriterionParameter param = new AdvanceSearchCriterionParameter();
    params.getItem().add(param);

    ST objName = iso.ST();
    objName.setValue("edu.duke.cabig.c3pr.domain.Identifier");
    param.setObjectName(objName);

    ST attrName = iso.ST();
    attrName.setValue("value");
    param.setAttributeName(attrName);

    ST value = iso.ST();
    value.setValue(RandomStringUtils.randomAlphanumeric(32));
    param.setValues(new DSETST());
    param.getValues().getItem().add(value);

    CD pred = new CD();
    pred.setCode("=");
    param.setPredicate(pred);

    ST ctxName = iso.ST();
    ctxName.setNullFlavor(NullFlavor.NI);
    param.setObjectContextName(ctxName);

    // valid token, should go through.
    SubjectManagement service = getService(SOAPUtils.PATH_TO_SAML_TOKEN);
    List<Subject> list = service.advancedQuerySubject(request).getSubjects().getItem();
    assertNotNull(list);

    // tampered token
    service = getService(SOAPUtils.PATH_TO_TAMPERED_SAML_TOKEN);
    try {
        service.advancedQuerySubject(request);
        fail("Tampered token went through.");
    } catch (SecurityExceptionFaultMessage e) {
        logger.info(e.getMessage());
        assertTrue(e.getMessage().contains("failed to validate signature value"));
    }

    // Inexistent user
    service = getService(SOAPUtils.PATH_TO_UNEXISTENT_USER_SAML_TOKEN);
    try {
        service.advancedQuerySubject(request);
        fail("Unexistent user went through.");
    } catch (SecurityExceptionFaultMessage e) {
        logger.info(e.getMessage());
        assertTrue(e.getMessage().contains("User does not exist"));
    }

    // untrusted STS
    service = getService(SOAPUtils.PATH_TO_UNTRUSTED_SAML_TOKEN);
    try {
        service.advancedQuerySubject(request);
        fail("Untrusted STS went through.");
    } catch (SecurityExceptionFaultMessage e) {
        logger.info(e.getMessage());
        assertTrue(e.getMessage().contains("certificate is not trusted"));
    }

}

From source file:net.przemkovv.sphinx.compiler.MSVCCompiler.java

private CompilationResult runCompiler(List<File> files, File output_file, List<String> args, File working_dir)
        throws InvalidCompilerException {
    try {/* ww  w .  j  a  v a  2  s.  c  o  m*/

        if (output_file == null) {
            output_file = new File(working_dir, RandomStringUtils.randomAlphanumeric(8) + ".exe");
        }
        ArrayList<String> cmd = new ArrayList<>();
        if (prepare_env != null) {

            cmd.add(prepare_env.getAbsolutePath());
            cmd.add("&&");
        }
        cmd.add(msvc.getAbsolutePath());
        cmd.add("/Fe" + output_file.getAbsolutePath());
        if (args != null) {
            cmd.addAll(args);
        }
        if (files != null) {
            for (File file : files) {
                if (FilenameUtils.isExtension(file.getName(), "cpp")
                        || FilenameUtils.isExtension(file.getName(), "c")) {
                    cmd.add(file.getAbsolutePath());
                }

            }
        }

        logger.debug("Compiler command line: {}", cmd);
        final Process process = Runtime.getRuntime().exec(cmd.toArray(new String[cmd.size()]), null,
                output_file.getParentFile());

        Future<String> output_error_result = pool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return Utils.readAllFromInputStream(process.getErrorStream());
            }
        });
        Future<String> output_result = pool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return Utils.readAllFromInputStream(process.getInputStream());
            }
        });
        process.waitFor();
        CompilationResult result = new CompilationResult();
        result.output_errror = output_error_result.get();
        result.output = output_result.get();
        result.exit_value = process.exitValue();
        result.executable_file = output_file;
        result.prepare_env = prepare_env;
        return result;
    } catch (IOException | InterruptedException ex) {
        throw new InvalidCompilerException(ex);

    } catch (ExecutionException ex) {
        java.util.logging.Logger.getLogger(MSVCCompiler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.athena.peacock.controller.web.machine.MachineService.java

public void insertMachine(MachineDto machine) throws Exception {
    MachineDto m = machineDao.getMachine(machine.getMachineId());

    if (m != null) {
        if (StringUtils.isEmpty(machine.getDisplayId())) {
            machine.setDisplayId(m.getDisplayId());
        }//from w  w  w. j av  a  2  s.  c om
        if (StringUtils.isEmpty(machine.getDisplayName())) {
            machine.setDisplayName(m.getDisplayName());
            machine.setIsPrd(m.getIsPrd());
        }
        // Edit Instance ?  IP  RHEV Manager ? ??  
        // hypervisorId ? cluster    .
        // ?  ?  .
        if (StringUtils.isEmpty(machine.getCluster())) {
            machine.setCluster(m.getCluster());
            machine.setIsVm(m.getIsVm());
        }
        if (machine.getHypervisorId() == null) {
            machine.setHypervisorId(m.getHypervisorId());
            machine.setIsVm(m.getIsVm());
        }
        machineDao.updateMachine(machine);
    } else {
        String displayId = "i-" + RandomStringUtils.randomAlphanumeric(8).toLowerCase();

        while (true) {
            if (machineDao.checkDuplicateDisplayId(displayId) == 0) {
                machine.setDisplayId(displayId);
                break;
            } else {
                displayId = "i-" + RandomStringUtils.randomAlphanumeric(8).toLowerCase();
            }
        }

        machineDao.insertMachine(machine);
    }
}

From source file:de.willuhn.jameica.hbci.server.KontoauszugPdfUtil.java

/**
 * Liefert das File-Objekt fuer diesen Kontoauszug.
 * Wenn er direkt im Filesystem gespeichert ist, wird dieses geliefert.
 * Wurde er jedoch per Messaging gespeichert, dann ruft die Funktion ihn
 * vom Archiv ab und erzeugt eine Temp-Datei mit dem Kontoauszug.
 * @param ka der Kontoauszug.//from  www. j av a2 s  . com
 * @return die Datei.
 * @throws ApplicationException
 */
public static File getFile(Kontoauszug ka) throws ApplicationException {
    if (ka == null)
        throw new ApplicationException(i18n.tr("Bitte whlen Sie den zu ffnenden Kontoauszug"));

    try {
        // Wenn ein Pfad und Dateiname angegeben ist, dann sollte die Datei
        // dort auch liegen
        final String path = StringUtils.trimToNull(ka.getPfad());
        final String name = StringUtils.trimToNull(ka.getDateiname());

        if (path != null && name != null) {
            File file = new File(path, name);

            Logger.info("trying to open pdf file from: " + file);
            if (!file.exists()) {
                Logger.error("file does not exist (anymore): " + file);
                throw new ApplicationException(i18n
                        .tr("Datei \"{0}\" existiert nicht mehr. Wurde sie gelscht?", file.getAbsolutePath()));
            }

            if (!file.canRead()) {
                Logger.error("cannot read file: " + file);
                throw new ApplicationException(i18n.tr("Datei \"{0}\" nicht lesbar", file.getAbsolutePath()));
            }

            return file;
        }

        final String uuid = StringUtils.trimToNull(ka.getUUID());

        Logger.info("trying to open pdf file using messaging, uuid: " + uuid);

        // Das kann eigentlich nicht sein. Dann wuerde ja alles fehlen
        if (uuid == null)
            throw new ApplicationException(i18n.tr("Ablageort des Kontoauszuges unbekannt"));

        QueryMessage qm = new QueryMessage(uuid, null);
        Application.getMessagingFactory().getMessagingQueue("jameica.messaging.get").sendSyncMessage(qm);
        byte[] data = (byte[]) qm.getData();
        if (data == null) {
            Logger.error("got no data from messaging for uuid: " + uuid);
            throw new ApplicationException(
                    i18n.tr("Datei existiert nicht mehr im Archiv. Wurde sie gelscht?"));
        }
        Logger.info("got " + data.length + " bytes from messaging for uuid: " + uuid);

        File file = File.createTempFile("kontoauszug-" + RandomStringUtils.randomAlphanumeric(5), ".pdf");
        file.deleteOnExit();

        OutputStream os = null;

        try {
            os = new BufferedOutputStream(new FileOutputStream(file));
            IOUtil.copy(new ByteArrayInputStream(data), os);
        } finally {
            IOUtil.close(os);
        }

        Logger.info("copied messaging data into temp file: " + file);
        return file;
    } catch (ApplicationException ae) {
        throw ae;
    } catch (Exception e) {
        Logger.error("unable to open file", e);
        throw new ApplicationException(i18n.tr("Fehler beim ffnen des Kontoauszuges: {0}", e.getMessage()));
    }
}

From source file:com.haulmont.cuba.gui.components.filter.condition.FtsCondition.java

protected String generateSessionIdParamName() {
    return "__sessionId" + RandomStringUtils.randomAlphanumeric(6);
}

From source file:com.google.code.ssm.aop.ReadThroughMultiCacheTest.java

@Test
public void testInitialKey2Result() {
    final AnnotationData annotation = new AnnotationData();
    annotation.setNamespace(RandomStringUtils.randomAlphanumeric(6));
    final Map<String, Object> expectedString2Object = new HashMap<String, Object>();
    final Map<String, Object> key2Result = new HashMap<String, Object>();
    final Set<Object> missObjects = new HashSet<Object>();
    final int length = 15;
    for (int ix = 0; ix < length; ix++) {

        final String object = RandomStringUtils.randomAlphanumeric(2 + ix);
        final String key = cut.getCacheBase().getCacheKeyBuilder().getCacheKey(object,
                annotation.getNamespace());
        expectedString2Object.put(key, object);

        // There are 3 possible outcomes when fetching by key from memcached:
        // 0) You hit, and the key & result are in the map
        // 1) You hit, but the result is null, which counts as a miss.
        // 2) You miss, and the key doesn't even get into the result map.
        final int option = RandomUtils.nextInt(3);
        if (option == 0) {
            key2Result.put(key, key + RandomStringUtils.randomNumeric(5));
        }//from  w  w w .java  2 s  .  c  om
        if (option == 1) {
            key2Result.put(key, null);
            missObjects.add(object);
        }
        if (option == 2) {
            missObjects.add(object);
        }
    }

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

    coord.getKey2Obj().putAll(expectedString2Object);
    coord.setInitialKey2Result(key2Result);

    assertTrue(coord.getMissedObjects().containsAll(missObjects));
    assertTrue(missObjects.containsAll(coord.getMissedObjects()));

}

From source file:com.eviware.soapui.security.scan.FuzzerSecurityScan.java

private String fuzzedValue() {
    int count = (int) (Math.random() * (maximal + 1 - minimal)) + minimal;
    return RandomStringUtils.randomAlphanumeric(count);
}

From source file:net.przemkovv.sphinx.compiler.GXXCompiler.java

private CompilationResult runCompiler(List<File> files, File output_file, List<String> args, File working_dir)
        throws InvalidCompilerException {
    // TODO: extract the main functionality of running compiler
    try {//www  . ja v a  2s . c  o m
        if (output_file == null) {
            output_file = new File(working_dir, RandomStringUtils.randomAlphanumeric(8) + ".exe");
        }
        ArrayList<String> cmd = new ArrayList<>();
        if (prepare_env_cmd != null) {
            cmd.add(prepare_env_cmd.getAbsolutePath());
            cmd.add("&&");
        }
        cmd.add(compiler_cmd.getAbsolutePath());
        cmd.add("-o" + output_file.getAbsolutePath());
        if (args != null) {
            cmd.addAll(args);
        }
        return compile(cmd, files, output_file);
    } catch (IOException | InterruptedException ex) {
        throw new InvalidCompilerException(ex);
    } catch (ExecutionException ex) {
        java.util.logging.Logger.getLogger(GXXCompiler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:gemlite.core.internal.testing.generator.writer.impl.LogInfoWriter.java

/**
 * support delete old file before save it.
 * //w ww.  j  a v  a 2  s  .co  m
 * @param filePath
 * @param fileName
 * @param lineSep
 * @param deleteOldFile
 */
public LogInfoWriter(String filePath, String fileName, String lineSep, boolean deleteOldFile) {
    if (StringUtils.isBlank(filePath))
        filePath = RandomStringUtils.randomAlphanumeric(4) + "/";
    else {
        if (!filePath.endsWith("/"))
            filePath = filePath + "/";
        if (!filePath.startsWith("/"))
            filePath = "/" + filePath;
    }
    if (StringUtils.isBlank(fileName))
        fileName = RandomStringUtils.randomAlphanumeric(6) + ".txt";

    String nodeName = ServerConfigHelper.getConfig(ITEMS.NODE_NAME);
    if (nodeName == null || nodeName.equals(""))
        nodeName = "basic";

    String path = "/server/" + nodeName + filePath;
    String gs_work = ServerConfigHelper.getConfig(ITEMS.GS_WORK);
    WorkPathHelper.verifyPath(gs_work, path, false);
    fullFilePath = gs_work + path + fileName;
    File f = new File(fullFilePath);

    try { // delete old file
        if (deleteOldFile) {
            if (f != null && f.isFile() && f.exists())
                f.delete();
        }
    } catch (Exception e1) {
    }

    try {
        fw = new FileWriterWithEncoding(f, TEST_FILE_ENCODING);
    } catch (IOException e) {
        e.printStackTrace();
        fw = null;
        fullFilePath = null;
    }

    this.lineSep = (lineSep != null ? lineSep : "\n");
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.api.user.MMXUsersResourceTest.java

public static AppEntity createRandomApp() throws Exception {

    String serverUserId = "serverUser";
    String appName = "usersresourcetestapp";
    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.j  a  v  a 2s  . co m*/
    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;
}