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.site.HostingTest.java

@Test
// Test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=382760 
public void testDisallowedSiteAccess()
        throws SAXException, IOException, JSONException, URISyntaxException, CoreException {
    User userBObject = createUser("userB", "userB");
    String userB = userBObject.getLogin();

    // User "test": create file in test's workspace
    final String filename = "foo.html";
    final String fileContent = "<html><body>This is a test file</body></html>";
    WebResponse createdFile = createFileOnServer("", filename, fileContent);
    URL fileLocation = createdFile.getURL();
    IPath filepath = new Path(fileLocation.getPath());
    filepath = filepath.removeFirstSegments(new Path(FILE_SERVLET_LOCATION).segmentCount()); // chop off leading /file/
    filepath = filepath.removeLastSegments(1); // chop off trailing /foo.html
    filepath = filepath.makeAbsolute();//from   ww w  .  ja  v  a  2  s.co m
    filepath = filepath.addTrailingSeparator();
    String parentFolder = filepath.toString();

    // User B: Create a workspace that User B has access to
    WebResponse createWorkspaceResp = basicCreateWorkspace("userB");
    String bWorkspaceId = new JSONObject(createWorkspaceResp.getText()).getString(ProtocolConstants.KEY_ID);
    AuthorizationService.addUserRight(userBObject.getUid(), createWorkspaceResp.getURL().getPath());
    AuthorizationService.addUserRight(userBObject.getUid(), createWorkspaceResp.getURL().getPath() + "/*");

    // User B: create a site against B's workspace that exposes a file in test's workspace
    final String siteName = "My hosted site";
    final String filePath = parentFolder; //"/" + filename;
    final String mountAt = "/"; //"/file.html";
    final JSONArray mappings = makeMappings(new String[][] { { mountAt, filePath } });

    WebRequest createSiteReq = getCreateSiteRequest(siteName, bWorkspaceId, mappings, null);
    setAuthentication(createSiteReq, userB, userB);
    WebResponse createSiteResp = webConversation.getResponse(createSiteReq);
    assertEquals(HttpURLConnection.HTTP_CREATED, createSiteResp.getResponseCode());
    JSONObject siteObject = new JSONObject(createSiteResp.getText());

    // User B: Start the site
    String location = siteObject.getString(ProtocolConstants.HEADER_LOCATION);
    siteObject = startSite(location, userB, userB);

    final JSONObject hostingStatus = siteObject.getJSONObject(SiteConfigurationConstants.KEY_HOSTING_STATUS);
    final String hostedURL = hostingStatus.getString(SiteConfigurationConstants.KEY_HOSTING_STATUS_URL);

    // Attempt to access file on user B's site, should fail
    WebRequest getFileReq = new GetMethodWebRequest(hostedURL + mountAt);
    WebResponse getFileResp = webConversation.getResponse(getFileReq);
    assertEquals(HttpURLConnection.HTTP_FORBIDDEN, getFileResp.getResponseCode());
}

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

/**
 * Create a workspace on the Orion server for the test user.
 * /*www.j av a2s  .c o  m*/
 * @param webConversation
 * @param login
 * @param password
 * @param site
 * @return
 * @throws URISyntaxException
 * @throws IOException
 * @throws JSONException
 * @throws SAXException 
 */
protected int createSite(WebConversation webConversation, String login, String password, String site)
        throws URISyntaxException, IOException, JSONException, SAXException {
    assertEquals(HttpURLConnection.HTTP_OK, login(webConversation, login, password));

    JSONObject json = new JSONObject();
    json.put(SiteConfigurationConstants.KEY_WORKSPACE, getWorkspaceId(login));
    json.put(ProtocolConstants.KEY_NAME, site);
    json.put(SiteConfigurationConstants.KEY_HOST_HINT, site.toLowerCase().replaceAll(" ", "-"));
    WebRequest request = new PostMethodWebRequest(getOrionServerURI("/site"),
            IOUtilities.toInputStream(json.toString()), "application/json");
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

    JSONObject jsonObject = new JSONObject(response.getText());
    String location = jsonObject.getString("Location");
    String name = jsonObject.getString("Name");
    System.out.println("Created Site: " + name + " at Location: " + location);
    return response.getResponseCode();
}

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

public boolean getAccessToken() {
    HttpURLConnection conn = null;
    StringBuffer strBOutput = new StringBuffer();
    boolean boolOK = true;
    String input = null;//  www . j  a  v a2 s  .  c  o  m
    StringBuffer stbInput = new StringBuffer();

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

        conn = getEventServiceSEConnection(methodAccessToken, endpointOauth, headerContentTypeFormUrlencoded);

        stbInput.append(
                "client_id=522a3819dc268f33c983&client_secret=169d587f10e75316501483280d0c4843c3333144&grant_type=password&username=ktekQuser&password=F20st67R&scope=write");

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

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

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

        log.debug("getAccessToken OutputStream wrote");

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

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

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

        conn.disconnect();

        boolOK = true;

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

    return boolOK;
}

From source file:it.geosolutions.geonetwork.util.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>/* www. j a  va 2s .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.
 */
protected String send(final EntityEnclosingMethod httpMethod, String url, RequestEntity requestEntity) {

    try {
        setAuth(client, url, username, pw);

        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        if (requestEntity != null)
            httpMethod.setRequestEntity(requestEntity);

        lastHttpStatus = client.executeMethod(httpMethod);

        switch (lastHttpStatus) {
        case HttpURLConnection.HTTP_OK:
        case HttpURLConnection.HTTP_CREATED:
        case HttpURLConnection.HTTP_ACCEPTED:
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("HTTP " + httpMethod.getStatusText() + " <-- " + url);
            if (ignoreResponseContentOnSuccess)
                return "";
            String response = IOUtils.toString(httpMethod.getResponseBodyAsStream());
            return response;
        default:
            String badresponse = IOUtils.toString(httpMethod.getResponseBodyAsStream());
            String message = getGeoNetworkErrorMessage(badresponse);

            LOGGER.warn("Bad response: " + lastHttpStatus + " " + httpMethod.getStatusText() + " -- "
                    + httpMethod.getName() + " " + url + " : " + message);
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("GeoNetwork response:\n" + badresponse);
            return null;
        }
    } catch (ConnectException e) {
        LOGGER.info("Couldn't connect to [" + url + "]");
        return null;
    } catch (IOException e) {
        LOGGER.error("Error talking to " + url + " : " + e.getLocalizedMessage());
        return null;
    } finally {
        if (httpMethod != null)
            httpMethod.releaseConnection();
    }
}

From source file:com.aptana.jira.core.JiraManager.java

/**
 * Adds an attachment to a JIRA ticket.//from  ww  w  . j  a  va 2  s . c  o  m
 * 
 * @param path
 *            the path of the file to be attached
 * @param issue
 *            the JIRA ticket
 * @throws JiraException
 */
public void addAttachment(IPath path, JiraIssue issue) throws JiraException {
    if (path == null || issue == null) {
        return;
    }
    if (user == null) {
        throw new JiraException(Messages.JiraManager_ERR_NotLoggedIn);
    }

    // Use Apache HTTPClient to POST the file
    HttpClient httpclient = new HttpClient();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user.getUsername(), user.getPassword());
    httpclient.getState().setCredentials(new AuthScope(HOST_NAME, 443), creds);
    httpclient.getParams().setAuthenticationPreemptive(true);
    PostMethod filePost = null;
    try {
        filePost = new PostMethod(createAttachmentURL(issue));
        File file = path.toFile();
        // MUST USE "file" AS THE NAME!!!
        Part[] parts = { new FilePart("file", file) }; //$NON-NLS-1$
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        filePost.setContentChunked(true);
        filePost.setDoAuthentication(true);
        // Special header to tell JIRA not to do XSFR checking
        filePost.setRequestHeader("X-Atlassian-Token", "nocheck"); //$NON-NLS-1$ //$NON-NLS-2$

        int responseCode = httpclient.executeMethod(filePost);
        if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_CREATED) {
            // TODO This is a JSON response that we should parse out "errorMessages" value(s) (its an array of
            // strings).
            throw new JiraException(filePost.getResponseBodyAsString());
        }
        String json = filePost.getResponseBodyAsString();
        IdeLog.logInfo(JiraCorePlugin.getDefault(), json);
    } catch (JiraException e) {
        throw e;
    } catch (Exception e) {
        throw new JiraException(e.getMessage(), e);
    } finally {
        if (filePost != null) {
            filePost.releaseConnection();
        }
    }
}

From source file:net.dahanne.gallery3.client.business.G3Client.java

private HttpEntity requestToResponseEntity(String appendToGalleryUrl, List<NameValuePair> nameValuePairs,
        String requestMethod, File file)
        throws UnsupportedEncodingException, IOException, ClientProtocolException, G3GalleryException {
    HttpClient defaultHttpClient = new DefaultHttpClient();
    HttpRequestBase httpMethod;/*  www  . j a v a 2s. c o m*/
    //are we using rewritten urls ?
    if (this.isUsingRewrittenUrls && appendToGalleryUrl.contains(INDEX_PHP_REST)) {
        appendToGalleryUrl = StringUtils.remove(appendToGalleryUrl, "index.php");
    }

    logger.debug("requestToResponseEntity , url requested : {}", galleryItemUrl + appendToGalleryUrl);
    if (POST.equals(requestMethod)) {
        httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl);
        httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        if (file != null) {
            MultipartEntity multipartEntity = new MultipartEntity();

            String string = nameValuePairs.toString();
            // dirty fix to remove the enclosing entity{}
            String substring = string.substring(string.indexOf("{"), string.lastIndexOf("}") + 1);

            StringBody contentBody = new StringBody(substring, Charset.forName("UTF-8"));
            multipartEntity.addPart("entity", contentBody);
            FileBody fileBody = new FileBody(file);
            multipartEntity.addPart("file", fileBody);
            ((HttpPost) httpMethod).setEntity(multipartEntity);
        } else {
            ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }
    } else if (PUT.equals(requestMethod)) {
        httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl);
        httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } else if (DELETE.equals(requestMethod)) {
        httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl);
        httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        //this is to avoid the HTTP 414 (length too long) error
        //it should only happen when getting items, index.php/rest/items?urls=
        //      } else if(appendToGalleryUrl.length()>2000) {
        //         String resource = appendToGalleryUrl.substring(0,appendToGalleryUrl.indexOf("?"));
        //         String variable = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("?")+1,appendToGalleryUrl.indexOf("="));
        //         String value = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("=")+1);
        //         httpMethod = new HttpPost(galleryItemUrl + resource);
        //         httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        //         nameValuePairs.add(new BasicNameValuePair(variable, value));
        //         ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(
        //               nameValuePairs));
    } else {
        httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl);
    }
    if (existingApiKey != null) {
        httpMethod.setHeader(X_GALLERY_REQUEST_KEY, existingApiKey);
    }
    //adding the userAgent to the request
    httpMethod.setHeader(USER_AGENT, userAgent);
    HttpResponse response = null;

    String[] patternsArray = new String[3];
    patternsArray[0] = "EEE, dd MMM-yyyy-HH:mm:ss z";
    patternsArray[1] = "EEE, dd MMM yyyy HH:mm:ss z";
    patternsArray[2] = "EEE, dd-MMM-yyyy HH:mm:ss z";
    try {
        // be extremely careful here, android httpclient needs it to be
        // an
        // array of string, not an arraylist
        defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsArray);
        response = defaultHttpClient.execute(httpMethod);
    } catch (ClassCastException e) {
        List<String> patternsList = Arrays.asList(patternsArray);
        defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsList);
        response = defaultHttpClient.execute(httpMethod);
    }

    int responseStatusCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = null;
    if (response.getEntity() != null) {
        responseEntity = response.getEntity();
    }

    switch (responseStatusCode) {
    case HttpURLConnection.HTTP_CREATED:
        break;
    case HttpURLConnection.HTTP_OK:
        break;
    case HttpURLConnection.HTTP_MOVED_TEMP:
        //the gallery is using rewritten urls, let's remember it and re hit the server
        this.isUsingRewrittenUrls = true;
        responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file);
        break;
    case HttpURLConnection.HTTP_BAD_REQUEST:
        throw new G3BadRequestException();
    case HttpURLConnection.HTTP_FORBIDDEN:
        //for some reasons, the gallery may respond with 403 when trying to log in with the wrong url
        if (appendToGalleryUrl.contains(INDEX_PHP_REST)) {
            this.isUsingRewrittenUrls = true;
            responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file);
            break;
        }
        throw new G3ForbiddenException();
    case HttpURLConnection.HTTP_NOT_FOUND:
        throw new G3ItemNotFoundException();
    default:
        throw new G3GalleryException("HTTP code " + responseStatusCode);
    }

    return responseEntity;
}

From source file:org.openbaton.sdk.api.util.RestRequest.java

/**
 * Executes a http post with to a given url, while serializing the object content as json. The
 * type parameter specifies to which object type the post response should be mapped before
 * returning it. This can be useful if the method's return type is not the same as the type of the
 * object parameter.//from   ww  w . ja v  a2s.c o  m
 *
 * @param object the object content to be serialized as json
 * @param type the object type to which the response should be mapped
 * @return a string containing the response content
 */
public Serializable requestPost(final String id, final Serializable object, final Type type)
        throws SDKException {
    CloseableHttpResponse response = null;
    HttpPost httpPost = null;
    try {
        log.trace("Object is: " + object);
        String fileJSONNode = mapper.toJson(object);
        log.trace("sending: " + fileJSONNode.toString());
        log.debug("baseUrl: " + baseUrl);
        log.debug("id: " + baseUrl + "/" + id);

        try {
            checkToken();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new SDKException("Could not get token", e);
        }

        // call the api here
        log.debug("Executing post on: " + this.baseUrl + "/" + id);
        httpPost = new HttpPost(this.baseUrl + "/" + id);
        httpPost.setHeader(new BasicHeader("accept", "application/json"));
        httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));
        httpPost.setHeader(new BasicHeader("project-id", projectId));
        if (token != null)
            httpPost.setHeader(new BasicHeader("authorization", bearerToken.replaceAll("\"", "")));
        httpPost.setEntity(new StringEntity(fileJSONNode));

        response = httpClient.execute(httpPost);

        // check response status
        checkStatus(response, HttpURLConnection.HTTP_CREATED);
        // return the response of the request
        String result = "";
        if (response.getEntity() != null)
            result = EntityUtils.toString(response.getEntity());

        if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) {
            JsonParser jsonParser = new JsonParser();
            JsonElement jsonElement = jsonParser.parse(result);
            result = mapper.toJson(jsonElement);
            log.trace("received: " + result);

            log.trace("Casting it into: " + type);
            return mapper.fromJson(result, type);
        }
        response.close();
        httpPost.releaseConnection();
        return null;
    } catch (IOException e) {
        // catch request exceptions here
        log.error(e.getMessage(), e);
        if (httpPost != null)
            httpPost.releaseConnection();
        throw new SDKException("Could not http-post or open the object properly", e);
    } catch (SDKException e) {
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            token = null;
            if (httpPost != null)
                httpPost.releaseConnection();
            return requestPost(id);
        } else {
            if (httpPost != null)
                httpPost.releaseConnection();
            throw new SDKException("Status is " + response.getStatusLine().getStatusCode());
        }
    }
}

From source file:org.shredzone.flattr4j.connector.impl.FlattrConnection.java

/**
 * Assert that the HTTP result is OK, otherwise generate and throw an appropriate
 * {@link FlattrException}./*  w  w w.  j  ava 2  s.com*/
 *
 * @param conn
 *            {@link HttpURLConnection} to assert
 * @return {@code true} if the status is OK and there is a content, {@code false} if
 *         the status is OK but there is no content. (If the status is not OK, an
 *         exception is thrown.)
 */
private boolean assertStatusOk(HttpURLConnection conn) throws FlattrException {
    String error = null, desc = null, httpStatus = null;

    try {
        int statusCode = conn.getResponseCode();

        if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) {
            return true;
        }
        if (statusCode == HttpURLConnection.HTTP_NO_CONTENT) {
            return false;
        }

        httpStatus = "HTTP " + statusCode + ": " + conn.getResponseMessage();

        JSONObject errorData = (JSONObject) new JSONTokener(readResponse(conn)).nextValue();
        LOG.verbose("<- ERROR {0}: {1}", statusCode, errorData);

        error = errorData.optString("error");
        desc = errorData.optString("error_description");
        LOG.error("Flattr ERROR {0}: {1}", error, desc);
    } catch (HttpRetryException ex) {
        // Could not read error response because HttpURLConnection sucketh
    } catch (IOException ex) {
        throw new FlattrException("Could not read response", ex);
    } catch (ClassCastException ex) {
        // An unexpected JSON type was returned, just throw a generic error
    } catch (JSONException ex) {
        // No valid error message was returned, just throw a generic error
    }

    if (error != null && desc != null) {
        if ("flattr_once".equals(error) || "flattr_owner".equals(error) || "thing_owner".equals(error)
                || "forbidden".equals(error) || "insufficient_scope".equals(error)
                || "unauthorized".equals(error) || "subscribed".equals(error)) {
            throw new ForbiddenException(error, desc);

        } else if ("no_means".equals(error) || "no_money".equals(error)) {
            throw new NoMoneyException(error, desc);

        } else if ("not_found".equals(error)) {
            throw new NotFoundException(error, desc);

        } else if ("rate_limit_exceeded".equals(error)) {
            throw new RateLimitExceededException(error, desc);

        } else if ("invalid_parameters".equals(error) || "invalid_scope".equals(error)
                || "validation".equals(error)) {
            throw new ValidationException(error, desc);
        }

        // "not_acceptable", "server_error", "invalid_request", everything else...
        throw new FlattrServiceException(error, desc);
    }

    LOG.error("Flattr {0}", httpStatus);
    throw new FlattrException(httpStatus);
}

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

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

    WebRequest request = getPostFilesRequest(directoryPath,
            getNewFileJSON(null /* skip Name field*/).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:org.eclipse.orion.server.tests.servlets.site.HostingTest.java

@Test
public void testRemoteProxyRequest() throws SAXException, IOException, JSONException, URISyntaxException {
    final String siteName = "My remote hosting site";
    final String remoteRoot = "/remoteWeb", remotePrefPath = "/remotePref", remoteFilePath = "/remoteFile";

    final JSONArray mappings = makeMappings(new String[][] { { remoteRoot, SERVER_LOCATION },
            { remoteFilePath, SERVER_LOCATION + FILE_SERVLET_LOCATION },
            { remotePrefPath, SERVER_LOCATION + "/prefs" } });
    WebRequest createSiteReq = getCreateSiteRequest(siteName, workspaceId, mappings, null);
    WebResponse createSiteResp = webConversation.getResponse(createSiteReq);
    assertEquals(HttpURLConnection.HTTP_CREATED, createSiteResp.getResponseCode());
    JSONObject siteObject = new JSONObject(createSiteResp.getText());

    // Start the site
    String location = siteObject.getString(ProtocolConstants.HEADER_LOCATION);
    siteObject = startSite(location);//from   w  w w.  j a  v  a2 s .co  m

    final JSONObject hostingStatus = siteObject.getJSONObject(SiteConfigurationConstants.KEY_HOSTING_STATUS);
    final String hostedURL = hostingStatus.getString(SiteConfigurationConstants.KEY_HOSTING_STATUS_URL);

    // Access the remote URL through the site
    WebRequest getRemoteUrlReq = new GetMethodWebRequest(hostedURL + remoteRoot);
    WebResponse getRemoteUrlResp = webConversation.getResource(getRemoteUrlReq);
    final String lowerCaseContent = getRemoteUrlResp.getText().toLowerCase();
    assertEquals("Looks like our orion jetty server", true,
            lowerCaseContent.contains("orion") || lowerCaseContent.contains("jetty"));

    // Test that we can invoke the Orion file API through the site, to create a file
    final String fileName = "fizz.txt";
    final String fileContent = "Created through a site";
    createFileOnServer(hostedURL + remoteFilePath + testProjectBaseLocation, fileName, fileContent);

    // Bugs 369813, 366098, 369811, 390732: ensure query parameters are passed through the site unmangled
    // For this we'll call the 'prefs' API which uses query parameters
    String prefKey = "foo[-]bar baz+quux";
    String prefValue = "pref value";
    String remotePrefUrl = hostedURL + remotePrefPath + "/user";
    WebRequest putPrefReq = createSetPreferenceRequest(remotePrefUrl, prefKey, prefValue);
    setAuthentication(putPrefReq);
    WebResponse putPrefResp = webConversation.getResponse(putPrefReq);
    assertEquals(HttpURLConnection.HTTP_NO_CONTENT, putPrefResp.getResponseCode());

    // Check pref value
    WebRequest getPrefReq = new GetMethodWebRequest(remotePrefUrl + "?key=" + URLEncoder.encode(prefKey));
    setAuthentication(getPrefReq);
    WebResponse getPrefResp = webConversation.getResponse(getPrefReq);
    assertEquals(HttpURLConnection.HTTP_OK, getPrefResp.getResponseCode());
    JSONObject prefObject = new JSONObject(getPrefResp.getText());
    assertEquals("Pref obtained through site has correct value", prefObject.optString(prefKey), prefValue);

    // Stop the site
    stopSite(location);

    // Check that remote URL can't be accessed anymore
    WebRequest getRemoteUrl404Req = new GetMethodWebRequest(hostedURL + remoteRoot);
    WebResponse getRemoteUrl404Resp = webConversation.getResponse(getRemoteUrl404Req);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, getRemoteUrl404Resp.getResponseCode());
}