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:eu.vital.vitalcep.restApp.filteringApi.StaticFiltering.java

/**
 * Gets a filter./* ww  w  . j av a  2s . co m*/
 *
 * @param info
     * @param req
 * @return the filter 
 * @throws java.io.IOException 
 */
@POST
@Path("filterstaticquery")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response filterstaticquery(String info, @Context HttpServletRequest req) throws IOException {

    JSONObject jo = new JSONObject(info);

    if (jo.has("dolceSpecification") && jo.has("query")) {
        // && jo.has("data") for demo
        StringBuilder ck = new StringBuilder();
        Security slogin = new Security();

        JSONObject credentials = new JSONObject();

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

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

        try {
            db.getCollection("staticqueryfilters");
        } 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);

                CEP cepProcess = new CEP();

                if (!(cepProcess.CEPStart(CEP.CEPType.QUERY, ds, mqin, mqout, confFile, jo.getString("query"),
                        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:CEPFilterStaticQuerySensor");
                Document doc = new Document(dbObject.toMap());

                try {
                    db.getCollection("staticqueryfilters").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("staticqueryfiltersobservations").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();

                JSONArray aData = new JSONArray();

                try {

                    DMSManager oDMS = new DMSManager(dmsURL, cookie);

                    aData = oDMS.getObservations(jo.getString("query"));

                    if (aData.length() < 1) {
                        CepContainer.deleteCepProcess(cepProcess.PID);

                        if (!cepProcess.cepDispose()) {
                            java.util.logging.Logger.getLogger(StaticFiltering.class.getName())
                                    .log(Level.SEVERE, "bcep Instance not terminated");
                        }
                        ;
                        db = null;
                        if (mongo != null) {
                            mongo.close();
                            mongo = null;
                        }
                        return Response.status(Response.Status.BAD_REQUEST).entity("no data to be filtered")
                                .build();
                    }

                } catch (KeyManagementException | KeyStoreException ex) {
                    java.util.logging.Logger.getLogger(StaticFiltering.class.getName()).log(Level.SEVERE, null,
                            ex);
                }

                //DMSManager oDMS = new DMSManager(dmsURL,req.getHeader("vitalAccessToken"));

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

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

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

                //FORMATTING OBSERVATIONS OUTPUT
                Encoder encoder = new Encoder();

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

                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 + "]";

                try {

                    DMSManager pDMS = new DMSManager(dmsURL, cookie);

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

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

                } catch (IOException | KeyManagementException | NoSuchAlgorithmException
                        | KeyStoreException ex) {
                    db = null;
                    if (mongo != null) {
                        mongo.close();
                        mongo = null;
                    }
                    java.util.logging.Logger.getLogger(StaticFiltering.class.getName()).log(Level.SEVERE, null,
                            ex);
                }

                CepContainer.deleteCepProcess(cepProcess.PID);

                if (!cepProcess.cepDispose()) {
                    java.util.logging.Logger.getLogger(StaticFiltering.class.getName()).log(Level.SEVERE,
                            "bcep Instance not terminated");
                }
                ;
                db = null;
                if (mongo != null) {
                    mongo.close();
                    mongo = null;
                }
                return Response.status(Response.Status.OK).entity(sOutput).build();

            } catch (IOException | JSONException | NoSuchAlgorithmException | 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:com.kixeye.chassis.transport.WebSocketTransportTest.java

@Test
public void testWebSocketServiceWithProtobuf() 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 {/*  ww  w .j  a v a  2 s  .com*/
        context.refresh();

        final MessageSerDe serDe = context.getBean(ProtobufMessageSerDe.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();
            while (context.isActive()) {
                Thread.sleep(100);
            }
        }
    }
}

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

@Test
public void addServerAsDevSlaveDnsServer() {
    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.DEV);
        server.setServerStatus(ServerStatus.ONLINE);
        server.setServerType(ServerType.DNSSLAVE);
        server.setServerComments("app server");
        server.setAssignedEngineer(userAccount);
        server.setCpuType("AMD 1.0 GHz");
        server.setCpuCount(1);//from  w  ww  .  jav a  2 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:com.cws.esolutions.security.processors.impl.AccountChangeProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IAccountChangeProcessor#changeUserSecurity(com.cws.esolutions.security.processors.dto.AccountChangeRequest)
 *///w ww  . java 2  s  .  c om
public AccountChangeResponse changeUserSecurity(final AccountChangeRequest request)
        throws AccountChangeException {
    final String methodName = IAccountChangeProcessor.CNAME
            + "#changeUserSecurity(final AccountChangeRequest request) throws AccountChangeException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("AccountChangeRequest: {}", request);
    }

    AccountChangeResponse response = new AccountChangeResponse();

    final Calendar calendar = Calendar.getInstance();
    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount requestor = request.getRequestor();
    final UserAccount userAccount = request.getUserAccount();
    final AuthenticationData reqSecurity = request.getUserSecurity();

    if (DEBUG) {
        DEBUGGER.debug("Calendar: {}", calendar);
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount: {}", requestor);
        DEBUGGER.debug("UserAccount: {}", userAccount);
    }

    // ok, first things first. if this is an administrative reset, make sure the requesting user
    // is authorized to perform the action.
    if (!(StringUtils.equals(userAccount.getGuid(), requestor.getGuid()))) {
        // requesting user is not the same as the user being reset. no authorization here,
        // no one is allowed to change user security but the owning user
        response.setRequestStatus(SecurityRequestStatus.UNAUTHORIZED);

        return response;
    }

    try {
        // otherwise, keep going
        // make sure the two questions and answers arent the same
        if ((StringUtils.equals(reqSecurity.getSecQuestionOne(), reqSecurity.getSecQuestionTwo()))) {
            throw new AccountChangeException("The security questions must be different.");
        } else if ((StringUtils.equals(reqSecurity.getSecAnswerOne(), reqSecurity.getSecAnswerTwo()))) {
            throw new AccountChangeException("The security answers must be different.");
        } else {
            // ok, authenticate first
            String userSalt = userSec.getUserSalt(userAccount.getGuid(), SaltType.LOGON.name());

            if (StringUtils.isNotEmpty(userSalt)) {
                // we aren't getting the data back here because we don't need it. if the request
                // fails we'll get an exception and not process further. this might not be the
                // best flow control, but it does exactly what we need where we need it.
                authenticator.performLogon(userAccount.getUsername(),
                        PasswordUtils.encryptText(reqSecurity.getPassword(), userSalt,
                                secBean.getConfigData().getSecurityConfig().getAuthAlgorithm(),
                                secBean.getConfigData().getSecurityConfig().getIterations(),
                                secBean.getConfigData().getSystemConfig().getEncoding()));

                // ok, thats out of the way. lets keep moving.
                String newUserSalt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

                if (StringUtils.isNotEmpty(newUserSalt)) {
                    // get rollback information in case something breaks...
                    // we already have the existing expiry and password, all we really need to get here is the salt.
                    String existingSalt = userSec.getUserSalt(userAccount.getGuid(), SaltType.RESET.name());

                    if (StringUtils.isNotEmpty(existingSalt)) {
                        // make the backout
                        List<String> currentSec = authenticator.obtainSecurityData(userAccount.getUsername(),
                                userAccount.getGuid());

                        // good, move forward
                        // make the modification in the user repository
                        boolean isComplete = userManager.modifyUserSecurity(userAccount.getUsername(),
                                new ArrayList<String>(Arrays.asList(reqSecurity.getSecQuestionOne(),
                                        reqSecurity.getSecQuestionTwo(),
                                        PasswordUtils.encryptText(reqSecurity.getSecAnswerOne(), newUserSalt,
                                                secConfig.getAuthAlgorithm(), secConfig.getIterations(),
                                                secBean.getConfigData().getSystemConfig().getEncoding()),
                                        PasswordUtils.encryptText(reqSecurity.getSecAnswerTwo(), newUserSalt,
                                                secConfig.getAuthAlgorithm(), secConfig.getIterations(),
                                                secBean.getConfigData().getSystemConfig().getEncoding()))));

                        if (DEBUG) {
                            DEBUGGER.debug("isComplete: {}", isComplete);
                        }

                        if (isComplete) {
                            // now update the salt
                            isComplete = userSec.addOrUpdateSalt(userAccount.getGuid(), newUserSalt,
                                    SaltType.RESET.name());

                            if (isComplete) {
                                response.setRequestStatus(SecurityRequestStatus.SUCCESS);
                            } else {
                                // something failed. we're going to undo what we did in the user
                                // repository, because we couldnt update the salt value. if we don't
                                // undo it then the user will never be able to login without admin
                                // intervention
                                boolean isReverted = userManager.modifyUserSecurity(userAccount.getUsername(),
                                        new ArrayList<String>(Arrays.asList(currentSec.get(0),
                                                currentSec.get(1), currentSec.get(2), currentSec.get(3))));

                                if (DEBUG) {
                                    DEBUGGER.debug("isReverted: {}", isReverted);
                                }

                                boolean backoutSalt = userSec.addOrUpdateSalt(userAccount.getGuid(),
                                        existingSalt, SaltType.RESET.name());

                                if (DEBUG) {
                                    DEBUGGER.debug("backoutSalt: {}", backoutSalt);
                                }

                                if (!(isReverted) && (!(backoutSalt))) {
                                    throw new AccountChangeException(
                                            "Failed to modify the user account and unable to revert to existing state.");
                                }

                                response.setRequestStatus(SecurityRequestStatus.FAILURE);
                            }
                        } else {
                            response.setRequestStatus(SecurityRequestStatus.FAILURE);
                        }
                    } else {
                        ERROR_RECORDER.error("Unable to generate new salt for provided user account.");

                        response.setRequestStatus(SecurityRequestStatus.FAILURE);
                    }
                } else {
                    ERROR_RECORDER
                            .error("Unable to obtain existing salt value from datastore. Cannot continue.");

                    response.setRequestStatus(SecurityRequestStatus.FAILURE);
                }
            } else {
                ERROR_RECORDER.error("Unable to obtain configured user salt. Cannot continue");

                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), sqx);

        throw new AccountChangeException(sqx.getMessage(), sqx);
    } catch (UserManagementException umx) {
        ERROR_RECORDER.error(umx.getMessage(), umx);

        throw new AccountChangeException(umx.getMessage(), umx);
    } catch (AuthenticatorException ax) {
        ERROR_RECORDER.error(ax.getMessage(), ax);

        throw new AccountChangeException(ax.getMessage(), ax);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new AccountChangeException(sx.getMessage(), sx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.ADDSECURITY);
            auditEntry.setUserAccount(requestor);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getApplicationName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();
            auditRequest.setAuditEntry(auditEntry);

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

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

@Test
public void addServerAsQaSlaveDnsServer() {
    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.DNSSLAVE);
        server.setServerComments("app server");
        server.setAssignedEngineer(userAccount);
        server.setCpuType("AMD 1.0 GHz");
        server.setCpuCount(1);//  w  w  w  .j av a  2 s .  com
        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:edu.duke.cabig.c3pr.webservice.integration.StudyUtilityWebServiceTest.java

private void executeQueryConsentTest() throws SecurityExceptionFaultMessage, StudyUtilityFaultMessage {
    StudyUtility service = getService();

    // all consents of the study
    final QueryStudyConsentRequest request = new QueryStudyConsentRequest();
    final DocumentIdentifier studyId = createStudyPrimaryIdentifier();
    request.setStudyIdentifier(studyId);
    List<Consent> list = service.queryStudyConsent(request).getConsents().getItem();
    assertEquals(1, list.size());//from   w ww  .j  a  v a 2  s .c om

    // consent with data
    Consent example = createConsent(TEST_CONSENT_TITLE, "");
    example.setMandatoryIndicator(null);
    request.setConsent(example);
    list = service.queryStudyConsent(request).getConsents().getItem();
    assertEquals(1, list.size());
    example = createConsent(TEST_CONSENT_TITLE, "");
    assertTrue(BeanUtils.deepCompare(example, list.get(0)));

    // consent does not exist
    example.setOfficialTitle(iso.ST(RandomStringUtils.randomAlphanumeric(256)));
    request.setConsent(example);
    list = service.queryStudyConsent(request).getConsents().getItem();
    assertEquals(0, list.size());

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

}

From source file:com.thoughtworks.cruise.utils.configfile.CruiseConfigDom.java

/** Looks for variables of type: ${http_repo*} in REPO_URL property and replaces it. Example:
  *    <repositories>//from  w  w w.j a  va 2s  . c o m
  *        <repository id="repo-id" name="tw-repo">
  *          <pluginConfiguration id="yum" version="1"/>
  *          <configuration>
  *            <property>
  *              <key>REPO_URL</key>
  *              <value>http://192.168.0.101:8081/${http_repo1}</value>
  *            </property>
  *
  *     TO
  *
  *    <repositories>
  *        <repository id="repo-id" name="tw-repo">
  *          <pluginConfiguration id="yum" version="1"/>
  *          <configuration>
  *            <property>
  *              <key>REPO_URL</key>
  *              <value>http://192.168.0.101:8081/pkgrepo-RANDOM1234</value>
  *            </property>
  *
  *      AND return a map which contains: {"http_repo1" => "pkgrepo-RANDOM1234"}
 */
public Map<String, String> replacePackageRepositoryURIForHttpBasedRepos(Map<String, String> currentRepoNames) {
    Pattern httpRepoNameVariablePattern = Pattern.compile("\\$\\{(http_repo[^\\}]*)\\}");
    Map<String, String> httpRepoNameInConfigToItsNameAtRuntime = new HashMap<String, String>(currentRepoNames);

    List<Element> allRepoUrlPropertyKeys = root()
            .selectNodes("/cruise//repositories/repository/configuration/property/key[text()='REPO_URL']");
    for (Element repoUrlKeyElement : allRepoUrlPropertyKeys) {
        Node repoUrlPropertyInConfig = repoUrlKeyElement.getParent().selectSingleNode("value");
        String existingValueOfRepoUrl = repoUrlPropertyInConfig.getText();

        Matcher matcherForVariable = httpRepoNameVariablePattern.matcher(existingValueOfRepoUrl);
        if (matcherForVariable.find()) {
            String variableName = matcherForVariable.group(1);

            String replacementRepoName = httpRepoNameInConfigToItsNameAtRuntime.get(variableName);
            if (!httpRepoNameInConfigToItsNameAtRuntime.containsKey(variableName)) {
                replacementRepoName = "pkgrepo-" + RandomStringUtils.randomAlphanumeric(10);
                httpRepoNameInConfigToItsNameAtRuntime.put(variableName, replacementRepoName);
            }

            String replacementRepoURL = existingValueOfRepoUrl
                    .replaceFirst(httpRepoNameVariablePattern.pattern(), replacementRepoName);
            repoUrlPropertyInConfig.setText(replacementRepoURL);
        }
    }

    return httpRepoNameInConfigToItsNameAtRuntime;
}

From source file:edu.duke.cabig.c3pr.webservice.integration.StudyUtilityWebServiceTest.java

private void executeQueryStudyTest() throws SecurityExceptionFaultMessage, StudyUtilityFaultMessage {
    StudyUtility service = getService();
    QueryStudyAbstractRequest request = new QueryStudyAbstractRequest();
    DSETAdvanceSearchCriterionParameter params = new DSETAdvanceSearchCriterionParameter();
    request.setParameters(params);//from w ww.  j a v  a 2s.  co m

    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(STUDY_ID);
    param.setValues(new DSETST());
    param.getValues().getItem().add(value);

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

    ST ctxName = iso.ST();
    ctxName.setValue("Study");
    param.setObjectContextName(ctxName);

    List<StudyProtocolVersion> list = service.queryStudyAbstract(request).getStudies().getItem();
    assertEquals(1, list.size());
    StudyProtocolVersion foundStudy = list.get(0);
    assertTrue(BeanUtils.deepCompare(createStudy(""), foundStudy));

    // nothing found
    value.setValue(RandomStringUtils.randomAlphanumeric(32));
    list = service.queryStudyAbstract(request).getStudies().getItem();
    assertEquals(0, list.size());

}

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

@Test
public void addServerAsPrdSlaveDnsServer() {
    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.DNSSLAVE);
        server.setServerComments("app server");
        server.setAssignedEngineer(userAccount);
        server.setCpuType("AMD 1.0 GHz");
        server.setCpuCount(1);/*from  w  w w  .j  av  a2 s  .  com*/
        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.kixeye.chassis.transport.WebSocketTransportTest.java

@Test
public void testWebSocketServiceWithXml() 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   www.  j a  v  a  2s . c om*/
        context.refresh();

        final MessageSerDe serDe = context.getBean(XmlMessageSerDe.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(5000, 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();
            while (context.isActive()) {
                Thread.sleep(100);
            }
        }
    }
}