List of usage examples for java.net HttpURLConnection HTTP_CREATED
int HTTP_CREATED
To view the source code for java.net HttpURLConnection HTTP_CREATED.
Click Source Link
From source file:org.eclipse.orion.server.tests.servlets.site.HostingTest.java
@Test /**/*from w w w .j a v a 2 s .c o m*/ * Tests accessing a workspace file and that it has the expected MIME type. */ public void testSiteFileMime() throws SAXException, IOException, JSONException, URISyntaxException { // Expose a directory named my.css and ensure it doesn't get "text/css" content-type // https://bugs.eclipse.org/bugs/show_bug.cgi?id=389252 final String filename = "foo.html"; final String fileContent = "<html><body>This is a test file</body></html>"; final String dirName = "my.css"; createDirectoryOnServer(dirName); createFileOnServer(dirName + "/", filename, fileContent); IPath path = new Path(URI.create(makeResourceURIAbsolute(filename)).getPath()); while (path.segmentCount() != 0 && !path.segment(0).equals("file")) { if (path.segment(0).equals("file")) { break; } path = path.removeFirstSegments(1); } String filePath = path.toString(); if (filePath.startsWith("/")) { filePath = filePath.substring(1); } Assert.assertTrue(filePath.startsWith("file/")); filePath = filePath.substring(5); final String mountAt = "/"; final JSONArray mappings = makeMappings(new String[][] { { mountAt, filePath } }); WebRequest createSiteReq = getCreateSiteRequest("testMime", workspaceId, mappings, null); WebResponse createSiteResp = webConversation.getResponse(createSiteReq); assertEquals(HttpURLConnection.HTTP_CREATED, createSiteResp.getResponseCode()); JSONObject siteObject = new JSONObject(createSiteResp.getText()); // Start site String location = siteObject.getString(ProtocolConstants.HEADER_LOCATION); siteObject = startSite(location); // Access the directory through the site final JSONObject hostingStatus = siteObject.getJSONObject(SiteConfigurationConstants.KEY_HOSTING_STATUS); final String hostedURL = hostingStatus.getString(SiteConfigurationConstants.KEY_HOSTING_STATUS_URL); WebRequest getFileReq = new GetMethodWebRequest(hostedURL + mountAt); WebResponse getFileResp = webConversation.getResponse(getFileReq); assertEquals(true, getFileResp.getText().contains(filename)); assertEquals(false, "text/html".equals(getFileResp.getHeaderField("Content-Type").toLowerCase())); // Stop the site stopSite(location); }
From source file:org.eclipse.orion.server.tests.servlets.files.CoreFilesTest.java
@Test public void testCreateEmptyFile() throws CoreException, IOException, SAXException, JSONException { String directoryPath = "sample/directory/path" + System.currentTimeMillis(); createDirectory(directoryPath);/*from www.j a v 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()); 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 direcory information in response", responseObject); checkFileMetadata(responseObject, fileName, null, null, null, null, null, null, null, null); }
From source file:org.eclipse.orion.server.tests.servlets.git.GitUtilsTest.java
@Test public void testGitDirsClonedIntoSubfolder() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); String workspaceId = workspaceIdFromLocation(workspaceLocation); JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null); // create folder1 String folderName = "clone1"; WebRequest request = getPostFilesRequest("", getNewDirJSON(folderName).toString(), folderName); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); JSONObject cloneFolder1 = new JSONObject(response.getText()); IPath clonePath = getClonePath(workspaceId, project).append(folderName).makeAbsolute(); clone(clonePath);//from w w w . j a v a 2 s . c o m // create folder2 folderName = "clone2"; request = getPostFilesRequest("", getNewDirJSON(folderName).toString(), folderName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); JSONObject cloneFolder2 = new JSONObject(response.getText()); clonePath = getClonePath(workspaceId, project).append(folderName).makeAbsolute(); clone(clonePath); String cloneLocation = cloneFolder1.getString(ProtocolConstants.KEY_LOCATION); URI subfolderUri = URI.create(toRelativeURI(cloneLocation)); IPath subfolderPath = new Path(subfolderUri.getPath()); Map<IPath, File> gitDirs = GitUtils.getGitDirs(subfolderPath, Traverse.GO_DOWN); assertFalse(gitDirs.isEmpty()); gitDirs.clear(); cloneLocation = cloneFolder2.getString(ProtocolConstants.KEY_LOCATION); subfolderUri = URI.create(toRelativeURI(cloneLocation)); subfolderPath = new Path(subfolderUri.getPath()); gitDirs = GitUtils.getGitDirs(subfolderPath, Traverse.GO_DOWN); assertFalse(gitDirs.isEmpty()); gitDirs.clear(); String projectLocation = project.getString(ProtocolConstants.KEY_CONTENT_LOCATION); URI projectUri = URI.create(toRelativeURI(projectLocation)); IPath projectPath = new Path(projectUri.getPath()); gitDirs = GitUtils.getGitDirs(projectPath, Traverse.GO_DOWN); assertFalse(gitDirs.isEmpty()); assertEquals(2, gitDirs.size()); }
From source file:io.joynr.messaging.bounceproxy.monitoring.BounceProxyStartupReporter.java
/** * Reports the lifecycle event to the monitoring service as HTTP request. * //from w w w . j a va2s .c o m * @throws IOException * if the connection with the bounce proxy controller could not * be established * @throws JoynrHttpException * if the bounce proxy responded that registering the bounce * proxy did not succeed */ private void reportEventAsHttpRequest() throws IOException { final String url = bounceProxyControllerUrl.buildReportStartupUrl(controlledBounceProxyUrl); logger.debug("Using monitoring service URL: {}", url); HttpPut putReportStartup = new HttpPut(url.trim()); CloseableHttpResponse response = null; try { response = httpclient.execute(putReportStartup); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); switch (statusCode) { case HttpURLConnection.HTTP_NO_CONTENT: // bounce proxy instance was already known at the bounce proxy // controller // nothing else to do logger.info("Bounce proxy was already registered with the controller"); break; case HttpURLConnection.HTTP_CREATED: // bounce proxy instance was registered for the very first time // TODO maybe read URL logger.info("Registered bounce proxy with controller"); break; default: logger.error("Failed to send startup notification: {}", response); throw new JoynrHttpException(statusCode, "Failed to send startup notification. Bounce Proxy won't get any channels assigned."); } } finally { if (response != null) { response.close(); } } }
From source file:fi.cosky.sdk.API.java
private <T extends BaseData> T sendRequest(Link l, Class<T> tClass, Object object) throws IOException { URL serverAddress;// w w w .ja v a 2 s . c o m BufferedReader br; String result = ""; HttpURLConnection connection = null; String url = l.getUri().contains("://") ? l.getUri() : this.baseUrl + l.getUri(); try { String method = l.getMethod(); String type = l.getType(); serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); boolean doOutput = doOutput(method); connection.setDoOutput(doOutput); connection.setRequestMethod(method); connection.setInstanceFollowRedirects(false); if (method.equals("GET") && useMimeTypes) if (type == null || type.equals("")) { addMimeTypeAcceptToRequest(object, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); } if (!useMimeTypes) connection.setRequestProperty("Accept", "application/json"); if (doOutput && useMimeTypes) { //this handles the case if the link is self made and the type field has not been set. if (type == null || type.equals("")) { addMimeTypeContentTypeToRequest(l, tClass, connection); addMimeTypeAcceptToRequest(l, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); connection.addRequestProperty("Content-Type", helper.getSupportedType(type)); } } if (!useMimeTypes) connection.setRequestProperty("Content-Type", "application/json"); if (tokenData != null) { connection.addRequestProperty("Authorization", tokenData.getTokenType() + " " + tokenData.getAccessToken()); } addVersionNumberToHeader(object, url, connection); if (method.equals("POST") || method.equals("PUT")) { String json = object != null ? gson.toJson(object) : ""; //should handle the case when POST without object. connection.addRequestProperty("Content-Length", json.getBytes("UTF-8").length + ""); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream()); osw.write(json); osw.flush(); osw.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER) { ResponseData data = new ResponseData(); Link link = parseLocationLinkFromString(connection.getHeaderField("Location")); link.setType(type); data.setLocation(link); connection.disconnect(); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println( "Authentication expired " + connection.getResponseMessage() + " trying to reauthenticate"); if (retry && this.tokenData != null) { this.tokenData = null; retry = false; if (authenticate()) { System.out.println("Reauthentication success, will continue with " + l.getMethod() + " request on " + l.getRel()); return sendRequest(l, tClass, object); } } else throw new IOException( "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API"); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { return (T) objectCache.getObject(url); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { return (T) new ResponseData(); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + method); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) { if (retry) { System.out.println("Request caused internal server error, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println("Requst caused internal server error, please contact dev@nfleet.fi"); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_GATEWAY) { if (retry) { System.out.println("Could not connect to NFleet-API, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println( "Could not connect to NFleet-API, please check service status from http://status.nfleet.fi and try again later."); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } result = readDataFromConnection(connection); } catch (MalformedURLException e) { throw e; } catch (ProtocolException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; } catch (IOException e) { throw e; } catch (SecurityException e) { throw e; } catch (IllegalArgumentException e) { throw e; } finally { assert connection != null; connection.disconnect(); } Object newEntity = gson.fromJson(result, tClass); objectCache.addUri(url, newEntity); return (T) newEntity; }
From source file:org.openbaton.sdk.api.util.RestRequest.java
public Serializable requestPost(final String id, final Serializable object) throws SDKException { CloseableHttpResponse response = null; HttpPost httpPost = null;//from ww w . j av a 2s . c o m try { log.trace("Object is: " + object); String fileJSONNode; if (object instanceof String) fileJSONNode = (String) object; else 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); if (!(object instanceof String)) { 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) { if (object instanceof String) return result; JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(result); result = mapper.toJson(jsonElement); log.trace("received: " + result); log.trace("Casting it into: " + object.getClass()); return mapper.fromJson(result, object.getClass()); } 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 != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { token = null; if (httpPost != null) httpPost.releaseConnection(); return requestPost(id); } else if (response != null) { if (httpPost != null) httpPost.releaseConnection(); throw new SDKException("Status is " + response.getStatusLine().getStatusCode()); } else { throw e; } } }
From source file:org.eclipse.orion.server.tests.servlets.workspace.WorkspaceServiceTest.java
@Test public void testMoveProject() throws IOException, SAXException, JSONException { //create workspace String workspaceName = WorkspaceServiceTest.class.getName() + "#testMoveProject"; URI workspaceLocation = createWorkspace(workspaceName); //create a project String projectName = "Source Project"; WebRequest request = getCreateProjectRequest(workspaceLocation, projectName, null); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); String sourceLocation = response.getHeaderField(ProtocolConstants.HEADER_LOCATION); // move the project String destinationName = "Destination Project"; request = getCopyMoveProjectRequest(workspaceLocation, destinationName, sourceLocation, true); response = webConversation.getResponse(request); //since project already existed, we should get OK rather than CREATED assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); String destinationLocation = response.getHeaderField(ProtocolConstants.HEADER_LOCATION); //assert the move (rename) took effect assertEquals(sourceLocation, destinationLocation); JSONObject resultObject = new JSONObject(response.getText()); assertEquals(destinationName, resultObject.getString(ProtocolConstants.KEY_NAME)); }
From source file:com.flurry.proguard.UploadProGuardMapping.java
/** * Upload the archive to Flurry//from www . j a v a 2s.com * * @param file the archive to send * @param projectId the project's id * @param uploadId the the upload's id * @param token the Flurry auth token */ private static void sendToUploadService(File file, String projectId, String uploadId, String token) { String uploadServiceUrl = String.format("%s/upload/%s/%s", UPLOAD_BASE, projectId, uploadId); List<Header> requestHeaders = getUploadServiceHeaders(file.length(), token); HttpPost postRequest = new HttpPost(uploadServiceUrl); postRequest.setEntity(new FileEntity(file)); HttpResponse response = executeHttpRequest(postRequest, requestHeaders); expectStatus(response, HttpURLConnection.HTTP_CREATED, HttpURLConnection.HTTP_ACCEPTED); }
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 *///from w w w. j a v a 2s. c o m @Test public void testImportFromURL() 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); request.setHeaderField(ProtocolConstants.HEADER_XFER_OPTIONS, "raw"); WebResponse postResponse = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, postResponse.getResponseCode()); String location = postResponse.getHeaderField("Location"); assertNotNull(location); //assert the file has been imported but not unzipped assertTrue(checkFileExists(directoryPath + "/org.eclipse.core.tools.restorer_3.0.0.zip")); }
From source file:i5.las2peer.services.gamificationApplicationService.GamificationApplicationService.java
/** * Create a new app/* w w w .j a va 2 s . co m*/ * * @param contentType form content type * @param formData form data * @return Application data in JSON */ @POST @Path("/data") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "createApplication", notes = "Method to create a new application") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Database Error"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Error in parsing form data"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "App ID already exist"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "App ID cannot be empty"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Error checking app ID exist"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "New application created") }) public HttpResponse createApplication( @ApiParam(value = "Application detail in multiple/form-data type", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType, @ApiParam(value = "Content of form data", required = true) @ContentParam byte[] formData) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/applications/data"); long randomLong = new Random().nextLong(); //To be able to match JSONObject objResponse = new JSONObject(); UserAgent userAgent = (UserAgent) getContext().getMainAgent(); String name = userAgent.getLoginName(); String appid = null; String appdesc = null; String commtype = null; Connection conn = null; if (name.equals("anonymous")) { return unauthorizedMessage(); } Map<String, FormDataPart> parts; try { conn = dbm.getConnection(); parts = MultipartHelper.getParts(formData, contentType); FormDataPart partAppID = parts.get("appid"); if (partAppID != null) { // these data belong to the (optional) file id text input form element appid = partAppID.getContent(); // appid must be unique System.out.println(appid); if (applicationAccess.isAppIdExist(conn, appid)) { // app id already exist objResponse.put("message", "App ID already exist"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } FormDataPart partAppDesc = parts.get("appdesc"); if (partAppDesc != null) { appdesc = partAppDesc.getContent(); } else { appdesc = ""; } FormDataPart partCommType = parts.get("commtype"); if (partAppDesc != null) { commtype = partCommType.getContent(); } else { commtype = "def_type"; } ApplicationModel newApp = new ApplicationModel(appid, appdesc, commtype); try { L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_1, "" + randomLong); applicationAccess.addNewApplication(conn, newApp); applicationAccess.addMemberToApp(conn, newApp.getId(), name); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_2, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_3, "" + name); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_4, "" + newApp.getId()); objResponse.put("message", "New application created"); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_CREATED); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot Add New Application. Database Error. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } else { // app id cannot be empty objResponse.put("message", "Cannot Add New Application. App ID cannot be empty."); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } } catch (IOException e) { e.printStackTrace(); objResponse.put("message", "Cannot Add New Application. Error in parsing form data. " + 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 Add New Application. Error checking app ID exist. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } // always close connections finally { try { conn.close(); } catch (SQLException e) { logger.printStackTrace(e); } } }