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:org.eclipse.orion.server.tests.servlets.git.GitResetTest.java

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

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

        // get project/folder metadata
        WebRequest request = getGetRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject folder = new JSONObject(response.getText());

        JSONObject testTxt = getChild(folder, "test.txt");
        modifyFile(testTxt, "hello");

        String fileName = "new.txt";
        request = getPostFilesRequest(folder.getString(ProtocolConstants.KEY_LOCATION),
                getNewFileJSON(fileName).toString(), fileName);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

        JSONObject folder1 = getChild(folder, "folder");
        JSONObject folderTxt = getChild(folder1, "folder.txt");
        deleteFile(folderTxt);//from w ww  .j av a  2 s  . co m

        JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
        String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
        String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS);

        // "git status"
        assertStatus(new StatusResult().setMissing(1).setModified(1).setUntracked(1), gitStatusUri);

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

        // "git status"
        assertStatus(new StatusResult().setAdded(1).setChanged(1).setRemoved(1), gitStatusUri);

        // "git reset --hard HEAD"
        request = getPostGitIndexRequest(gitIndexUri /* reset all */, ResetType.HARD);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // "git status", should be clean, nothing to commit
        assertStatus(StatusResult.CLEAN, gitStatusUri);
    }
}

From source file:it.geosolutions.figis.requester.HTTPUtils.java

/**
* Send an HTTP request (PUT or POST) to a server.
* <BR>Basic auth is used if both username and pw are not null.
* <P>//from w w  w . j av  a 2 s.co  m
* Only <UL>
* <LI>200: OK</LI>
* <LI>201: ACCEPTED</LI>
* <LI>202: CREATED</LI>
* </UL> are accepted as successful codes; in these cases the response string will be returned.
*
* @return the HTTP response or <TT>null</TT> on errors.
*/
private static String send(final EntityEnclosingMethod httpMethod, String url, RequestEntity requestEntity,
        String username, String pw) {

    try {
        HttpClient client = new HttpClient();
        setAuth(client, url, username, pw);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        if (requestEntity != null) {
            httpMethod.setRequestEntity(requestEntity);
        }

        int status = client.executeMethod(httpMethod);

        switch (status) {
        case HttpURLConnection.HTTP_OK:
        case HttpURLConnection.HTTP_CREATED:
        case HttpURLConnection.HTTP_ACCEPTED:

            String response = IOUtils.toString(httpMethod.getResponseBodyAsStream());
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("HTTP " + httpMethod.getStatusText() + ": " + response);
            }
            return response;
        default:
            LOGGER.warn("Bad response: code[" + status + "]" + " msg[" + httpMethod.getStatusText() + "]"
                    + " url[" + url + "]" + " method[" + httpMethod.getClass().getSimpleName() + "]: "
                    + IOUtils.toString(httpMethod.getResponseBodyAsStream()));

            return null;
        }
    } catch (ConnectException e) {
        LOGGER.error("Couldn't connect to [" + url + "]", e);

        return null;
    } catch (IOException e) {
        LOGGER.error("Error talking to " + url + " : " + e.getLocalizedMessage(), e);

        return null;
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:org.eclipse.orion.server.tests.servlets.xfer.TransferTest.java

/**
 * Tests importing a zip file from a remote URL, and verifying that it is imported and unzipped.
 */// w ww  .  j av  a 2s  . c o m
@Test
public void testImportAndUnzipFromURL() throws CoreException, IOException, SAXException {
    //just a known zip file that we can use for testing that is stable
    String sourceZip = "http://eclipse.org/eclipse/platform-core/downloads/tools/org.eclipse.core.tools.restorer_3.0.0.zip";

    //create a directory to upload to
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);

    //start the import
    String requestPath = getImportRequestPath(directoryPath) + "?source=" + sourceZip;
    PostMethodWebRequest request = new PostMethodWebRequest(requestPath);
    setAuthentication(request);
    WebResponse postResponse = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, postResponse.getResponseCode());
    String location = postResponse.getHeaderField("Location");
    assertNotNull(location);

    //assert the file has been unzipped in the workspace
    assertTrue(checkFileExists(directoryPath
            + "/org.eclipse.core.tools.restorer_3.0.0/org.eclipse.core.tools.restorer_3.0.0.200607121527.jar"));
}

From source file:org.eclipse.orion.server.tests.servlets.files.CoreFilesTest.java

/**
 * Tests creating a file whose name is an encoded URL.
 */// ww  w . ja  va  2s . co  m
@Test
public void testCreateFileEncodedName() throws CoreException, IOException, SAXException, JSONException {
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);
    String fileName = "http%2525253A%2525252F%2525252Fwww.example.org%2525252Fwinery%2525252FTEST%2525252Fjclouds1";

    WebRequest request = getPostFilesRequest(directoryPath, getNewFileJSON(fileName).toString(), fileName);
    WebResponse response = webConversation.getResponse(request);

    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    assertTrue("Create file response was OK, but the file does not exist",
            checkFileExists(directoryPath + "/" + fileName));
    assertEquals("Response should contain file metadata in JSON, but was " + response.getText(),
            "application/json", response.getContentType());
    JSONObject responseObject = new JSONObject(response.getText());
    assertNotNull("No file information in response", responseObject);
    checkFileMetadata(responseObject, fileName, null, null, null, null, null, null, null, null);

    //should be able to perform GET on location header to obtain metadata
    String location = response.getHeaderField("Location");
    request = getGetRequest(location + "?parts=meta");
    response = webConversation.getResource(request);
    assertNotNull(location);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    responseObject = new JSONObject(response.getText());
    assertNotNull("No directory information in response", responseObject);
    checkFileMetadata(responseObject, fileName, null, null, null, null, null, null, null, null);

    //a GET on the parent folder should return a file with that name
    request = getGetFilesRequest(directoryPath + "?depth=1");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    responseObject = new JSONObject(response.getText());
    System.out.println(responseObject);
    JSONArray children = responseObject.getJSONArray(ProtocolConstants.KEY_CHILDREN);
    assertEquals(1, children.length());
    JSONObject child = children.getJSONObject(0);
    assertEquals(fileName, child.getString(ProtocolConstants.KEY_NAME));

}

From source file:i5.las2peer.services.loadStoreGraphService.LoadStoreGraphService.java

/**
 * /*from   w  w  w. j ava2  s .  co  m*/
 * storeGraph
 * 
 * @param graph a JSONObject
 * 
 * @return HttpResponse
 * 
 */
@POST
@Path("/")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "internalError"),
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "graphStored") })
@ApiOperation(value = "storeGraph", notes = "")
public HttpResponse storeGraph(@ContentParam String graph) {
    JSONObject graph_JSON = (JSONObject) JSONValue.parse(graph);
    String insertQuery = "";
    int id = (int) graph_JSON.get("graphId");
    if (id == -1) {
        id = 0; // in case of a new graph
    }
    String description = (String) graph_JSON.get("description");
    JSONArray array = (JSONArray) graph_JSON.get("nodes");
    String nodes = array.toJSONString();
    array = (JSONArray) graph_JSON.get("links");
    String links = array.toJSONString();
    Connection conn = null;
    PreparedStatement stmnt = null;
    try {
        conn = dbm.getConnection();
        // formulate statement
        insertQuery = "INSERT INTO graphs ( graphId,  description,  nodes,  links ) " + "VALUES ('" + id
                + "', '" + description + "', '" + nodes + "', '" + links + "') ON DUPLICATE KEY UPDATE "
                + "description = + '" + description + "', " + "nodes = + '" + nodes + "', " + "links = + '"
                + links + "';";
        stmnt = conn.prepareStatement(insertQuery, Statement.RETURN_GENERATED_KEYS);
        // execute query
        stmnt.executeUpdate();
        ResultSet genKeys = stmnt.getGeneratedKeys();
        if (genKeys.next()) {
            int newId = genKeys.getInt(1);
            // return HTTP response on success with new id
            String r = newId + "";
            HttpResponse graphStored = new HttpResponse(r, HttpURLConnection.HTTP_CREATED);
            return graphStored;
        }
        // return HTTP response on success with id of updated graph
        String r = id + "";
        HttpResponse graphStored = new HttpResponse(r, HttpURLConnection.HTTP_CREATED);
        return graphStored;
    } catch (Exception e) {
        String er = "Internal error: " + e.getMessage();
        HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
        return internalError;
    } finally {
        // free resources
        if (stmnt != null) {
            try {
                stmnt.close();
            } catch (Exception e) {
                String er = "Internal error: " + e.getMessage();
                HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
                return internalError;
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());
                String er = "Internal error: " + e.getMessage();
                HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
                return internalError;
            }
        }
    }
}

From source file:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java

/**
 * Post a new badge/*from   w ww  .  j av a 2s.c  o  m*/
 * @param appId application id
 * @param formData form data
 * @param contentType content type
 * @return HttpResponse returned as JSON object
 */
@POST
@Path("/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "{\"status\": 3, \"message\": \"Badge upload success ( (badgeid) )\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (badgeid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the badge. Badge ID already exist!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Badge ID cannot be null!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"File content null. Failed to upload (badgeid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"Failed to upload (badgeid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "{\"status\": 3, \"message\": \"Badge upload success ( (badgeid) )}") })
@ApiOperation(value = "createNewBadge", notes = "A method to store a new badge with details (badge ID, badge name, badge description, and badge image")
public HttpResponse createNewBadge(
        @ApiParam(value = "Application ID to store a new badge", required = true) @PathParam("appId") String appId,
        @ApiParam(value = "Content-type in header", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
        @ApiParam(value = "Badge detail in multiple/form-data type", required = true) @ContentParam byte[] formData) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/badges/" + appId);
    long randomLong = new Random().nextLong(); //To be able to match 

    // parse given multipart form data
    JSONObject objResponse = new JSONObject();
    String filename = null;
    byte[] filecontent = null;
    String mimeType = null;
    String badgeid = null;
    // Badge ID for the filesystem is appended with app id to make sure it is unique
    String badgename = null;
    String badgedescription = null;
    String badgeImageURI = null;
    boolean badgeusenotification = false;
    String badgenotificationmessage = null;
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_14, "" + randomLong);

        try {
            if (!badgeAccess.isAppIdExist(conn, appId)) {
                logger.info("App not found >> ");
                objResponse.put("message", "Cannot create badge. App not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
            logger.info(
                    "Cannot check whether application ID exist or not. Database error. >> " + e1.getMessage());
            objResponse.put("message",
                    "Cannot create badge. Cannot check whether application ID exist or not. Database error. "
                            + e1.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }

        Map<String, FormDataPart> parts = MultipartHelper.getParts(formData, contentType);
        FormDataPart partBadgeID = parts.get("badgeid");
        if (partBadgeID != null) {
            // these data belong to the (optional) file id text input form element
            badgeid = partBadgeID.getContent();

            if (badgeAccess.isBadgeIdExist(conn, appId, badgeid)) {
                // Badge id already exist
                logger.info("Failed to add the badge. Badge ID already exist!");
                objResponse.put("message",
                        "Cannot create badge. Failed to add the badge. Badge ID already exist!.");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

            }
            FormDataPart partFilecontent = parts.get("badgeimageinput");
            if (partFilecontent != null) {
                System.out.println(partFilecontent.getContent());
                // these data belong to the file input form element
                filename = partFilecontent.getHeader(HEADER_CONTENT_DISPOSITION).getParameter("filename");
                byte[] filecontentbefore = partFilecontent.getContentRaw();
                //                         validate input
                if (filecontentbefore == null) {
                    logger.info("File content null");
                    objResponse.put("message",
                            "Cannot create badge. File content null. Failed to upload " + badgeid);
                    L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
                }

                // in unit test, resize image will turn the image into null BufferedImage
                // but, it works in web browser
                FormDataPart partDev = parts.get("dev");
                if (partDev != null) {
                    filecontent = filecontentbefore;
                } else {
                    filecontent = resizeImage(filecontentbefore);
                }
                mimeType = partFilecontent.getContentType();
                logger.info("upload request (" + filename + ") of mime type '" + mimeType
                        + "' with content length " + filecontent.length);
            }

            FormDataPart partBadgeName = parts.get("badgename");
            if (partBadgeName != null) {
                badgename = partBadgeName.getContent();
            }
            FormDataPart partDescription = parts.get("badgedesc");
            if (partDescription != null) {
                // optional description text input form element
                badgedescription = partDescription.getContent();
            }

            FormDataPart partNotificationCheck = parts.get("badgenotificationcheck");
            if (partNotificationCheck != null) {
                // checkbox is checked
                badgeusenotification = true;
            } else {
                badgeusenotification = false;
            }
            FormDataPart partNotificationMsg = parts.get("badgenotificationmessage");
            if (partNotificationMsg != null) {
                badgenotificationmessage = partNotificationMsg.getContent();
            } else {
                badgenotificationmessage = "";
            }

            try {

                storeBadgeDataToSystem(appId, badgeid, filename, filecontent, mimeType, badgedescription);
                BadgeModel badge = new BadgeModel(badgeid, badgename, badgedescription, badgeusenotification,
                        badgenotificationmessage);

                try {
                    badgeAccess.addNewBadge(conn, appId, badge);
                    objResponse.put("message", "Badge upload success (" + badgeid + ")");
                    L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_15, "" + randomLong);
                    L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_24, "" + name);
                    L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_25, "" + appId);
                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_CREATED);

                } catch (SQLException e) {
                    e.printStackTrace();
                    objResponse.put("message",
                            "Cannot create badge. Failed to upload " + badgeid + ". " + e.getMessage());
                    L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
                }

            } catch (AgentNotKnownException | L2pServiceException | L2pSecurityException | InterruptedException
                    | TimeoutException e) {
                e.printStackTrace();
                objResponse.put("message",
                        "Cannot create badge. Failed to upload " + badgeid + ". " + e.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

            }
        } else {
            logger.info("Badge ID cannot be null");
            objResponse.put("message", "Cannot create badge. Badge ID cannot be null!");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }

    } catch (MalformedStreamException e) {
        // the stream failed to follow required syntax
        objResponse.put("message", "Cannot create badge. Failed to upload " + badgeid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

    } catch (IOException e) {
        // a read or write error occurred
        objResponse.put("message", "Cannot create badge. Failed to upload " + badgeid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot create badge. Failed to upload " + badgeid + ". " + e.getMessage());
        //L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        L2pLogger.logEvent(this, Event.AGENT_UPLOAD_FAILED, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (NullPointerException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot create badge. Failed to upload " + badgeid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

From source file:jetbrains.buildServer.commitPublisher.github.api.impl.GitHubApiImpl.java

public void postComment(@NotNull final String ownerName, @NotNull final String repoName,
        @NotNull final String hash, @NotNull final String comment) throws IOException {

    final String requestUrl = myUrls.getAddCommentUrl(ownerName, repoName, hash);
    final GSonEntity requestEntity = new GSonEntity(myGson, new IssueComment(comment));
    final HttpPost post = new HttpPost(requestUrl);
    try {/* www .  j a  v a  2  s  .  c  o  m*/
        post.setEntity(requestEntity);
        includeAuthentication(post);
        setDefaultHeaders(post);

        logRequest(post, requestEntity.getText());

        final HttpResponse execute = myClient.execute(post);
        if (execute.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_CREATED) {
            logFailedResponse(post, requestEntity.getText(), execute);
            throw new IOException("Failed to complete request to GitHub. Status: " + execute.getStatusLine());
        }
    } finally {
        post.abort();
    }
}

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

/**
 * Adds a tenant.//  ww w  .j a  va  2  s  . co  m
 *
 * @param tenantId The identifier of the tenant.
 * @param tenantSpec The information to register for the tenant.
 * @return The outcome of the operation indicating success or failure.
 * @throws NullPointerException if any of the parameters are {@code null}.
 */
public TenantResult<JsonObject> add(final String tenantId, final JsonObject tenantSpec) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(tenantSpec);

    if (tenants.containsKey(tenantId)) {
        return TenantResult.from(HttpURLConnection.HTTP_CONFLICT);
    } else {
        try {
            final TenantObject tenant = tenantSpec.mapTo(TenantObject.class);
            tenant.setTenantId(tenantId);
            final TenantObject conflictingTenant = getByCa(tenant.getTrustedCaSubjectDn());
            if (conflictingTenant != null) {
                // we are trying to use the same CA as an already existing tenant
                return TenantResult.from(HttpURLConnection.HTTP_CONFLICT);
            } else {
                tenants.put(tenantId, tenant);
                dirty = true;
                return TenantResult.from(HttpURLConnection.HTTP_CREATED);
            }
        } catch (IllegalArgumentException e) {
            return TenantResult.from(HttpURLConnection.HTTP_BAD_REQUEST);
        }
    }
}

From source file:org.apache.hadoop.fs.http.server.TestHttpFSServer.java

/**
 * Talks to the http interface to create a file.
 *
 * @param filename The file to create/* w  w w. j ava2  s .  c o m*/
 * @param perms The permission field, if any (may be null)
 * @throws Exception
 */
private void createWithHttp(String filename, String perms) throws Exception {
    String user = HadoopUsersConfTestHelper.getHadoopUsers()[0];
    // Remove leading / from filename
    if (filename.charAt(0) == '/') {
        filename = filename.substring(1);
    }
    String pathOps;
    if (perms == null) {
        pathOps = MessageFormat.format("/webhdfs/v1/{0}?user.name={1}&op=CREATE", filename, user);
    } else {
        pathOps = MessageFormat.format("/webhdfs/v1/{0}?user.name={1}&permission={2}&op=CREATE", filename, user,
                perms);
    }
    URL url = new URL(TestJettyHelper.getJettyURL(), pathOps);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("Content-Type", "application/octet-stream");
    conn.setRequestMethod("PUT");
    conn.connect();
    Assert.assertEquals(HttpURLConnection.HTTP_CREATED, conn.getResponseCode());
}

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

@Test
public void testCheckoutUntrackedFile() throws Exception {
    // clone a repo
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = getClonePath(workspaceId, project);
    clone(clonePath);/*from   www.  ja v  a2  s . c om*/

    // get project metadata
    WebRequest request = getGetRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project = new JSONObject(response.getText());

    String fileName = "new.txt";
    request = getPostFilesRequest(project.getString(ProtocolConstants.KEY_LOCATION),
            getNewFileJSON(fileName).toString(), fileName);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

    JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
    String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS);
    String gitCloneUri = getCloneUri(gitStatusUri);

    // checkout the new file
    request = getCheckoutRequest(gitCloneUri, new String[] { fileName });
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // nothing has changed, checkout doesn't touch untracked files
    assertStatus(new StatusResult().setUntrackedNames(fileName), gitStatusUri);

    // discard the new file
    request = getCheckoutRequest(gitCloneUri, new String[] { fileName }, true);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    assertStatus(StatusResult.CLEAN, gitStatusUri);
}