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.workspace.WorkspaceServiceTest.java
@Test public void testCreateProject() throws Exception { //create workspace String workspaceName = WorkspaceServiceTest.class.getName() + "#testCreateProject"; URI workspaceLocation = createWorkspace(workspaceName); //create a project String projectName = "My Project"; WebRequest request = getCreateProjectRequest(workspaceLocation, projectName, null); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); String locationHeader = response.getHeaderField(ProtocolConstants.HEADER_LOCATION); assertNotNull(locationHeader);/*from w w w . ja va2 s . c o m*/ JSONObject project = new JSONObject(response.getText()); assertEquals(projectName, project.getString(ProtocolConstants.KEY_NAME)); String projectId = project.optString(ProtocolConstants.KEY_ID, null); assertNotNull(projectId); //ensure project location = <workspace location>/project/<projectName> URI projectLocation = new URI(toAbsoluteURI(locationHeader)); URI relative = workspaceLocation.relativize(projectLocation); IPath projectPath = new Path(relative.getPath()); assertEquals(2, projectPath.segmentCount()); assertEquals("project", projectPath.segment(0)); assertEquals(projectName, projectPath.segment(1)); //ensure project appears in the workspace metadata request = new GetMethodWebRequest(addSchemeHostPort(workspaceLocation).toString()); setAuthentication(request); response = webConversation.getResponse(request); JSONObject workspace = new JSONObject(response.getText()); assertNotNull(workspace); JSONArray projects = workspace.getJSONArray(ProtocolConstants.KEY_PROJECTS); assertEquals(1, projects.length()); JSONObject createdProject = projects.getJSONObject(0); assertEquals(projectId, createdProject.get(ProtocolConstants.KEY_ID)); assertNotNull(createdProject.optString(ProtocolConstants.KEY_LOCATION, null)); //check for children element to conform to structure of file API JSONArray children = workspace.optJSONArray(ProtocolConstants.KEY_CHILDREN); assertNotNull(children); assertEquals(1, children.length()); JSONObject child = children.getJSONObject(0); assertEquals(projectName, child.optString(ProtocolConstants.KEY_NAME)); assertEquals("true", child.optString(ProtocolConstants.KEY_DIRECTORY)); String contentLocation = child.optString(ProtocolConstants.KEY_LOCATION); assertNotNull(contentLocation); //ensure project content exists if (OrionConfiguration.getMetaStore() instanceof SimpleMetaStore) { // simple metastore, projects not in the same simple location anymore, so do not check } else { // legacy metastore, use what was in the original test IFileStore projectStore = EFS.getStore(makeLocalPathAbsolute(projectId)); assertTrue(projectStore.fetchInfo().exists()); } //add a file in the project String fileName = "file.txt"; request = getPostFilesRequest(toAbsoluteURI(contentLocation), getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); 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, projectName); }
From source file:io.joynr.messaging.http.HttpMessageSender.java
public void sendMessage(final MessageContainer messageContainer, final FailureAction failureAction) { logger.trace("SEND messageId: {} channelId: {}", messageContainer.getMessageId(), messageContainer.getChannelId()); HttpContext context = new BasicHttpContext(); String channelId = messageContainer.getChannelId(); String messageId = messageContainer.getMessageId(); if (messageContainer.isExpired()) { logger.error("SEND executionQueue.run channelId: {}, messageId: {} TTL expired: ", messageId, messageContainer.getExpiryDate()); failureAction.execute(new JoynrTimeoutException(messageContainer.getExpiryDate())); return;// ww w . j a va2 s . c om } // execute http command to send CloseableHttpResponse response = null; String sendUrl = null; try { String serializedMessage = messageContainer.getSerializedMessage(); sendUrl = urlResolver.getSendUrl(messageContainer.getChannelId()); logger.debug("SENDING message channelId: {}, messageId: {} toUrl: {}", new String[] { channelId, messageId, sendUrl }); if (sendUrl == null) { logger.error("SEND executionQueue.run channelId: {}, messageId: {} No channelId found", messageId, messageContainer.getExpiryDate()); failureAction.execute(new JoynrMessageNotSentException("no channelId found")); return; } HttpPost httpPost = httpRequestFactory.createHttpPost(URI.create(sendUrl)); httpPost.addHeader(new BasicHeader(httpConstants.getHEADER_CONTENT_TYPE(), httpConstants.getAPPLICATION_JSON() + ";charset=UTF-8")); httpPost.setEntity(new StringEntity(serializedMessage, "UTF-8")); // Clone the default config Builder requestConfigBuilder = RequestConfig.copy(defaultRequestConfig); requestConfigBuilder.setConnectionRequestTimeout(httpConstants.getSEND_MESSAGE_REQUEST_TIMEOUT()); httpPost.setConfig(requestConfigBuilder.build()); response = httpclient.execute(httpPost, context); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); String statusText = statusLine.getReasonPhrase(); switch (statusCode) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_CREATED: logger.debug("SEND to ChannelId: {} messageId: {} completed successfully", channelId, messageId); break; case HttpURLConnection.HTTP_BAD_REQUEST: HttpEntity entity = response.getEntity(); if (entity == null) { logger.error( "SEND to ChannelId: {} messageId: {} completed in error. No further reason found in message body", channelId, messageId); return; } String body = EntityUtils.toString(entity, "UTF-8"); JoynrMessagingError error = objectMapper.readValue(body, JoynrMessagingError.class); JoynrMessagingErrorCode joynrMessagingErrorCode = JoynrMessagingErrorCode .getJoynrMessagingErrorCode(error.getCode()); logger.error(error.toString()); switch (joynrMessagingErrorCode) { case JOYNRMESSAGINGERROR_CHANNELNOTFOUND: failureAction.execute(new JoynrChannelMissingException("Channel does not exist. Status: " + statusCode + " error: " + error.getCode() + "reason:" + error.getReason())); break; default: logger.error("SEND error channelId: {}, messageId: {} url: {} error: {} code: {} reason: {} ", new Object[] { channelId, messageId, sendUrl, statusText, error.getCode(), error.getReason() }); failureAction.execute(new JoynrCommunicationException("Http Error while communicating: " + statusText + body + " error: " + error.getCode() + "reason:" + error.getReason())); break; } break; default: logger.error("SEND to ChannelId: {} messageId: {} - unexpected response code: {} reason: {}", new Object[] { channelId, messageId, statusCode, statusText }); break; } } catch (Exception e) { // An exception occured - this could still be a communication error (e.g Connection refused) logger.error("SEND error channelId: {}, messageId: {} url: {} error: {}", new Object[] { channelId, messageId, sendUrl, e.getMessage() }); failureAction.execute(new JoynrCommunicationException( e.getClass().getName() + "Exception while communicating. error: " + e.getMessage())); } finally { if (response != null) { try { response.close(); } catch (IOException e) { } } } }
From source file:org.orbisgis.core.layerModel.mapcatalog.Workspace.java
/** * Add a mapcontext to the workspace/*from w w w . j ava 2 s. co m*/ * @param mapContext * @return The ID of the published map context * @throws IOException */ public int publishMapContext(MapContext mapContext, Integer mapContextId) throws IOException { // Construct request URL requestWorkspacesURL; if (mapContextId == null) { // Post a new map context requestWorkspacesURL = new URL(RemoteCommons.getUrlPostContext(cParams, workspaceName)); } else { // Update an existing map context requestWorkspacesURL = new URL(RemoteCommons.getUrlUpdateContext(cParams, workspaceName, mapContextId)); } // Establish connection HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setConnectTimeout(cParams.getConnectionTimeOut()); connection.addRequestProperty("Content-Type", "text/xml"); OutputStream out = connection.getOutputStream(); mapContext.write(out); // Send map context out.close(); // Get response int responseCode = connection.getResponseCode(); if (!((responseCode == HttpURLConnection.HTTP_CREATED && mapContextId == null) || (responseCode == HttpURLConnection.HTTP_OK && mapContextId != null))) { throw new IOException(I18N.tr("HTTP Error {0} message : {1} with the URL {2}", connection.getResponseCode(), connection.getResponseMessage(), requestWorkspacesURL)); } if (mapContextId == null) { // Get response content BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), RemoteCommons.getConnectionCharset(connection))); XMLInputFactory factory = XMLInputFactory.newInstance(); // Parse Data XMLStreamReader parser; try { parser = factory.createXMLStreamReader(in); // Fill workspaces int resId = parsePublishResponse(parser); parser.close(); return resId; } catch (XMLStreamException ex) { throw new IOException(I18N.tr("Invalid XML content"), ex); } } else { return mapContextId; } }
From source file:org.eclipse.orion.server.tests.servlets.files.AdvancedFilesTest.java
/** * Test commented out due to failure/*www.j av a 2 s . co m*/ */ public void _testETagHandling() throws JSONException, IOException, SAXException { String fileName = "testfile.txt"; //setup: create a file WebRequest request = getPostFilesRequest("", getNewFileJSON(fileName).toString(), fileName); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); //obtain file metadata and ensure data is correct request = getGetFilesRequest(fileName + "?parts=meta"); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject responseObject = new JSONObject(response.getText()); assertNotNull("No file information in response", responseObject); String etag1 = responseObject.getString(ProtocolConstants.KEY_ETAG); assertEquals(etag1, response.getHeaderField(ProtocolConstants.KEY_ETAG)); //modify file request = getPutFileRequest(fileName, "something"); request.setHeaderField("If-Match", etag1); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); responseObject = new JSONObject(response.getText()); assertNotNull("No file information in response", responseObject); String etag2 = responseObject.getString(ProtocolConstants.KEY_ETAG); assertEquals(etag2, response.getHeaderField(ProtocolConstants.KEY_ETAG)); // should be different as file was modified assertFalse(etag2.equals(etag1)); //fetch the metadata again and ensure it is changed and correct request = getGetFilesRequest(fileName + "?parts=meta"); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); responseObject = new JSONObject(response.getText()); String etag3 = responseObject.getString(ProtocolConstants.KEY_ETAG); assertEquals(etag3, response.getHeaderField(ProtocolConstants.KEY_ETAG)); assertEquals(etag2, etag3); }
From source file:bluevia.InitService.java
boolean subscribeNotifications() { boolean result = true; String[] countryShortNumbers = { MO_UK, MO_SP, MO_GE, MO_BR, MO_MX, MO_AR, MO_CH, MO_CO }; int i = 0;//from w w w. ja v a 2s .c o m for (i = 0; i < countryShortNumbers.length; i++) { try { OAuthConsumer consumer = (OAuthConsumer) new DefaultOAuthConsumer(Util.BlueViaOAuth.consumer_key, Util.BlueViaOAuth.consumer_secret); consumer.setMessageSigner(new HmacSha1MessageSigner()); com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate(); URL apiURI = new URL( "https://api.bluevia.com/services/REST/SMS/inbound/subscriptions?version=v1&alt=json"); HttpURLConnection request = (HttpURLConnection) apiURI.openConnection(); Random rand = new Random(); Date now = new Date(); rand.setSeed(now.getTime()); Long correlator = rand.nextLong(); if (correlator < 0) correlator = -1 * correlator; String jsonSubscriptionMsg = "{\"smsNotification\":{\"reference\":{\"correlator\": \"%s\",\"endpoint\": \"%s\"},\"destinationAddress\":{\"phoneNumber\":\"%s\"},\"criteria\":\"%s\"}}"; String szBody = String.format(jsonSubscriptionMsg, "bv" + correlator.toString().substring(0, 16), Util.getCallbackDomain() + "/notifySmsReception", countryShortNumbers[i], Util.BlueViaOAuth.app_keyword); request.setRequestProperty("Content-Type", "application/json"); request.setRequestProperty("Content-Length", "" + Integer.toString(szBody.getBytes().length)); request.setRequestMethod("POST"); request.setDoOutput(true); consumer.sign(request); request.connect(); OutputStream os = request.getOutputStream(); os.write(szBody.getBytes()); os.flush(); int rc = request.getResponseCode(); if (rc == HttpURLConnection.HTTP_CREATED) Util.addUnsubscriptionURI(countryShortNumbers[i], request.getHeaderField("Location"), "bv" + correlator.toString().substring(0, 16)); else { logger.severe(String.format("Error %d registering Notification URLs:%s", rc, request.getResponseMessage())); } } catch (Exception e) { logger.severe("Exception raised: %s" + e.getMessage()); } } return result; }
From source file:org.eclipse.hono.service.registration.RegistrationHttpEndpoint.java
private void registerDevice(final RoutingContext ctx, final JsonObject payload) { if (payload == null) { HttpUtils.badRequest(ctx, "missing body"); } else {/*w w w . j a v a 2s. c om*/ final Object deviceId = payload.remove(RegistrationConstants.FIELD_PAYLOAD_DEVICE_ID); if (deviceId == null) { HttpUtils.badRequest(ctx, String.format("'%s' param is required", RegistrationConstants.FIELD_PAYLOAD_DEVICE_ID)); } else if (!(deviceId instanceof String)) { HttpUtils.badRequest(ctx, String.format("'%s' must be a string", RegistrationConstants.FIELD_PAYLOAD_DEVICE_ID)); } else { final String tenantId = getTenantParam(ctx); logger.debug("registering data for device [tenant: {}, device: {}, payload: {}]", tenantId, deviceId, payload); final JsonObject requestMsg = EventBusMessage.forOperation(RegistrationConstants.ACTION_REGISTER) .setTenant(tenantId).setDeviceId((String) deviceId).setJsonPayload(payload).toJson(); sendAction(ctx, requestMsg, getDefaultResponseHandler(ctx, status -> status == HttpURLConnection.HTTP_CREATED, response -> response.putHeader(HttpHeaders.LOCATION, String.format("/%s/%s/%s", RegistrationConstants.REGISTRATION_ENDPOINT, tenantId, deviceId)))); } } }
From source file:org.eclipse.orion.server.tests.metastore.RemoteMetaStoreTests.java
/** * Create a folder in a project on the Orion server for the test user. * /*from w ww . j a v a2 s. c o m*/ * @param webConversation * @param login * @param password * @param projectName * @return * @throws IOException * @throws JSONException * @throws URISyntaxException * @throws SAXException */ protected int createFolder(WebConversation webConversation, String login, String password, String project) throws IOException, JSONException, URISyntaxException, SAXException { assertEquals(HttpURLConnection.HTTP_OK, login(webConversation, login, password)); JSONObject jsonObject = new JSONObject(); jsonObject.put("Directory", "true"); jsonObject.put("Name", "folder"); jsonObject.put("LocalTimeStamp", "0"); String parent = "/file/" + getWorkspaceId(login) + "/" + project; WebRequest request = new PostMethodWebRequest(getOrionServerURI(parent), IOUtilities.toInputStream(jsonObject.toString()), "application/json"); request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1"); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); System.out.println("Created Folder: " + parent + "/folder"); return response.getResponseCode(); }
From source file:es.tekniker.framework.ktek.questionnaire.mng.server.EventServiceClient.java
public boolean updateContext(String codUser, String nameContext, String typeContext, String valueContext, boolean valueIsjson) { HttpURLConnection conn = null; StringBuffer strBOutput = new StringBuffer(); boolean boolOK = true; String input = null;//from w w w . j ava2 s .c o m StringBuffer stbInput = new StringBuffer(); try { log.debug("updateContext Start "); conn = getEventServiceSEConnection(methodUpdateContext, endpointEventService, headerContentTypeJSON); stbInput.append("{\"contextElements\": [{\"type\": \"" + typeContextValue + "\",\"isPattern\": \"false\",\"id\": \"" + codUser + "\",\"attributes\":"); if (valueIsjson) stbInput.append(" [{\"name\": \"" + nameContext + "\",\"type\": \"" + typeContext + "\",\"value\": " + valueContext + "}]}]"); else stbInput.append(" [{\"name\": \"" + nameContext + "\",\"type\": \"" + typeContext + "\",\"value\": \"" + valueContext + "\"}]}]"); stbInput.append(",\"updateAction\": \"APPEND\"}"); input = stbInput.toString(); log.debug(input); OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() == 200) { log.debug("updateContext Response code " + conn.getResponseCode()); } else { if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException( "updateContext Failed : HTTP error code : " + conn.getResponseCode()); } } log.debug("updateContext OutputStream wrote"); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); log.debug("updateContext Waiting server response "); String output; log.debug("updateContext Output from Server .... \n"); while ((output = br.readLine()) != null) { strBOutput.append(output); log.debug(output); } conn.disconnect(); boolOK = true; } catch (MalformedURLException e) { log.error("updateContext MalformedURLException " + e.getMessage()); e.printStackTrace(); boolOK = false; } catch (IOException e) { log.error("updateContext IOException " + e.getMessage()); e.printStackTrace(); boolOK = false; } return boolOK; }
From source file:org.jboss.narayana.rts.TransactionAwareResource.java
private String enlist(String enlistUrl, String linkHeader) { Map<String, String> reqHeaders = new HashMap<>(); reqHeaders.put("Link", linkHeader); return new TxSupport().httpRequest(new int[] { HttpURLConnection.HTTP_CREATED }, enlistUrl, "POST", TxMediaType.POST_MEDIA_TYPE, null, null, reqHeaders); }
From source file:it.infn.ct.indigo.futuregateway.server.FGServerManager.java
/** * Add a new resource into the FG service. * * @param companyId The id of the instance * @param collection The name of the collection to post the new resource * @param resourceId The id of the resource to add. If provided the * resource will be overwritten * @param resource The resource information in JSON format * @param token The token of the user performing the action * @return The Id of the new resource/*w w w. j av a 2s. c o m*/ * @throws PortalException Cannot retrieve the server endpoint * @throws IOException Connect communicate with the server */ public final String addResource(final long companyId, final String collection, final String resourceId, final String resource, final String token) throws PortalException, IOException { log.debug("Updating/adding the resource in " + collection + ": " + resource); HttpURLConnection connection; boolean resourceExist = false; if (resourceId != null && !resourceId.isEmpty()) { resourceExist = true; connection = getFGConnection(companyId, collection, resourceId, token, HttpMethods.PUT, FutureGatewayAdminPortletKeys.FUTURE_GATEWAY_CONTENT_TYPE); } else { connection = getFGConnection(companyId, collection, null, token, HttpMethods.POST, FutureGatewayAdminPortletKeys.FUTURE_GATEWAY_CONTENT_TYPE); } OutputStream os = connection.getOutputStream(); os.write(resource.getBytes()); os.flush(); if (resourceExist && connection.getResponseCode() == HttpURLConnection.HTTP_OK) { return resourceId; } if (!resourceExist && connection.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new IOException("Impossible to add the resource. " + "Server response with code: " + connection.getResponseCode()); } StringBuilder result = new StringBuilder(); try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String readLine; while ((readLine = br.readLine()) != null) { result.append(readLine); } } connection.disconnect(); JSONObject jRes = JSONFactoryUtil.createJSONObject(result.toString()); return jRes.getString(FGServerConstants.ATTRIBUTE_ID); }