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:i5.las2peer.services.gamificationLevelService.GamificationLevelService.java

/**
 * Post a new level// w  w  w  .  j  a v  a  2 s  .c  o m
 * @param appId applicationId
 * @param formData form data
 * @param contentType content type
 * @return HttpResponse with the returnString
 */
@POST
@Path("/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "{\"status\": 3, \"message\": \"Level upload success ( (levelnum) )\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (levelnum)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the level. levelnum already exist!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Level number cannot be null!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"File content null. Failed to upload (levelnum)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"Failed to upload (levelnum)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "{\"status\": 3, \"message\": \"Level upload success ( (levelnum) )}") })
@ApiOperation(value = "createLevel", notes = "A method to store a new level with details (Level number, level name, level point value, level point id)")
public HttpResponse createLevel(
        @ApiParam(value = "Application ID to store a new level", required = true) @PathParam("appId") String appId,
        @ApiParam(value = "Content-type in header", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
        @ApiParam(value = "Level detail in multiple/form-data type", required = true) @ContentParam byte[] formData) {

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

    // parse given multipart form data
    JSONObject objResponse = new JSONObject();
    int levelnum = 0;
    String levelname = null;
    int levelpointvalue = 0;

    boolean levelnotifcheck = false;
    String levelnotifmessage = 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 (!levelAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot create level. 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();
            objResponse.put("message",
                    "Cannot create level. 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 partNum = parts.get("levelnum");
        if (partNum != null) {
            levelnum = Integer.parseInt(partNum.getContent());
            if (levelAccess.isLevelNumExist(conn, appId, levelnum)) {
                // level id already exist
                objResponse.put("message",
                        "Cannot create level. Failed to add the level. levelnum already exist!");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

            }
            FormDataPart partName = parts.get("levelname");
            if (partName != null) {
                levelname = partName.getContent();
            }

            FormDataPart partPV = parts.get("levelpointvalue");
            if (partPV != null) {
                // optional description text input form element
                levelpointvalue = Integer.parseInt(partPV.getContent());
            }
            FormDataPart partNotificationCheck = parts.get("levelnotificationcheck");
            if (partNotificationCheck != null) {
                // checkbox is checked
                levelnotifcheck = true;

            } else {
                levelnotifcheck = false;
            }
            FormDataPart partNotificationMsg = parts.get("levelnotificationmessage");
            if (partNotificationMsg != null) {
                levelnotifmessage = partNotificationMsg.getContent();
            } else {
                levelnotifmessage = "";
            }
            LevelModel model = new LevelModel(levelnum, levelname, levelpointvalue, levelnotifcheck,
                    levelnotifmessage);

            try {
                levelAccess.addNewLevel(conn, appId, model);
                objResponse.put("message", "Level upload success (" + levelnum + ")");
                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 level. Failed to upload " + levelnum + ". " + e.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        } else {
            objResponse.put("message", "Cannot create level. Level number 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 level. Failed to upload. " + levelnum + 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 level. Failed to upload " + levelnum + ". " + 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 level. Failed to upload " + levelnum + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (NullPointerException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot create level. Failed to upload " + levelnum + ". " + 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:com.trafficspaces.api.controller.Connector.java

public String sendRequest(String path, String contentType, String method, String data)
        throws IOException, TrafficspacesAPIException {

    URL url = new URL(endPoint.baseURI + path);

    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);//from   www .j a  v a2 s  .co  m
    httpCon.setRequestMethod(method.toUpperCase());

    String basicAuth = "Basic " + Base64.encodeBytes((endPoint.username + ":" + endPoint.password).getBytes());
    httpCon.setRequestProperty("Authorization", basicAuth);

    httpCon.setRequestProperty("Content-Type", contentType + "; charset=UTF-8");
    httpCon.setRequestProperty("Accept", contentType);

    if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) {
        httpCon.setRequestProperty("Content-Length", String.valueOf(data.length()));
        OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
        out.write(data);
        out.close();
    } else {
        httpCon.connect();
    }

    char[] responseData = null;
    try {
        responseData = readResponseData(httpCon.getInputStream(), "UTF-8");
    } catch (FileNotFoundException fnfe) {
        // HTTP 404. Ignore and return null
    }
    String responseDataString = null;
    if (responseData != null) {
        int responseCode = httpCon.getResponseCode();
        String redirectURL = null;
        if ((responseCode == HttpURLConnection.HTTP_MOVED_PERM
                || responseCode == HttpURLConnection.HTTP_MOVED_PERM
                || responseCode == HttpURLConnection.HTTP_CREATED)
                && (redirectURL = httpCon.getHeaderField("Location")) != null) {
            //System.out.println("Response code = " +responseCode + ". Redirecting to " + redirectURL);
            return sendRequest(redirectURL, contentType);
        }
        if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_CREATED) {
            throw new TrafficspacesAPIException(
                    "HTTP Error: " + responseCode + "; Data: " + new String(responseData));
        }
        //System.out.println("Headers: " + httpCon.getHeaderFields());
        //System.out.println("Data: " + new String(responseData));
        responseDataString = new String(responseData);
    }
    return responseDataString;
}

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

@Test
public void testAddSelected() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());

    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), gitDir.toString());

    // get project/folder 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());

    request = getPostFilesRequest(project.getString(ProtocolConstants.KEY_LOCATION),
            getNewFileJSON("added.txt").toString(), "added.txt");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    JSONObject addedTxt = getChild(project, "added.txt");

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

    JSONObject testTxt = getChild(project, "test.txt");
    modifyFile(testTxt, "testAddSelected");
    JSONObject folder = getChild(project, "folder");
    JSONObject folderTxt = getChild(folder, "folder.txt");
    modifyFile(folderTxt, "testAddSelected");

    // add 2 of 4
    addFile(testTxt, addedTxt);//from w w w.  jav a  2  s.  c  o  m

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

    assertStatus(new StatusResult().setChangedNames("test.txt").setModifiedNames("folder/folder.txt")
            .setAddedNames("added.txt").setUntrackedNames("untracked.txt"), gitStatusUri);
}

From source file:org.eclipse.hono.client.impl.RegistrationClientImpl.java

/**
 * Invokes the <em>Register Device</em> operation of Hono's
 * <a href="https://www.eclipse.org/hono/api/Device-Registration-API">Device Registration API</a>
 * on the service represented by the <em>sender</em> and <em>receiver</em> links.
 *///from  w  ww. j  ava 2  s . co m
@Override
public final Future<Void> register(final String deviceId, final JsonObject data) {

    Objects.requireNonNull(deviceId);

    final Future<RegistrationResult> regResultTracker = Future.future();
    createAndSendRequest(RegistrationConstants.ACTION_REGISTER, createDeviceIdProperties(deviceId), data,
            regResultTracker.completer());
    return regResultTracker.map(response -> {
        switch (response.getStatus()) {
        case HttpURLConnection.HTTP_CREATED:
            return null;
        default:
            throw StatusCodeMapper.from(response);
        }
    });
}

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

@Test
public void testCreateDirectory() throws CoreException, IOException, SAXException, JSONException {
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);//  ww w . ja  va  2s .com

    String dirName = "testdir";
    webConversation.setExceptionsThrownOnErrorStatus(false);

    WebRequest request = getPostFilesRequest(directoryPath, getNewDirJSON(dirName).toString(), dirName);
    WebResponse response = webConversation.getResponse(request);

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

    //should be able to perform GET on location header to obtain metadata
    String location = response.getHeaderField(ProtocolConstants.HEADER_LOCATION);
    request = getGetRequest(location);
    response = webConversation.getResource(request);
    assertNotNull(location);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    responseObject = new JSONObject(response.getText());
    assertNotNull("No direcory information in response", responseObject);
    checkDirectoryMetadata(responseObject, dirName, null, null, null, null, null);

}

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

@Test
public void testGitUrisForRepositoryClonedIntoSubfolder() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());

    String workspaceId = workspaceIdFromLocation(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    String folderName = "subfolder";
    WebRequest request = getPostFilesRequest("", getNewDirJSON(folderName).toString(), folderName);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    IPath clonePath = getClonePath(workspaceId, project).append(folderName).makeAbsolute();
    clone(clonePath);/*from  w w  w .  j av a 2  s  . c  o m*/

    String location = project.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
    request = getGetRequest(location);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject responseJSON = new JSONObject(response.getText());

    // no Git section for /file/{projectId}
    assertNull(responseJSON.optString(GitConstants.KEY_STATUS, null));
    assertNull(responseJSON.optString(GitConstants.KEY_DIFF, null));
    assertNull(responseJSON.optString(GitConstants.KEY_DIFF, null));
    assertNull(responseJSON.optString(GitConstants.KEY_COMMIT, null));
    assertNull(responseJSON.optString(GitConstants.KEY_REMOTE, null));
    assertNull(responseJSON.optString(GitConstants.KEY_TAG, null));
    assertNull(responseJSON.optString(GitConstants.KEY_CLONE, null));

    request = getGetRequest(responseJSON.getString(ProtocolConstants.KEY_CHILDREN_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText()));
    assertEquals(1, children.size());

    // expected Git section for /file/{projectId}/?depth=1
    assertGitSectionExists(children.get(0));
    JSONObject gitSection = children.get(0).getJSONObject(GitConstants.KEY_GIT);
    assertCloneUri(gitSection.optString(GitConstants.KEY_CLONE, null));

    location = children.get(0).getString(ProtocolConstants.KEY_LOCATION);
    request = getGetRequest(location);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    responseJSON = new JSONObject(response.getText());

    // expected Git section for /file/{projectId}/subfolder
    assertGitSectionExists(responseJSON);
    gitSection = responseJSON.getJSONObject(GitConstants.KEY_GIT);
    assertCloneUri(gitSection.optString(GitConstants.KEY_CLONE, null));
}

From source file:com.upnext.blekit.util.http.HttpClient.java

public <T> Response<T> fetchResponse(Class<T> clazz, String path, Map<String, String> params, String httpMethod,
        String payload, String payloadContentType) {
    try {/* w w  w . j  ava2  s.  co m*/
        String fullUrl = urlWithParams(path != null ? url + path : url, params);
        L.d("[" + httpMethod + "] " + fullUrl);
        final URLConnection connection = new URL(fullUrl).openConnection();
        if (connection instanceof HttpURLConnection) {
            final HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setDoInput(true);
            if (httpMethod != null) {
                httpConnection.setRequestMethod(httpMethod);
                if (httpMethod.equals("POST")) {
                    connection.setDoOutput(true); // Triggers POST.
                    connection.setRequestProperty("Accept-Charset", "UTF-8");
                    connection.setRequestProperty("Content-Type", payloadContentType);
                }
            } else {
                httpConnection.setRequestMethod(params != null ? "POST" : "GET");
            }
            httpConnection.addRequestProperty("Accept", "application/json");
            httpConnection.connect();
            if (payload != null) {
                OutputStream outputStream = httpConnection.getOutputStream();
                try {
                    if (LOG_RESPONSE) {
                        L.d("[payload] " + payload);
                    }
                    OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
                    writer.write(payload);
                    writer.close();
                } finally {
                    outputStream.close();
                }
            }
            InputStream input = null;
            try {
                input = connection.getInputStream();
            } catch (IOException e) {
                // workaround for Android HttpURLConnection ( IOException is thrown for 40x error codes ).
                final int statusCode = httpConnection.getResponseCode();
                if (statusCode == -1)
                    throw e;
                return new Response<T>(Error.httpError(httpConnection.getResponseCode()));
            }
            final int statusCode = httpConnection.getResponseCode();
            L.d("statusCode " + statusCode);
            if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) {
                try {
                    T value = null;
                    if (clazz != Void.class) {
                        if (LOG_RESPONSE || clazz == String.class) {
                            StringBuilder sb = new StringBuilder();
                            BufferedReader br = new BufferedReader(new InputStreamReader(input));
                            String read = br.readLine();
                            while (read != null) {
                                sb.append(read);
                                read = br.readLine();
                            }
                            String response = sb.toString();
                            if (LOG_RESPONSE) {
                                L.d("response " + response);
                            }
                            if (clazz == String.class) {
                                value = (T) response;
                            } else {
                                value = (T) objectMapper.readValue(response, clazz);
                            }
                        } else {
                            value = (T) objectMapper.readValue(input, clazz);
                        }
                    }
                    return new Response<T>(value);
                } catch (JsonMappingException e) {
                    return new Response<T>(Error.serlizerError(e));
                } catch (JsonParseException e) {
                    return new Response<T>(Error.serlizerError(e));
                }
            } else if (statusCode == HttpURLConnection.HTTP_NO_CONTENT) {
                try {
                    T def = clazz.newInstance();
                    if (LOG_RESPONSE) {
                        L.d("statusCode  == HttpURLConnection.HTTP_NO_CONTENT");
                    }
                    return new Response<T>(def);
                } catch (InstantiationException e) {
                    return new Response<T>(Error.ioError(e));
                } catch (IllegalAccessException e) {
                    return new Response<T>(Error.ioError(e));
                }
            } else {
                if (LOG_RESPONSE) {
                    L.d("error, statusCode " + statusCode);
                }
                return new Response<T>(Error.httpError(statusCode));
            }
        }
        return new Response<T>(Error.ioError(new Exception("Url is not a http link")));
    } catch (IOException e) {
        if (LOG_RESPONSE) {
            L.d("error, ioError " + e);
        }
        return new Response<T>(Error.ioError(e));
    }
}

From source file:es.tekniker.framework.ktek.questionnaire.mng.server.EventServiceClient.java

public String queryContext(String codUser) {
    String strJSON = null;/*from  www  .  j  a v a2s .  com*/
    HttpURLConnection conn = null;
    StringBuffer strBOutput = new StringBuffer();
    boolean boolOK = true;
    String input = null;
    StringBuffer stbInput = new StringBuffer();

    try {
        log.debug("queryContext Start ");

        conn = getEventServiceSEConnection(methodQueryContext, endpointEventService, headerContentTypeJSON);

        stbInput.append("{\"entities\": [ {\"type\": \"" + typeContextValue
                + "\", \"isPattern\": \"false\", \"id\": \"" + codUser + "\"}]}");

        input = stbInput.toString();
        log.debug(input);

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() == 200) {
            log.debug("queryContext Response code " + conn.getResponseCode());
        } else {
            if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
            }
        }

        log.debug("queryContext OutputStream wrote");

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

        log.debug("queryContext Waiting server response ");

        String output;
        log.debug("queryContext Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            strBOutput.append(output);
            log.debug(output);
        }

        conn.disconnect();

        strJSON = strBOutput.toString();

        boolOK = true;

    } catch (MalformedURLException e) {
        log.error("queryContext MalformedURLException " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        log.error("queryContext IOException " + e.getMessage());
        e.printStackTrace();
    }

    return strJSON;
}

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

@Test
public void testResetMixedAll() 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 w  w . jav  a  2 s  . c  o  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 --mixed HEAD"
        request = getPostGitIndexRequest(gitIndexUri /* reset all */, ResetType.MIXED);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // "git status", should be the same result as called for the first time
        assertStatus(new StatusResult().setMissing(1).setModified(1).setUntracked(1), gitStatusUri);
    }
}

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

protected JSONObject createProjectOrLink(URI workspaceLocation, String projectName, String contentLocation)
        throws JSONException, IOException, SAXException {
    JSONObject body = new JSONObject();
    if (contentLocation != null) {
        body.put(ProtocolConstants.KEY_CONTENT_LOCATION, contentLocation);
        ServletTestingSupport.allowedPrefixes = contentLocation;
    }//w w w . j  av  a  2  s  . co m
    WebRequest request = new PostMethodWebRequest(workspaceLocation.toString(),
            IOUtilities.toInputStream(body.toString()), "UTF-8");
    if (projectName != null)
        request.setHeaderField(ProtocolConstants.HEADER_SLUG, projectName);
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    setAuthentication(request);
    WebResponse response = webConversation.getResponse(request);
    if (response.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
        String msg = response.getText();
        LogHelper
                .log(new org.eclipse.core.runtime.Status(IStatus.ERROR, "org.eclipse.orion.server.tests", msg));
        assertTrue("Unexpected failure cloning: " + msg, false);
    }
    JSONObject project = new JSONObject(response.getText());
    assertEquals(projectName, project.getString(ProtocolConstants.KEY_NAME));
    String projectId = project.optString(ProtocolConstants.KEY_ID, null);
    assertNotNull(projectId);
    IPath workspacePath = new Path(workspaceLocation.getPath());
    String workspaceId = workspacePath.segment(workspacePath.segmentCount() - 1);
    testProjectBaseLocation = "/" + workspaceId + '/' + projectName;
    testProjectLocalFileLocation = "/" + project.optString(ProtocolConstants.KEY_ID, null);
    return project;
}