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:mayoapp.migrations.V0400_2024__move_order_items_to_own_table.java

@Override
public void migrate(Connection connection) throws Exception {
    connection.setAutoCommit(false);/*from  www . j  a v a  2s. c o m*/

    Statement queryStatement = connection.createStatement();
    ResultSet data = queryStatement.executeQuery("SELECT * from purchase_order");

    List<Order> orders = Lists.newArrayList();
    List<OrderItem> orderItems = Lists.newArrayList();

    ObjectMapper mapper = new ObjectMapper();

    while (data.next()) {
        Order order = new Order();
        order.setId((UUID) data.getObject("entity_id"));

        String orderDataString = data.getString("order_data");
        Map<String, Object> orderData = mapper.readValue(orderDataString,
                new TypeReference<Map<String, Object>>() {
                });

        List<Map<String, Object>> items = (List<Map<String, Object>>) orderData.get("items");

        for (Map<String, Object> item : items) {
            OrderItem orderItem = new OrderItem();

            orderItem.setId(UUID.randomUUID());
            orderItem.setOrderId(order.getId());

            if (item.containsKey("id") && String.class.isAssignableFrom(item.get("id").getClass())) {
                orderItem.setPurchasableId(UUID.fromString((String) item.get("id")));
            }
            orderItem.setType((String) item.get("type"));
            orderItem.setTitle((String) item.get("title"));
            orderItem.setQuantity(((Integer) item.get("quantity")).longValue());
            orderItem.setUnitPrice(BigDecimal.valueOf((Double) item.get("unitPrice")));
            orderItem.setItemTotal(BigDecimal.valueOf((Double) item.get("itemTotal")));
            if (item.containsKey("vatRate")) {
                orderItem.setVatRate(BigDecimal.valueOf((Double) item.get("vatRate")));
            }

            if (item.containsKey("addons")) {
                orderItem.addData("addons", convertAddonsToMap((List<Map<String, Object>>) item.get("addons")));
            }

            orderItems.add(orderItem);
        }

        orderData.remove("items");
        order.setOrderData(orderData);
        orders.add(order);
    }

    queryStatement.close();

    // 1. Update orders

    PreparedStatement updateOrders = connection
            .prepareStatement("UPDATE purchase_order SET order_data = CAST (? AS json) WHERE entity_id =?");

    for (Order order : orders) {
        updateOrders.setObject(1, mapper.writeValueAsString(order.getOrderData()));
        updateOrders.setObject(2, order.getId());
        updateOrders.addBatch();
    }

    updateOrders.executeBatch();

    // 2. Insert items

    PreparedStatement insertItems = connection.prepareStatement(
            "INSERT INTO purchase_order_item (id, order_id, purchasable_id, type, title, quantity, unit_price, "
                    + "item_total, vat_rate, data) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CAST (? as json))");

    for (OrderItem item : orderItems) {
        insertItems.setObject(1, item.getId());
        insertItems.setObject(2, item.getOrderId());
        insertItems.setObject(3, item.getPurchasableId());
        insertItems.setString(4, item.getType());
        insertItems.setString(5, item.getTitle());
        insertItems.setLong(6, item.getQuantity());
        insertItems.setBigDecimal(7, item.getUnitPrice());
        insertItems.setBigDecimal(8, item.getItemTotal());
        insertItems.setBigDecimal(9, item.getVatRate());
        insertItems.setString(10, mapper.writeValueAsString(item.getData()));
        insertItems.addBatch();
    }

    insertItems.executeBatch();
}

From source file:org.trustedanalytics.servicebroker.zk.plans.ZookeeperPlanShared.java

@Override
public Map<String, Object> bind(ServiceInstance serviceInstance) throws ServiceBrokerException {
    UUID instanceId = UUID.fromString(serviceInstance.getServiceInstanceId());
    return zookeeperSimpleBindingOperations.createCredentialsMap(instanceId);
}

From source file:org.trustedanalytics.metadata.datacatalog.DataCatalogClientTest.java

/**
 * This test should prevent anyone from carelessly breaking the service communication.
 * *///www .j av a2  s .c  o  m
@Test
public void metadataSerialization_requestProperlySerialized() throws IOException {
    // RestTemplate is using Jackson so we use it in the test
    ObjectMapper mapper = new ObjectMapper();

    Map<String, String> properSerilizedValues = new HashMap<String, String>() {
        {
            put("category", "test category");
            put("dataSample", "test sample");
            put("format", "test format");
            put("isPublic", "true");
            put("orgUUID", UUID.randomUUID().toString());
            put("recordCount", "13");
            put("size", "123");
            put("sourceUri", "test source uri");
            put("targetUri", "test target uri");
            put("title", "test title");
        }
    };

    Metadata meta = new Metadata();

    meta.setCategory(properSerilizedValues.get("category"));
    meta.setDataSample(properSerilizedValues.get("dataSample"));
    meta.setFormat(properSerilizedValues.get("format"));
    meta.setPublic(Boolean.valueOf(properSerilizedValues.get("isPublic")));
    meta.setOrgUUID(UUID.fromString(properSerilizedValues.get("orgUUID")));
    meta.setRecordCount(Integer.valueOf(properSerilizedValues.get("recordCount")));
    meta.setSize(Integer.valueOf(properSerilizedValues.get("size")));
    meta.setSourceUri(properSerilizedValues.get("sourceUri"));
    meta.setTargetUri(properSerilizedValues.get("targetUri"));
    meta.setTitle(properSerilizedValues.get("title"));

    String serializedMeta = mapper.writeValueAsString(meta);
    Map<String, String> deserializedMap = mapper.readValue(serializedMeta,
            new TypeReference<HashMap<String, String>>() {
            });

    Assert.assertEquals(properSerilizedValues, deserializedMap);
}

From source file:org.mayocat.shop.billing.store.jdbi.mapper.OrderMapper.java

@Override
public Order map(int index, ResultSet resultSet, StatementContext ctx) throws SQLException {
    Order order = new Order();
    fillOrderSummary(resultSet, order);//from  w w  w . j  ava2  s .  co  m

    ObjectMapper mapper = new ObjectMapper();
    //mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    try {
        List<Map<String, Object>> itemsData = mapper.readValue(resultSet.getString("items"),
                new TypeReference<List<Map<String, Object>>>() {
                });

        List<OrderItem> items = FluentIterable.from(itemsData)
                .transform(new Function<Map<String, Object>, OrderItem>() {
                    public OrderItem apply(Map<String, Object> map) {
                        OrderItem orderItem = new OrderItem();
                        orderItem.setId(UUID.fromString((String) map.get("id")));
                        orderItem.setOrderId(UUID.fromString((String) map.get("order_id")));
                        if (map.containsKey("purchasable_id") && map.get("purchasable_id") != null) {
                            // There might not be a purchasable id
                            orderItem.setPurchasableId(UUID.fromString((String) map.get("purchasable_id")));
                        }
                        orderItem.setType((String) map.get("type"));
                        orderItem.setTitle((String) map.get("title"));
                        orderItem.setMerchant((String) map.get("merchant"));
                        orderItem.setQuantity(((Integer) map.get("quantity")).longValue());
                        orderItem.setUnitPrice(BigDecimal.valueOf((Double) map.get("unit_price")));
                        orderItem.setItemTotal(BigDecimal.valueOf((Double) map.get("item_total")));
                        if (map.containsKey("vat_rate") && map.get("vat_rate") != null) {
                            // There might not be a VAT rate
                            orderItem.setVatRate(BigDecimal.valueOf((Double) map.get("vat_rate")));
                        }
                        if (map.containsKey("data") && map.get("data") != null) {
                            // There might not be data
                            orderItem.addData((Map<String, Object>) map.get("data"));
                        }
                        return orderItem;
                    }
                }).toList();
        order.setOrderItems(items);
    } catch (IOException e) {
        logger.error("Failed to deserialize order data", e);
    }

    try {
        resultSet.findColumn("email");
        Customer customer = new Customer();
        customer.setId(order.getCustomerId());
        customer.setSlug(resultSet.getString("customer_slug"));
        customer.setEmail(resultSet.getString("email"));
        customer.setFirstName(resultSet.getString("first_name"));
        customer.setLastName(resultSet.getString("last_name"));
        customer.setPhoneNumber(resultSet.getString("phone_number"));
        order.setCustomer(customer);
    } catch (SQLException e) {
        // Nevermind
    }

    try {
        if (resultSet.getObject("billing_address_id") != null) {
            resultSet.findColumn("billing_address_full_name");
            Address billing = new Address();
            billing.setId((UUID) resultSet.getObject("billing_address_id"));
            billing.setFullName(resultSet.getString("billing_address_full_name"));
            billing.setStreet(resultSet.getString("billing_address_street"));
            billing.setStreetComplement(resultSet.getString("billing_address_street_complement"));
            billing.setZip(resultSet.getString("billing_address_zip"));
            billing.setCity(resultSet.getString("billing_address_city"));
            billing.setCountry(resultSet.getString("billing_address_country"));
            billing.setNote(resultSet.getString("billing_address_note"));
            order.setBillingAddress(billing);
        }
    } catch (SQLException e) {
        // Nevermind
    }

    try {
        if (resultSet.getObject("delivery_address_id") != null) {
            resultSet.findColumn("delivery_address_full_name");
            Address delivery = new Address();
            delivery.setId((UUID) resultSet.getObject("delivery_address_id"));
            delivery.setFullName(resultSet.getString("delivery_address_full_name"));
            delivery.setStreet(resultSet.getString("delivery_address_street"));
            delivery.setStreetComplement(resultSet.getString("delivery_address_street_complement"));
            delivery.setZip(resultSet.getString("delivery_address_zip"));
            delivery.setCity(resultSet.getString("delivery_address_city"));
            delivery.setCountry(resultSet.getString("delivery_address_country"));
            delivery.setNote(resultSet.getString("delivery_address_note"));
            order.setDeliveryAddress(delivery);
        }
    } catch (SQLException e) {
        // Nevermind
    }

    return order;
}

From source file:io.acme.solution.query.handler.ProfileRegisteredEventHandler.java

@Override
public void handleMessage(final Map<String, Object> eventEntries) {

    if (eventEntries.containsKey(MEMKEY_AGGREGATE_ID)) {
        final UUID id = UUID.fromString(eventEntries.get(MEMKEY_AGGREGATE_ID).toString());
        final Long version = eventEntries.get(MEMKEY_VERSION) != null
                ? Double.valueOf(eventEntries.get(MEMKEY_VERSION).toString()).longValue()
                : null;//from w w  w.  j  a v  a 2 s.  c o  m
        final String username = eventEntries.get(MAPKEY_USERNAME) != null
                ? eventEntries.get(MAPKEY_USERNAME).toString()
                : null;
        final String email = eventEntries.get(MAPKEY_EMAIL) != null ? eventEntries.get(MAPKEY_EMAIL).toString()
                : null;
        final String hashedPassword = eventEntries.get(MAPKEY_HASHEDPASS) != null
                ? eventEntries.get(MAPKEY_HASHEDPASS).toString()
                : null;

        if (id != null && username != null && version != null && email != null && hashedPassword != null) {
            final QueryableProfile profile = new QueryableProfile(id, version, username, email);
            final ProfileCredentials credentials = new ProfileCredentials(id, hashedPassword);

            this.profileDao.save(profile);
            this.profileCredentialsDao.save(credentials);

            log.info("New profile registered");
        } else {
            log.trace("Profile discarded due to missing mandatory attributes in the event entries");
        }
    } else {
        log.trace("Profile discarded due to missing aggregateId in the event entries");
    }
}

From source file:com.drevelopment.couponcodes.canary.CanaryModTransformer.java

@Override
public String getPlayerName(String uuid) {
    return Canary.getServer().getOfflinePlayer(UUID.fromString(uuid)).getName();
}

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

/**
 * <code>GET /v1/profile/{name}</code>
 *
 * Looks up a profile based on its name or identifier.
 *
 * @param name a name or identifier.//from w  w  w .j  av a 2  s.  com
 * @return a response entity.
 */
@Nonnull
@RequestMapping(path = "/{name}", method = RequestMethod.GET)
public ResponseEntity<PlayerProfile> lookup(@Nonnull @PathVariable("name") String name) {
    final Profile profile;

    if (UUID_PATTERN.matcher(name).matches()) {
        UUID identifier = UUID.fromString(name);
        profile = this.profileService.get(identifier);
    } else {
        profile = this.profileService.find(name);
    }

    return new ResponseEntity<>(profile.toRestRepresentation(),
            (profile.isCached() ? HttpStatus.OK : HttpStatus.CREATED));
}

From source file:com.haulmont.restapi.controllers.FileDownloadController.java

@GetMapping("/{fileDescriptorId}")
public void downloadFile(@PathVariable String fileDescriptorId,
        @RequestParam(required = false) Boolean attachment, HttpServletResponse response) {
    UUID uuid;/*from w  w  w  .j a v a 2 s .  com*/
    try {
        uuid = UUID.fromString(fileDescriptorId);
    } catch (IllegalArgumentException e) {
        throw new RestAPIException("Invalid entity ID",
                String.format("Cannot convert %s into valid entity ID", fileDescriptorId),
                HttpStatus.BAD_REQUEST);
    }
    LoadContext<FileDescriptor> ctx = LoadContext.create(FileDescriptor.class).setId(uuid);
    FileDescriptor fd = dataService.load(ctx);
    if (fd == null) {
        throw new RestAPIException("File not found", "File not found. Id: " + fileDescriptorId,
                HttpStatus.NOT_FOUND);
    }

    try {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Type", getContentType(fd));
        response.setHeader("Content-Disposition", (BooleanUtils.isTrue(attachment) ? "attachment" : "inline")
                + "; filename=\"" + fd.getName() + "\"");

        downloadFromMiddlewareAndWriteResponse(fd, response);
    } catch (Exception e) {
        log.error("Error on downloading the file {}", fileDescriptorId, e);
        throw new RestAPIException("Error on downloading the file", "", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:com.blackducksoftware.integration.hub.util.HubUrlParser.java

public static UUID getUUIDFromURLString(final String identifier, final String url) throws MissingUUIDException {
    if (StringUtils.isBlank(identifier)) {
        throw new IllegalArgumentException("No identifier was provided.");
    }/* ww  w.  j  a  va 2 s. c  om*/
    if (url == null) {
        throw new IllegalArgumentException("No url String was provided to parse.");
    }
    UUID uuid = null;

    final String[] urlParts = url.split("/");

    for (int i = 0; i < urlParts.length; i++) {
        if (urlParts[i].equalsIgnoreCase(identifier)) {
            try {
                uuid = UUID.fromString(urlParts[i + 1]);
            } catch (final IllegalArgumentException e) {
            }
            break;
        }
    }

    if (uuid == null) {
        throw new MissingUUIDException("The String provided : " + url
                + ", does not contain any UUID's for the specified identifer : " + identifier);
    }

    return uuid;
}

From source file:fm.last.musicbrainz.data.dao.impl.ArtistDaoImplIT.java

@Test
public void getByExistingGidReturnsOneArtistThatHasNoRedirectedGids() {
    UUID gid = UUID.fromString("194fcd41-2831-4318-9825-66bacbcf2cfe");
    Artist artist = dao.getByGid(gid);// w ww  .j  a  v a 2s  .c  om
    assertThat(artist.getName(), is("Mono"));
}