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.dtolabs.rundeck.core.execution.impl.common.DefaultFileCopierUtil.java

/**
 * Return a temporary filepath for a file to be copied to the node, given the input filename (without directory
 * path)//  w w w .  j a v  a2s  .c  o m
 *
 * @param node           the destination node
 * @param project        project
 * @param framework      framework
 * @param scriptfileName the name of the file to copy
 * @param fileExtension  optional extension to use for the temp file, or null for default
 * @param identity       unique identifier, or null to include a random string
 *
 * @return a filepath specifying destination of the file to copy that should be unique
 */
@Override
public String generateRemoteFilepathForNode(final INodeEntry node, final IRundeckProject project,
        final IFramework framework, final String scriptfileName, final String fileExtension,
        final String identity) {
    String tempfilename = String.format("%d-%s-%s-%s", counter.getAndIncrement(),
            identity != null ? identity : RandomStringUtils.randomAlphanumeric(10), node.getNodename(),
            scriptfileName);

    String extension = fileExtension;
    if (null == extension) {
        //determine based on node
        extension = defaultRemoteFileExtensionForNode(node);
    }
    final String remoteFilename = appendRemoteFileExtension(cleanFileName(tempfilename),
            null != extension ? cleanFileName(extension) : null);
    final String remotedir = getRemoteDirForNode(node, project, framework);

    return remotedir + remoteFilename;
}

From source file:com.ironiacorp.statistics.r.AbstractRClient.java

@Override
public Map<String, LinearModelSummary> rowApplyLinearModel(String dataMatrixVarName, String modelFormula,
        String[] factorNames) {//from  w ww . j  a va2 s .  c o m

    String lmres = "lmlist." + RandomStringUtils.randomAlphanumeric(10);

    loadScript(this.getClass().getResourceAsStream("/com/ironiacorp/statistics/r/linearModels.R"));
    String command = lmres + "<-rowlm(" + modelFormula + ", data.frame(" + dataMatrixVarName + ") )";
    this.voidEval(command);

    REXP rawLmSummaries = this.eval("lapply(" + lmres + ", function(x){ try(summary(x), silent=T)})");
    if (rawLmSummaries == null) {
        return null;
    }

    REXP rawAnova = this.eval("lapply(" + lmres + ", function(x){ try(anova(x), silent=T)})");

    Map<String, LinearModelSummary> result = new HashMap<String, LinearModelSummary>();
    try {
        RList rawLmList = rawLmSummaries.asList();
        if (rawLmList == null) {
            return null;
        }

        RList rawAnovaList = rawAnova.asList();
        if (rawAnovaList == null) {
            return null;
        }

        for (int i = 0; i < rawLmList.size(); i++) {
            REXP lmSummary = rawLmList.at(i);
            REXP anova = rawAnovaList.at(i);
            String elementIdentifier = rawLmList.keyAt(i);
            if (!lmSummary.isList() || !lmSummary.getAttribute("class").asString().equals("summary.lm")) {
                result.put(elementIdentifier, new LinearModelSummary());
            } else {
                result.put(elementIdentifier, new LinearModelSummary(lmSummary, anova, factorNames));
            }

        }
    } catch (REXPMismatchException e) {
        throw new RuntimeException(e);
    }

    return result;
}

From source file:com.cws.esolutions.core.processors.impl.ServerManagementProcessorImplTest.java

@Test
public void addServerAsPrdAppServer() {
    Server dmgrServer = new Server();
    dmgrServer.setServerGuid("fde6d6e9-8bac-4a82-99c6-ef225945d846");

    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.PRD);
        server.setServerStatus(ServerStatus.ONLINE);
        server.setServerType(ServerType.APPSERVER);
        server.setServerComments("app server");
        server.setAssignedEngineer(userAccount);
        server.setCpuType("AMD 1.0 GHz");
        server.setCpuCount(1);/*  w  w w .  ja va  2  s  . co 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:gov.nih.nci.cabig.caaers.service.ProxyWebServiceFacade.java

private String syncStudy(String operationName, String sponsorIdentifierValue) {
    try {/*from w w w .j  a v a  2s  .  c  o  m*/
        //invoke the webservice
        Map<String, String> criteriaMap = new HashMap<String, String>();
        criteriaMap.put("nciDocumentNumber", sponsorIdentifierValue);

        String correlationId = RandomStringUtils.randomAlphanumeric(15);

        String message = buildMessage(correlationId, "adeers", "study", operationName, "async", criteriaMap);
        String xmlStudyDetails = simpleSendAndReceive(message);
        if (log.isDebugEnabled())
            log.debug("result for getStudyDetails : for (" + sponsorIdentifierValue + ") :" + xmlStudyDetails);
        String studyDbId = xsltTransformer.toText(xmlStudyDetails, "xslt/c2a_generic_response.xslt");
        studyDbId = StringUtils.trim(studyDbId);
        if (log.isInfoEnabled())
            log.info("Got study details : Study DB ID :" + studyDbId);
        return studyDbId;
    } catch (Exception e) {
        log.error("Error occurred while invoking ServiceMix Study Details : " + e.getMessage(), e);
        return "Import study failed:" + e.getMessage();
    }

}

From source file:de.thm.arsnova.service.UserServiceImpl.java

@Override
public UserProfile create(String username, String password) {
    String lcUsername = username.toLowerCase();

    if (null == keygen) {
        keygen = KeyGenerators.secureRandom(16);
    }// www.ja v  a2s  .c  o m

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

    if (null == mailPattern || !mailPattern.matcher(lcUsername).matches()) {
        logger.info("User registration failed. {} does not match pattern.", lcUsername);

        return null;
    }

    if (null != userRepository.findByAuthProviderAndLoginId(UserProfile.AuthProvider.ARSNOVA, lcUsername)) {
        logger.info("User registration failed. {} already exists.", lcUsername);

        return null;
    }

    UserProfile userProfile = new UserProfile();
    UserProfile.Account account = new UserProfile.Account();
    userProfile.setAccount(account);
    userProfile.setAuthProvider(UserProfile.AuthProvider.ARSNOVA);
    userProfile.setLoginId(lcUsername);
    account.setPassword(encodePassword(password));
    account.setActivationKey(RandomStringUtils.randomAlphanumeric(32));
    userProfile.setCreationTimestamp(new Date());

    /* Repository is accessed directly without EntityService to skip permission check */
    UserProfile result = userRepository.save(userProfile);
    if (null != result) {
        sendActivationEmail(result);
    } else {
        logger.error("User registration failed. {} could not be created.", lcUsername);
    }

    return result;
}

From source file:com.edgenius.wiki.service.impl.ExportServiceImpl.java

/**
 * @param spaceUname//from   w ww .jav  a2 s.c o  m
 * @param pageTitle
 * @return
 * @throws ExportException
 */
private File export(String spaceUname, String pageTitle, int type) throws ExportException {
    FileOutputStream fos = null;
    String dir = null;
    try {
        dir = FileUtil.createTempDirectory(TMP_EXPORT);
        String cannoicalDir = new File(dir).getCanonicalPath();

        File subdir = new File(FileUtil.getFullPath(dir, ExportService.EXPORT_HTML_SUB_DIR));
        subdir.mkdir();
        File html = new File(FileUtil.getFullPath(dir, EXPORT_HTML_FILENAME));

        fos = new FileOutputStream(html, true);
        Map<File, String> list = new HashMap<File, String>();
        User viewer = WikiUtil.getUser();

        List<Page> pages = null;
        if (StringUtils.isEmpty(pageTitle)) {
            //export all pages in space
            pages = pageService.getPagesInSpace(spaceUname, null, 0, viewer);
        } else {
            //export single page
            Page page = pageService.getCurrentPageByTitle(spaceUname, pageTitle);
            if (page != null) {
                pages = new ArrayList<Page>();
                pages.add(page);
            }
        }

        String skinPath = Global.Skin;

        //add first part of whole exported HTML
        Template tmpl = templateEngine.getConfiguration().getTemplate(ExportTemplPre);
        Map<String, String> preMap = new HashMap<String, String>();
        preMap.put("skinpath", skinPath);
        fos.write(FreeMarkerTemplateUtils.processTemplateIntoString(tmpl, preMap).getBytes());

        if (pages != null) {
            int count = pages.size();
            for (Page page : pages) {

                String content = exportPageHTML(RenderContext.RENDER_TARGET_EXPORT, page);
                if (content != null) {
                    //save this page attachment - try to save by original name, if failed, try to append -x on file name
                    fos.write("<div class=\"print-page\">\n".getBytes());
                    //anchor
                    fos.write(new StringBuffer("<a href='#' name='")
                            .append(StringEscapeUtils.escapeHtml(spaceUname)).append("_")
                            .append(StringEscapeUtils.escapeHtml(page.getTitle())).append("'></a>").toString()
                            .getBytes());

                    fos.write(content.getBytes());
                    fos.write("\n</div>".getBytes());

                    //download all latest version node - 
                    //TODO:is necessary? or only image files? but if there are {attachment} macro? so at moment, just download all
                    ITicket ticket = repositoryService.login(spaceUname, spaceUname, spaceUname);
                    List<FileNode> nodes = repositoryService.getAllIdentifierNodes(ticket,
                            RepositoryService.TYPE_ATTACHMENT, page.getPageUuid(), false);
                    if (nodes != null && nodes.size() > 0) {

                        Set<String> nodeUuids = new HashSet<String>();
                        File pdir = new File(subdir, page.getPageUuid());
                        if (pdir.mkdir()) {
                            for (FileNode fileNode : nodes) {
                                //skip same nodeUuid -- only download once(latest) file
                                if (nodeUuids.contains(fileNode.getNodeUuid()))
                                    continue;
                                nodeUuids.add(fileNode.getNodeUuid());

                                //download to _export/export_files/pageUid/xxx
                                FileOutputStream out = null;
                                InputStream in = null;
                                try {
                                    File att = new File(pdir, fileNode.getFilename());
                                    out = new FileOutputStream(att);
                                    FileNode down = repositoryService.downloadFile(ticket,
                                            fileNode.getNodeUuid(), null, null);
                                    in = down.getFile();
                                    int len = 0;
                                    byte[] ch = new byte[10240];
                                    while ((len = in.read(ch)) != -1) {
                                        out.write(ch, 0, len);
                                    }
                                    if (type == EXPORT_HTML) {
                                        //put attachment into zip list - pdf does not need zip attachment 
                                        list.put(att, cannoicalDir);
                                    }
                                } catch (Exception e) {
                                    log.error("Write attachment export file failed", e);
                                } finally {
                                    if (in != null) {
                                        try {
                                            in.close();
                                        } catch (Exception e2) {
                                        }
                                    }
                                    if (out != null) {
                                        try {
                                            out.close();
                                        } catch (Exception e2) {
                                        }
                                    }
                                }
                            }
                        } else {
                            AuditLogger.error("Export page attachment failed - unable make sub dir "
                                    + (page != null ? page.getPageUuid() : "") + " on space " + spaceUname);
                        }
                    }

                    if (count > 1) {
                        //print page separator for multiple pages export scenario
                        fos.write("<div class=\"print-page-separator\"></div>".getBytes());
                    }
                } else {
                    AuditLogger.error("Export page failed: " + (page != null ? page.getTitle() : "")
                            + " on space " + spaceUname);
                }
            }

            //export static resource for style sheet or images etc.
            exportResources(cannoicalDir, subdir, list, skinPath);
        }

        //append last part of whole exported HTML
        StringWriter post = new StringWriter();
        tmpl = templateEngine.getConfiguration().getTemplate(ExportTemplPost);
        tmpl.dump(post);
        fos.write(post.toString().getBytes());
        if (type == EXPORT_HTML) {
            //put exported html in zip list
            list.put(html, cannoicalDir);
        } else {
            //convert HMTL to PDF and zip
            File pdf = convertHTMLtoPDF(dir, html);
            list.put(pdf, cannoicalDir);
        }
        //for final zip file
        String target = "export.zip";
        //failure tolerance
        int retry = 0;
        do {
            target = FileUtil.getFullPath(targetDir,
                    EXPORT_ZIP + "-" + RandomStringUtils.randomAlphanumeric(10) + ".zip");
            retry++;
        } while (new File(target).exists() && retry < 50);

        ZipFileUtil.createZipFile(target, list, false);

        return new File(target);
    } catch (Exception e) {
        log.error("Failed export " + spaceUname + " on " + pageTitle, e);
        throw new ExportException(e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
            }
        }
        if (dir != null) {
            try {
                FileUtil.deleteDir(dir);
            } catch (IOException e) {
                log.error("Unable to delete directory " + dir);
            }
        }
    }
}

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

@Test
public void testWebSocketServiceWithJsonWithPskEncryption() throws Exception {
    // create AES shared key cipher
    Security.addProvider(new BouncyCastleProvider());
    KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC");
    kgen.init(128);//  w  ww  . jav  a2s . com
    SecretKey key = kgen.generateKey();
    byte[] aesKey = key.getEncoded();

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

    properties.put("websocket.crypto.enabled", "true");
    properties.put("websocket.crypto.cipherProvider", "BC");
    properties.put("websocket.crypto.cipherTransformation", "AES/ECB/PKCS7Padding");
    properties.put("websocket.crypto.secretKeyAlgorithm", "AES");
    properties.put("websocket.crypto.secretKeyData", BaseEncoding.base16().encode(aesKey));

    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 {
        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,
                context.getBean(WebSocketPskFrameProcessor.class));

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

        byte[] rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

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

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        envelope = new Envelope("getStuff", null, null, null);

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

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

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

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

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

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

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

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

private void executeUpdateStudyStatusTest()
        throws DataSetException, IOException, SQLException, DatabaseUnitException, Exception {
    StudyUtility service = getService();

    // successful add
    UpdateStudyStatusRequest request = new UpdateStudyStatusRequest();
    final DocumentIdentifier studyId = createStudyPrimaryIdentifier();
    request.setStudyIdentifier(studyId);
    PermissibleStudySubjectRegistryStatus status = createPermissibleStudySubjectRegistryStatus();
    status.getRegistryStatus().getCode().setCode(STATUS_INACTIVE);
    status.getSecondaryReason().get(0).setCode(iso.CD(TEST_SECONDARY_REASON_CODE + "-to be updated"));
    status.getSecondaryReason().get(0).setDescription(iso.ST(TEST_SECONDARY_REASON_DESCR + "-to be updated"));
    request.setStatus(status);/*ww w  . j  a  v  a  2 s  . c  om*/
    request.setUpdateMode(UpdateMode.A);
    PermissibleStudySubjectRegistryStatus updatedStatus = service.updateStudyStatus(request).getStatus();
    assertEquals(STATUS_INACTIVE, updatedStatus.getRegistryStatus().getCode().getCode());
    assertEquals(TEST_SECONDARY_REASON_CODE + "-to be updated",
            updatedStatus.getSecondaryReason().get(0).getCode().getCode());
    assertEquals(TEST_SECONDARY_REASON_DESCR + "-to be updated",
            updatedStatus.getSecondaryReason().get(0).getDescription().getValue());

    // successful update
    status = createPermissibleStudySubjectRegistryStatus();
    status.getRegistryStatus().getCode().setCode(STATUS_INACTIVE);
    request.setStatus(status);
    request.setUpdateMode(UpdateMode.U);
    updatedStatus = service.updateStudyStatus(request).getStatus();
    assertEquals(STATUS_INACTIVE, updatedStatus.getRegistryStatus().getCode().getCode());
    assertEquals(TEST_SECONDARY_REASON_CODE, updatedStatus.getSecondaryReason().get(0).getCode().getCode());
    assertEquals(TEST_SECONDARY_REASON_DESCR,
            updatedStatus.getSecondaryReason().get(0).getDescription().getValue());

    // successful delete
    request.setUpdateMode(UpdateMode.D);
    updatedStatus = service.updateStudyStatus(request).getStatus();
    assertEquals(STATUS_INACTIVE, updatedStatus.getRegistryStatus().getCode().getCode());
    assertEquals(TEST_SECONDARY_REASON_CODE, updatedStatus.getSecondaryReason().get(0).getCode().getCode());
    assertEquals(TEST_SECONDARY_REASON_DESCR,
            updatedStatus.getSecondaryReason().get(0).getDescription().getValue());

    // invalid status code
    status.getRegistryStatus().getCode().setCode("WRONG");
    try {
        service.updateStudyStatus(request);
        fail();
    } catch (StudyUtilityFaultMessage e) {
        logger.info("Invalid status code testing passed.");
    }

    // study does not exist.
    studyId.getIdentifier().setExtension(RandomStringUtils.randomAlphanumeric(32));
    try {
        service.updateStudyStatus(request);
        fail();
    } catch (StudyUtilityFaultMessage e) {
        logger.info("Unexistent study creation passed.");
    }

}

From source file:com.cws.esolutions.core.processors.impl.ServerManagementProcessorImplTest.java

@Test
public void addServerAsPrdWebServer() {
    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.PRD);
        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  .ja  v a 2s .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:com.google.cloud.bigtable.hbase.TestPut.java

private void multiplePutsOneBad(int numberOfGoodPuts, byte[][] goodkeys, byte[] badkey) throws IOException {
    Table table = getConnection().getTable(TABLE_NAME);
    List<Put> puts = new ArrayList<Put>();
    for (int i = 0; i < numberOfGoodPuts; ++i) {
        byte[] qualifier = Bytes.toBytes("testQualifier-" + RandomStringUtils.randomAlphanumeric(8));
        byte[] value = Bytes.toBytes("testValue-" + RandomStringUtils.randomAlphanumeric(8));
        Put put = new Put(goodkeys[i]);
        put.addColumn(COLUMN_FAMILY, qualifier, value);
        puts.add(put);/*from   w w  w  .  j a v  a2  s.  c om*/
    }

    // Insert a bad put in the middle
    byte[] badfamily = Bytes.toBytes("badcolumnfamily-" + RandomStringUtils.randomAlphanumeric(8));
    byte[] qualifier = Bytes.toBytes("testQualifier-" + RandomStringUtils.randomAlphanumeric(8));
    byte[] value = Bytes.toBytes("testValue-" + RandomStringUtils.randomAlphanumeric(8));
    Put put = new Put(badkey);
    put.addColumn(badfamily, qualifier, value);
    puts.add(numberOfGoodPuts / 2, put);
    RetriesExhaustedWithDetailsException thrownException = null;
    try {
        table.put(puts);
    } catch (RetriesExhaustedWithDetailsException e) {
        thrownException = e;
    }
    Assert.assertNotNull("Exception should have been thrown", thrownException);
    Assert.assertEquals("Expecting one exception", 1, thrownException.getNumExceptions());
    Assert.assertArrayEquals("Row key", badkey, thrownException.getRow(0).getRow());
    Assert.assertTrue("Cause: NoSuchColumnFamilyException",
            thrownException.getCause(0) instanceof NoSuchColumnFamilyException);
    table.close();
}