List of usage examples for org.apache.http.client.methods HttpUriRequest setHeader
void setHeader(String str, String str2);
From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java
@Override public void createStorageAccount(String accountName, String label, String description, String location, String affinityGroup, AsyncResultCallback callback) { if (accountName == null) throw new IllegalArgumentException("Storage account name is required!"); if (label == null) throw new IllegalArgumentException("Label is required!"); if (description == null) description = ""; String lc = ""; if (location != null && location.length() > 0) { lc = MessageFormat.format(HOSTED_SERVICE_LOCATION, location); if (!isLocationExist(location)) throw new IllegalArgumentException("Location is not exist!"); }//from w w w.j av a 2s. com if (affinityGroup != null && affinityGroup.length() > 0) { if (lc.length() > 0) { throw new IllegalArgumentException("Specify either Location or AffinityGroup, but not both!"); } else { lc = MessageFormat.format(HOSTED_SERVICE_AFFINITYGROUP, affinityGroup); } } HttpUriRequest request = HttpUtilities .createServiceHttpRequest(URI.create(getBaseUrl() + SERVICES_STORAGESERVICE), HttpMethod.Post); request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2011_06_01); request.addHeader(HeaderNames.ContentType, APPLICATION_XML); String base64Label = Base64.encode(label.getBytes()); String body = MessageFormat.format(CREATE_STORAGE_SERVICE, accountName, base64Label, description, lc); ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body.getBytes())); sendAsynchronousRequest(request, callback); }
From source file:com.buffalokiwi.aerodrome.jet.JetAPI.java
/** * Checks the authentication state, and if it needs to be authenticated, this * locks the api and authenticates. //from w w w . j a v a 2s.c o m * @param hr * @throws APIException */ private void checkAuth(final HttpUriRequest hr) throws APIException { try { if (!authLock.isHeldByCurrentThread() && authLock.tryLock(1000L, TimeUnit.MILLISECONDS) && !isReauth.get()) { APILog.debug(LOG, "Thread " + Thread.currentThread().getName() + " obtained the authentication lock"); try { if (!config.isAuthenticated()) { performReauth(hr); } } finally { try { APILog.debug(LOG, "Thread " + Thread.currentThread().getName() + " has released the authentication lock"); authLock.unlock(); } catch (Exception e) { APILog.debug(LOG, e, "Thread " + Thread.currentThread().getName() + " Caused an exception while trying to release it's lock"); } } } else { if (!authLock.isHeldByCurrentThread()) APILog.debug(LOG, "Thread " + Thread.currentThread().getName() + " is waiting for authentication"); int ct = 0; while (!authLock.isHeldByCurrentThread() && !config.isAuthenticated() && !isReauth.get()) { Thread.sleep(1000L); } hr.setHeader("Authorization", config.getAuthorizationHeaderValue()); } } catch (InterruptedException e) { //..do nothing } catch (Exception e) { throw e; } }
From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java
/** * The Create Hosted Service operation creates a new hosted service in * Windows Azure./* w w w. ja v a 2 s . co m*/ * * @param serviceName * @param configuration * @return */ public void createHostedService(String serviceName, String label, String description, String location, String affinityGroup) { if (serviceName == null) throw new IllegalArgumentException("Service name is required!"); if (label == null) throw new IllegalArgumentException("Service label is required!"); if (isServiceExist(serviceName)) throw new IllegalArgumentException("Service already exist!"); if (description == null) description = ""; String lc = ""; if (location != null && location.length() > 0) { lc = MessageFormat.format(HOSTED_SERVICE_LOCATION, location); if (!isLocationExist(location)) throw new IllegalArgumentException("Location is not exist!"); } if (affinityGroup != null && affinityGroup.length() > 0) { if (lc.length() > 0) { throw new IllegalArgumentException("Specify either Location or AffinityGroup, but not both!"); } else { lc = MessageFormat.format(HOSTED_SERVICE_AFFINITYGROUP, affinityGroup); } } HttpUriRequest request = HttpUtilities .createServiceHttpRequest(URI.create(getBaseUrl() + SERVICES_HOSTEDSERVICES), HttpMethod.Post); request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2010_10_28); request.addHeader(HeaderNames.ContentType, APPLICATION_XML); String base64Label = Base64.encode(label.getBytes()); String body = MessageFormat.format(CREATE_HOSTED_SERVICE, serviceName, base64Label, description, lc); try { ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body.getBytes())); HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory()); if (response.getStatusCode() == HttpStatus.SC_OK || response.getStatusCode() == HttpStatus.SC_CREATED) { return; } else { HttpUtilities.processUnexpectedStatusCode(response); } } catch (StorageException we) { throw HttpUtilities.translateWebException(we); } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:org.tellervo.desktop.wsi.WebJaxbAccessor.java
private INTYPE doRequest() throws IOException { HttpClient client = new ContentEncodingHttpClient(); HttpUriRequest req; JAXBContext context;/*w w w . j ava 2s. c o m*/ Document outDocument = null; try { context = getJAXBContext(); } catch (JAXBException jaxb) { throw new IOException("Unable to acquire JAXB context: " + jaxb.getMessage()); } try { if (requestMethod == RequestMethod.POST) { if (this.sendingObject == null) throw new NullPointerException("requestDocument is null yet required for this type of query"); // Create a new POST request HttpPost post = new HttpPost(url); // Make it a multipart post MultipartEntity postEntity = new MultipartEntity(); req = post; // create an XML document from the given objects outDocument = marshallToDocument(context, sendingObject, getNamespacePrefixMapper()); // add it to the http post request XMLBody xmlb = new XMLBody(outDocument, "application/tellervo+xml", null); postEntity.addPart("xmlrequest", xmlb); postEntity.addPart("traceback", new StringBody(getStackTrace())); post.setEntity(postEntity); } else { // well, that's nice and easy req = new HttpGet(url); } // debug this transaction... TransactionDebug.sent(outDocument, noun); // load cookies ((AbstractHttpClient) client).setCookieStore(WSCookieStoreHandler.getCookieStore().toCookieStore()); req.setHeader("User-Agent", "Tellervo WSI " + Build.getUTF8Version() + " (" + clientModuleVersion + "; ts " + Build.getCompleteVersionNumber() + ")"); if (App.prefs.getBooleanPref(PrefKey.WEBSERVICE_USE_STRICT_SECURITY, false)) { // Using strict security so don't allow self signed certificates for SSL } else { // Not using strict security so allow self signed certificates for SSL if (url.getScheme().equals("https")) WebJaxbAccessor.setSelfSignableHTTPSScheme(client); } // create a responsehandler JaxbResponseHandler<INTYPE> responseHandler = new JaxbResponseHandler<INTYPE>(context, receivingObjectClass); // set the schema we validate against responseHandler.setValidateSchema(getValidationSchema()); // execute the actual http query INTYPE inObject = null; try { inObject = client.execute(req, responseHandler); } catch (EOFException e4) { log.debug("Caught EOFException"); } TransactionDebug.received(inObject, noun, context); // save our cookies? WSCookieStoreHandler.getCookieStore().fromCookieStore(((AbstractHttpClient) client).getCookieStore()); // ok, now inspect the document we got back //TellervoDocumentInspector inspector = new TellervoDocumentInspector(inDocument); // Verify our document based on schema validity //inspector.validate(); // Verify our document structure, throw any exceptions! //inspector.verifyDocument(); return inObject; } catch (UnknownHostException e) { throw new IOException("The URL of the server you have specified is unknown"); } catch (HttpResponseException hre) { if (hre.getStatusCode() == 404) { throw new IOException("The URL of the server you have specified is unknown"); } BugReport bugs = new BugReport(hre); bugs.addDocument("sent.xml", outDocument); new BugDialog(bugs); throw new IOException("The server returned a protocol error " + hre.getStatusCode() + ": " + hre.getLocalizedMessage()); } catch (IllegalStateException ex) { throw new IOException("Webservice URL must be a full URL qualified with a communications protocol.\n" + "Tellervo currently supports http:// and https://."); } catch (ResponseProcessingException rspe) { Throwable cause = rspe.getCause(); BugReport bugs = new BugReport(cause); Document invalidDoc = rspe.getNonvalidatingDocument(); File invalidFile = rspe.getInvalidFile(); if (outDocument != null) bugs.addDocument("sent.xml", outDocument); if (invalidDoc != null) bugs.addDocument("recv-nonvalid.xml", invalidDoc); if (invalidFile != null) bugs.addDocument("recv-malformed.xml", invalidFile); new BugDialog(bugs); XMLDebugView.addDocument(BugReport.getStackTrace(cause), "Parsing Exception", true); // it's probably an ioexception... if (cause instanceof IOException) throw (IOException) cause; throw rspe; } catch (XMLParsingException xmlpe) { Throwable cause = xmlpe.getCause(); BugReport bugs = new BugReport(cause); Document invalidDoc = xmlpe.getNonvalidatingDocument(); File invalidFile = xmlpe.getInvalidFile(); bugs.addDocument("sent.xml", outDocument); if (invalidDoc != null) bugs.addDocument("recv-nonvalid.xml", invalidDoc); if (invalidFile != null) bugs.addDocument("recv-malformed.xml", invalidFile); new BugDialog(bugs); XMLDebugView.addDocument(BugReport.getStackTrace(cause), "Parsing Exception", true); // it's probably an ioexception... if (cause instanceof IOException) throw (IOException) cause; throw xmlpe; } catch (IOException ioe) { throw ioe; } catch (Exception uhe) { BugReport bugs = new BugReport(uhe); bugs.addDocument("sent.xml", outDocument); /* // MalformedDocs are handled automatically by BugReport class if(!(uhe instanceof MalformedDocumentException) && inDocument != null) bugs.addDocument("received.xml", inDocument); */ new BugDialog(bugs); throw new IOException("Exception " + uhe.getClass().getName() + ": " + uhe.getLocalizedMessage()); } finally { //? } }
From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java
@Override public void updateAffinityGroup(String groupName, String label, String description) { if (groupName == null) throw new IllegalArgumentException("Group name is required!"); if (label == null) throw new IllegalArgumentException("Label is required!"); HttpUriRequest request = HttpUtilities.createServiceHttpRequest( URI.create(getBaseUrl() + SERVICES_AFFINITYGROUPS + ConstChars.Slash + groupName), HttpMethod.Put); request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2011_02_25); request.addHeader(HeaderNames.ContentType, APPLICATION_XML); String base64Label = Base64.encode(label.getBytes()); if (description == null) description = ""; else//from w ww.j a va 2 s . c o m description = "<Description>" + description + "</Description>"; String body = MessageFormat.format(UPDATE_AFFINITY_GROUP, base64Label, description); try { ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body.getBytes())); HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory()); if (response.getStatusCode() == HttpStatus.SC_OK) { return; } else { HttpUtilities.processUnexpectedStatusCode(response); } } catch (StorageException we) { throw HttpUtilities.translateWebException(we); } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java
@Override public void deleteAffinityGroup(String groupName) { HttpUriRequest request = HttpUtilities.createServiceHttpRequest( URI.create(getBaseUrl() + SERVICES_AFFINITYGROUPS + ConstChars.Slash + groupName), HttpMethod.Delete);/*from ww w. j a va 2 s .c o m*/ try { request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2011_02_25); HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory()); if (isRequestAccepted(response)) { return; } else { HttpUtilities.processUnexpectedStatusCode(response); } } catch (StorageException we) { throw HttpUtilities.translateWebException(we); } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java
@Override public void updateStorageAccount(String accountName, String label, String description) { if (label == null && description == null) throw new IllegalArgumentException( "You must specify a value for either Label or Description, or for both."); HttpUriRequest request = HttpUtilities.createServiceHttpRequest( URI.create(getBaseUrl() + SERVICES_STORAGESERVICE + ConstChars.Slash + accountName), HttpMethod.Put);//from w w w. j a v a 2s. com request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2011_06_01); request.addHeader(HeaderNames.ContentType, APPLICATION_XML); String base64Label = ""; if (label != null) base64Label = "<Label>" + Base64.encode(label.getBytes()) + "</Label>"; if (description == null) description = ""; else description = "<Description>" + description + "</Description>"; String body = MessageFormat.format(UPDATE_STORAGE_SERVICE, description, base64Label); try { ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body.getBytes())); HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory()); if (response.getStatusCode() == HttpStatus.SC_OK) { return; } else { HttpUtilities.processUnexpectedStatusCode(response); } } catch (StorageException we) { throw HttpUtilities.translateWebException(we); } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java
/** * The Update Hosted Service operation updates the label and/or the * description for a hosted service in Windows Azure. * //w w w . j a v a 2s . c om * @param serviceName */ public void updateHostedService(String serviceName, String label, String description) { if (label == null && description == null) throw new IllegalArgumentException( "You must specify a value for either Label or Description, or for both."); HttpUriRequest request = HttpUtilities.createServiceHttpRequest( URI.create(getBaseUrl() + SERVICES_HOSTEDSERVICES + ConstChars.Slash + serviceName), HttpMethod.Put); request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2010_10_28); request.addHeader(HeaderNames.ContentType, APPLICATION_XML); String base64Label = ""; if (label != null) base64Label = "<Label>" + Base64.encode(label.getBytes()) + "</Label>"; if (description == null) description = ""; else description = "<Description>" + description + "</Description>"; String body = MessageFormat.format(UPDATE_HOSTED_SERVICE, base64Label, description); try { ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body.getBytes())); HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory()); if (response.getStatusCode() == HttpStatus.SC_OK) { return; } else { HttpUtilities.processUnexpectedStatusCode(response); } } catch (StorageException we) { throw HttpUtilities.translateWebException(we); } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java
/** * The Delete Hosted Service operation deletes the specified hosted service * from Windows Azure.// w ww . j a va2 s .c o m * * @param serviceName */ public void deleteHostedService(String serviceName) { HttpUriRequest request = HttpUtilities.createServiceHttpRequest( URI.create(getBaseUrl() + SERVICES_HOSTEDSERVICES + ConstChars.Slash + serviceName), HttpMethod.Delete); try { request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2010_10_28); HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory()); if (isRequestAccepted(response)) { return; } else { HttpUtilities.processUnexpectedStatusCode(response); } } catch (StorageException we) { throw HttpUtilities.translateWebException(we); } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java
@Override public void deleteStorageAccount(String accountName) { HttpUriRequest request = HttpUtilities.createServiceHttpRequest( URI.create(getBaseUrl() + SERVICES_STORAGESERVICE + ConstChars.Slash + accountName), HttpMethod.Delete);//from ww w . ja v a 2s . c o m try { request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2011_06_01); HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory()); if (isRequestAccepted(response)) { return; } else { HttpUtilities.processUnexpectedStatusCode(response); } } catch (StorageException we) { throw HttpUtilities.translateWebException(we); } catch (Exception e) { throw new IllegalStateException(e); } }