Search in sources :

Example 1 with APPLICATION_JSON_TYPE

use of javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE in project linuxtools by eclipse.

the class AbstractRegistry method retrieveTagsFromRegistryV1.

/**
 * Retrieves the list of tags for a given repository, assuming that the
 * target registry is a registry v2 instance.
 *
 * @param client
 *            the client to use
 * @param repository
 *            the repository to look-up
 * @return the list of tags for the given repository
 * @throws CancellationException
 *             - if the computation was cancelled
 * @throws ExecutionException
 *             - if the computation threw an exception
 * @throws InterruptedException
 *             - if the current thread was interrupted while waiting
 */
private List<IRepositoryTag> retrieveTagsFromRegistryV1(final Client client, final String repository) throws InterruptedException, ExecutionException {
    final GenericType<Map<String, String>> REPOSITORY_TAGS_RESULT_LIST = new GenericType<Map<String, String>>() {
    };
    final WebTarget queryTagsResource = client.target(getHTTPServerAddress()).path(// $NON-NLS-1$
    "v1").path("repositories").path(repository).path(// $NON-NLS-1$ //$NON-NLS-2$
    "tags");
    return queryTagsResource.request(APPLICATION_JSON_TYPE).async().method(GET, REPOSITORY_TAGS_RESULT_LIST).get().entrySet().stream().map(e -> new RepositoryTag(e.getKey(), e.getValue())).collect(Collectors.toList());
}
Also used : GET(javax.ws.rs.HttpMethod.GET) ClientConfig(org.glassfish.jersey.client.ClientConfig) Client(javax.ws.rs.client.Client) TimeoutException(java.util.concurrent.TimeoutException) ArrayList(java.util.ArrayList) RepositoryTag(org.eclipse.linuxtools.internal.docker.core.RepositoryTag) ClientBuilder(javax.ws.rs.client.ClientBuilder) ImageSearchResultV1(org.eclipse.linuxtools.internal.docker.core.ImageSearchResultV1) Map(java.util.Map) Status(javax.ws.rs.core.Response.Status) ObjectMapperProvider(com.spotify.docker.client.ObjectMapperProvider) CancellationException(java.util.concurrent.CancellationException) NLS(org.eclipse.osgi.util.NLS) JacksonFeature(org.glassfish.jersey.jackson.JacksonFeature) Collectors(java.util.stream.Collectors) ImageSearchResultV2(org.eclipse.linuxtools.internal.docker.core.ImageSearchResultV2) BearerTokenResponse(org.eclipse.linuxtools.internal.docker.core.OAuth2Utils.BearerTokenResponse) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) GenericType(javax.ws.rs.core.GenericType) List(java.util.List) ImageSearchResult(com.spotify.docker.client.messages.ImageSearchResult) Response(javax.ws.rs.core.Response) DockerImageSearchResult(org.eclipse.linuxtools.internal.docker.core.DockerImageSearchResult) RepositoryTagV2(org.eclipse.linuxtools.internal.docker.core.RepositoryTagV2) APPLICATION_JSON_TYPE(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE) WebTarget(javax.ws.rs.client.WebTarget) OAuth2Utils(org.eclipse.linuxtools.internal.docker.core.OAuth2Utils) GenericType(javax.ws.rs.core.GenericType) RepositoryTag(org.eclipse.linuxtools.internal.docker.core.RepositoryTag) WebTarget(javax.ws.rs.client.WebTarget) Map(java.util.Map)

Example 2 with APPLICATION_JSON_TYPE

use of javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE in project linuxtools by eclipse.

the class AbstractRegistry method getImages.

@Override
public List<IDockerImageSearchResult> getImages(String term) throws DockerException {
    final Client client = ClientBuilder.newClient(DEFAULT_CONFIG);
    List<IDockerImageSearchResult> result = new ArrayList<>();
    WebTarget queryImagesResource;
    if (isVersion2()) {
        final GenericType<ImageSearchResultV2> IMAGE_SEARCH_RESULT_LIST = new GenericType<ImageSearchResultV2>() {
        };
        ImageSearchResultV2 cisr = null;
        queryImagesResource = client.target(getHTTPServerAddress()).path("v2").path(// $NON-NLS-1$ //$NON-NLS-2$
        "_catalog");
        try {
            cisr = queryImagesResource.request(APPLICATION_JSON_TYPE).async().method(GET, IMAGE_SEARCH_RESULT_LIST).get();
        } catch (InterruptedException | ExecutionException e) {
            throw new DockerException(e);
        }
        List<ImageSearchResult> tmp = cisr.getRepositories().stream().filter(e -> e.name().contains(term)).collect(Collectors.toList());
        result.addAll(tmp.stream().map(r -> new DockerImageSearchResult(r.description(), r.official(), r.automated(), r.name(), r.starCount())).collect(Collectors.toList()));
    } else {
        ImageSearchResultV1 pisr = null;
        final GenericType<ImageSearchResultV1> IMAGE_SEARCH_RESULT_LIST = new GenericType<ImageSearchResultV1>() {
        };
        int page = 0;
        try {
            while (pisr == null || pisr.getPage() < pisr.getTotalPages()) {
                page++;
                queryImagesResource = client.target(getHTTPServerAddress()).path("v1").path(// $NON-NLS-1$ //$NON-NLS-2$
                "search").queryParam("q", // $NON-NLS-1$
                term).queryParam("page", // $NON-NLS-1$
                page);
                pisr = queryImagesResource.request(APPLICATION_JSON_TYPE).async().method(GET, IMAGE_SEARCH_RESULT_LIST).get();
                List<ImageSearchResult> tmp = pisr.getResult();
                result.addAll(tmp.stream().map(r -> new DockerImageSearchResult(r.description(), r.official(), r.automated(), r.name(), r.starCount())).collect(Collectors.toList()));
            }
        } catch (InterruptedException | ExecutionException e) {
            throw new DockerException(e);
        }
    }
    return result;
}
Also used : GET(javax.ws.rs.HttpMethod.GET) ClientConfig(org.glassfish.jersey.client.ClientConfig) Client(javax.ws.rs.client.Client) TimeoutException(java.util.concurrent.TimeoutException) ArrayList(java.util.ArrayList) RepositoryTag(org.eclipse.linuxtools.internal.docker.core.RepositoryTag) ClientBuilder(javax.ws.rs.client.ClientBuilder) ImageSearchResultV1(org.eclipse.linuxtools.internal.docker.core.ImageSearchResultV1) Map(java.util.Map) Status(javax.ws.rs.core.Response.Status) ObjectMapperProvider(com.spotify.docker.client.ObjectMapperProvider) CancellationException(java.util.concurrent.CancellationException) NLS(org.eclipse.osgi.util.NLS) JacksonFeature(org.glassfish.jersey.jackson.JacksonFeature) Collectors(java.util.stream.Collectors) ImageSearchResultV2(org.eclipse.linuxtools.internal.docker.core.ImageSearchResultV2) BearerTokenResponse(org.eclipse.linuxtools.internal.docker.core.OAuth2Utils.BearerTokenResponse) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) GenericType(javax.ws.rs.core.GenericType) List(java.util.List) ImageSearchResult(com.spotify.docker.client.messages.ImageSearchResult) Response(javax.ws.rs.core.Response) DockerImageSearchResult(org.eclipse.linuxtools.internal.docker.core.DockerImageSearchResult) RepositoryTagV2(org.eclipse.linuxtools.internal.docker.core.RepositoryTagV2) APPLICATION_JSON_TYPE(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE) WebTarget(javax.ws.rs.client.WebTarget) OAuth2Utils(org.eclipse.linuxtools.internal.docker.core.OAuth2Utils) ImageSearchResultV2(org.eclipse.linuxtools.internal.docker.core.ImageSearchResultV2) GenericType(javax.ws.rs.core.GenericType) ImageSearchResultV1(org.eclipse.linuxtools.internal.docker.core.ImageSearchResultV1) ArrayList(java.util.ArrayList) ImageSearchResult(com.spotify.docker.client.messages.ImageSearchResult) DockerImageSearchResult(org.eclipse.linuxtools.internal.docker.core.DockerImageSearchResult) DockerImageSearchResult(org.eclipse.linuxtools.internal.docker.core.DockerImageSearchResult) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) ExecutionException(java.util.concurrent.ExecutionException)

Example 3 with APPLICATION_JSON_TYPE

use of javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE in project component-runtime by Talend.

the class Github method load.

public Collection<Contributor> load() {
    final String token = "Basic " + Base64.getEncoder().encodeToString((user + ':' + password).getBytes(StandardCharsets.UTF_8));
    final Client client = ClientBuilder.newClient().register(new JsonbJaxrsProvider<>());
    final WebTarget gravatarBase = client.target(Gravatars.GRAVATAR_BASE);
    final ForkJoinPool pool = new ForkJoinPool(Math.max(4, Runtime.getRuntime().availableProcessors() * 8));
    try {
        return pool.submit(() -> contributors(client, token, "https://api.github.com/repos/talend/component-runtime/contributors").parallel().collect(toMap(e -> normalizeLogin(e.login), identity(), (c1, c2) -> {
            c1.contributions += c2.contributions;
            return c1;
        })).values().stream().map(contributor -> {
            if (contributor.url == null) {
                try {
                    final Contributor gravatar = Gravatars.loadGravatar(gravatarBase, contributor.email);
                    return Contributor.builder().name(contributor.name).commits(contributor.contributions).description(gravatar.getDescription()).gravatar(gravatar.getGravatar()).build();
                } catch (final Exception e) {
                    log.warn(e.getMessage(), e);
                    return new Contributor(contributor.email, contributor.email, "", Gravatars.url(contributor.email), contributor.contributions);
                }
            }
            final GithubUser user = client.target(contributor.url).request(APPLICATION_JSON_TYPE).header("Authorization", token).get(GithubUser.class);
            return Contributor.builder().id(contributor.login).name(ofNullable(user.name).orElse(contributor.name)).description((user.bio == null ? "" : user.bio) + (user.blog != null && !user.blog.trim().isEmpty() && (user.bio == null || !user.bio.contains(user.blog)) ? "\n\nBlog: " + user.blog : "")).commits(contributor.contributions).gravatar(ofNullable(contributor.avatarUrl).orElseGet(() -> {
                final String gravatarId = contributor.gravatarId == null || contributor.gravatarId.isEmpty() ? contributor.email : contributor.gravatarId;
                try {
                    final Contributor gravatar = Gravatars.loadGravatar(gravatarBase, gravatarId);
                    return gravatar.getGravatar();
                } catch (final Exception e) {
                    log.warn(e.getMessage(), e);
                    return Gravatars.url(gravatarId);
                }
            })).build();
        }).filter(Objects::nonNull).sorted(comparing(Contributor::getCommits).reversed()).collect(toList())).get(15, MINUTES);
    } catch (final ExecutionException ee) {
        if (WebApplicationException.class.isInstance(ee.getCause())) {
            final Response response = WebApplicationException.class.cast(ee.getCause()).getResponse();
            if (response != null && response.getEntity() != null) {
                log.error(response.readEntity(String.class));
            }
        }
        throw new IllegalStateException(ee.getCause());
    } catch (final InterruptedException | TimeoutException e) {
        throw new IllegalStateException(e);
    } finally {
        client.close();
        pool.shutdownNow();
    }
}
Also used : Client(javax.ws.rs.client.Client) TimeoutException(java.util.concurrent.TimeoutException) MINUTES(java.util.concurrent.TimeUnit.MINUTES) ClientBuilder(javax.ws.rs.client.ClientBuilder) Collectors.toMap(java.util.stream.Collectors.toMap) Comparator.comparing(java.util.Comparator.comparing) ROOT(java.util.Locale.ROOT) JsonbJaxrsProvider(org.apache.johnzon.jaxrs.jsonb.jaxrs.JsonbJaxrsProvider) Optional.ofNullable(java.util.Optional.ofNullable) Collection(java.util.Collection) Server(org.talend.sdk.component.maven.Server) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) ExecutionException(java.util.concurrent.ExecutionException) GenericType(javax.ws.rs.core.GenericType) Collectors.toList(java.util.stream.Collectors.toList) Base64(java.util.Base64) JsonbProperty(javax.json.bind.annotation.JsonbProperty) Slf4j(lombok.extern.slf4j.Slf4j) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) ForkJoinPool(java.util.concurrent.ForkJoinPool) Function.identity(java.util.function.Function.identity) Data(lombok.Data) APPLICATION_JSON_TYPE(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE) WebApplicationException(javax.ws.rs.WebApplicationException) WebTarget(javax.ws.rs.client.WebTarget) MavenDecrypter(org.talend.sdk.component.maven.MavenDecrypter) AllArgsConstructor(lombok.AllArgsConstructor) WebApplicationException(javax.ws.rs.WebApplicationException) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) WebApplicationException(javax.ws.rs.WebApplicationException) Response(javax.ws.rs.core.Response) Objects(java.util.Objects) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) ExecutionException(java.util.concurrent.ExecutionException) ForkJoinPool(java.util.concurrent.ForkJoinPool) TimeoutException(java.util.concurrent.TimeoutException)

Example 4 with APPLICATION_JSON_TYPE

use of javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE in project component-runtime by Talend.

the class Gravatars method loadGravatar.

public static Contributor loadGravatar(final WebTarget target, final String input) {
    final String hash = gravatarHash(input);
    final String gravatarUrl = "https://www.gravatar.com/avatar/" + hash + "?s=140";
    final Response gravatar = target.path(hash + ".json").request(APPLICATION_JSON_TYPE).get();
    return ofNullable(gravatar).filter(r -> r.getStatus() == HttpURLConnection.HTTP_OK).map(r -> r.readEntity(Gravatar.class).getEntry()).map(e -> e[0]).map(e -> Contributor.builder().id(e.getId()).name(ofNullable(e.getName()).map(n -> ofNullable(n.getFormatted()).orElse(ofNullable(n.getGivenName()).orElse("") + ofNullable(n.getFamilyName()).orElse(""))).orElseGet(() -> ofNullable(e.getDisplayName()).orElse(ofNullable(e.getPreferredUsername()).orElse(input)))).description(ofNullable(e.getAboutMe()).orElse("")).gravatar(gravatarUrl).build()).orElse(Contributor.builder().name(input).id(input).description("").gravatar(gravatarUrl).build());
}
Also used : Response(javax.ws.rs.core.Response) HttpURLConnection(java.net.HttpURLConnection) Optional.ofNullable(java.util.Optional.ofNullable) MessageDigest(java.security.MessageDigest) Slf4j(lombok.extern.slf4j.Slf4j) Response(javax.ws.rs.core.Response) Builder(lombok.Builder) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Data(lombok.Data) APPLICATION_JSON_TYPE(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE) WebTarget(javax.ws.rs.client.WebTarget) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PRIVATE(lombok.AccessLevel.PRIVATE) NoArgsConstructor(lombok.NoArgsConstructor)

Example 5 with APPLICATION_JSON_TYPE

use of javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE in project component-runtime by Talend.

the class ProjectResource method createZip.

@POST
@Path("zip/form")
@Produces("application/zip")
public Response createZip(@FormParam("project") final String compressedModel, @Context final Providers providers) {
    final MessageBodyReader<ProjectModel> jsonReader = providers.getMessageBodyReader(ProjectModel.class, ProjectModel.class, NO_ANNOTATION, APPLICATION_JSON_TYPE);
    final ProjectModel model;
    try (final InputStream gzipInputStream = new ByteArrayInputStream(Base64.getUrlDecoder().decode(compressedModel))) {
        model = jsonReader.readFrom(ProjectModel.class, ProjectModel.class, NO_ANNOTATION, APPLICATION_JSON_TYPE, new MultivaluedHashMap<>(), gzipInputStream);
    } catch (final IOException e) {
        throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorMessage(e.getMessage())).type(APPLICATION_JSON_TYPE).build());
    }
    final String filename = ofNullable(model.getArtifact()).orElse("zip") + ".zip";
    return Response.ok().entity((StreamingOutput) out -> {
        generator.generate(toRequest(model), out);
        out.flush();
    }).header("Content-Disposition", "inline; filename=" + filename).build();
}
Also used : MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) BufferedInputStream(java.io.BufferedInputStream) Produces(javax.ws.rs.Produces) ErrorMessage(org.talend.sdk.component.starter.server.model.ErrorMessage) Path(javax.ws.rs.Path) GithubProject(org.talend.sdk.component.starter.server.model.GithubProject) Collections.singletonList(java.util.Collections.singletonList) MediaType(javax.ws.rs.core.MediaType) Collectors.toMap(java.util.stream.Collectors.toMap) ByteArrayInputStream(java.io.ByteArrayInputStream) Consumes(javax.ws.rs.Consumes) Locale(java.util.Locale) Map(java.util.Map) ENGLISH(java.util.Locale.ENGLISH) ZipEntry(java.util.zip.ZipEntry) ProjectGenerator(org.talend.sdk.component.starter.server.service.ProjectGenerator) Context(javax.ws.rs.core.Context) Providers(javax.ws.rs.ext.Providers) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Collections.emptyList(java.util.Collections.emptyList) StandardOpenOption(java.nio.file.StandardOpenOption) StreamingOutput(javax.ws.rs.core.StreamingOutput) NullProgressMonitor(org.eclipse.jgit.lib.NullProgressMonitor) Collectors.joining(java.util.stream.Collectors.joining) StandardCharsets(java.nio.charset.StandardCharsets) Base64(java.util.Base64) List(java.util.List) FileUtils(org.eclipse.jgit.util.FileUtils) Slf4j(lombok.extern.slf4j.Slf4j) Response(javax.ws.rs.core.Response) Writer(java.io.Writer) Annotation(java.lang.annotation.Annotation) PostConstruct(javax.annotation.PostConstruct) WebApplicationException(javax.ws.rs.WebApplicationException) ProjectModel(org.talend.sdk.component.starter.server.model.ProjectModel) ApplicationScoped(javax.enterprise.context.ApplicationScoped) CreateProjectRequest(org.talend.sdk.component.starter.server.model.github.CreateProjectRequest) ZipInputStream(java.util.zip.ZipInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) GET(javax.ws.rs.GET) Client(javax.ws.rs.client.Client) Entity.entity(javax.ws.rs.client.Entity.entity) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) ClientBuilder(javax.ws.rs.client.ClientBuilder) StarterConfiguration(org.talend.sdk.component.starter.server.configuration.StarterConfiguration) FactoryConfiguration(org.talend.sdk.component.starter.server.model.FactoryConfiguration) Collections.emptyMap(java.util.Collections.emptyMap) FormParam(javax.ws.rs.FormParam) POST(javax.ws.rs.POST) Files(java.nio.file.Files) Optional.ofNullable(java.util.Optional.ofNullable) FileWriter(java.io.FileWriter) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) File(java.io.File) CreateProjectResponse(org.talend.sdk.component.starter.server.model.github.CreateProjectResponse) TimeUnit(java.util.concurrent.TimeUnit) Result(org.talend.sdk.component.starter.server.model.Result) Collectors.toList(java.util.stream.Collectors.toList) TreeMap(java.util.TreeMap) APPLICATION_JSON_TYPE(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE) BufferedReader(java.io.BufferedReader) Git(org.eclipse.jgit.api.Git) Comparator(java.util.Comparator) ProjectRequest(org.talend.sdk.component.starter.server.service.domain.ProjectRequest) InputStream(java.io.InputStream) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) WebApplicationException(javax.ws.rs.WebApplicationException) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ProjectModel(org.talend.sdk.component.starter.server.model.ProjectModel) ErrorMessage(org.talend.sdk.component.starter.server.model.ErrorMessage) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Aggregations

APPLICATION_JSON_TYPE (javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE)9 List (java.util.List)7 Map (java.util.Map)7 WebTarget (javax.ws.rs.client.WebTarget)7 ArrayList (java.util.ArrayList)6 GenericType (javax.ws.rs.core.GenericType)6 File (java.io.File)5 StandardCharsets (java.nio.charset.StandardCharsets)5 Base64 (java.util.Base64)5 Optional.ofNullable (java.util.Optional.ofNullable)5 Response (javax.ws.rs.core.Response)5 Slf4j (lombok.extern.slf4j.Slf4j)5 IOException (java.io.IOException)4 InputStream (java.io.InputStream)4 Collection (java.util.Collection)4 Collections.singletonList (java.util.Collections.singletonList)4 Comparator (java.util.Comparator)4 Collectors.toList (java.util.stream.Collectors.toList)4 Collectors.toMap (java.util.stream.Collectors.toMap)4 Inject (javax.inject.Inject)4