Search in sources :

Example 1 with ErrorMessage

use of org.talend.sdk.component.starter.server.model.ErrorMessage in project component-runtime by Talend.

the class ProjectResource method createOnGithub.

@POST
@Path("github")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Result createOnGithub(final GithubProject project) {
    // create an in-memory zip of the project
    final ByteArrayOutputStream zip = new ByteArrayOutputStream();
    generator.generate(toRequest(project.getModel()), zip);
    final GithubProject.Repository githubConfig = project.getRepository();
    final boolean useOrganization = githubConfig.isUseOrganization();
    final String organization = useOrganization ? githubConfig.getOrganization() : githubConfig.getUsername();
    // create the github project
    final Client client = ClientBuilder.newClient();
    try {
        client.target(starterConfiguration.githubBaseApi()).path(useOrganization ? starterConfiguration.githubOrgCreateProjectPath() : starterConfiguration.githubCreateProjectPath()).resolveTemplate("name", organization).request(APPLICATION_JSON_TYPE).header("Accept", "application/vnd.github.v3+json").header("Authorization", "Basic " + Base64.getEncoder().encodeToString((githubConfig.getUsername() + ':' + githubConfig.getPassword()).getBytes(StandardCharsets.UTF_8))).method(starterConfiguration.githubCreateProjectMethod(), entity(new CreateProjectRequest(project.getModel().getArtifact(), project.getModel().getDescription(), false), APPLICATION_JSON_TYPE), CreateProjectResponse.class);
    } finally {
        client.close();
    }
    // clone the project in a temp repo
    final File workDir = new File(starterConfiguration.workDir().replace("${java.io.tmpdir}", System.getProperty("java.io.tmpdir")), githubConfig.getRepository() + "_" + System.nanoTime());
    if (!workDir.mkdirs()) {
        throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorMessage("can't create a temporary folder")).type(APPLICATION_JSON_TYPE).build());
    }
    final UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(githubConfig.getUsername(), githubConfig.getPassword());
    try (final Git git = Git.cloneRepository().setBranch("master").setURI(String.format(starterConfiguration.githubRepository(), organization, githubConfig.getRepository())).setDirectory(workDir).setProgressMonitor(NullProgressMonitor.INSTANCE).setCredentialsProvider(credentialsProvider).call()) {
        {
            // copy the zip files into the project temporary folder
            try (final ZipInputStream file = new ZipInputStream(new ByteArrayInputStream(zip.toByteArray()))) {
                ZipEntry entry;
                while ((entry = file.getNextEntry()) != null) {
                    if (entry.isDirectory()) {
                        continue;
                    }
                    final InputStream in = new BufferedInputStream(file) {

                        @Override
                        public void close() throws IOException {
                            file.closeEntry();
                        }
                    };
                    // drop the root folder to import it directly into the repo
                    final String path = entry.getName().substring(ofNullable(project.getModel().getArtifact()).orElse("application").length() + 1);
                    final File out = new File(workDir, path);
                    out.getParentFile().mkdirs();
                    // see codenvy facet for more details
                    if (path.equals("README.adoc") || path.endsWith(".json")) {
                        try (final BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
                            final String content = reader.lines().collect(joining("\n"));
                            Files.write(out.toPath(), content.replace("@organization@", organization).replace("@repository@", githubConfig.getRepository()).getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE_NEW);
                        }
                    } else {
                        Files.copy(in, out.toPath(), StandardCopyOption.REPLACE_EXISTING);
                    }
                }
            }
        }
        // add a gitignore, we could use the template but the default doesn't match what we want
        // see https://github.com/github/gitignore/
        final File gitIgnore = new File(workDir, ".gitignore");
        if (!gitIgnore.exists()) {
            try (final Writer writer = new FileWriter(gitIgnore)) {
                switch(ofNullable(project.getModel().getBuildType()).orElse("Maven").toLowerCase(ENGLISH)) {
                    case "gradle":
                        writer.write(".gradle\n" + "/build/\n" + "\n" + "# Ignore Gradle GUI config\n" + "gradle-app.setting\n" + "\n" + "# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)\n" + "!gradle-wrapper.jar\n" + "\n" + "# Cache of project\n" + ".gradletasknamecache\n" + "\n" + "# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898\n" + "# gradle/wrapper/gradle-wrapper.properties\n");
                        break;
                    default:
                        // maven
                        writer.write("target/\n" + "pom.xml.tag\n" + "pom.xml.releaseBackup\n" + "pom.xml.versionsBackup\n" + "pom.xml.next\n" + "release.properties\n" + "dependency-reduced-pom.xml\n" + "buildNumber.properties\n" + ".mvn/timing.properties\n");
                }
            }
        }
        // commit them all and push
        git.add().addFilepattern(".").call();
        git.commit().setMessage("Importing Talend Component Project from the Starter application").setAuthor("Talend Component Kit Starter WebApp", "tacokit@talend.com").call();
        git.push().setProgressMonitor(NullProgressMonitor.INSTANCE).setCredentialsProvider(credentialsProvider).setTimeout((int) TimeUnit.MINUTES.toSeconds(5)).call();
    } catch (final GitAPIException | IOException e) {
        throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorMessage(e.getMessage())).type(APPLICATION_JSON_TYPE).build());
    } finally {
        try {
            FileUtils.delete(workDir, FileUtils.RECURSIVE);
        } catch (final IOException e) {
            log.warn(e.getMessage(), e);
        }
    }
    return new Result(true);
}
Also used : CreateProjectRequest(org.talend.sdk.component.starter.server.model.github.CreateProjectRequest) WebApplicationException(javax.ws.rs.WebApplicationException) ZipEntry(java.util.zip.ZipEntry) FileWriter(java.io.FileWriter) Result(org.talend.sdk.component.starter.server.model.Result) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) BufferedInputStream(java.io.BufferedInputStream) Client(javax.ws.rs.client.Client) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) InputStreamReader(java.io.InputStreamReader) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ZipInputStream(java.util.zip.ZipInputStream) Git(org.eclipse.jgit.api.Git) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader) GithubProject(org.talend.sdk.component.starter.server.model.GithubProject) ErrorMessage(org.talend.sdk.component.starter.server.model.ErrorMessage) File(java.io.File) Writer(java.io.Writer) FileWriter(java.io.FileWriter) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 2 with ErrorMessage

use of org.talend.sdk.component.starter.server.model.ErrorMessage 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

BufferedInputStream (java.io.BufferedInputStream)2 BufferedReader (java.io.BufferedReader)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 FileWriter (java.io.FileWriter)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 InputStreamReader (java.io.InputStreamReader)2 Writer (java.io.Writer)2 ZipEntry (java.util.zip.ZipEntry)2 ZipInputStream (java.util.zip.ZipInputStream)2 Consumes (javax.ws.rs.Consumes)2 POST (javax.ws.rs.POST)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 Client (javax.ws.rs.client.Client)2 Git (org.eclipse.jgit.api.Git)2 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)2