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:net.sf.mpaxs.spi.computeHost.StartUp.java

/**
 *
 * @param cfg//from  w ww  .j a va  2s. c  om
 */
public StartUp(Configuration cfg) {
    Settings settings = new Settings(cfg);
    try {
        System.setProperty("java.rmi.server.codebase", settings.getCodebase().toString());
        Logger.getLogger(StartUp.class.getName()).log(Level.INFO, "RMI Codebase at {0}",
                settings.getCodebase().toString());
    } catch (MalformedURLException ex) {
        Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
    }
    File policyFile;
    policyFile = new File(new File(settings.getOption(ConfigurationKeys.KEY_COMPUTE_HOST_WORKING_DIR)),
            settings.getPolicyName());
    if (!policyFile.exists()) {
        System.out.println("Did not find security policy, will create default one!");
        policyFile.getParentFile().mkdirs();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                StartUp.class.getResourceAsStream("/net/sf/mpaxs/spi/computeHost/wideopen.policy")));
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(policyFile));
            String s = null;
            while ((s = br.readLine()) != null) {
                bw.write(s + "\n");
            }
            bw.flush();
            bw.close();
            br.close();
            Logger.getLogger(StartUp.class.getName()).log(Level.INFO,
                    "Using security policy at " + policyFile.getAbsolutePath());
        } catch (IOException ex) {
            Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        Logger.getLogger(StartUp.class.getName()).log(Level.INFO,
                "Found existing policy file at " + policyFile.getAbsolutePath());
    }
    System.setProperty("java.security.policy", policyFile.getAbsolutePath());

    System.setProperty("java.net.preferIPv4Stack", "true");

    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new SecurityManager());
    }

    Logger.getLogger(StartUp.class.getName()).log(Level.FINE, "Creating host");
    Host h = new Host();
    Logger.getLogger(StartUp.class.getName()).log(Level.FINE, "Configuring host");
    h.configure(cfg);
    Logger.getLogger(StartUp.class.getName()).log(Level.FINE,
            "Setting auth token " + settings.getOption(ConfigurationKeys.KEY_AUTH_TOKEN));
    String at = settings.getOption(ConfigurationKeys.KEY_AUTH_TOKEN);
    h.setAuthenticationToken(UUID.fromString(at));
    Logger.getLogger(StartUp.class.getName()).log(Level.INFO, "Starting host {0}", settings.getHostID());
    h.startComputeHost();
}

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

private PersistedResult getPersistedResultOrDie(final String applicationName, final String resourceName) {
    if (!Util.isValidApplicationName(applicationName)) {
        throw new IllegalArgumentException("Invalid application name: " + applicationName);
    }//from  w ww  . j av  a 2s.  c o  m

    final UUID jobId = UUID.fromString(FilenameUtils.getBaseName(resourceName));

    final PersistedResult persistedResult = resultStore.findByApplicationNameAndJobId(applicationName,
            getUserName(), jobId);

    if (persistedResult == null) {
        throw new WebApplicationException(Response.status(Status.NOT_FOUND).build());
    }

    return persistedResult;
}

From source file:ac.dynam.rundeck.plugin.resources.ovirt.oVirtSDKWrapper.java

public Action ticketVm(String vmid) {
    try {//from   www . ja  v a2 s.c o  m
        VM vm = this.api.getVMs().get(UUID.fromString(vmid));
        return vm.ticket(new Action());
    } catch (ClientProtocolException e) {
        this.message = "Protocol Exception: " + e.getMessage();
    } catch (ServerException e) {
        this.message = "Server Exception: " + e.getReason() + ": " + e.getDetail();
    } catch (IOException e) {
        this.message = "IOException Exception: " + e.getMessage();
    }
    return null;
}

From source file:se.vgregion.urlservice.controllers.AdminGuiController.java

private UUID findDeletedId(HttpServletRequest request) {
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        if (name.startsWith("delete-")) {
            return UUID.fromString(name.substring(7));
        }//  w w  w . java 2  s  .c om
    }

    return null;
}

From source file:com.edmunds.etm.common.api.AgentInstance.java

public static AgentInstance readDto(AgentInstanceDto dto) {
    if (dto == null) {
        return null;
    }/* w w w  .  j  a  va  2s .  c  o m*/

    UUID id = null;
    try {
        id = UUID.fromString(dto.getId());
    } catch (IllegalArgumentException e) {
        logger.error(String.format("Cannot parse UUID from dto: %s", dto), e);
        return null;
    }

    AgentInstance obj = null;
    try {
        obj = new AgentInstance(id, dto.getIpAddress(), dto.getVersion());
        obj.setActiveRuleSetDigest(dto.getActiveRuleSetDigest());
        obj.setLastDeploymentEvent(RuleSetDeploymentEvent.readDto(dto.getLastDeploymentEvent()));
        obj.setLastFailedDeploymentEvent(RuleSetDeploymentEvent.readDto(dto.getLastFailedDeploymentEvent()));
    } catch (IllegalArgumentException e) {
        logger.error("Invalid agent instance DTO", e);
    }

    return obj;
}

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

/**
 * /*from   w w w  . jav  a2s.  com*/
 * @param entity
 * @return
 */
@Post("json")
public String request(final String entity) {
    long startTime = System.currentTimeMillis();
    addAllowOrigin();

    JSONObject request = null;

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

    final String clientIpRaw = getIP();
    System.out.println(MessageFormat.format(labels.getString("NEW_SETTINGS_REQUEST"), clientIpRaw));

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

            String lang = request.optString("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));
            } else
                lang = settings.getString("RMBT_DEFAULT_LANGUAGE");

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

            if (conn != null) {

                final Client client = new Client(conn);
                int typeId = 0;

                if (request.optString("type").length() > 0) {
                    typeId = client.getTypeId(request.getString("type"));
                    if (client.hasError())
                        errorList.addError(client.getError());
                }

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

                final JSONArray settingsList = new JSONArray();
                final JSONObject jsonItem = new JSONObject();

                if (clientNames.contains(request.optString("name")) && typeId > 0) {

                    // String clientName = request.getString("name");
                    // String clientVersionCode =
                    // request.getString("version_name");
                    // String clientVersionName =
                    // request.optString("version_code", "");

                    UUID uuid = null;
                    long clientUid = 0;

                    final String uuidString = request.optString("uuid", "");
                    try {
                        if (!Strings.isNullOrEmpty(uuidString))
                            uuid = UUID.fromString(uuidString);
                    } catch (IllegalArgumentException e) // not a valid uuid
                    {
                    }

                    if (uuid != null && errorList.getLength() == 0) {
                        clientUid = client.getClientByUuid(uuid);
                        if (client.hasError())
                            errorList.addError(client.getError());
                    }

                    boolean tcAccepted = request.optInt("terms_and_conditions_accepted_version", 0) > 0; // accept any version for now
                    if (!tcAccepted) // allow old non-version parameter
                        tcAccepted = request.optBoolean("terms_and_conditions_accepted", false);
                    {
                        if (tcAccepted && (uuid == null || clientUid == 0)) {

                            final Timestamp tstamp = java.sql.Timestamp
                                    .valueOf(new Timestamp(System.currentTimeMillis()).toString());

                            final Calendar timeWithZone = Helperfunctions
                                    .getTimeWithTimeZone(Helperfunctions.getTimezoneId());

                            client.setTimeZone(timeWithZone);
                            client.setTime(tstamp);
                            client.setClient_type_id(typeId);
                            client.setTcAccepted(tcAccepted);

                            uuid = client.storeClient();

                            if (client.hasError())
                                errorList.addError(client.getError());
                            else
                                jsonItem.put("uuid", uuid.toString());
                        }

                        if (client.getUid() > 0) {
                            /* map server */

                            final Series<Parameter> ctxParams = getContext().getParameters();
                            final String host = ctxParams.getFirstValue("RMBT_MAP_HOST");
                            final String sslStr = ctxParams.getFirstValue("RMBT_MAP_SSL");
                            final String portStr = ctxParams.getFirstValue("RMBT_MAP_PORT");
                            if (host != null && sslStr != null && portStr != null) {
                                JSONObject mapServer = new JSONObject();
                                mapServer.put("host", host);
                                mapServer.put("port", Integer.parseInt(portStr));
                                mapServer.put("ssl", Boolean.parseBoolean(sslStr));
                                jsonItem.put("map_server", mapServer);
                            }

                            // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                            // HISTORY / FILTER

                            final JSONObject subItem = new JSONObject();

                            final JSONArray netList = new JSONArray();

                            try {

                                // deviceList:

                                subItem.put("devices", getSyncGroupDeviceList(errorList, client));

                                // network_type:

                                final PreparedStatement st = conn.prepareStatement("SELECT DISTINCT group_name"
                                        + " FROM test t" + " JOIN network_type nt ON t.network_type=nt.uid"
                                        + " WHERE t.deleted = false AND t.status = 'FINISHED' "
                                        + " AND (t.client_id IN (SELECT ? UNION SELECT uid FROM client WHERE sync_group_id = ? ))"
                                        + " AND group_name IS NOT NULL ORDER BY group_name;");

                                st.setLong(1, client.getUid());
                                st.setInt(2, client.getSync_group_id());

                                final ResultSet rs = st.executeQuery();

                                if (rs != null)
                                    while (rs.next())
                                        // netList.put(Helperfunctions.getNetworkTypeName(rs.getInt("network_type")));
                                        netList.put(rs.getString("group_name"));
                                else
                                    errorList.addError("ERROR_DB_GET_SETTING_HISTORY_NETWORKS_SQL");

                                rs.close();
                                st.close();

                                subItem.put("networks", netList);

                            } catch (final SQLException e) {
                                e.printStackTrace();
                                errorList.addError("ERROR_DB_GET_SETTING_HISTORY_SQL");
                                // errorList.addError("ERROR_DB_GET_CLIENT_SQL");
                            }

                            if (errorList.getLength() == 0)
                                jsonItem.put("history", subItem);

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

                    //also put there: basis-urls for all services
                    final JSONObject jsonItemURLs = new JSONObject();
                    jsonItemURLs.put("open_data_prefix", getSetting("url_open_data_prefix", lang));
                    jsonItemURLs.put("statistics", getSetting("url_statistics", lang));
                    jsonItemURLs.put("control_ipv4_only", getSetting("control_ipv4_only", lang));
                    jsonItemURLs.put("control_ipv6_only", getSetting("control_ipv6_only", lang));
                    jsonItemURLs.put("url_ipv4_check", getSetting("url_ipv4_check", lang));
                    jsonItemURLs.put("url_ipv6_check", getSetting("url_ipv6_check", lang));

                    jsonItem.put("urls", jsonItemURLs);

                    final JSONObject jsonControlServerVersion = new JSONObject();
                    jsonControlServerVersion.put("control_server_version", RevisionHelper.getVerboseRevision());
                    jsonItem.put("versions", jsonControlServerVersion);

                    try {
                        final Locale locale = new Locale(lang);
                        final QoSTestTypeDescDao testTypeDao = new QoSTestTypeDescDao(conn, locale);
                        final JSONArray testTypeDescArray = new JSONArray();
                        for (QoSTestTypeDesc desc : testTypeDao.getAll()) {
                            JSONObject json = new JSONObject();
                            json.put("test_type", desc.getTestType().name());
                            json.put("name", desc.getName());
                            testTypeDescArray.put(json);
                        }
                        jsonItem.put("qostesttype_desc", testTypeDescArray);
                    } catch (SQLException e) {
                        errorList.addError("ERROR_DB_CONNECTION");
                    }

                    settingsList.put(jsonItem);
                    answer.put("settings", settingsList);

                    //debug: print settings response (JSON)
                    //System.out.println(settingsList);

                } else
                    errorList.addError("ERROR_CLIENT_VERSION");

            } else
                errorList.addError("ERROR_DB_CONNECTION");

        } catch (final JSONException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            System.out.println("Error parsing JSDON Data " + e.toString());
        }
    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());
    }

    answerString = answer.toString();

    //        try
    //        {
    //            System.out.println(answer.toString(4));
    //        }
    //        catch (final JSONException e)
    //        {
    //            e.printStackTrace();
    //        }

    answerString = answer.toString();
    long elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println(MessageFormat.format(labels.getString("NEW_SETTINGS_REQUEST_SUCCESS"), clientIpRaw,
            Long.toString(elapsedTime)));

    return answerString;
}

From source file:io.hakbot.controller.resources.v1.BaseResourceTest.java

@Before
@SuppressWarnings("unchecked")
public void before() {
    PersistenceManager pm = PersistenceManagerFactory.createPersistenceManager();

    pm.currentTransaction().begin();/*from  ww  w .  j  a v a2s.  c om*/

    ApiKey apiKey = new ApiKey();
    apiKey.setKey(HEADER_API_KEY_VALUE);

    LdapUser adminUser = new LdapUser();
    adminUser.setDN("cn=admin,o=example,c=us");
    adminUser.setUsername("admin");

    LdapUser user = new LdapUser();
    user.setDN("cn=user,o=example,c=us");
    user.setUsername("user");

    pm.makePersistentAll(apiKey, adminUser, user);
    pm.currentTransaction().commit();
    pm.currentTransaction().begin();

    Team admins = new Team();
    admins.setName("Administrators");
    admins.setUuid(UUID.fromString("00000000-0000-0000-0000-000000000000"));
    admins.setHakmaster(true);
    admins.setLdapUsers(new ArrayList<LdapUser>() {
        {
            add(adminUser);
        }
    });

    Team users = new Team();
    users.setName("Users");
    users.setUuid(UUID.fromString("00000000-0000-0000-0000-000000000001"));
    users.setHakmaster(false);
    users.setLdapUsers(new ArrayList<LdapUser>() {
        {
            add(user);
        }
    });

    pm.makePersistentAll(admins, users);
    pm.currentTransaction().commit();
    pm.currentTransaction().begin();

    for (int i = 0; i < 10; i++) {
        Job job = new Job();
        job.setName("Job " + i);
        job.setUuid("00000000-0000-0000-0000-00000000000" + i);
        job.setCreated(new Date());
        job.setState(State.CREATED);
        job.setProvider(ShellProvider.class.getCanonicalName());
        job.setStartedByApiKeyId(apiKey.getId());
        pm.makePersistent(job);
    }
    pm.currentTransaction().commit();

    HEADER_AUTH_TOKEN_ADMIN = "Bearer " + createJsonWebToken(adminUser);
    HEADER_AUTH_TOKEN_USER = "Bearer " + createJsonWebToken(user);

    pm.close();
}

From source file:com.github.rnewson.couchdb.lucene.couchdb.Database.java

public UUID getUuid() throws IOException, JSONException {
    try {//from   w w w  . j  a  v  a  2 s  . c  o  m
        final CouchDocument local = getDocument("_local/lucene");
        return UUID.fromString(local.asJson().getString("uuid"));
    } catch (final HttpResponseException e) {
        switch (e.getStatusCode()) {
        case HttpStatus.SC_NOT_FOUND:
            return null;
        default:
            throw e;
        }
    }
}

From source file:com.hurence.logisland.processor.ModifyIdTest.java

@Test
public void testRandomUidStrategy() {
    final TestRunner testRunner = TestRunners.newTestRunner(new ModifyId());
    testRunner.setProperty(ModifyId.STRATEGY, ModifyId.RANDOM_UUID_STRATEGY.getValue());
    testRunner.setProperty(ModifyId.FIELDS_TO_USE, "string1");
    testRunner.assertValid();/*from   w w  w.  ja va2s.c o  m*/

    Record record1 = getRecord1();
    testRunner.enqueue(record1);
    testRunner.run();
    testRunner.assertAllInputRecordsProcessed();
    testRunner.assertOutputRecordsCount(1);
    MockRecord outputRecord = testRunner.getOutputRecords().get(0);

    String uid = UUID.randomUUID().toString();

    outputRecord.assertRecordSizeEquals(4);
    outputRecord.assertFieldEquals("string1", "value1");
    outputRecord.assertFieldEquals("string2", "value2");
    outputRecord.assertFieldEquals("long1", 1);
    outputRecord.assertFieldEquals("long2", 2);
    String recordId = outputRecord.getId();
    Assert.assertTrue("recordId should be an UUID", UUID.fromString(recordId) != null);
}

From source file:com.soft160.app.blobstore.HttpMessageHandler.java

private UUID parseUUID(String s) {
    try {//from  w w w .j a  va  2s .  c  om
        return UUID.fromString(s);
    } catch (Exception e) {
        LOGGER.warn("Parse UUID error " + s + ", " + e);
    }
    return null;
}