Example usage for java.net HttpURLConnection HTTP_CREATED

List of usage examples for java.net HttpURLConnection HTTP_CREATED

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_CREATED.

Prototype

int HTTP_CREATED

To view the source code for java.net HttpURLConnection HTTP_CREATED.

Click Source Link

Document

HTTP Status-Code 201: Created.

Usage

From source file:jetbrains.buildServer.vmgr.agent.Utils.java

public String executeAPI(String jSON, String apiUrl, String url, boolean requireAuth, String user,
        String password, String requestMethod, BuildProgressLogger logger, boolean dynamicUserId,
        String buildID, String workPlacePath) throws Exception {

    try {//from   w w w  .  ja v a 2  s.c o  m

        boolean notInTestMode = true;
        if (logger == null) {
            notInTestMode = false;
        }

        String apiURL = url + "/rest" + apiUrl;

        if (notInTestMode) {
            logger.message("vManager vAPI - Trying to call vAPI '" + "/rest" + apiUrl + "'");
        }
        String input = jSON;
        HttpURLConnection conn = getVAPIConnection(apiURL, requireAuth, user, password, requestMethod,
                dynamicUserId, buildID, workPlacePath, logger);

        if ("PUT".equals(requestMethod) || "POST".equals(requestMethod)) {
            OutputStream os = conn.getOutputStream();
            os.write(input.getBytes());
            os.flush();
        }

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK
                && conn.getResponseCode() != HttpURLConnection.HTTP_NO_CONTENT
                && conn.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED
                && conn.getResponseCode() != HttpURLConnection.HTTP_CREATED
                && conn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL
                && conn.getResponseCode() != HttpURLConnection.HTTP_RESET) {
            String reason = "";
            if (conn.getResponseCode() == 503)
                reason = "vAPI process failed to connect to remote vManager server.";
            if (conn.getResponseCode() == 401)
                reason = "Authentication Error";
            if (conn.getResponseCode() == 415)
                reason = "The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.  Check if you selected the right request method (GET/POST/DELETE/PUT).";
            if (conn.getResponseCode() == 405)
                reason = "The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.  Check if you selected the right request method (GET/POST/DELETE/PUT).";
            if (conn.getResponseCode() == 412)
                reason = "vAPI requires vManager 'Integration Server' license.";
            String errorMessage = "Failed : HTTP error code : " + conn.getResponseCode() + " (" + reason + ")";
            if (notInTestMode) {
                logger.message(errorMessage);
                logger.message(conn.getResponseMessage());
            }

            System.out.println(errorMessage);
            return errorMessage;
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        StringBuilder result = new StringBuilder();
        String output;
        while ((output = br.readLine()) != null) {
            result.append(output);
        }

        conn.disconnect();

        // Flush the output into workspace
        String fileOutput = workPlacePath + File.separator + buildID + File.separator + "vapi.output";

        FileWriter writer = new FileWriter(fileOutput);

        writer.append(result.toString());
        writer.flush();
        writer.close();

        String textOut = "API Call Success: Output was saved into: " + fileOutput;

        if (notInTestMode) {
            logger.message(textOut);
        } else {

            System.out.println(textOut);
        }

        return "success";

    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Failed: Error: " + e.getMessage());
        return e.getMessage();
    }
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitConfigTest.java

@Test
public void testUpdateConfigEntryUsingPUT() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project metadata
        WebRequest request = getGetRequest(contentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());
        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
        String gitConfigUri = gitSection.getString(GitConstants.KEY_CONFIG);

        // set some dummy value
        final String ENTRY_KEY = "a.b.c";
        final String ENTRY_VALUE = "v";

        request = getPostGitConfigRequest(gitConfigUri, ENTRY_KEY, ENTRY_VALUE);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

        JSONObject configResponse = new JSONObject(response.getText());
        String entryLocation = configResponse.getString(ProtocolConstants.KEY_LOCATION);

        // update config entry using PUT
        final String NEW_ENTRY_VALUE = "v2";

        request = getPutGitConfigRequest(entryLocation, NEW_ENTRY_VALUE);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        JSONObject configEntry = listConfigEntries(entryLocation);
        assertConfigOption(configEntry, ENTRY_KEY, NEW_ENTRY_VALUE);
    }/*from  w  w  w  .  j av  a  2 s  .  c om*/
}

From source file:org.eclipse.rdf4j.http.client.RDF4JProtocolSession.java

public synchronized void beginTransaction(IsolationLevel isolationLevel)
        throws RDF4JException, IOException, UnauthorizedException {
    checkRepositoryURL();/* ww  w.jav a  2  s  .  c  om*/

    if (transactionURL != null) {
        throw new IllegalStateException("Transaction URL is already set");
    }

    HttpPost method = new HttpPost(Protocol.getTransactionsLocation(getRepositoryURL()));

    try {
        method.setHeader("Content-Type", Protocol.FORM_MIME_TYPE + "; charset=utf-8");

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        if (isolationLevel != null) {
            params.add(new BasicNameValuePair(Protocol.ISOLATION_LEVEL_PARAM_NAME,
                    isolationLevel.getURI().stringValue()));
        }

        method.setEntity(new UrlEncodedFormEntity(params, UTF8));
        HttpResponse response = execute(method);
        try {
            int code = response.getStatusLine().getStatusCode();

            if (code == HttpURLConnection.HTTP_CREATED) {
                transactionURL = response.getFirstHeader("Location").getValue();
                if (transactionURL == null) {
                    throw new RepositoryException("no valid transaction ID received in server response.");
                }
            } else {
                throw new RepositoryException("unable to start transaction. HTTP error code " + code);
            }
        } finally {
            EntityUtils.consume(response.getEntity());
        }
    } finally {
        method.reset();
    }
}

From source file:org.eclipse.orion.server.tests.servlets.site.HostingTest.java

private void createDirectoryOnServer(String dirname) throws SAXException, IOException, JSONException {
    webConversation.setExceptionsThrownOnErrorStatus(false);
    WebRequest createDirReq = getPostFilesRequest("", getNewDirJSON(dirname).toString(), dirname);
    WebResponse createDirResp = webConversation.getResponse(createDirReq);
    assertEquals(HttpURLConnection.HTTP_CREATED, createDirResp.getResponseCode());
}

From source file:org.eclipse.orion.server.tests.metastore.RemoteMetaStoreTests.java

/**
 * Create a project on the Orion server for the test user.
 * //ww w . j a  v a  2 s .  co  m
 * @throws IOException
 * @throws JSONException
 * @throws URISyntaxException
 * @throws SAXException 
 */
@Test
public void testCreateProject() throws IOException, JSONException, URISyntaxException, SAXException {
    WebConversation webConversation = new WebConversation();
    assertEquals(HttpURLConnection.HTTP_CREATED,
            createProject(webConversation, getOrionTestName(), getOrionTestName(), "Project"));
}

From source file:com.smartbear.collaborator.issue.IssueRest.java

private static void checkResponseStatus(ClientResponse response) throws Exception {
    if (response == null) {
        throw new Exception("Response from Fisheye server is null or empty.");
    }/*from w  w  w.  j av a2 s  .co  m*/

    if (response.getStatus() != HttpURLConnection.HTTP_OK
            && response.getStatus() != HttpURLConnection.HTTP_ACCEPTED
            && response.getStatus() != HttpURLConnection.HTTP_CREATED) {
        throw new Exception("Response status is " + response.getStatus());
    }
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitCommitTest.java

@Test
public void testCommitterAndAuthorFallback() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project metadata
        WebRequest request = getGetRequest(contentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());
        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);

        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);
        String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
        String gitConfigUri = gitSection.getString(GitConstants.KEY_CONFIG);

        // set user.name and user.email
        final String name = "name";
        final String email = "email";
        final String defaultName = "default name";
        final String defaultEmail = "default email";
        request = GitConfigTest.getPostGitConfigRequest(gitConfigUri, "user.name", defaultName);
        response = webConversation.getResponse(request);
        assertEquals(response.getText(), HttpURLConnection.HTTP_CREATED, response.getResponseCode());
        request = GitConfigTest.getPostGitConfigRequest(gitConfigUri, "user.email", defaultEmail);
        response = webConversation.getResponse(request);
        assertEquals(response.getText(), HttpURLConnection.HTTP_CREATED, response.getResponseCode());

        // "git add ."
        request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
        response = webConversation.getResponse(request);
        assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());

        // commit - author and committer not specified
        request = getPostGitCommitRequest(gitHeadUri, "1", false, null, null, null, null);
        response = webConversation.getResponse(request);
        assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());

        // log - expect default values
        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(2, commitsArray.length());

        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals(defaultName, commit.get(GitConstants.KEY_COMMITTER_NAME));
        assertEquals(defaultEmail, commit.get(GitConstants.KEY_COMMITTER_EMAIL));
        assertEquals(defaultName, commit.get(GitConstants.KEY_AUTHOR_NAME));
        assertEquals(defaultEmail, commit.get(GitConstants.KEY_AUTHOR_EMAIL));

        // commit - only committer given
        request = getPostGitCommitRequest(gitHeadUri, "2", true, name, email, null, null);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // log - expect author is the same as committer
        commitsArray = log(gitHeadUri);//from  w w  w . ja  va  2 s. c om
        assertEquals(2, commitsArray.length());

        commit = commitsArray.getJSONObject(0);
        assertEquals(name, commit.get(GitConstants.KEY_COMMITTER_NAME));
        assertEquals(email, commit.get(GitConstants.KEY_COMMITTER_EMAIL));
        assertEquals(name, commit.get(GitConstants.KEY_AUTHOR_NAME));
        assertEquals(email, commit.get(GitConstants.KEY_AUTHOR_EMAIL));

        // commit - only committer name given
        request = getPostGitCommitRequest(gitHeadUri, "3", true, name, null, null, null);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // log - expect author is the same as committer and their email is defaultEmail
        commitsArray = log(gitHeadUri);
        assertEquals(2, commitsArray.length());

        commit = commitsArray.getJSONObject(0);
        assertEquals(name, commit.get(GitConstants.KEY_COMMITTER_NAME));
        assertEquals(defaultEmail, commit.get(GitConstants.KEY_COMMITTER_EMAIL));
        assertEquals(name, commit.get(GitConstants.KEY_AUTHOR_NAME));
        assertEquals(defaultEmail, commit.get(GitConstants.KEY_AUTHOR_EMAIL));
    }
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitConfigTest.java

@Test
public void testDeleteConfigEntry() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project metadata
        WebRequest request = getGetRequest(contentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());
        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
        String gitConfigUri = gitSection.getString(GitConstants.KEY_CONFIG);

        // set some dummy value
        final String ENTRY_KEY = "a.b.c";
        final String ENTRY_VALUE = "v";

        request = getPostGitConfigRequest(gitConfigUri, ENTRY_KEY, ENTRY_VALUE);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

        JSONObject configResponse = new JSONObject(response.getText());
        String entryLocation = configResponse.getString(ProtocolConstants.KEY_LOCATION);

        // check if it exists
        request = getGetGitConfigRequest(entryLocation);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // delete config entry
        request = getDeleteGitConfigRequest(entryLocation);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // it shouldn't exist
        request = getGetGitConfigRequest(entryLocation);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());

        // so next delete operation should fail
        request = getDeleteGitConfigRequest(entryLocation);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());
    }//from w  ww . ja  va2  s . co m
}

From source file:org.eclipse.orion.server.tests.servlets.site.HostingTest.java

private WebResponse createFileOnServer(String fileServletLocation, String filename, String fileContent)
        throws SAXException, IOException, JSONException, URISyntaxException {
    webConversation.setExceptionsThrownOnErrorStatus(false);
    WebRequest createFileReq = getPostFilesRequest(fileServletLocation, getNewFileJSON(filename).toString(),
            filename);/*from w w  w  .j a v  a2 s .co  m*/
    WebResponse createFileResp = webConversation.getResponse(createFileReq);
    assertEquals(HttpURLConnection.HTTP_CREATED, createFileResp.getResponseCode());
    createFileReq = getPutFileRequest(createFileResp.getHeaderField("Location"), fileContent);
    createFileResp = webConversation.getResponse(createFileReq);
    assertEquals(HttpURLConnection.HTTP_OK, createFileResp.getResponseCode());
    return createFileResp;
}

From source file:org.eclipse.orion.server.tests.metastore.RemoteMetaStoreTests.java

/**
 * Create a site on the Orion server for the test user.
 * /*from  w  ww  .ja  v a2s .c  om*/
 * @throws URISyntaxException
 * @throws IOException
 * @throws JSONException
 * @throws SAXException 
 */
@Test
public void testCreateSite() throws URISyntaxException, IOException, JSONException, SAXException {
    WebConversation webConversation = new WebConversation();
    assertEquals(HttpURLConnection.HTTP_CREATED,
            createSite(webConversation, getOrionTestName(), getOrionTestName(), "First Site"));
}