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.haulmont.ext.core.app.restapi.CreateCallfromOktell.java

@RequestMapping(method = RequestMethod.GET, value = "/task/call")
public void getTaskStates(HttpServletResponse response, @RequestParam(value = "s") String sessionId,
        @RequestParam(value = "p") String phone) throws IOException, JSONException {
    Authentication authentication = Authentication.me(sessionId);
    if (authentication == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;//from   ww  w.  j  a v a  2  s .  co  m
    }
    try {

        Call call = new Call();

        call.setName("? :" + phone);

        LoadContext catctx = new LoadContext(Category.class);
        catctx.setQueryString("select t from sys$Category t where t.id = :uuid").addParameter("uuid",
                UUID.fromString("053ae7ee-d327-4a90-909a-f540e4357324"));
        DataService catService = Locator.lookup(DataService.NAME);
        Category cat = catService.load(catctx);
        call.setCategory(cat);

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String stringDate = formatter.format(TimeProvider.currentTimestamp());
        call.setCallDescription("?  ? : " + stringDate);

        Priority priority = findPriorityByOrder(3);
        call.setPriority(priority);
        call.setNumber(callGNS.getNextNumber(call));

        LoadContext procctx = new LoadContext(Proc.class);
        procctx.setQueryString("select p from wf$Proc p where p.name =:name").addParameter("name",
                " ");
        procctx.setView("edit");
        DataService procService = Locator.lookup(DataService.NAME);
        Proc proc = procService.load(procctx);
        call.setProc(proc);

        String roleInitiator = "oktell";
        String roleExecutor = "office_manager";

        String initiator = findUserByRole(roleInitiator).getLogin();
        String executor = findUserByRole(roleExecutor).getLogin();

        if (call.getRoles() == null) {
            call.setRoles(new ArrayList<CardRole>());
        }

        for (ProcRole procRole : proc.getRoles()) {
            if ((roleInitiator).equals(procRole.getCode()) && initiator != null) {
                updateCardRole(procRole, call, initiator);
            } else if ((roleExecutor).equals(procRole.getCode()) && executor != null)
                updateCardRole(procRole, call, executor);
        }

        Set<Entity> toCommit = new HashSet<Entity>();

        MetaClass metaClass = call.getMetaClass();
        for (MetaProperty metaProperty : metaClass.getProperties()) {
            Object value = call.getValue(metaProperty.getName());
            if (value instanceof List) {
                for (Object entity : ((List) value))
                    toCommit.add((Entity) entity);
            }
        }

        LoadContext extClt = new LoadContext(ExtClient.class);
        extClt.setQueryString("select c from ext$Client c where c.numberTel = :phone").addParameter("phone",
                phone);
        extClt.setView("_local");
        DataService dataServiceClt = Locator.lookup(DataService.NAME);
        ExtClient extClient = dataServiceClt.load(extClt);

        if (extClient != null) {
            call.setExtClient(extClient);
            call.setTelephoneNumber(extClient.getNumberTel());
            call.setCallDescription("?  ? : " + stringDate
                    + "  " + extClient.getName());
        }
        call.setTelephoneNumber(phone);

        //List<CardRole> roleList = call.getRoles().get(0).getProcRole().;

        toCommit.add(call);
        dataService.commit(new CommitContext(toCommit));

        wfService.startProcess(call);

        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter writer = new PrintWriter(response.getOutputStream());
        JSONObject responseJson = new JSONObject();
        responseJson.put("id", call.getId());
        writer.write(responseJson.toString());
        writer.close();

    } finally {
        authentication.forget();
    }
}

From source file:domain.Employee.java

private static String uuidToBase64(String str) {
    UUID uuid = UUID.fromString(str);
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return Base64.encodeBase64URLSafeString(bb.array());
}

From source file:com.torchmind.stockpile.server.controller.v1.ProfileController.java

/**
 * <code>DELETE /v1/profile/{name}</code>
 *
 * Purges a profile from the cache.//from w ww. j a v  a 2 s .  c om
 *
 * @param name a name or identifier.
 */
@ResponseStatus(HttpStatus.NO_CONTENT)
@RequestMapping(path = "/{name}", method = RequestMethod.DELETE)
public void purge(@Nonnull @PathVariable("name") String name) {
    if (UUID_PATTERN.matcher(name).matches()) {
        UUID identifier = UUID.fromString(name);
        this.profileService.purge(identifier);
        return;
    }

    this.profileService.purge(name);
}

From source file:com.kolich.havalo.components.RepositoryManagerComponent.java

private static final RepositoryManager createInitialAdminRepository(final ServletContext context) {
    RepositoryManager repoManager = null;
    try {/*from  w  ww  . j ava  2s  .  c  o  m*/
        repoManager = getRepositoryManager(context);
        final String adminUUID = getHavaloAdminUUID();
        if (adminUUID == null) {
            final String msg = "Config property '" + HAVALO_ADMIN_API_UUID_PROPERTY + "' not set. Cannot "
                    + "start until this property contains a valid UUID.";
            logger__.error(msg);
            throw new BootstrapException(msg);
        } else {
            try {
                UUID.fromString(adminUUID);
            } catch (Exception e) {
                logger__.error("Config property '" + HAVALO_ADMIN_API_UUID_PROPERTY + "' was set, but "
                        + "did not contain a valid UUID. Cannot " + "start until this property contains a well "
                        + "formed UUID.", e);
                throw new BootstrapException(e);
            }
        }
        // Verify a proper admin API accout secret is set.
        final String adminSecret = getHavaloAdminSecret();
        if (adminSecret == null) {
            final String msg = "Config property '" + HAVALO_ADMIN_API_SECRET_PROPERTY + "' not set. Cannot "
                    + "start until this property contains a valid secret.";
            logger__.error(msg);
            throw new BootstrapException(msg);
        }
        logger__.debug("Admin API account initialized (uuid=" + adminUUID + ", secret="
                + abbreviate(adminSecret, 8) + ")");
        // Create a new keypair for the default ADMIN level user.
        final KeyPair adminKeyPair = new KeyPair(new HavaloUUID(adminUUID), adminSecret,
                Arrays.asList(new UserRole[] { ADMIN }));
        // Actually attempt to create a new Repository for the Admin user.
        // This should work, if not, bail the whole app.
        repoManager.createRepository(adminKeyPair.getKey(), adminKeyPair);
        return repoManager;
    } catch (RepositoryCreationException e) {
        // Log in TRACE and continue silently.  This is a normal case,
        // when the admin repo has already been created on firstboot
        // but Havalo is being re-started.
        logger__.trace("Failed to create ADMIN user repository -- " + "repository already exists.", e);
    } catch (Exception e) {
        // Hm, something else went wrong on startup, need to log
        // and then bail.  The application cannot continue at this point.
        logger__.error("Failed to create ADMIN user repository -- " + "cannot continue, giving up.", e);
        throw new BootstrapException(e);
    }
    return repoManager;
}

From source file:eu.openanalytics.rsb.component.ResultsResource.java

@Path("/{jobId}")
@GET//from w ww. j  ava  2  s.  com
public Result getSingleResult(@PathParam("applicationName") final String applicationName,
        @PathParam("jobId") final String jobId, @Context final HttpHeaders httpHeaders,
        @Context final UriInfo uriInfo) throws URISyntaxException, IOException {

    validateApplicationName(applicationName);
    validateJobId(jobId);

    final PersistedResult persistedResult = resultStore.findByApplicationNameAndJobId(applicationName,
            getUserName(), UUID.fromString(jobId));
    if (persistedResult == null) {
        throw new NotFoundException();
    }

    return buildResult(applicationName, httpHeaders, uriInfo, persistedResult);
}

From source file:Main.java

private static byte[] encodeUrnUuid(String urn, int position, ByteBuffer bb) {
    String uuidString = urn.substring(position, urn.length());
    UUID uuid;//from  w  w  w .j a  v  a 2s.  c  om
    try {
        uuid = UUID.fromString(uuidString);
    } catch (IllegalArgumentException e) {
        //Log.w(TAG, "encodeUrnUuid invalid urn:uuid format - " + urn);
        return null;
    }
    // UUIDs are ordered as byte array, which means most significant first
    bb.order(ByteOrder.BIG_ENDIAN);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return byteBufferToArray(bb);
}

From source file:edu.purdue.cybercenter.dm.service.VocabularyService.java

private void fixVersion(Vocabulary vocabulary) {
    String version = vocabulary.getVersion();
    boolean isUsed = false;

    if (StringUtils.isBlank(version)) {
        isUsed = true;//w  ww  .  j  av  a  2s  .com
    } else {
        List<edu.purdue.cybercenter.dm.domain.Vocabulary> allVersions = findByUuid(
                UUID.fromString(vocabulary.getUuid()));
        for (edu.purdue.cybercenter.dm.domain.Vocabulary v : allVersions) {
            if (version.equals(v.getVersionNumber().toString())) {
                isUsed = true;
                break;
            }
        }
    }

    if (isUsed) {
        vocabulary.setVersion(UUID.randomUUID().toString());
    }
}

From source file:cf.spring.servicebroker.ServiceBrokerHandler.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!authenticator.authenticate(request, response)) {
        return;/*w  ww .j a  v a  2  s.  c o m*/
    }
    ApiVersionValidator.validateApiVersion(request);
    try {
        response.setContentType(Constants.JSON_CONTENT_TYPE);
        final Matcher matcher = URI_PATTERN.matcher(request.getRequestURI());
        if (!matcher.matches()) {
            throw new NotFoundException("Resource not found");
        }
        final String instanceId = matcher.group(1);
        final String bindingId = matcher.group(3);
        if ("put".equalsIgnoreCase(request.getMethod())) {
            if (bindingId == null) {
                final ProvisionBody provisionBody = mapper.readValue(request.getInputStream(),
                        ProvisionBody.class);
                final String serviceId = provisionBody.getServiceId();
                final BrokerServiceAccessor accessor = getServiceAccessor(serviceId);
                final ProvisionRequest provisionRequest = new ProvisionRequest(UUID.fromString(instanceId),
                        provisionBody.getPlanId(), provisionBody.getOrganizationGuid(),
                        provisionBody.getSpaceGuid());
                final ProvisionResponse provisionResponse = accessor.provision(provisionRequest);
                if (provisionResponse.isCreated()) {
                    response.setStatus(HttpServletResponse.SC_CREATED);
                }
                mapper.writeValue(response.getOutputStream(), provisionResponse);
            } else {
                final BindBody bindBody = mapper.readValue(request.getInputStream(), BindBody.class);
                final String serviceId = bindBody.getServiceId();
                final BrokerServiceAccessor accessor = getServiceAccessor(serviceId);

                final BindRequest bindRequest = new BindRequest(UUID.fromString(instanceId),
                        UUID.fromString(bindingId), bindBody.applicationGuid, bindBody.getPlanId());
                final BindResponse bindResponse = accessor.bind(bindRequest);
                if (bindResponse.isCreated()) {
                    response.setStatus(HttpServletResponse.SC_CREATED);
                }
                mapper.writeValue(response.getOutputStream(), bindResponse);
            }
        } else if ("delete".equalsIgnoreCase(request.getMethod())) {
            final String serviceId = request.getParameter(SERVICE_ID_PARAM);
            final String planId = request.getParameter(PLAN_ID_PARAM);
            final BrokerServiceAccessor accessor = getServiceAccessor(serviceId);
            try {
                if (bindingId == null) {
                    // Deprovision
                    final DeprovisionRequest deprovisionRequest = new DeprovisionRequest(
                            UUID.fromString(instanceId), planId);
                    accessor.deprovision(deprovisionRequest);
                } else {
                    // Unbind
                    final UnbindRequest unbindRequest = new UnbindRequest(UUID.fromString(bindingId),
                            UUID.fromString(instanceId), planId);
                    accessor.unbind(unbindRequest);
                }
            } catch (MissingResourceException e) {
                response.setStatus(HttpServletResponse.SC_GONE);
            }
            response.getWriter().write("{}");
        } else {
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    } catch (ConflictException e) {
        response.setStatus(HttpServletResponse.SC_CONFLICT);
        response.getWriter().write("{}");
    } catch (ServiceBrokerException e) {
        LOGGER.warn("An error occurred processing a service broker request", e);
        response.setStatus(e.getHttpResponseCode());
        mapper.writeValue(response.getOutputStream(), new ErrorBody(e.getMessage()));
    } catch (Throwable e) {
        LOGGER.error(e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        mapper.writeValue(response.getOutputStream(), new ErrorBody(e.getMessage()));
    }
}

From source file:at.alladin.rmbt.qos.QoSUtil.java

/**
 * //from   w w w  . j  a va 2  s  . co  m
 * @param settings
 * @param conn
 * @param answer
 * @param lang
 * @param errorList
 * @throws SQLException 
 * @throws JSONException 
 * @throws HstoreParseException 
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 */
public static void evaluate(final ResourceBundle settings, final Connection conn, final TestUuid uuid,
        final JSONObject answer, String lang, final ErrorList errorList) throws SQLException,
        HstoreParseException, JSONException, IllegalArgumentException, IllegalAccessException {
    // 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);
    } else {
        lang = settings.getString("RMBT_DEFAULT_LANGUAGE");
    }

    if (conn != null) {

        final Client client = new Client(conn);
        final Test test = new Test(conn);

        boolean necessaryDataAvailable = false;

        if (uuid != null && uuid.getType() != null && uuid.getUuid() != null) {
            switch (uuid.getType()) {
            case OPEN_TEST_UUID:
                if (test.getTestByOpenTestUuid(UUID.fromString(uuid.getUuid())) > 0
                        && client.getClientByUid(test.getField("client_id").intValue())) {
                    necessaryDataAvailable = true;
                }
                break;
            case TEST_UUID:
                if (test.getTestByUuid(UUID.fromString(uuid.getUuid())) > 0
                        && client.getClientByUid(test.getField("client_id").intValue())) {
                    necessaryDataAvailable = true;
                }
                break;
            }
        }

        final long timeStampFullEval = System.currentTimeMillis();

        if (necessaryDataAvailable) {

            final Locale locale = new Locale(lang);
            final ResultOptions resultOptions = new ResultOptions(locale);
            final JSONArray resultList = new JSONArray();

            QoSTestResultDao resultDao = new QoSTestResultDao(conn);
            List<QoSTestResult> testResultList = resultDao.getByTestUid(test.getUid());
            if (testResultList == null || testResultList.isEmpty()) {
                throw new UnsupportedOperationException("test " + test + " has no result list");
            }
            //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<>();

            //Staring timestamp for evaluation time measurement
            final long timeStampEval = System.currentTimeMillis();

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

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

                //get the correct class of the result;
                TestType testType = null;
                try {
                    testType = TestType.valueOf(testResult.getTestType().toUpperCase(Locale.US));
                } catch (IllegalArgumentException e) {
                    final String errorMessage = "WARNING: QoS TestType '"
                            + testResult.getTestType().toUpperCase(Locale.US)
                            + "' not supported by ControlServer. Test with UID: " + testResult.getUid()
                            + " skipped.";
                    System.out.println(errorMessage);
                    errorList.addErrorString(errorMessage);
                    testType = null;
                }

                if (testType == null) {
                    continue;
                }

                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
                compareTestResults(testResult, result, resultKeys, testType, resultOptions);

                //resultList.put(testResult.toJson());

                //save all test results after the success and failure counters have been set
                //resultDao.updateCounter(testResult);
            }

            //ending timestamp for evaluation time measurement
            final long timeStampEvalEnd = System.currentTimeMillis();

            //-------------------------------------------------------------
            //fetch all result strings from the db
            QoSTestDescDao descDao = new QoSTestDescDao(conn, locale);

            //FIRST: get all test descriptions
            Set<String> testDescToFetchSet = testDescSet;
            testDescToFetchSet.addAll(testSummarySet);

            Map<String, String> testDescMap = descDao.getAllByKeyToMap(testDescToFetchSet);

            for (QoSTestResult testResult : testResultList) {

                //and set the test results + put each one to the result list json array
                String preParsedDesc = testDescMap.get(testResult.getTestDescription());
                if (preParsedDesc != null) {
                    String description = String.valueOf(
                            TestScriptInterpreter.interprete(testDescMap.get(testResult.getTestDescription()),
                                    QoSUtil.HSTORE_PARSER, testResult.getResult(), true, resultOptions));
                    testResult.setTestDescription(description);
                }

                //do the same for the test summary:
                String preParsedSummary = testDescMap.get(testResult.getTestSummary());
                if (preParsedSummary != null) {
                    String description = String.valueOf(
                            TestScriptInterpreter.interprete(testDescMap.get(testResult.getTestSummary()),
                                    QoSUtil.HSTORE_PARSER, testResult.getResult(), true, resultOptions));
                    testResult.setTestSummary(description);
                }

                resultList.put(testResult.toJson(uuid.getType()));
            }

            //finally put results to json
            answer.put("testresultdetail", resultList);

            JSONArray resultDescArray = new JSONArray();

            //SECOND: fetch all test result descriptions 
            for (TestType testType : resultKeys.keySet()) {
                TreeSet<ResultDesc> descSet = resultKeys.get(testType);
                //fetch results to same object
                descDao.loadToTestDesc(descSet);

                //another tree set for duplicate entries:
                //TODO: there must be a better solution 
                //(the issue is: compareTo() method returns differnt values depending on the .value attribute (if it's set or not))
                TreeSet<ResultDesc> descSetNew = new TreeSet<>();
                //add fetched results to json

                for (ResultDesc desc : descSet) {
                    if (!descSetNew.contains(desc)) {
                        descSetNew.add(desc);
                    } else {
                        for (ResultDesc d : descSetNew) {
                            if (d.compareTo(desc) == 0) {
                                d.getTestResultUidList().addAll(desc.getTestResultUidList());
                            }
                        }
                    }
                }

                for (ResultDesc desc : descSetNew) {
                    if (desc.getValue() != null) {
                        resultDescArray.put(desc.toJson());
                    }
                }

            }
            //System.out.println(resultDescArray);
            //put result descriptions to json
            answer.put("testresultdetail_desc", resultDescArray);

            QoSTestTypeDescDao testTypeDao = new QoSTestTypeDescDao(conn, locale);
            JSONArray testTypeDescArray = new JSONArray();
            for (QoSTestTypeDesc desc : testTypeDao.getAll()) {
                final JSONObject testTypeDesc = desc.toJson();
                if (testTypeDesc != null) {
                    testTypeDescArray.put(testTypeDesc);
                }
            }

            //put result descriptions to json
            answer.put("testresultdetail_testdesc", testTypeDescArray);
            JSONObject evalTimes = new JSONObject();
            evalTimes.put("eval", (timeStampEvalEnd - timeStampEval));
            evalTimes.put("full", (System.currentTimeMillis() - timeStampFullEval));
            answer.put("eval_times", evalTimes);

            //System.out.println(answer);
        } else
            errorList.addError("ERROR_REQUEST_TEST_RESULT_DETAIL_NO_UUID");

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

From source file:com.spectralogic.ds3client.helpers.RequestMatchers.java

public static AllocateJobChunkSpectraS3Request hasChunkId(final UUID chunkId) {
    return argThat(new TypeSafeMatcher<AllocateJobChunkSpectraS3Request>() {
        @Override//  ww  w.  j  a  v  a2 s .  c o  m
        public void describeTo(final Description description) {
            describeRequest(chunkId, description);
        }

        @Override
        protected boolean matchesSafely(final AllocateJobChunkSpectraS3Request item) {
            return chunkId.equals(UUID.fromString(item.getJobChunkId()));
        }

        @Override
        protected void describeMismatchSafely(final AllocateJobChunkSpectraS3Request item,
                final Description mismatchDescription) {
            describeRequest(UUID.fromString(item.getJobChunkId()), mismatchDescription);
        }

        private void describeRequest(final UUID chunkIdValue, final Description description) {
            description.appendText("AllocateJobChunkResponse with chunk id: ").appendValue(chunkIdValue);
        }
    });
}