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.metastore.RemoteMetaStoreTests.java

/**
 * Create additional users, workspaces and projects to test migration.
 * /*from  w  ww.  j ava2  s.c o  m*/
 * @throws IOException
 * @throws URISyntaxException
 * @throws JSONException
 * @throws SAXException 
 */
@Test
public void testZCreateMigrationContent() throws IOException, URISyntaxException, JSONException, SAXException {
    // a user with no workspace or projects
    String none = "n" + getOrionTestName();
    WebConversation webConversation = new WebConversation();
    assertEquals(HttpURLConnection.HTTP_OK, createUser(webConversation, none, none));

    // a user with no projects
    String noprojects = "np" + getOrionTestName();
    webConversation = new WebConversation();
    assertEquals(HttpURLConnection.HTTP_OK, createUser(webConversation, noprojects, noprojects));
    assertEquals(HttpURLConnection.HTTP_OK, createWorkspace(webConversation, noprojects, noprojects));

    // a user with two projects
    String twoprojects = "tp" + getOrionTestName();
    webConversation = new WebConversation();
    assertEquals(HttpURLConnection.HTTP_OK, createUser(webConversation, twoprojects, twoprojects));
    assertEquals(HttpURLConnection.HTTP_OK, createWorkspace(webConversation, twoprojects, twoprojects));
    assertEquals(HttpURLConnection.HTTP_CREATED,
            createProject(webConversation, twoprojects, twoprojects, "Project One"));
    assertEquals(HttpURLConnection.HTTP_CREATED,
            createFolder(webConversation, twoprojects, twoprojects, "Project One"));
    assertEquals(HttpURLConnection.HTTP_OK,
            createFile(webConversation, twoprojects, twoprojects, "Project One"));
    assertEquals(HttpURLConnection.HTTP_CREATED,
            createProject(webConversation, twoprojects, twoprojects, "Project Two"));
    assertEquals(HttpURLConnection.HTTP_CREATED,
            createFolder(webConversation, twoprojects, twoprojects, "Project Two"));
    assertEquals(HttpURLConnection.HTTP_OK,
            createFile(webConversation, twoprojects, twoprojects, "Project Two"));

    // a user with a project with two sites
    String twosites = "ts" + getOrionTestName();
    webConversation = new WebConversation();
    assertEquals(HttpURLConnection.HTTP_OK, createUser(webConversation, twosites, twosites));
    assertEquals(HttpURLConnection.HTTP_OK, createWorkspace(webConversation, twosites, twosites));
    assertEquals(HttpURLConnection.HTTP_CREATED, createProject(webConversation, twosites, twosites, "Project"));
    assertEquals(HttpURLConnection.HTTP_CREATED, createSite(webConversation, twosites, twosites, "Site One"));
    assertEquals(HttpURLConnection.HTTP_CREATED, createSite(webConversation, twosites, twosites, "Site Two"));
}

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

@Test
public void testMoveFileNoOverwrite() throws Exception {
    String directoryPath = "testMoveFile/directory/path" + System.currentTimeMillis();
    String sourcePath = directoryPath + "/source.txt";
    String destName = "destination.txt";
    String destPath = directoryPath + "/" + destName;
    createDirectory(directoryPath);//www  . j  a va 2 s. c  o m
    createFile(sourcePath, "This is the contents");
    JSONObject requestObject = new JSONObject();
    addSourceLocation(requestObject, sourcePath);
    WebRequest request = getPostFilesRequest(directoryPath, requestObject.toString(), "destination.txt");
    request.setHeaderField("X-Create-Options", "move");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    JSONObject responseObject = new JSONObject(response.getText());
    checkFileMetadata(responseObject, destName, null, null, null, null, null, null, null, null);
    assertFalse(checkFileExists(sourcePath));
    assertTrue(checkFileExists(destPath));
}

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

@Test
public void testImportAndUnzipWithOverride() throws CoreException, IOException, SAXException {
    //create a directory to upload to
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    String filePath = "/org.eclipse.e4.webide/static/js/navigate-tree";
    createDirectory(directoryPath + filePath);
    //create a file that is to be overwritten
    String fileContents = "This is the file contents";
    createFile(directoryPath + filePath + "/navigate-tree.js", fileContents);
    //start the import
    URL entry = ServerTestsActivator.getContext().getBundle().getEntry("testData/importTest/client.zip");
    File source = new File(FileLocator.toFileURL(entry).getPath());
    long length = source.length();
    InputStream in = new BufferedInputStream(new FileInputStream(source));
    PostMethodWebRequest request = new PostMethodWebRequest(getImportRequestPath(directoryPath), in,
            "application/zip");
    request.setHeaderField("Content-Length", "" + length);
    request.setHeaderField("Content-Type", "application/octet-stream");
    request.setHeaderField("Slug", "client.zip");
    request.setHeaderField("X-Xfer-Options", "overwrite-older");
    setAuthentication(request);//  www  . j a v  a  2s .c o  m
    WebResponse postResponse = webConversation.getResponse(request);
    //assert the server accepts the override
    assertEquals(HttpURLConnection.HTTP_CREATED, postResponse.getResponseCode());
    String location = postResponse.getHeaderField("Location");
    assertNotNull(location);
    String type = postResponse.getHeaderField("Content-Type");
    assertNotNull(type);
    //assert the unzip still occurred in the workspace
    assertTrue(checkFileExists(
            directoryPath + "/org.eclipse.e4.webide/static/images/unit_test/add-test-config.png"));
    //assert that imported file was overwritten
    assertFalse(checkContentEquals(createTempFile("expectedFile", fileContents),
            directoryPath + filePath + "/navigate-tree.js"));
}

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

@Test
public void testGetOthersClones() throws Exception {
    // my clone/*from   w  w w . j a  v a 2  s . c  om*/
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = getWorkspaceId(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    clone(workspaceId, project);

    JSONArray clonesArray = listClones(workspaceId, null);
    assertEquals(1, clonesArray.length());

    createUser("bob", "bob");
    // URI bobWorkspaceLocation = createWorkspace(getMethodName() + "bob");
    String workspaceName = getClass().getName() + "#" + getMethodName() + "bob";
    WebRequest request = new PostMethodWebRequest(SERVER_LOCATION + "/workspace");
    request.setHeaderField(ProtocolConstants.HEADER_SLUG, workspaceName);
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    setAuthentication(request, "bob", "bob");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    URI bobWorkspaceLocation = SERVER_URI.resolve(response.getHeaderField(ProtocolConstants.HEADER_LOCATION));
    String bobWorkspaceId = workspaceIdFromLocation(bobWorkspaceLocation);

    // String bobWorkspaceId = getWorkspaceId(bobWorkspaceLocation);
    request = new GetMethodWebRequest(bobWorkspaceLocation.toString());
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    setAuthentication(request, "bob", "bob");
    response = webConversation.getResponse(request);

    // JSONObject bobProject = createProjectOrLink(bobWorkspaceLocation, getMethodName() + "bob", null);
    JSONObject body = new JSONObject();
    request = new PostMethodWebRequest(bobWorkspaceLocation.toString(),
            IOUtilities.toInputStream(body.toString()), "UTF-8");
    request.setHeaderField(ProtocolConstants.HEADER_SLUG, getMethodName() + "bob");
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    setAuthentication(request, "bob", "bob");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    JSONObject bobProject = new JSONObject(response.getText());
    assertEquals(getMethodName() + "bob", bobProject.getString(ProtocolConstants.KEY_NAME));
    String bobProjectId = bobProject.optString(ProtocolConstants.KEY_ID, null);
    assertNotNull(bobProjectId);

    IPath bobClonePath = getClonePath(bobWorkspaceId, bobProject);

    // bob's clone
    URIish uri = new URIish(gitDir.toURI().toURL());
    request = getPostGitCloneRequest(uri, null, bobClonePath, null, null, null);
    setAuthentication(request, "bob", "bob");
    response = webConversation.getResponse(request);
    ServerStatus status = waitForTask(response, "bob", "bob");
    String cloneLocation = status.getJsonData().getString(ProtocolConstants.KEY_LOCATION);
    assertNotNull(cloneLocation);

    // validate the clone metadata
    request = getGetRequest(cloneLocation);
    setAuthentication(request, "bob", "bob");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // list my clones again
    clonesArray = listClones(workspaceId, null);
    assertEquals(1, clonesArray.length()); // nothing has been added

    // try to get Bob's clone
    request = getGetRequest(cloneLocation);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());
}

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

@Test
public void testWriteFile() throws CoreException, IOException, SAXException, JSONException {
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);//from  www  . j ava2s . c  o m
    String fileName = "testfile.txt";

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

    //put to file location should succeed
    String location = response.getHeaderField("Location");
    String fileContent = "New contents";
    request = getPutFileRequest(location, fileContent);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    //get should return new contents
    request = getGetRequest(location);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals("Invalid file content", fileContent, response.getText());
}

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

protected WebResponse branch(String branchesLocation, String branchName, String startPoint)
        throws IOException, JSONException, SAXException {
    assertBranchUri(branchesLocation);//  w w  w.  j a  va  2 s. c  om
    WebRequest request = getPostGitBranchRequest(branchesLocation, branchName, startPoint);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    return response;
}

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

@Test
public void testWriteFileFromURL() throws CoreException, IOException, SAXException, JSONException {
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);//from  w w w  . j av  a2 s  .c o m
    String fileName = "testfile.txt";

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

    //put to file location should succeed
    String location = response.getHeaderField("Location");
    //just need some stable file here
    request = getPutFileRequest(
            location + "?source=http://eclipse.org/eclipse/project-info/home-page-one-liner.html", "");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    //get should return new contents
    request = getGetRequest(location);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals("Invalid file content", "<a href=\"/eclipse/\">Eclipse Project</a>", response.getText());
}

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

@Test
public void testWriteImageFromURL() throws CoreException, IOException, SAXException, JSONException {
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);//from w w  w .  j  ava 2  s. com
    String fileName = "testfile.gif";

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

    //put to file location should succeed
    String location = response.getHeaderField("Location");
    //just need some stable file here
    request = getPutFileRequest(location + "?source=http://eclipse.org/eclipse/development/images/Adarrow.gif",
            "");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    //get should return new contents
    request = getGetRequest(location);
    response = webConversation.getResponse(request);
    assertEquals("image/gif", response.getHeaderField("CONTENT-TYPE"));
    assertEquals("857", response.getHeaderField("CONTENT-LENGTH"));
}

From source file:org.wso2.carbon.registry.app.RegistryAdapter.java

/**
 * Method to post a feed.//w  ww . java2s  . c o  m
 *
 * @param request the request context.
 *
 * @return the response context.
 */
public ResponseContext postFeed(RequestContext request) {
    Document<Feed> doc;
    try {
        doc = request.getDocument();
    } catch (IOException e) {
        return new StackTraceResponseContext(e);
    }
    Feed feed = doc.getRoot();
    String slug = request.getSlug();
    if (slug == null) {
        slug = feed.getTitle();
    }

    // Following code replaces spaces with "_". Commenting out Sanitizer.sanitize and doing the same thing other
    // replacing spaces with "_". 
    // slug = Sanitizer.sanitize(slug, "-", SANITIZE_PATTERN);
    slug = slug.replaceAll(SANITIZE_PATTERN, "-");

    String parentPath = ((ResourceTarget) request.getTarget()).getResource().getPath();
    if (!parentPath.endsWith(RegistryConstants.PATH_SEPARATOR)) {
        parentPath += RegistryConstants.PATH_SEPARATOR;
    }
    String path = parentPath + slug;
    String real;
    try {
        final Registry registry = getSecureRegistry(request);
        Collection resource = registry.newCollection();
        org.wso2.carbon.registry.app.Properties properties = feed
                .getExtension(PropertyExtensionFactory.PROPERTIES);
        RemoteRegistry.createPropertiesFromExtensionElement(properties, resource);
        resource.setDescription(feed.getSubtitle());
        if (feed.getSimpleExtension(
                new QName(APPConstants.NAMESPACE, APPConstants.NAMESPACE_MEDIA_TYPE)) != null) {
            resource.setMediaType(feed
                    .getSimpleExtension(new QName(APPConstants.NAMESPACE, APPConstants.NAMESPACE_MEDIA_TYPE)));
        }
        if (feed.getSimpleExtension(APPConstants.QN_UUID_TYPE) != null) {
            resource.setUUID(feed.getSimpleExtension(APPConstants.QN_UUID_TYPE));
        }
        real = registry.put(path, resource);
    } catch (RegistryException e) {
        return new StackTraceResponseContext(e);
    }
    StringResponseContext responseContext = new StringResponseContext("Feed created at " + real,
            HttpURLConnection.HTTP_CREATED);
    Map<String, String> map = new HashMap<String, String>();
    map.put("collection", real.substring(1));
    try {
        responseContext.setLocation(URLDecoder.decode(request.absoluteUrlFor(TargetType.TYPE_COLLECTION, map),
                RegistryConstants.DEFAULT_CHARSET_ENCODING).replaceAll(" ", "+"));
    } catch (UnsupportedEncodingException e) {
        log.error("The encoding is not supported.", e);
    }
    return responseContext;
}

From source file:org.openecomp.sdnc.sli.aai.AAIService.java

@Override
public boolean postPInterfaceData(String hostname, String interfaceName, PInterface request)
        throws AAIServiceException {
    InputStream inputStream = null;

    try {/* w w w.  j  a v  a  2s  .c o  m*/

        ObjectMapper mapper = getObjectMapper();
        String json_text = mapper.writeValueAsString(request);

        SSLSocketFactory sockFact = CTX.getSocketFactory();

        String request_url = target_uri + p_interface_path;
        String encoded_vnf = encodeQuery(hostname);
        request_url = request_url.replace("{hostname}", encoded_vnf);
        encoded_vnf = encodeQuery(interfaceName);
        request_url = request_url.replace("{interface-name}", encoded_vnf);
        URL http_req_url = new URL(request_url);

        HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);

        OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
        osw.write(json_text);
        osw.flush();
        osw.close();

        LOGwriteFirstTrace("PUT", request_url);
        LOGwriteDateTrace("hostname", hostname);
        LOGwriteDateTrace("interface-name", interfaceName);
        LOGwriteDateTrace("PInterface", json_text);

        // Check for errors
        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED
                || responseCode == HttpURLConnection.HTTP_ACCEPTED
                || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            inputStream = con.getInputStream();
        } else {
            inputStream = con.getErrorStream();
        }

        // Process the response
        BufferedReader reader;
        String line = null;
        reader = new BufferedReader(new InputStreamReader(inputStream));

        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED
                || responseCode == HttpURLConnection.HTTP_ACCEPTED
                || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            StringBuilder stringBuilder = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            LOGwriteEndingTrace(responseCode, "SUCCESS",
                    (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
            return true;
        } else {
            ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
            LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));

            throw new AAIServiceException(responseCode, errorresponse);
        }
    } catch (AAIServiceException aaiexc) {
        throw aaiexc;
    } catch (Exception exc) {
        LOG.warn("postPInterfaceData", exc);
        throw new AAIServiceException(exc);
    } finally {
        try {
            if (inputStream != null)
                inputStream.close();
        } catch (Exception exc) {

        }
    }
}