kong.unirest.UnirestException Java Examples

The following examples show how to use kong.unirest.UnirestException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApiClient.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
public UUID createProject(String name, String version) throws UnirestException {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final HttpResponse<JsonNode> response = ui.put(baseUrl + "/api/v1/project")
            .header("Content-Type", "application/json")
            .header("X-API-Key", apiKey)
            .body(new JSONObject()
                    .put("name", name)
                    .put("version", version)
            )
            .asJson();
    if (response.getStatus() == 201) {
        return UUID.fromString(response.getBody().getObject().getString("uuid"));
    }
    System.out.println("Error creating project " + name + " status: " + response.getStatus());
    return null;
}
 
Example #2
Source File: OssIndexAnalysisTask.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
/**
 * Submits the payload to the Sonatype OSS Index service
 */
private List<ComponentReport> submit(final JSONObject payload) throws UnirestException {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final HttpResponse<JsonNode> jsonResponse = ui.post(API_BASE_URL)
            .header(HttpHeaders.ACCEPT, "application/json")
            .header(HttpHeaders.CONTENT_TYPE, "application/json")
            .header(HttpHeaders.USER_AGENT, ManagedHttpClientFactory.getUserAgent())
            .basicAuth(apiUsername, apiToken)
            .body(payload)
            .asJson();
    if (jsonResponse.getStatus() == 200) {
        final OssIndexParser parser = new OssIndexParser();
        return parser.parse(jsonResponse.getBody());
    } else {
        handleUnexpectedHttpResponse(LOGGER, API_BASE_URL, jsonResponse.getStatus(), jsonResponse.getStatusText());
    }
    return new ArrayList<>();
}
 
Example #3
Source File: NpmAuditAnalysisTask.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
/**
 * Submits the payload to the NPM service
 */
private List<Advisory> submit(final JSONObject payload) throws UnirestException {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final HttpResponse<JsonNode> jsonResponse = ui.post(API_BASE_URL)
            .header("user-agent", "npm/6.1.0 node/v10.5.0 linux x64")
            .header("npm-in-ci", "false")
            .header("npm-scope", "")
            .header("npm-session", generateRandomSession())
            .header("content-type", "application/json")
            .body(payload)
            .asJson();
    if (jsonResponse.getStatus() == 200) {
        final NpmAuditParser parser = new NpmAuditParser();
        return parser.parse(jsonResponse.getBody());
    } else {
        handleUnexpectedHttpResponse(LOGGER, API_BASE_URL, jsonResponse.getStatus(), jsonResponse.getStatusText());
    }
    return new ArrayList<>();
}
 
Example #4
Source File: NugetMetaAnalyzer.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
private boolean performVersionCheck(final MetaModel meta, final Component component) {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final String url = String.format(baseUrl + VERSION_QUERY_URL, component.getPurl().getName().toLowerCase());
    try {
        final HttpResponse<JsonNode> response = ui.get(url)
                .header("accept", "application/json")
                .asJson();
        if (response.getStatus() == 200) {
            if (response.getBody() != null && response.getBody().getObject() != null) {
                final JSONArray versions = response.getBody().getObject().getJSONArray("versions");
                final String latest = versions.getString(versions.length()-1); // get the last version in the array
                meta.setLatestVersion(latest);
            }
            return true;
        } else {
            handleUnexpectedHttpResponse(LOGGER, url, response.getStatus(), response.getStatusText(), component);
        }
    } catch (UnirestException e) {
        handleRequestException(LOGGER, e);
    }
    return false;
}
 
Example #5
Source File: GemMetaAnalyzer.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MetaModel analyze(final Component component) {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final MetaModel meta = new MetaModel(component);
    if (component.getPurl() != null) {
        final String url = String.format(baseUrl + API_URL, component.getPurl().getName());
        try {
            final HttpResponse<JsonNode> response = ui.get(url)
                    .header("accept", "application/json")
                    .asJson();
            if (response.getStatus() == 200) {
                if (response.getBody() != null && response.getBody().getObject() != null) {
                    final String latest = response.getBody().getObject().getString("version");
                    meta.setLatestVersion(latest);
                }
            } else {
                handleUnexpectedHttpResponse(LOGGER, url, response.getStatus(), response.getStatusText(), component);
            }
        } catch (UnirestException e) {
            handleRequestException(LOGGER, e);
        }
    }
    return meta;
}
 
Example #6
Source File: ClientAuthenticator.java    From minecraft-world-downloader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Make the authentication request to the Mojang session server. We need to do this as the one sent by the
 * real client will have had our 'fake' public key instead of the server's real one, and as such the server will
 * not accept the connection.
 * @param hash hash based on the server information.
 */
public void makeRequest(String hash) throws UnirestException {
    AuthDetails details = profiles.getAuthDetails();

    Map<String, String> body = new HashMap<>();
    body.put("accessToken", details.getAccessToken());
    body.put("selectedProfile", details.getUuid());
    body.put("serverId", hash);


    HttpResponse<String> str = Unirest.post(AUTH_URL)
        .header("Content-Type", "application/json")
        .body(new Gson().toJson(body))
        .asString();

    if (str.getStatus() != STATUS_SUCCESS) {
        throw new RuntimeException("Client not authenticated! " + str.getBody());
    } else {
        System.out.println("Successfully authenticated user with Mojang session server.");
    }
}
 
Example #7
Source File: PinataPinningService.java    From Mahuta with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getTracked() {
    log.debug("get pinned files on Pinata");

    try {
        log.trace("GET {}/data/pinList?status=pinned&pageLimit=1000", endpoint);
        HttpResponse<String> response = Unirest.get(endpoint + "/data/pinList?status=pinned&pageLimit=1000")
                .header(HEADER_API_KEY, apiKey)
                .header(HEADER_SECRET_API_KEY, secretApiKey)
                .asString()
                .ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
        log.trace("response: {}", response.getBody());

        PinataTrackedResponse result = mapper.readValue(response.getBody(), PinataTrackedResponse.class);
        
        log.debug("get pinned files on Pinata [count: {}]", result.getCount());
        return result.getRows()
                .stream()
                .map(r -> r.getHash())
                .collect(Collectors.toList());

    } catch (UnirestException | IOException ex) {
        log.error("Exception whilst requesting the tracked data", ex);
        throw new TechnicalException("Exception whilst requesting the tracked data", ex);
    }
}
 
Example #8
Source File: IPFSClusterPinningService.java    From Mahuta with Apache License 2.0 6 votes vote down vote up
public static IPFSClusterPinningService connect(String host, Integer port, String protocol) {
    ValidatorUtils.rejectIfEmpty("host", host);
    ValidatorUtils.rejectIfNegative("port", port);
    ValidatorUtils.rejectIfDifferentThan("protocol", protocol, "http", "https");

    try {
        log.trace("call GET {}://{}:{}/id", protocol, host, port);
        HttpResponse<String> response = Unirest.get(String.format(BASE_URI + "/id", protocol, host, port))
                .asString()
                .ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
        log.info("Connected to IPFS-Cluster [protocol: {}, host: {}, port: {}]: Info {}", protocol, host, port,
                response.getBody());

        return new IPFSClusterPinningService(host, port, protocol);

    } catch (UnirestException ex) {
        String msg = String.format("Error whilst connecting to IPFS-Cluster [host: %s, port: %s]", host, port);
        log.error(msg, ex);
        throw new ConnectionException(msg, ex);
    }
}
 
Example #9
Source File: IPFSClusterPinningService.java    From Mahuta with Apache License 2.0 6 votes vote down vote up
@Override
public void pin(String cid) {
    log.debug("pin CID {} on IPFS-cluster", cid);

    try {
        ValidatorUtils.rejectIfEmpty("cid", cid);
        
        log.trace("call POST {}://{}:{}/pins/{}", protocol, host, port, cid);
        
        Unirest.post(String.format(BASE_URI + "/pins/%s", protocol, host, port, cid))
            .asString()
            .ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
        
        log.debug("CID {} pinned on IPFS-cluster", cid);
        
    } catch (UnirestException ex) {
        String msg = String.format("Error whilst sending request to IPFS-Cluster [host: %s, port: %s]", host, port);
        log.error(msg, ex);
        throw new TechnicalException(msg, ex);
    }
}
 
Example #10
Source File: IPFSClusterPinningService.java    From Mahuta with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getTracked() {
    log.debug("get pinned files on IPFS-cluster");

    try {
        log.trace("GET {}://{}:{}/pins", protocol, host, port);
        HttpResponse<String> response = Unirest.get(String.format(BASE_URI + "/pins", protocol, host, port))
                .asString()
                .ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
        log.debug("response: {}", response);
        IPFSClusterTrackedResponse result = mapper.readValue(response.getBody(), IPFSClusterTrackedResponse.class);

        log.debug("get pinned files on IPFS-cluster");
        return result.getPins();

    } catch (UnirestException | IOException ex) {
        log.error("Exception converting HTTP response to JSON", ex);
        throw new TechnicalException("Exception converting HTTP response to JSON", ex);
    }
}
 
Example #11
Source File: IPFSClusterPinningService.java    From Mahuta with Apache License 2.0 6 votes vote down vote up
@Override
public void unpin(String cid) {
    log.debug("unpin CID {} on IPFS-cluster", cid);

    try {
        ValidatorUtils.rejectIfEmpty("cid", cid);

        log.trace("call DELETE {}://{}:{}/pins/{}", protocol, host, port, cid);
        
        Unirest.delete(String.format(BASE_URI + "/pins/%s", protocol, host, port, cid))
            .asString()
            .ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });

        log.debug("unpin {} pinned on IPFS-cluster", cid);
    } catch (UnirestException ex) {
        String msg = String.format("Error whilst sending request to IPFS-Cluster [host: %s, port: %s]", host, port);
        log.error(msg, ex);
        throw new TechnicalException(msg, ex);
    }
}
 
Example #12
Source File: PinataPinningService.java    From Mahuta with Apache License 2.0 5 votes vote down vote up
@Override
public void unpin(String cid) {
    log.debug("unpin CID {} on Pinata", cid);

    try {
        ValidatorUtils.rejectIfEmpty("cid", cid);
        
        PinataUnpinRequest request = new PinataUnpinRequest(cid);
        log.trace("call POST {}/pinning/removePinFromIPFS {}", endpoint, mapper.writeValueAsString(request));
        
        HttpResponse<String> response = Unirest.post(endpoint + "/pinning/removePinFromIPFS")
            .header(HEADER_CONTENT_TYPE, HEADER_CONTENT_TYPE_VAL)
            .header(HEADER_API_KEY, apiKey)
            .header(HEADER_SECRET_API_KEY, secretApiKey)
            .body(mapper.writeValueAsString(request))
            .asString()
            .ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
        log.trace("response: {}", response.getBody());
        
        log.debug("CID {} unpinned on Pinata", cid);
        
    } catch (UnirestException | JsonProcessingException ex) {
        String msg = String.format("Error whilst sending request to Pinata [endpoint: %s/pinning/removePinFromIPFS, cid: %s]", endpoint, cid);
        log.error(msg, ex);
        throw new TechnicalException(msg, ex);
    }
}
 
Example #13
Source File: RestCustomerDao.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
@Override
public Customer getCustomer(int id) throws WarehouseException {
    try {
        return toCustomer(getObject(CUSTOMERS_URL + "/" + id));
    } catch (UnirestException ex) {
        throw new WarehouseException(String.format("Problem while fetching customer (%s) from API", id), ex);
    }
}
 
Example #14
Source File: AbstractRestDao.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
protected Stream<JSONObject> getArray(String url) throws UnirestException {
    HttpResponse<JsonNode> res = Unirest.get(url)
        .asJson();
    if (!res.isSuccess()) {
        throw new UnirestException(res.getStatusText());
    }
    JSONArray array = res
        .getBody()
        .getArray();
    return stream(array.spliterator(), false)
        .map(JSONObject.class::cast);
}
 
Example #15
Source File: ServerAuthenticator.java    From minecraft-world-downloader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Verify the user that is connecting to us is actually the user who we just authenticated with Mojang, otherwise
 * we could be giving a malicious user access to our account on the server we are proxying. The user would
 * also have to supply a username matching ours so it should never be accidentally attempted.
 * @param hash hash based on the server information.
 */
public void makeRequest(String hash) throws UnirestException {
    HttpResponse<JsonNode> str = Unirest.get(AUTH_URL)
        .queryString("username", username)
        .queryString("serverId", hash)
        .asJson();

    if (str.getStatus() != 200) {
        System.out.println("WARNING: Connection attempt by using pretending to be you! Closing connection.");
        throw new RuntimeException("Server could not authenticate client! " + str.getBody());
    } else {
        System.out.println("User identity confirmed with Mojang.");
    }
}
 
Example #16
Source File: CloudPersistence.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
private void saveToCloud( final TestReport report, final byte[] data ) {
	final HttpResponse<String> uploadUrlResponse = getUploadUrl();
	if ( uploadUrlResponse.isSuccess() ) {
		final ReportUploadContainer metadata = ReportUploadContainer.builder() //
				.reportName( String.join( ", ", getTestClasses( report ) ) ) //
				.data( data ) //
				.uploadUrl( uploadUrlResponse.getBody() ) //
				.build();
		final boolean hasChanges = report.containsChanges();

		final int maxAttempts = RecheckProperties.getInstance().rehubReportUploadAttempts();
		for ( int remainingAttempts = maxAttempts - 1; remainingAttempts >= 0; remainingAttempts-- ) {
			try {
				uploadReport( metadata );
				break; // Successful, abort retry
			} catch ( final UnirestException e ) {
				if ( !hasChanges ) {
					log.warn(
							"Failed to upload report. Ignoring exception because the report does not have any differences.",
							e );
					break;
				}
				if ( remainingAttempts == 0 ) {
					log.error(
							"Failed to upload report. Aborting, because maximum retries have been reached. If this happens often, consider increasing the property '{}={}'.",
							RecheckProperties.REHUB_REPORT_UPLOAD_ATTEMPTS, maxAttempts, e );
					throw e;
				} else {
					log.warn( "Failed to upload report. Retrying another {} times.", remainingAttempts, e );
				}
			}
		}
	}
}
 
Example #17
Source File: PinataPinningService.java    From Mahuta with Apache License 2.0 5 votes vote down vote up
public static PinataPinningService connect(String endpoint, String apiKey, String secretApiKey, List<String> addresses) {
    ValidatorUtils.rejectIfEmpty("endpoint", endpoint);
    ValidatorUtils.rejectIfEmpty("apiKey", apiKey);
    ValidatorUtils.rejectIfEmpty("secretApiKey", secretApiKey);
    
    if(addresses != null)
        addresses.forEach(MultiAddress::new); // Validate multiAddress

    try {
        log.trace("call GET {}/data/testAuthentication", endpoint);
        HttpResponse<String> response = Unirest.get(endpoint + "/data/testAuthentication")
                .header(HEADER_API_KEY, apiKey)
                .header(HEADER_SECRET_API_KEY, secretApiKey)
                .asString()
                .ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
        log.info("Connected to Pinata [endpoint: {}, apiKey: {}, secretApiKey: {}, addresses: {}]: Info {}",
                endpoint, apiKey, obfuscateKey(secretApiKey), addresses,
                response.getBody());

        return new PinataPinningService(endpoint, apiKey, secretApiKey, addresses);

    } catch (UnirestException ex) {
        String msg = String.format("Error whilst connecting to Pinata  [endpoint: %s, apiKey: %s, secretApiKey: %s, addresses: %s]",
                endpoint, apiKey, obfuscateKey(secretApiKey), addresses);
        log.error(msg, ex);
        throw new ConnectionException(msg, ex);
    }
}
 
Example #18
Source File: PinataPinningService.java    From Mahuta with Apache License 2.0 5 votes vote down vote up
@Override
public void pin(String cid, String name, Map<String, Object> metadata) {
    log.debug("pin CID {} on Pinata [name: {}, metadata: {}]", cid, name, metadata);

    try {
        ValidatorUtils.rejectIfEmpty("cid", cid);
        
        // Transform metadata
        Map<String, String> keyvalues = Optional.ofNullable(metadata).orElseGet(() -> new HashMap<String, Object>())
                .entrySet()
                .stream()
                .limit(MAX_METADATA)
                .collect (Collectors.toMap(Entry::getKey, e->e.getValue().toString()));
        
        PinataPinRequest request = new PinataPinRequest(cid, addresses, 
                new PinataMetadata(name, keyvalues));
        log.trace("call POST {}/pinning/pinHashToIPFS {}", endpoint, mapper.writeValueAsString(request));
        
        HttpResponse<String> response = Unirest.post(endpoint + "/pinning/pinHashToIPFS")
            .header(HEADER_CONTENT_TYPE, HEADER_CONTENT_TYPE_VAL)
            .header(HEADER_API_KEY, apiKey)
            .header(HEADER_SECRET_API_KEY, secretApiKey)
            .body(mapper.writeValueAsString(request))
            .asString()
            .ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
        log.trace("response: {}", response.getBody());
        
        log.debug("CID {} pinned on Pinata", cid);
        
    } catch (UnirestException | JsonProcessingException ex) {
        String msg = String.format("Error whilst sending request to Pinata [endpoint: %s/pinning/pinHashToIPFS, cid: %s]", endpoint, cid);
        log.error(msg, ex);
        throw new TechnicalException(msg, ex);
    }
}
 
Example #19
Source File: Rest.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
private static Map<Integer, JSONObject> fetchCustomers() throws UnirestException {
    return stream(Unirest.get(EXTERNAL_CUSTOMERS_URL)
        .asJson()
        .getBody()
        .getArray()
        .spliterator(), false)
        .map(JSONObject.class::cast)
        .collect(Collectors.toUnmodifiableMap(o -> o.getInt("id"), o -> o));
}
 
Example #20
Source File: NpmMetaAnalyzer.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MetaModel analyze(final Component component) {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final MetaModel meta = new MetaModel(component);
    if (component.getPurl() != null) {

        final String packageName;
        if (component.getPurl().getNamespace() != null) {
            packageName = component.getPurl().getNamespace().replace("@", "%40") + "%2F" + component.getPurl().getName();
        } else {
            packageName = component.getPurl().getName();
        }

        final String url = String.format(baseUrl + API_URL, packageName);
        try {
            final HttpResponse<JsonNode> response = ui.get(url)
                    .header("accept", "application/json")
                    .asJson();
            if (response.getStatus() == 200) {
                if (response.getBody() != null && response.getBody().getObject() != null) {
                    final String latest = response.getBody().getObject().getString("latest");
                    meta.setLatestVersion(latest);
                }
            } else {
                handleUnexpectedHttpResponse(LOGGER, url, response.getStatus(), response.getStatusText(), component);
            }
        } catch (UnirestException e) {
            handleRequestException(LOGGER, e);
        }
    }
    return meta;
}
 
Example #21
Source File: OssIndexAnalysisTask.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * Analyzes a list of Components.
 * @param components a list of Components
 */
public void analyze(final List<Component> components) {
    final Pageable<Component> paginatedComponents = new Pageable<>(100, components);
    while (!paginatedComponents.isPaginationComplete()) {
        final List<String> coordinates = new ArrayList<>();
        final List<Component> paginatedList = paginatedComponents.getPaginatedList();
        for (final Component component: paginatedList) {
            if (!component.isInternal() && shouldAnalyze(component.getPurl())) {
                //coordinates.add(component.getPurl().canonicalize()); // todo: put this back when minimizePurl() is removed
                coordinates.add(minimizePurl(component.getPurl()));
            }
        }
        if (CollectionUtils.isEmpty(coordinates)) {
            return;
        }
        final JSONObject json = new JSONObject();
        json.put("coordinates", coordinates);
        try {
            final List<ComponentReport> report = submit(json);
            processResults(report, paginatedList);
        } catch (UnirestException e) {
            handleRequestException(LOGGER, e);
        }
        LOGGER.info("Analyzing " + coordinates.size() + " component(s)");
        doThrottleDelay();
        paginatedComponents.nextPage();
    }
}
 
Example #22
Source File: ApiClient.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
public boolean uploadBom(UUID uuid, File bom) throws IOException, UnirestException {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final HttpResponse<JsonNode> response = ui.put(baseUrl + "/api/v1/bom")
            .header("Content-Type", "application/json")
            .header("X-API-Key", apiKey)
            .body(new JSONObject()
                    .put("project", uuid.toString())
                    .put("bom", Base64.encode(FileUtils.readFileToByteArray(bom)))
            )
            .asJson();
    return (response.getStatus() == 200);
}
 
Example #23
Source File: ApiClient.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
public boolean uploadScan(UUID uuid, File scan) throws IOException, UnirestException {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final HttpResponse<JsonNode> response = ui.put(baseUrl + "/api/v1/scan")
            .header("Content-Type", "application/json")
            .header("X-API-Key", apiKey)
            .body(new JSONObject()
                    .put("project", uuid.toString())
                    .put("scan", Base64.encode(FileUtils.readFileToByteArray(scan)))
            )
            .asJson();
    return (response.getStatus() == 200);
}
 
Example #24
Source File: RestCustomerDao.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
@Override
public void deleteCustomer(int id) throws WarehouseException {
    try {
        deleteObject(CUSTOMERS_URL + "/" + id);
    } catch (UnirestException ex) {
        throw new WarehouseException(String.format("Problem while deleting customer (%s) via API", id), ex);
    }
}
 
Example #25
Source File: Tool.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    Map<Customer, JSONArray> allTodos = new HashMap<>();
    try {
        CustomerDao dao = new RestCustomerDao();
        Collection<Customer> customers = dao.getCustomers();
        for (Customer customer : customers) {
            JsonNode body = Unirest.get(EXTERNAL_TODOS_URL)
                .queryString("userId", customer.getId())
                .asJson()
                .getBody();
            JSONArray todos = body.getArray();
            allTodos.put(customer, todos);
        }
    } catch (WarehouseException | UnirestException ex) {
        System.err.printf("Problem during execution: %s%n", ex.getMessage());
    }

    allTodos.entrySet()
        .stream()
        .sorted((a, b) -> Integer.compare(b.getValue().length(), a.getValue().length()))
        .limit(3L)
        .collect(Collectors.toList())
        .forEach(e -> System.out.printf("%s - %s (%s)%n",
            e.getKey().getId(),
            e.getKey().getName(),
            e.getValue().length()));
}
 
Example #26
Source File: Tool.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    Map<Customer, JSONArray> allTodos = new HashMap<>();
    try {
        CustomerDao dao = new RestCustomerDao();
        Collection<Customer> customers = dao.getCustomers();
        for (Customer customer : customers) {
            JsonNode body = Unirest.get(EXTERNAL_TODOS_URL)
                .queryString("userId", customer.getId())
                .asJson()
                .getBody();
            JSONArray todos = body.getArray();
            allTodos.put(customer, todos);
        }
    } catch (WarehouseException | UnirestException ex) {
        System.err.printf("Problem during execution: %s%n", ex.getMessage());
    }

    allTodos.entrySet()
        .stream()
        .sorted((a, b) -> Integer.compare(b.getValue().length(), a.getValue().length()))
        .limit(3L)
        .collect(Collectors.toList())
        .forEach(e -> System.out.printf("%s - %s (%s)%n",
            e.getKey().getId(),
            e.getKey().getName(),
            e.getValue().length()));
}
 
Example #27
Source File: Rest.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
private static Map<Integer, JSONObject> fetchCustomers() throws UnirestException {
    return stream(Unirest.get(EXTERNAL_CUSTOMERS_URL)
        .asJson()
        .getBody()
        .getArray()
        .spliterator(), false)
        .map(JSONObject.class::cast)
        .collect(Collectors.toUnmodifiableMap(o -> o.getInt("id"), o -> o));
}
 
Example #28
Source File: RestProductDao.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
@Override
public Collection<Product> getProducts() throws WarehouseException {
    try {
        return getArray(PRODUCTS_URL)
            .map(JSONObject.class::cast)
            .map(RestProductDao::toProduct)
            .sorted(Comparator.comparing(Product::getId))
            .collect(toList());
    } catch (UnirestException ex) {
        throw new WarehouseException("Problem while fetching products from API.", ex);
    }
}
 
Example #29
Source File: RestProductDao.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
@Override
public Product getProduct(int id) throws WarehouseException {
    try {
        return toProduct(getObject(PRODUCTS_URL + "/" + id));
    } catch (UnirestException ex) {
        throw new WarehouseException(String.format("Problem while fetching product (%s) from API", id), ex);
    }
}
 
Example #30
Source File: RestProductDao.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
@Override
public void addProduct(Product product) throws WarehouseException {
    try {
        postObject(PRODUCTS_URL, Map.of(
            "name", product.getName(),
            "price", product.getPrice()
        ));
    } catch (UnirestException ex) {
        throw new WarehouseException(String.format(
            "Problem while creating product (%s, %s) from API", product.getName(), product.getPrice()), ex);
    }
}