Example usage for java.util UUID fromString

List of usage examples for java.util UUID fromString

Introduction

In this page you can find the example usage for java.util UUID fromString.

Prototype

public static UUID fromString(String name) 

Source Link

Document

Creates a UUID from the string standard representation as described in the #toString method.

Usage

From source file:com.nesscomputing.service.discovery.server.announce.ConfigStaticAnnouncer.java

private Map<UUID, Map<String, String>> getAnnouncements() {
    final AbstractConfiguration subconfig = config.getConfiguration(CONFIG_ROOT);

    final Iterator<String> keys = subconfig.getKeys();

    final Map<UUID, Map<String, String>> configTree = Maps.newHashMap();

    while (keys.hasNext()) {
        final String key = keys.next();

        final String id = StringUtils.substringBefore(key, ".");

        UUID serviceId;//from   w ww  .  java 2  s .com

        try {
            serviceId = UUID.fromString(id);
        } catch (final IllegalArgumentException e) {
            throw new IllegalArgumentException(String.format("Invalid serviceId \"%s\"", id), e);
        }

        Map<String, String> configMap = configTree.get(serviceId);
        if (configMap == null) {
            configTree.put(serviceId, configMap = Maps.newHashMap());
        }

        configMap.put(StringUtils.substringAfter(key, "."), subconfig.getString(key));
    }
    return configTree;
}

From source file:dbsimulator.dal.mysql.MySqlSimDal.java

@Override
public boolean abort() {

    try (SQLConnection connection = getSQLConnection()) {
        UUID session = UUID.fromString(getSessionKey());
        boolean abort = _simdll.simGetSimAbort(connection, session);
        setAbortSimulation(abort);/*from   www . ja  v  a  2s.  c  om*/
        return abort;
    } catch (SQLException se) {
        _logger.error(se.getMessage());
    } catch (ReturnStatusException re) {
        _logger.error(re.getMessage());
    }
    // TODO just feels wrong to return false here
    return false;
}

From source file:at.alladin.rmbt.controlServer.QualityOfServiceResultResource.java

@Post("json")
public String request(final String entity) {
    final String secret = getContext().getParameters().getFirstValue("RMBT_SECRETKEY");

    addAllowOrigin();/*from  w w w.  j ava  2s. c  om*/

    JSONObject request = null;

    final ErrorList errorList = new ErrorList();
    final JSONObject answer = new JSONObject();

    System.out.println(MessageFormat.format(labels.getString("NEW_QOS_RESULT"), getIP()));

    if (entity != null && !entity.isEmpty())
        // try parse the string to a JSON object
        try {
            request = new JSONObject(entity);

            final String lang = request.optString("client_language");

            // Load Language Files for Client

            final List<String> langs = Arrays
                    .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

            if (langs.contains(lang)) {
                errorList.setLanguage(lang);
                labels = ResourceManager.getSysMsgBundle(new Locale(lang));
            }

            //                System.out.println(request.toString(4));

            if (conn != null) {
                ResultOptions resultOptions = new ResultOptions(new Locale(lang));

                conn.setAutoCommit(false);

                final Test test = new Test(conn);

                if (request.optString("test_token").length() > 0) {

                    final String[] token = request.getString("test_token").split("_");

                    try {
                        // Check if UUID
                        final UUID testUuid = UUID.fromString(token[0]);

                        final String data = token[0] + "_" + token[1];

                        final String hmac = Helperfunctions.calculateHMAC(secret, data);
                        if (hmac.length() == 0)
                            errorList.addError("ERROR_TEST_TOKEN");

                        if (token[2].length() > 0 && hmac.equals(token[2])) {

                            final List<String> clientNames = Arrays
                                    .asList(settings.getString("RMBT_CLIENT_NAME").split(",\\s*"));
                            final List<String> clientVersions = Arrays
                                    .asList(settings.getString("RMBT_VERSION_NUMBER").split(",\\s*"));

                            if (test.getTestByUuid(testUuid) > 0)
                                if (clientNames.contains(request.optString("client_name"))
                                        && clientVersions.contains(request.optString("client_version"))) {
                                    //save qos test results:
                                    JSONArray qosResult = request.optJSONArray("qos_result");
                                    if (qosResult != null) {
                                        QoSTestResultDao resultDao = new QoSTestResultDao(conn);

                                        Set<String> excludeTestTypeKeys = new TreeSet<>();
                                        excludeTestTypeKeys.add("test_type");
                                        excludeTestTypeKeys.add("qos_test_uid");

                                        for (int i = 0; i < qosResult.length(); i++) {
                                            JSONObject testObject = qosResult.optJSONObject(i);
                                            //String hstore = Helperfunctions.json2hstore(testObject, excludeTestTypeKeys);
                                            JSONObject resultJson = new JSONObject(testObject,
                                                    JSONObject.getNames(testObject));
                                            for (String excludeKey : excludeTestTypeKeys) {
                                                resultJson.remove(excludeKey);
                                            }
                                            QoSTestResult testResult = new QoSTestResult();
                                            //testResult.setResults(hstore);
                                            testResult.setResults(resultJson.toString());
                                            testResult.setTestType(testObject.getString("test_type"));
                                            testResult.setTestUid(test.getUid());
                                            long qosTestId = testObject.optLong("qos_test_uid", Long.MIN_VALUE);
                                            testResult.setQoSTestObjectiveId(qosTestId);
                                            resultDao.save(testResult);
                                        }
                                    }

                                    QoSTestResultDao resultDao = new QoSTestResultDao(conn);
                                    PreparedStatement updateCounterPs = resultDao
                                            .getUpdateCounterPreparedStatement();
                                    List<QoSTestResult> testResultList = resultDao.getByTestUid(test.getUid());
                                    //map that contains all test types and their result descriptions determined by the test result <-> test objectives comparison
                                    Map<TestType, TreeSet<ResultDesc>> resultKeys = new HashMap<>();

                                    //test description set:
                                    Set<String> testDescSet = new TreeSet<>();
                                    //test summary set:
                                    Set<String> testSummarySet = new TreeSet<>();

                                    //iterate through all result entries
                                    for (QoSTestResult testResult : testResultList) {

                                        //reset test counters
                                        testResult.setFailureCounter(0);
                                        testResult.setSuccessCounter(0);

                                        //get the correct class of the result;
                                        TestType testType = TestType
                                                .valueOf(testResult.getTestType().toUpperCase());
                                        Class<? extends AbstractResult<?>> clazz = testType.getClazz();
                                        //parse hstore data
                                        final JSONObject resultJson = new JSONObject(testResult.getResults());
                                        AbstractResult<?> result = QoSUtil.HSTORE_PARSER.fromJSON(resultJson,
                                                clazz);
                                        result.setResultJson(resultJson);

                                        if (result != null) {
                                            //add each test description key to the testDescSet (to fetch it later from the db)
                                            if (testResult.getTestDescription() != null) {
                                                testDescSet.add(testResult.getTestDescription());
                                            }
                                            if (testResult.getTestSummary() != null) {
                                                testSummarySet.add(testResult.getTestSummary());
                                            }
                                            testResult.setResult(result);

                                        }
                                        //compare test results with expected results 
                                        QoSUtil.compareTestResults(testResult, result, resultKeys, testType,
                                                resultOptions);
                                        //resultList.put(testResult.toJson());

                                        //update all test results after the success and failure counters have been set
                                        resultDao.updateCounter(testResult, updateCounterPs);
                                        //System.out.println("UPDATING: " + testResult.toString());
                                    }
                                } else
                                    errorList.addError("ERROR_CLIENT_VERSION");
                        } else
                            errorList.addError("ERROR_TEST_TOKEN_MALFORMED");
                    } catch (final IllegalArgumentException e) {
                        e.printStackTrace();
                        errorList.addError("ERROR_TEST_TOKEN_MALFORMED");
                    } catch (HstoreParseException e) {
                        e.printStackTrace();
                        errorList.addError("ERROR_DB_CONNECTION");
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                        errorList.addError("ERROR_TEST_TOKEN_MALFORMED");
                    }

                } else
                    errorList.addError("ERROR_TEST_TOKEN_MISSING");

                conn.commit();
            } else
                errorList.addError("ERROR_DB_CONNECTION");

        } catch (final JSONException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            //System.out.println("Error parsing JSDON Data " + e.toString());
            e.printStackTrace();
        } catch (final SQLException e) {
            //System.out.println("Error while storing data " + e.toString());
            e.printStackTrace();
        }
    else
        errorList.addErrorString("Expected request is missing.");

    try {
        answer.putOpt("error", errorList.getList());
    } catch (final JSONException e) {
        System.out.println("Error saving ErrorList: " + e.toString());
    }

    return answer.toString();
}

From source file:io.s4.client.Handshake.java

private ClientConnection clientConnectCreate(byte[] v, ByteArrayIOChannel io, Socket sock, List<String> reason)
        throws IOException {

    try {//  w  ww .j a  v a  2s. c  o  m
        JSONObject cInfo = new JSONObject(new String(v));

        String s = cInfo.optString("uuid", "");
        if (s.isEmpty()) {
            logger.error("missing client identifier during handshake.");
            reason.add("missing UUID");
            return null;
        }

        UUID u = UUID.fromString(s);

        logger.info("connecting to client " + u);

        s = cInfo.optString("readMode", "Private");
        ClientReadMode rmode = ClientReadMode.fromString(s);
        if (rmode == null) {
            logger.error(u + ": unknown readMode " + s);
            reason.add("unknown readMode " + s);
            return null;

        }

        s = cInfo.optString("writeMode", "Enabled");
        ClientWriteMode wmode = ClientWriteMode.fromString(s);
        if (wmode == null) {
            logger.error(u + ": unknown writeMode " + s);
            reason.add("unknown writeMode " + s);
            return null;
        }

        logger.info(u + " read=" + rmode + " write=" + wmode);

        if (rmode == ClientReadMode.None && wmode == ClientWriteMode.Disabled) {
            // client cannot disable read AND write...
            logger.error("client neither reads nor writes.");
            reason.add("read and write disabled");

            return null;
        }

        ClientConnection conn = new ClientConnection(clientStub, sock, u, rmode, wmode);

        if (rmode == ClientReadMode.Select) {
            JSONArray incl = cInfo.optJSONArray("readInclude");
            JSONArray excl = cInfo.optJSONArray("readExclude");

            if (incl == null && excl == null) {
                logger.error(u + ": missing stream selection information");
                reason.add("missing readInclude and readExclude");
                return null;
            }

            if (incl != null) {
                List<String> streams = new ArrayList<String>(incl.length());
                for (int i = 0; i < incl.length(); ++i)
                    streams.add(incl.getString(i));

                conn.includeStreams(streams);
            }

            if (excl != null) {
                List<String> streams = new ArrayList<String>(excl.length());
                for (int i = 0; i < excl.length(); ++i)
                    streams.add(excl.getString(i));

                conn.excludeStreams(streams);
            }

        }

        return conn;

    } catch (JSONException e) {
        logger.error("malformed JSON from client during handshake", e);
        reason.add("malformed JSON");

    } catch (NumberFormatException e) {
        logger.error("received malformed UUID", e);
        reason.add("malformed UUID");

    } catch (IllegalArgumentException e) {
        logger.error("received malformed UUID", e);
        reason.add("malformed UUID");
    }

    return null;
}

From source file:gov.usgs.cida.ConsulRegistratorMojoUnitTest.java

@org.junit.Test
public void testBlankCustomServiceId() {
    String serviceName = "mySuperService";
    String[] customServiceIds = { null, "" };
    for (String customServiceId : customServiceIds) {
        String result = ConsulRegistratorMojo.makeServiceId(serviceName, customServiceId);
        assert (result).startsWith(serviceName);
        String UuidCandidate = result.substring(serviceName.length());
        try {/*from  www. java  2  s. co m*/
            UUID myUuid = UUID.fromString(UuidCandidate);
        } catch (IllegalArgumentException ex) {
            //candidate was not a uuid
            fail();
        }
    }
}

From source file:uk.ac.soton.itinnovation.sad.service.controllers.ReportsController.java

/**
 * Processes new measurement for a measurement set with UUID and measurement
 * value with MEASUREMENT.//  w ww  .j  ava2 s  .  c  om
 *
 * @param inputData measurement data as JSON.
 * @return standard service response.
 * @throws java.lang.InterruptedException
 */
@RequestMapping(method = RequestMethod.POST, value = "/measurement")
@ResponseBody
public JsonResponse processNewMeasurement(@RequestBody final String inputData) throws InterruptedException {

    logger.debug("Received measurement: " + inputData);

    try {

        JSONObject response = new JSONObject();
        if (emClient.isEmClientOK()) {
            if (emClient.isMetricModelSetup()) {

                JSONObject inputDataAsJSON = (JSONObject) JSONSerializer.toJSON(inputData);

                if (!inputDataAsJSON.containsKey("uuid")) {
                    return new JsonResponse("error",
                            Util.dealWithException("Missing field \'uuid\' in request data", logger));
                }

                if (!inputDataAsJSON.containsKey("measurement")) {
                    return new JsonResponse("error",
                            Util.dealWithException("Missing field \'measurement\' in request data", logger));
                }

                String uuid = inputDataAsJSON.getString("uuid");
                String measurement = inputDataAsJSON.getString("measurement");
                boolean result = emClient.pushSingleMeasurementForMeasurementSetUuid(UUID.fromString(uuid),
                        measurement);

                response.put("message", "Push success: " + result);

                return new JsonResponse("ok", response);
            } else {
                return new JsonResponse("error",
                        Util.dealWithException("Received measurement will NOT be reported to ECC as "
                                + "metric model is yet to be created (start discovery phase or join running experiment)",
                                logger));
            }
        } else {
            return new JsonResponse("error",
                    Util.dealWithException("Received measurement will NOT be reported to ECC as "
                            + "EM client was not created, ECC reporting might be disabled", logger));
        }

    } catch (Throwable ex) {
        return new JsonResponse("error",
                Util.dealWithException("Failed to execute runPlugin method", ex, logger));
    }
}

From source file:com.formkiq.core.service.SpringSecurityService.java

/**
 * Gets the System User./*from w  w w  . j av  a2 s.  c  om*/
 * @return {@link UserDetails}
 */
public UserDetails getSystemUser() {

    User user = new User();
    user.setUserid(UUID.fromString("a549c513-b5d0-4309-b5dc-c6fa970454c9"));
    return user;
}

From source file:com.tcloud.bee.key.server.restful.DummyController.java

@GET
@Path("/uuid_test/{msg}")
public Response uuid_test(@PathParam("msg") String msg) {
    //String currentPrincipalName = authentication.getName();
    //logger.info("[{}]msg:{}", currentPrincipalName, msg);
    logger.info("Get uuid:{}", msg);
    KeyToken keyToken = keyTokenStore.getToken(UUID.fromString(msg));

    return Response.ok("password:" + new String(keyToken.getPassword())).build();
}

From source file:occi.infrastructure.Storage.java

public Storage(float size, State state, Set<Link> links, Set<String> attributes)
        throws URISyntaxException, SchemaViolationException {
    super(links, attributes);
    this.size = size;
    this.state = state;
    storageList.put(UUID.fromString(this.getId().toString()), this);
    generateActionNames();/*from  w w  w  .ja  va  2  s . c o  m*/
    generateAttributeList();
}

From source file:gr.upatras.ece.nam.baker.BakerClientIT.java

@Test
public void testBakerClientInstallBunAndGetStatus() throws Exception {

    logger.info("Executing TEST = testBakerRSInstallServiceAndGetStatus");

    List<Object> providers = new ArrayList<Object>();
    providers.add(new org.codehaus.jackson.jaxrs.JacksonJsonProvider());
    String uuid = UUID.fromString("77777777-668b-4c75-99a9-39b24ed3d8be").toString();

    // first delete an existing installation if exists

    WebClient client = WebClient.create(endpointUrl + "/services/api/client/ibuns/" + uuid, providers);
    Response r = client.accept("application/json").type("application/json").delete();
    if (Response.Status.NOT_FOUND.getStatusCode() != r.getStatus()) {

        assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());
        logger.info("Bun is already installed! We uninstall it first!");
        int guard = 0;
        InstalledBun insbun = null;//w ww .  j a v a2 s.  c om
        do {

            // ask again about this task
            client = WebClient.create(endpointUrl + "/services/api/client/ibuns/" + uuid);
            r = client.accept("application/json").type("application/json").get();

            MappingJsonFactory factory = new MappingJsonFactory();
            JsonParser parser = factory.createJsonParser((InputStream) r.getEntity());
            insbun = parser.readValueAs(InstalledBun.class);

            logger.info(
                    "Waiting for UNINSTALLED for test bun UUID=" + uuid + " . Now is: " + insbun.getStatus());
            Thread.sleep(2000);
            guard++;

        } while ((insbun != null) && (insbun.getStatus() != InstalledBunStatus.UNINSTALLED)
                && (insbun.getStatus() != InstalledBunStatus.FAILED) && (guard <= 30));

        if (insbun.getStatus() != InstalledBunStatus.FAILED)
            assertEquals(InstalledBunStatus.UNINSTALLED, insbun.getStatus());

    }

    // now post a new installation
    client = WebClient.create(endpointUrl + "/services/api/client/ibuns/", providers);
    InstalledBun is = prepareInstalledService(uuid);
    r = client.accept("application/json").type("application/json").post(is);
    assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());

    int guard = 0;

    InstalledBun insbun = null;
    do {

        // ask again about this task
        client = WebClient.create(endpointUrl + "/services/api/client/ibuns/" + uuid);
        r = client.accept("application/json").type("application/json").get();

        MappingJsonFactory factory = new MappingJsonFactory();
        JsonParser parser = factory.createJsonParser((InputStream) r.getEntity());
        insbun = parser.readValueAs(InstalledBun.class);

        logger.info("Waiting for STARTED for test bun UUID=" + uuid + " . Now is: " + insbun.getStatus());
        Thread.sleep(1000);
        guard++;

    } while ((insbun != null) && (insbun.getStatus() != InstalledBunStatus.STARTED) && (guard <= 30));

    assertEquals(uuid, insbun.getUuid());
    assertEquals(InstalledBunStatus.STARTED, insbun.getStatus());
    assertEquals("IntegrTestLocal example service", insbun.getName());

}