Example usage for org.apache.commons.httpclient HttpStatus SC_UNPROCESSABLE_ENTITY

List of usage examples for org.apache.commons.httpclient HttpStatus SC_UNPROCESSABLE_ENTITY

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_UNPROCESSABLE_ENTITY.

Prototype

int SC_UNPROCESSABLE_ENTITY

To view the source code for org.apache.commons.httpclient HttpStatus SC_UNPROCESSABLE_ENTITY.

Click Source Link

Document

422 Unprocessable Entity (WebDAV - RFC 2518)

Usage

From source file:de.mpg.imeji.test.rest.resources.test.integration.ItemTestBase.java

public void test_5_defaultSyntax_badTypedValues(String itemId, String jSon) throws IOException {

    FormDataMultiPart multiPart = new FormDataMultiPart();
    multiPart.bodyPart(new FileDataBodyPart("file", ImejiTestResources.getTestJpg()));

    LOGGER.info("Checking textual values ... ");
    // Put Number Value to a String metadata
    multiPart.field("json", replaceWithNumberValueNotLastField(jSon, "text"));
    Response response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking number values ... ");
    // Put String to Number Value metadata
    multiPart.getField("json").setValue(replaceWithStringValueNotLastField(jSon, "number"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking date values ... ");
    // Put "sometext" String to Date Value metadata
    multiPart.getField("json").setValue(replaceWithStringValueNotLastField(jSon, "date"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking longitude values with text ... ");
    // Put "sometext" String to Longitude Value metadata
    multiPart.getField("json").setValue(replaceWithStringValueNotLastField(jSon, "longitude"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking latitude values with text... ");
    // Put "sometext" String to Latitude (last) Value metadata
    multiPart.getField("json").setValue(replaceWithStringValueLastField(jSon, "latitude"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking longitude values with wrong value... ");
    // Put bad Value to Longitude Value metadata
    multiPart.getField("json").setValue(replaceWithNumberValueNotLastField(jSon, "longitude"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking latitude values with wrong value... ");
    // Put bad Value to Longitude Value metadata
    multiPart.getField("json").setValue(replaceWithNumberValueLastField(jSon, "latitude"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());
}

From source file:io.fabric8.jenkins.openshiftsync.BuildSyncRunListener.java

protected synchronized void pollRun(Run run) {
    if (!(run instanceof WorkflowRun)) {
        throw new IllegalStateException("Cannot poll a non-workflow run");
    }//from   w  w w . j a  va  2 s .c  om

    RunExt wfRunExt = RunExt.create((WorkflowRun) run);

    try {
        upsertBuild(run, wfRunExt);
    } catch (KubernetesClientException e) {
        if (e.getCode() == HttpStatus.SC_UNPROCESSABLE_ENTITY) {
            runsToPoll.remove(run);
            logger.log(WARNING, "Cannot update status: {0}", e.getMessage());
            return;
        }
        throw e;
    }
}

From source file:com.github.maven.plugin.client.impl.GithubClientImpl.java

public void upload(String artifactName, File file, String description, String repositoryUrl) {
    assertNotNull(artifactName, "artifactName");
    assertNotNull(file, "file");
    assertNotNull(repositoryUrl, "repositoryUrl");
    assertStartsWith(repositoryUrl, GITHUB_REPOSITORY_URL_PREFIX, "repositoryUrl");

    PostMethod githubPost = new PostMethod(toRepositoryDownloadUrl(repositoryUrl));
    githubPost.setRequestBody(new NameValuePair[] { new NameValuePair("login", login),
            new NameValuePair("token", token), new NameValuePair("file_name", artifactName),
            new NameValuePair("file_size", String.valueOf(file.length())),
            new NameValuePair("description", description == null ? "" : description) });

    try {/*from   ww  w.ja v  a2s  .c  om*/

        int response = httpClient.executeMethod(githubPost);

        if (response == HttpStatus.SC_OK) {

            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readValue(githubPost.getResponseBodyAsString(), JsonNode.class);

            PostMethod s3Post = new PostMethod(GITHUB_S3_URL);

            Part[] parts = { new StringPart("Filename", artifactName),
                    new StringPart("policy", node.path("policy").getTextValue()),
                    new StringPart("success_action_status", "201"),
                    new StringPart("key", node.path("path").getTextValue()),
                    new StringPart("AWSAccessKeyId", node.path("accesskeyid").getTextValue()),
                    new StringPart("Content-Type", node.path("mime_type").getTextValue()),
                    new StringPart("signature", node.path("signature").getTextValue()),
                    new StringPart("acl", node.path("acl").getTextValue()), new FilePart("file", file) };

            MultipartRequestEntity partEntity = new MultipartRequestEntity(parts, s3Post.getParams());
            s3Post.setRequestEntity(partEntity);

            int s3Response = httpClient.executeMethod(s3Post);
            if (s3Response != HttpStatus.SC_CREATED) {
                throw new GithubException(
                        "Cannot upload " + file.getName() + " to repository " + repositoryUrl);
            }

            s3Post.releaseConnection();
        } else if (response == HttpStatus.SC_NOT_FOUND) {
            throw new GithubRepositoryNotFoundException("Cannot found repository " + repositoryUrl);
        } else if (response == HttpStatus.SC_UNPROCESSABLE_ENTITY) {
            throw new GithubArtifactAlreadyExistException(
                    "File " + artifactName + " already exist in " + repositoryUrl + " repository");
        } else {
            throw new GithubException("Error " + HttpStatus.getStatusText(response));
        }
    } catch (IOException e) {
        throw new GithubException(e);
    }

    githubPost.releaseConnection();
}

From source file:de.mpg.imeji.test.rest.resources.test.integration.ItemTestBase.java

public void test_6_ExistingDefaultFields(String itemId, String jSon) throws IOException {
    // validates the name of each predefined metadata from a metadata record
    FormDataMultiPart multiPart = new FormDataMultiPart();
    multiPart.bodyPart(new FileDataBodyPart("file", ImejiTestResources.getTestJpg()));

    LOGGER.info("Checking text field label  ");
    multiPart.field("json", replaceFieldName(jSon, "text"));
    Response response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking geolocation field label  ");
    // Put Number Value to a String metadata
    multiPart.field("json", replaceFieldName(jSon, "geolocation"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking name field label  ");
    multiPart.field("json", replaceFieldName(jSon, "name"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking latitude field label  ");
    multiPart.field("json", replaceFieldName(jSon, "latitude"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking longitude field label  ");
    multiPart.field("json", replaceFieldName(jSon, "longitude"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking number field label  ");
    multiPart.field("json", replaceFieldName(jSon, "number"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking conePerson field label  ");
    multiPart.field("json", replaceFieldName(jSon, "conePerson"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking familyName field label  ");
    multiPart.field("json", replaceFieldName(jSon, "familyName"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking completeName field label  ");
    multiPart.field("json", replaceFieldName(jSon, "completeName"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking alternativeName field label  ");
    multiPart.field("json", replaceFieldName(jSon, "alternativeName"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking role field label  ");
    multiPart.field("json", replaceFieldName(jSon, "role"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking organizations field label  ");
    multiPart.field("json", replaceFieldName(jSon, "organizations"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking description field label  ");
    multiPart.field("json", replaceFieldName(jSon, "description"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking city field label  ");
    multiPart.field("json", replaceFieldName(jSon, "city"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking country field label  ");
    multiPart.field("json", replaceFieldName(jSon, "country"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking date field label  ");
    multiPart.field("json", replaceFieldName(jSon, "date"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking license field label  ");
    multiPart.field("json", replaceFieldName(jSon, "license"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking url field label  ");
    multiPart.field("json", replaceFieldName(jSon, "url"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking link field label  ");
    multiPart.field("json", replaceFieldName(jSon, "link"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking publication field label  ");
    multiPart.field("json", replaceFieldName(jSon, "publication"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());

    LOGGER.info("Checking citation field label  ");
    multiPart.field("json", replaceFieldName(jSon, "citation"));
    response = itemId.equals("")
            ? getCreateTargetAuth().post(Entity.entity(multiPart, multiPart.getMediaType()))
            : getUpdateTargetAuth(itemId).put(Entity.entity(multiPart, multiPart.getMediaType()));
    assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus());
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.webservice.client.impl.ShippedBiospecimenWSQueriesImpl.java

private <T> T handleClientResponse(final ClientResponse clientResponse, final Class<T> responseType) {
    T response = null;//from w w w. j  ava 2s  .c o m
    int responseStatus = clientResponse.getStatus();
    StringBuilder errorMessage = null;
    if (HttpStatus.SC_OK == responseStatus) {
        response = clientResponse.getEntity(responseType);
    } else if (HttpStatus.SC_UNPROCESSABLE_ENTITY == responseStatus) {
        // this actually means the entity was not found which might
        // be a valid response, so just return null, don't assume it's an error
        // HttpStatus 400
    } else if (HttpStatus.SC_BAD_REQUEST == responseStatus) {
        errorMessage = new StringBuilder().append("Request returned HTTP response status of '")
                .append(responseStatus).append(" - ").append(HttpStatus.getStatusText(responseStatus))
                .append("'. Check the request and try again.");
        // HttpStatus 413
    } else if (HttpStatus.SC_REQUEST_TOO_LONG == responseStatus) {
        errorMessage = new StringBuilder().append("Request returned HTTP response status of '")
                .append(responseStatus).append(" - ").append(HttpStatus.getStatusText(responseStatus))
                .append("'. The number of requests to this web service has exceeded the DCC limits.")
                .append(" You should reduce the number of concurrent instances of the stand-alone validator running or use the -noremote flag.");
        if (qcContext != null) {
            qcContext.addError(errorMessage.toString());
        }
        throw new RuntimeException(errorMessage.toString());
    }

    if (errorMessage != null) {
        handleErrorMessage(errorMessage.toString());
    }

    return response;
}

From source file:org.eclipse.mylyn.internal.gerrit.core.client.GerritClient.java

public ReviewerResult addReviewers(String reviewId, final List<String> reviewers, IProgressMonitor monitor)
        throws GerritException {
    Assert.isLegal(reviewers != null, "reviewers cannot be null"); //$NON-NLS-1$
    final Change.Id id = new Change.Id(id(reviewId));
    final String uri;
    uri = "/a/changes/" + id.get() + "/reviewers"; //$NON-NLS-1$ //$NON-NLS-2$

    Set<ReviewerInfo> reviewerInfos = new HashSet<ReviewerInfo>(reviewers.size());
    ReviewerResult reviewerResult = new ReviewerResult();
    for (final String reviewerId : reviewers) {
        try {//from   w w  w.  j a  va2 s  .  c om
            AddReviewerResult addReviewerResult = executePostRestRequest(uri, new ReviewerInput(reviewerId),
                    AddReviewerResult.class, null /*no error handler*/, monitor);
            reviewerInfos.addAll(addReviewerResult.getReviewers());
        } catch (GerritHttpException e) {
            if (e.getResponseCode() == HttpStatus.SC_UNPROCESSABLE_ENTITY) {
                reviewerResult.addError(new ReviewerResult.Error(null /* no type*/, reviewerId));
            }
        }
    }

    ChangeDetail changeDetail = getChangeDetail(id.get(), monitor);

    List<ApprovalDetail> approvalDetails = new ArrayList<ApprovalDetail>(reviewerInfos.size());
    for (ReviewerInfo reviewerInfo : reviewerInfos) {
        approvalDetails.add(reviewerInfo.toApprovalDetail(changeDetail.getCurrentPatchSet()));
    }
    changeDetail.setApprovals(approvalDetails);
    reviewerResult.setChange(changeDetail);
    return reviewerResult;
}

From source file:org.opens.tanaguru.util.http.HttpRequestHandler.java

private int computeStatus(int status) {
    switch (status) {
    case HttpStatus.SC_FORBIDDEN:
    case HttpStatus.SC_METHOD_NOT_ALLOWED:
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_NOT_FOUND:
    case HttpStatus.SC_NOT_ACCEPTABLE:
    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
    case HttpStatus.SC_REQUEST_TIMEOUT:
    case HttpStatus.SC_CONFLICT:
    case HttpStatus.SC_GONE:
    case HttpStatus.SC_LENGTH_REQUIRED:
    case HttpStatus.SC_PRECONDITION_FAILED:
    case HttpStatus.SC_REQUEST_TOO_LONG:
    case HttpStatus.SC_REQUEST_URI_TOO_LONG:
    case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
    case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
    case HttpStatus.SC_EXPECTATION_FAILED:
    case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
    case HttpStatus.SC_METHOD_FAILURE:
    case HttpStatus.SC_UNPROCESSABLE_ENTITY:
    case HttpStatus.SC_LOCKED:
    case HttpStatus.SC_FAILED_DEPENDENCY:
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
    case HttpStatus.SC_NOT_IMPLEMENTED:
    case HttpStatus.SC_BAD_GATEWAY:
    case HttpStatus.SC_SERVICE_UNAVAILABLE:
    case HttpStatus.SC_GATEWAY_TIMEOUT:
    case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED:
    case HttpStatus.SC_INSUFFICIENT_STORAGE:
        return 0;
    case HttpStatus.SC_CONTINUE:
    case HttpStatus.SC_SWITCHING_PROTOCOLS:
    case HttpStatus.SC_PROCESSING:
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
    case HttpStatus.SC_NO_CONTENT:
    case HttpStatus.SC_RESET_CONTENT:
    case HttpStatus.SC_PARTIAL_CONTENT:
    case HttpStatus.SC_MULTI_STATUS:
    case HttpStatus.SC_MULTIPLE_CHOICES:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_SEE_OTHER:
    case HttpStatus.SC_NOT_MODIFIED:
    case HttpStatus.SC_USE_PROXY:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        return 1;
    default:/*  w  w  w  .  j a  va2  s .  co  m*/
        return 1;
    }
}

From source file:org.wso2.carbon.appfactory.git.repository.provider.GithubRepositoryProvider.java

/**
 * {@inheritDoc}// w ww  .j a va 2 s  .com
 */
@Override
public String createRepository(String applicationKey, String tenantDomain) throws RepositoryMgtException {

    Repository repository = new Repository();
    repository.setName(applicationKey);
    repository.setType("git");

    Permission permission = new Permission();
    permission.setGroupPermission(true);
    permission.setName(applicationKey);
    permission.setType(PermissionType.WRITE);
    ArrayList<Permission> permissions = new ArrayList<Permission>();
    permissions.add(permission);

    repository.setPermissions(permissions);

    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod("https://api.github.com/orgs/" + ORG_NAME + "/repos");

    post.setDoAuthentication(true);
    post.addRequestHeader("Authorization", "Basic " + githubAuthtoken);

    StringRequestEntity requestEntity;
    try {
        requestEntity = new StringRequestEntity(
                "  {\n  \"name\":\"" + applicationKey + "\",\n\"auto_init\":\"true\"\n}", "application/json",
                "UTF-8");
    } catch (UnsupportedEncodingException e) {
        String msg = "Error while invoking gitHub API";
        log.error(msg, e);
        throw new RepositoryMgtException(msg, e);
    }
    post.setRequestEntity(requestEntity);

    try {
        client.executeMethod(post);
        log.debug("HTTP status " + post.getStatusCode() + " creating repo\n\n");

        if (post.getStatusCode() == HttpStatus.SC_CREATED) {
            log.debug("Repository creation successful");
        } else if (post.getStatusCode() == HttpStatus.SC_UNPROCESSABLE_ENTITY) {
            String msg = "Repository creation is failed for" + applicationKey
                    + ". Repository with the same name already exists";
            log.error(msg);
            throw new RepositoryMgtException(msg);
        } else {
            String msg = "Repository creation is failed for" + applicationKey + "Server returned status:"
                    + post.getStatusCode();
            log.error(msg);
            throw new RepositoryMgtException(msg);
        }

    } catch (IOException e) {
        String msg = "Error while invoking gitHub API";
        log.error(msg, e);
        throw new RepositoryMgtException(msg, e);
    } finally {
        post.releaseConnection();
    }

    createTeam(applicationKey);
    return getAppRepositoryURL(applicationKey, tenantDomain);
}

From source file:org.wso2.carbon.appfactory.git.repository.provider.GithubRepositoryProvider.java

private void createTeam(String applicationKey) throws RepositoryMgtException {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod("https://api.github.com/orgs/" + ORG_NAME + "/teams");
    // https://api.github.com/teams/627395/members/manishagele

    post.setDoAuthentication(true);//from   w w w .  ja va 2s  .c  o  m
    post.addRequestHeader("Authorization", "Basic " + githubAuthtoken);

    StringRequestEntity requestEntity;
    try {
        requestEntity = new StringRequestEntity("{\n" + "  \"name\": \"team_" + applicationKey + "\",\n"
                + "  \"permission\": \"push\",\n" + "  \"repo_names\": [\n" + "    \"" + ORG_NAME + "/"
                + applicationKey + "\"\n" + "  ]\n" + "}", "application/json", "UTF-8");
    } catch (UnsupportedEncodingException e) {
        String msg = "Error while invoking gitHub API";
        log.error(msg, e);
        throw new RepositoryMgtException(msg, e);
    }
    post.setRequestEntity(requestEntity);

    try {
        client.executeMethod(post);
        log.debug("HTTP status " + post.getStatusCode() + " creating team\n\n");

        if (post.getStatusCode() == HttpStatus.SC_CREATED) {
            log.debug("team creation successful");
        } else if (post.getStatusCode() == HttpStatus.SC_UNPROCESSABLE_ENTITY) {
            String msg = "team creation is failed for" + applicationKey
                    + ". team with the same name already exists";
            log.error(msg);
            throw new RepositoryMgtException(msg);
        } else {
            String msg = "team creation is failed for" + applicationKey + "Server returned status:"
                    + post.getStatusCode();
            log.error(msg);
            throw new RepositoryMgtException(msg);
        }

    } catch (IOException e) {
        String msg = "Error while invoking gitHub API";
        log.error(msg, e);
        throw new RepositoryMgtException(msg, e);
    } finally {
        post.releaseConnection();
    }
}