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:technology.tikal.accounts.dao.rest.SessionDaoRest.java
private void guardar(UserSession objeto, int intento) { //basic auth string String basicAuthString = config.getUser() + ":" + config.getPassword(); basicAuthString = new String(Base64.encodeBase64(basicAuthString.getBytes())); basicAuthString = "Basic " + basicAuthString; //mensaje remoto try {/* w w w. j a v a2 s . c o m*/ //config URL url = new URL(config.getUrl()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod(config.getMethod()); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Authorization", basicAuthString); connection.setInstanceFollowRedirects(false); //write OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(mapper.writeValueAsString(objeto)); //close writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) { return; } else { throw new MessageSourceResolvableException(new DefaultMessageSourceResolvable( new String[] { "SessionCreationRefused.SessionDaoRest.guardar" }, new String[] { connection.getResponseCode() + "" }, "")); } } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { if (intento <= maxRetry) { this.guardar(objeto, intento + 1); } else { throw new MessageSourceResolvableException(new DefaultMessageSourceResolvable( new String[] { "SessionCreationError.SessionDaoRest.guardar" }, new String[] { e.getMessage() }, "")); } } }
From source file:org.eclipse.orion.server.tests.servlets.site.SiteTest.java
@Test /**/*from ww w. ja va 2 s . c o m*/ * Create site via POST, check that the response has the parameters we expected. */ public void testCreateSite() throws IOException, SAXException, JSONException { final String siteName = "My great website"; final String workspaceId = workspaceObject.getString(ProtocolConstants.KEY_ID); final String hostHint = "mySite"; final String source = "/fizz"; final String target = "/buzz"; final JSONArray mappings = makeMappings(new String[][] { { source, target } }); WebRequest request = getCreateSiteRequest(siteName, workspaceId, mappings, hostHint); WebResponse siteResponse = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, siteResponse.getResponseCode()); JSONObject respObject = new JSONObject(siteResponse.getText()); JSONArray respMappings = respObject.getJSONArray(SiteConfigurationConstants.KEY_MAPPINGS); assertEquals(siteName, respObject.get(ProtocolConstants.KEY_NAME)); assertEquals(workspaceId, respObject.get(SiteConfigurationConstants.KEY_WORKSPACE)); assertEquals(hostHint, respObject.get(SiteConfigurationConstants.KEY_HOST_HINT)); assertEquals(1, respMappings.length()); assertEquals(source, respMappings.getJSONObject(0).get(SiteConfigurationConstants.KEY_SOURCE)); assertEquals(target, respMappings.getJSONObject(0).get(SiteConfigurationConstants.KEY_TARGET)); }
From source file:org.cm.podd.report.util.RequestDataUtil.java
public static ResponseObject post(String path, String query, String json, String token) { JSONObject jsonObj = null;//from w w w . jav a2 s . c o m int statusCode = 0; //SharedPreferences settings = PoddApplication.getAppContext().getSharedPreferences("PoddPrefsFile", 0); String serverUrl = settings.getString("serverUrl", BuildConfig.SERVER_URL); String reqUrl = ""; if (path.contains("http://") || path.contains("https://")) { reqUrl = String.format("%s%s", path, query == null ? "" : "?" + query); } else { reqUrl = String.format("%s%s%s", serverUrl, path, query == null ? "" : "?" + query); } Log.i(TAG, "submit url=" + reqUrl); Log.i(TAG, "post data=" + json); HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpClient client = new DefaultHttpClient(params); try { HttpPost post = new HttpPost(reqUrl); post.setHeader("Content-Type", "application/json"); if (token != null) { post.setHeader("Authorization", "Token " + token); } post.setEntity(new StringEntity(json, HTTP.UTF_8)); HttpResponse response; response = client.execute(post); HttpEntity entity = response.getEntity(); // Detect server complaints statusCode = response.getStatusLine().getStatusCode(); Log.v(TAG, "status code=" + statusCode); if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED || statusCode == HttpURLConnection.HTTP_BAD_REQUEST) { InputStream in = entity.getContent(); String resp = FileUtil.convertInputStreamToString(in); jsonObj = new JSONObject(resp); entity.consumeContent(); } } catch (ClientProtocolException e) { Log.e(TAG, "error post data", e); } catch (IOException e) { Log.e(TAG, "Can't connect server", e); } catch (JSONException e) { Log.e(TAG, "error convert json", e); } finally { client.getConnectionManager().shutdown(); } return new ResponseObject(statusCode, jsonObj); }
From source file:bluevia.SendSMS.java
public static void sendBlueViaSMS(String user_email, String phone_number, String sms_message) { try {//from www .j a v a2 s . c om Properties blueviaAccount = Util.getNetworkAccount(user_email, "BlueViaAccount"); if (blueviaAccount != null) { String consumer_key = blueviaAccount.getProperty("BlueViaAccount.consumer_key"); String consumer_secret = blueviaAccount.getProperty("BlueViaAccount.consumer_secret"); String access_key = blueviaAccount.getProperty("BlueViaAccount.access_key"); String access_secret = blueviaAccount.getProperty("BlueViaAccount.access_secret"); com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate(); OAuthConsumer consumer = (OAuthConsumer) new DefaultOAuthConsumer(consumer_key, consumer_secret); consumer.setMessageSigner(new HmacSha1MessageSigner()); consumer.setTokenWithSecret(access_key, access_secret); URL apiURI = new URL("https://api.bluevia.com/services/REST/SMS/outbound/requests?version=v1"); HttpURLConnection request = (HttpURLConnection) apiURI.openConnection(); request.setRequestProperty("Content-Type", "application/json"); request.setRequestMethod("POST"); request.setDoOutput(true); consumer.sign(request); request.connect(); String smsTemplate = "{\"smsText\": {\n \"address\": {\"phoneNumber\": \"%s\"},\n \"message\": \"%s\",\n \"originAddress\": {\"alias\": \"%s\"},\n}}"; String smsMsg = String.format(smsTemplate, phone_number, sms_message, access_key); OutputStream os = request.getOutputStream(); os.write(smsMsg.getBytes()); os.flush(); int rc = request.getResponseCode(); if (rc == HttpURLConnection.HTTP_CREATED) log.info(String.format("SMS sent to %s. Text: %s", phone_number, sms_message)); else log.severe(String.format("Error %d sending SMS:%s\n", rc, request.getResponseMessage())); } else log.warning("BlueVia Account seems to be not configured!"); } catch (Exception e) { log.severe(String.format("Exception sending SMS: %s", e.getMessage())); } }
From source file:org.eclipse.orion.server.tests.servlets.git.GitAddTest.java
@Test public void testAddAll() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); String projectName = getMethodName(); JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString()); String projectId = project.getString(ProtocolConstants.KEY_ID); JSONObject testTxt = getChild(project, "test.txt"); modifyFile(testTxt, "hello"); String fileName = "new.txt"; WebRequest request = getPostFilesRequest("", getNewFileJSON(fileName).toString(), fileName); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); JSONObject folder = getChild(project, "folder"); JSONObject folderTxt = getChild(folder, "folder.txt"); deleteFile(folderTxt);//from w w w . java 2 s.c o m JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT); String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX); String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS); assertStatus(new StatusResult().setMissing(1).setModified(1).setUntracked(1), gitStatusUri); request = getPutGitIndexRequest(gitIndexUri /* add all */, null); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); assertStatus(new StatusResult().setAdded(1).setChanged(1).setRemoved(1), gitStatusUri); }
From source file:org.eclipse.orion.server.tests.servlets.site.CoreSiteTest.java
/** * Creates a site and asserts that it was created. * @param mappings Can be null/*from w ww . ja v a 2 s.c o m*/ * @param hostHint Can be null * @param user If nonnull, string to use as username and password for auth */ protected WebResponse createSite(String name, String workspaceId, JSONArray mappings, String hostHint, String user) throws IOException, SAXException { WebRequest request = getCreateSiteRequest(name, workspaceId, mappings, hostHint); if (user == null) setAuthentication(request); else setAuthentication(request, user, user); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); return response; }
From source file:org.eclipse.orion.server.tests.servlets.git.GitCherryPickTest.java
@Test public void testCherryPick() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); IPath[] clonePaths = createTestProjects(workspaceLocation); for (IPath clonePath : clonePaths) { // clone a repo JSONObject clone = clone(clonePath); String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION); String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION); String branchesLocation = clone.getString(GitConstants.KEY_BRANCH); // 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()); String folderLocation = folder.getString(ProtocolConstants.KEY_LOCATION); JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT); String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX); String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); JSONObject testTxt = getChild(folder, "test.txt"); modifyFile(testTxt, "first line\nsec. line\nthird line\n"); addFile(testTxt);/* w ww .j a v a 2s.com*/ commitFile(testTxt, "lines in test.txt", false); // create new file String fileName = "new.txt"; request = getPostFilesRequest(folderLocation + "/", getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); // add all request = GitAddTest.getPutGitIndexRequest(gitIndexUri); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // commit request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "added new.txt", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // modify modifyFile(testTxt, "first line\nsec. line\nthird line\nfourth line\n"); // add addFile(testTxt); // commit request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "enlarged test.txt", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // modify modifyFile(testTxt, "first line\nsecond line\nthird line\nfourth line\n"); // add addFile(testTxt); // commit request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "fixed test.txt", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // remember starting point and commit to cherry-pick JSONArray commitsArray = log(gitHeadUri); assertEquals(5, commitsArray.length()); JSONObject commit = commitsArray.getJSONObject(0); assertEquals("fixed test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); String toCherryPick = commit.getString(ProtocolConstants.KEY_NAME); commit = commitsArray.getJSONObject(3); assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); String startingPoint = commit.getString(ProtocolConstants.KEY_NAME); // branch response = branch(branchesLocation, "side", startingPoint); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); response = checkoutBranch(cloneLocation, "side"); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // modify modifyFile(testTxt, "first line\nsec. line\nthird line\nfeature++\n"); // add addFile(testTxt); // commit request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "enhanced test.txt", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // CHERRY-PICK JSONObject cherryPick = cherryPick(gitHeadUri, toCherryPick); CherryPickStatus mergeResult = CherryPickStatus.valueOf(cherryPick.getString(GitConstants.KEY_RESULT)); assertEquals(CherryPickStatus.OK, mergeResult); assertTrue(cherryPick.getBoolean(GitConstants.KEY_HEAD_UPDATED)); // try again, should be OK, but nothing changed cherryPick = cherryPick(gitHeadUri, toCherryPick); mergeResult = CherryPickStatus.valueOf(cherryPick.getString(GitConstants.KEY_RESULT)); assertEquals(CherryPickStatus.OK, mergeResult); assertFalse(cherryPick.getBoolean(GitConstants.KEY_HEAD_UPDATED)); // 'new.txt' should be not there JSONObject newTxt = getChild(folder, "new.txt"); assertNull(newTxt); // check cherry-pick result in the file request = getGetRequest(testTxt.getString(ProtocolConstants.KEY_LOCATION)); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); assertEquals("first line\nsecond line\nthird line\nfeature++\n", response.getText()); // check log commitsArray = log(gitHeadUri); assertEquals(4, commitsArray.length()); commit = commitsArray.getJSONObject(0); assertEquals("fixed test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); commit = commitsArray.getJSONObject(1); assertEquals("enhanced test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); commit = commitsArray.getJSONObject(2); assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); commit = commitsArray.getJSONObject(3); assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); } }
From source file:nz.skytv.example.SwaggerApplication.java
@ApiOperation(value = "Create a book", notes = "Create a book.", response = Book.class, tags = { "book", "updates" }) @ApiResponses({ @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Book created successfully"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Something really bad happened") }) @RequestMapping(value = { "/rest/book" }, method = RequestMethod.POST, consumes = "application/json") ResponseEntity<Void> createBook( @ApiParam(value = "Book entity", required = true) @RequestBody @Valid final Book book) { LOG.debug("create {}", book); return new ResponseEntity<>(HttpStatus.CREATED); }
From source file:org.apache.hadoop.hdfs.server.namenode.web.resources.TestWebHdfsCreatePermissions.java
@Test public void testCreateFileNoPermissions() throws Exception { testPermissions(HttpURLConnection.HTTP_CREATED, "rw-r--r--", "/test-file", "op=CREATE"); }
From source file:com.netflix.genie.server.resources.CommandConfigResource.java
/** * Create a Command configuration./* w w w . j ava 2 s . c o m*/ * * @param command The command configuration to create * @return The command created * @throws GenieException For any error */ @POST @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Create a command", notes = "Create a command from the supplied information.", response = Command.class) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Created", response = Command.class), @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = "A command with the supplied id already exists"), @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid required parameter supplied"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") }) public Response createCommand( @ApiParam(value = "The command to create.", required = true) final Command command) throws GenieException { LOG.info("called to create new command configuration " + command.toString()); final Command createdCommand = this.commandConfigService.createCommand(command); return Response.created(this.uriInfo.getAbsolutePathBuilder().path(createdCommand.getId()).build()) .entity(createdCommand).build(); }