Skip to content

Commit

Permalink
Integration front end code (#142)
Browse files Browse the repository at this point in the history
* Integration code with front end, #130.

* Apply OAuth2 token for push to github.

Signed-off-by: Pan Li <[email protected]>
  • Loading branch information
Incarnation-p-lee authored Sep 11, 2018
1 parent d477e63 commit fd74b66
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 38 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package com.microsoft.azure.springcloudplayground.controller;

import com.microsoft.azure.springcloudplayground.exception.GithubProcessException;
import com.microsoft.azure.springcloudplayground.generator.MicroService;
import com.microsoft.azure.springcloudplayground.generator.ProjectGenerator;
import com.microsoft.azure.springcloudplayground.generator.ProjectRequest;
import com.microsoft.azure.springcloudplayground.github.GithubOperator;
import com.microsoft.azure.springcloudplayground.metadata.GeneratorMetadataProvider;
import com.microsoft.azure.springcloudplayground.util.PropertyLoader;
import com.microsoft.azure.springcloudplayground.util.TelemetryProxy;
Expand All @@ -11,6 +13,7 @@
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.ZipFileSet;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.NonNull;
import org.springframework.security.core.Authentication;
Expand Down Expand Up @@ -117,9 +120,19 @@ private void triggerLoginEvent(@NonNull String accountType) {
this.telemetryProxy.trackEvent(TELEMETRY_EVENT_LOGIN, properties);
}

private boolean isValidOAuth2Token(OAuth2AuthenticationToken token) {
if (token == null) {
return false;
} else if (StringUtils.isEmpty(token.getName())) {
return false;
} else {
return true;
}
}

@RequestMapping(path = "/", produces = "text/html")
public String home(Map<String, Object> model, OAuth2AuthenticationToken token) {
if (token != null && !StringUtils.isEmpty(token.getName())) {
if (isValidOAuth2Token(token)) {
model.put("loggedInUser", token.getPrincipal().getAttributes().get("login"));
}

Expand All @@ -130,11 +143,24 @@ public String home(Map<String, Object> model, OAuth2AuthenticationToken token) {
return "home";
}


@PostMapping("/push-to-github")
public String pushToGithub(@RequestBody @Nonnull ProjectRequest request) {
public ResponseEntity pushToGithub(@RequestBody @Nonnull ProjectRequest request, OAuth2AuthenticationToken token) {
log.info("Project request received: " + request);
return "push to github not implemented";

if (isValidOAuth2Token(token)) {
String username = token.getPrincipal().getAttributes().get("login").toString();
GithubOperator operator = new GithubOperator(username, getAccessToken().getTokenValue());
File dir = this.projectGenerator.generate(request);

try {
operator.createRepository(dir, request.getRepoName());
return new ResponseEntity(HttpStatus.CREATED);
} catch (GithubProcessException e) {
return new ResponseEntity(HttpStatus.NOT_ACCEPTABLE);
}
}

return new ResponseEntity(HttpStatus.UNAUTHORIZED);
}

@ResponseBody
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.microsoft.azure.springcloudplayground.exception;

public class GithubFileException extends RuntimeException {

public GithubFileException(String message, Throwable cause) {
super(message, cause);
}

public GithubFileException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.microsoft.azure.springcloudplayground.exception;


public class GithubProcessException extends RuntimeException {
public class GithubProcessException extends Exception {

public GithubProcessException(String message, Throwable cause) {
super(message, cause);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microsoft.azure.springcloudplayground.exception.GithubFileException;
import com.microsoft.azure.springcloudplayground.exception.GithubProcessException;
import com.microsoft.azure.springcloudplayground.github.gitdata.GitDataRequestBlob;
import com.microsoft.azure.springcloudplayground.github.gitdata.GitDataRequestCommit;
Expand Down Expand Up @@ -46,7 +47,7 @@ protected GithubApiWrapper(@NonNull String username, @NonNull String token) {
this.token = token;
}

private HttpResponse executeRequest(@NonNull HttpUriRequest request) {
private HttpResponse executeRequest(@NonNull HttpUriRequest request) throws GithubProcessException {
try {
request.setHeader(ACCEPT_HEADER, ACCEPT_VALUE);
HttpClient client = HttpClientBuilder.create().build();
Expand All @@ -61,22 +62,22 @@ private void appendAuthorizationHeader(@NonNull HttpUriRequest request) {
request.setHeader(AUTH_HEADER, String.format("token %s", this.token));
}

protected HttpResponse createRepository(@NonNull GithubRepository repository) {
protected HttpResponse createRepository(@NonNull GithubRepository repository) throws GithubProcessException {
HttpPost request = new HttpPost(CREATE_REPOSITORY_URL);

try {
StringEntity body = new StringEntity(MAPPER.writeValueAsString(repository), ContentType.APPLICATION_JSON);
request.setEntity(body);
} catch (JsonProcessingException e) {
throw new GithubProcessException("Failed to process GithubRepository to Json", e);
throw new GithubFileException("Failed to process GithubRepository to Json", e);
}

appendAuthorizationHeader(request);

return executeRequest(request);
}

protected HttpResponse deleteRepository(@NonNull String repositoryName) {
protected HttpResponse deleteRepository(@NonNull String repositoryName) throws GithubProcessException {
String url = "https://api.github.com/repos/%s/%s";
HttpDelete request = new HttpDelete(String.format(url, username, repositoryName));

Expand All @@ -85,28 +86,31 @@ protected HttpResponse deleteRepository(@NonNull String repositoryName) {
return executeRequest(request);
}

protected HttpResponse getAllCommits(@NonNull String repositoryName) {
protected HttpResponse getAllCommits(@NonNull String repositoryName) throws GithubProcessException {
String url = "https://api.github.com/repos/%s/%s/commits";
HttpGet request = new HttpGet(String.format(url, username, repositoryName));

return executeRequest(request);
}

protected HttpResponse getGitDataCommit(@NonNull String repositoryName, @NonNull String commitSha) {
protected HttpResponse getGitDataCommit(@NonNull String repositoryName, @NonNull String commitSha)
throws GithubProcessException {
String url = "https://api.github.com/repos/%s/%s/git/commits/%s";
HttpGet request = new HttpGet(String.format(url, username, repositoryName, commitSha));

return executeRequest(request);
}

protected HttpResponse getGitDataTree(@NonNull String repositoryName, @NonNull String treeSha) {
protected HttpResponse getGitDataTree(@NonNull String repositoryName, @NonNull String treeSha)
throws GithubProcessException {
String url = "https://api.github.com/repos/%s/%s/git/trees/%s";
HttpGet request = new HttpGet(String.format(url, username, repositoryName, treeSha));

return executeRequest(request);
}

protected HttpResponse createGitDataTree(@NonNull String repositoryName, @NonNull GitDataRequestTree tree) {
protected HttpResponse createGitDataTree(@NonNull String repositoryName, @NonNull GitDataRequestTree tree)
throws GithubProcessException {
String url = "https://api.github.com/repos/%s/%s/git/trees";
HttpPost request = new HttpPost(String.format(url, username, repositoryName));

Expand All @@ -122,7 +126,8 @@ protected HttpResponse createGitDataTree(@NonNull String repositoryName, @NonNul
return executeRequest(request);
}

protected HttpResponse createGitDataBlob(@NonNull String repositoryName, @NonNull GitDataRequestBlob blob) {
protected HttpResponse createGitDataBlob(@NonNull String repositoryName, @NonNull GitDataRequestBlob blob)
throws GithubProcessException {
String url = "https://api.github.com/repos/%s/%s/git/blobs";
HttpPost request = new HttpPost(String.format(url, username, repositoryName));

Expand All @@ -138,7 +143,8 @@ protected HttpResponse createGitDataBlob(@NonNull String repositoryName, @NonNul
return executeRequest(request);
}

protected HttpResponse createGitDataCommit(@NonNull String repositoryName, @NonNull GitDataRequestCommit commit) {
protected HttpResponse createGitDataCommit(@NonNull String repositoryName, @NonNull GitDataRequestCommit commit)
throws GithubProcessException {
String url = "https://api.github.com/repos/%s/%s/git/commits";
HttpPost request = new HttpPost(String.format(url, username, repositoryName));

Expand All @@ -155,7 +161,8 @@ protected HttpResponse createGitDataCommit(@NonNull String repositoryName, @NonN
}

protected HttpResponse updateGitDataReference(@NonNull String repositoryName,
@NonNull GitDataRequestReference reference) {
@NonNull GitDataRequestReference reference)
throws GithubProcessException {
String url = "https://api.github.com/repos/%s/%s/git/refs/heads/master";
HttpPatch request = new HttpPatch(String.format(url, username, repositoryName));

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.microsoft.azure.springcloudplayground.github;

import com.google.common.io.Files;
import com.microsoft.azure.springcloudplayground.exception.GithubFileException;
import com.microsoft.azure.springcloudplayground.exception.GithubProcessException;
import com.microsoft.azure.springcloudplayground.github.gitdata.*;
import com.microsoft.azure.springcloudplayground.github.metadata.Author;
Expand All @@ -22,7 +23,7 @@ public GithubOperator(@NonNull String username, @NonNull String token) {
super(username, token);
}

private String getContent(@NonNull HttpResponse response) {
private String getContent(@NonNull HttpResponse response) throws GithubProcessException {
try {
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
Expand All @@ -38,15 +39,15 @@ private String getContent(@NonNull HttpResponse response) {
}
}

private <T> T readValue(@NonNull String json, Class<T> clazz) {
private <T> T readValue(@NonNull String json, Class<T> clazz) throws GithubProcessException {
try {
return MAPPER.readValue(json, clazz);
} catch (IOException e) {
throw new GithubProcessException("Failed to retrieve object from json", e);
}
}

private GithubRepository createRepository(@NonNull String name) {
private GithubRepository createRepository(@NonNull String name) throws GithubProcessException {
GithubRepository repository = GithubRepository.builder(name).build();
HttpResponse response = super.createRepository(repository);

Expand All @@ -57,15 +58,15 @@ private GithubRepository createRepository(@NonNull String name) {
return repository;
}

public void deleteRepository(@NonNull GithubRepository repository) {
public void deleteRepository(@NonNull GithubRepository repository) throws GithubProcessException {
HttpResponse response = super.deleteRepository(repository.getName());

if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {
throw new GithubProcessException("Failed to delete: " + repository.getName());
}
}

private List<GithubCommit> getRepositoryCommits(@NonNull GithubRepository repository) {
private List<GithubCommit> getRepositoryCommits(@NonNull GithubRepository repository) throws GithubProcessException {
HttpResponse response = super.getAllCommits(repository.getName());

if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Expand All @@ -79,7 +80,8 @@ private List<GithubCommit> getRepositoryCommits(@NonNull GithubRepository reposi
return Arrays.asList(commit);
}

private GitDataCommit getGitDataCommit(@NonNull GithubRepository repository, @NonNull GithubCommit commit) {
private GitDataCommit getGitDataCommit(@NonNull GithubRepository repository, @NonNull GithubCommit commit)
throws GithubProcessException {
HttpResponse response = super.getGitDataCommit(repository.getName(), commit.getSha());

if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Expand All @@ -89,7 +91,8 @@ private GitDataCommit getGitDataCommit(@NonNull GithubRepository repository, @No
return readValue(getContent(response), GitDataCommit.class);
}

private GitDataTree getGitDataTree(@NonNull GithubRepository repository, @NonNull GitDataCommit commit) {
private GitDataTree getGitDataTree(@NonNull GithubRepository repository, @NonNull GitDataCommit commit)
throws GithubProcessException {
HttpResponse response = super.getGitDataTree(repository.getName(), commit.getTree().getSha());

if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Expand All @@ -108,7 +111,8 @@ private GitDataRequestTree getGitDataRequestTree(@NonNull GitDataTree baseTree)
return requestTree;
}

private GitDataBlob createGitDataBlob(@NonNull GithubRepository repository, @NonNull GitDataRequestBlob requestBlob) {
private GitDataBlob createGitDataBlob(@NonNull GithubRepository repository, @NonNull GitDataRequestBlob requestBlob)
throws GithubProcessException {
HttpResponse response = super.createGitDataBlob(repository.getName(), requestBlob);

if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
Expand All @@ -124,7 +128,7 @@ private GitDataRequestBlob getGitDataRequestBlob(@NonNull String filename) {

return new GitDataRequestBlob(content, "utf-8");
} catch (IOException e) {
throw new GithubProcessException("Failed to read file: " + filename, e);
throw new GithubFileException("Failed to read file: " + filename, e);
}
}

Expand All @@ -149,7 +153,8 @@ private GitDataRequestCommit getGitDateRequestCommit(@NonNull GitDataCommit pare
.build();
}

private GitDataCommit createGitDateCommit(@NonNull GithubRepository repository, @NonNull GitDataRequestCommit commit) {
private GitDataCommit createGitDateCommit(@NonNull GithubRepository repository, @NonNull GitDataRequestCommit commit)
throws GithubProcessException {
HttpResponse response = super.createGitDataCommit(repository.getName(), commit);

if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
Expand All @@ -159,7 +164,8 @@ private GitDataCommit createGitDateCommit(@NonNull GithubRepository repository,
return readValue(getContent(response), GitDataCommit.class);
}

private GithubTree createGitDataTree(@NonNull GithubRepository repository, @NonNull GitDataRequestTree tree) {
private GithubTree createGitDataTree(@NonNull GithubRepository repository, @NonNull GitDataRequestTree tree)
throws GithubProcessException {
HttpResponse response = super.createGitDataTree(repository.getName(), tree);

if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
Expand All @@ -174,7 +180,7 @@ private GitDataRequestReference getGitDataRequestReference(@NonNull GitDataCommi
}

private void updateGithubRepository(@NonNull GithubRepository repository,
@NonNull GitDataRequestReference reference) {
@NonNull GitDataRequestReference reference) throws GithubProcessException {
HttpResponse response = super.updateGitDataReference(repository.getName(), reference);

if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Expand Down Expand Up @@ -219,33 +225,30 @@ private String truncateFileNamePrefix(@NonNull String fileName) {
}

private GithubTree createGithubTree(@NonNull GithubRepository repository, @NonNull GitDataCommit parentCommit,
@NonNull File dir) {
@NonNull File dir) throws GithubProcessException {
List<String> files = getAllFiles(dir);
GitDataTree tree = getGitDataTree(repository, parentCommit);
GitDataRequestTree requestTree = getGitDataRequestTree(tree);
List<GitDataRequestBlob> requestBlobs = files.stream().map(this::getGitDataRequestBlob).collect(Collectors.toList());
List<GitDataBlob> blobs = requestBlobs.stream().map(b -> createGitDataBlob(repository, b)).collect(Collectors.toList());

for (int i = 0; i < files.size(); i++) {
String filename = files.get(i);
String sha = blobs.get(i).getSha();
GitDataBlob blob = createGitDataBlob(repository, requestBlobs.get(i));

requestTree.getTree().add(getRequestTreeNode(truncateFileNamePrefix(filename), sha));
requestTree.getTree().add(getRequestTreeNode(truncateFileNamePrefix(filename), blob.getSha()));
}

return createGitDataTree(repository, requestTree);
}

public void createRepository(@NonNull File dir) {
GithubRepository repository = createRepository("spring-cloud-azure-demo");
public void createRepository(@NonNull File dir, @NonNull String repositoryName) throws GithubProcessException {
GithubRepository repository = createRepository(repositoryName);
GitDataCommit parentCommit = getGitDataCommit(repository, getRepositoryCommits(repository).get(0));
GithubTree githubTree = createGithubTree(repository, parentCommit, dir);
GitDataRequestCommit requestCommit = getGitDateRequestCommit(parentCommit, githubTree);
GitDataCommit commit = createGitDateCommit(repository, requestCommit);
GitDataRequestReference reference = getGitDataRequestReference(commit);

updateGithubRepository(repository, reference);

deleteRepository(repository);
}
}
4 changes: 2 additions & 2 deletions src/main/resources/static/js/start.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,9 @@ $(function () {
generateInProgress();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4 && xhttp.status === 200) {
if (xhttp.readyState === 4 && xhttp.status === 201) {
generateSucceed();
} else {
} else if (xhttp.readyState === 4) {
generateFailed();
}
closeModal(githubConfigModal);
Expand Down

0 comments on commit fd74b66

Please sign in to comment.