List of usage examples for org.w3c.dom Node hasChildNodes
public boolean hasChildNodes();
From source file:org.dasein.cloud.aws.compute.EC2Instance.java
private @Nullable VirtualMachine toVirtualMachine(@Nonnull ProviderContext ctx, @Nullable Node instance, @Nonnull Iterable<IpAddress> addresses) throws CloudException { if (instance == null) { return null; }//from ww w .ja v a 2 s . c o m String rootDeviceName = null; NodeList attrs = instance.getChildNodes(); VirtualMachine server = new VirtualMachine(); server.setPersistent(false); server.setProviderOwnerId(ctx.getAccountNumber()); server.setCurrentState(VmState.PENDING); server.setName(null); server.setDescription(null); for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); String name; name = attr.getNodeName(); if (name.equals("instanceId")) { String value = attr.getFirstChild().getNodeValue().trim(); server.setProviderVirtualMachineId(value); } else if (name.equals("architecture")) { String value = attr.getFirstChild().getNodeValue().trim(); Architecture architecture; if (value.equalsIgnoreCase("i386")) { architecture = Architecture.I32; } else { architecture = Architecture.I64; } server.setArchitecture(architecture); } else if (name.equals("imageId")) { String value = attr.getFirstChild().getNodeValue().trim(); server.setProviderMachineImageId(value); } else if (name.equals("kernelId")) { String value = attr.getFirstChild().getNodeValue().trim(); server.setTag("kernelImageId", value); server.setProviderKernelImageId(value); } else if (name.equals("ramdiskId")) { String value = attr.getFirstChild().getNodeValue().trim(); server.setTag("ramdiskImageId", value); server.setProviderRamdiskImageId(value); } else if (name.equalsIgnoreCase("subnetId")) { server.setProviderSubnetId(attr.getFirstChild().getNodeValue().trim()); } else if (name.equalsIgnoreCase("vpcId")) { server.setProviderVlanId(attr.getFirstChild().getNodeValue().trim()); } else if (name.equals("instanceState")) { NodeList details = attr.getChildNodes(); for (int j = 0; j < details.getLength(); j++) { Node detail = details.item(j); name = detail.getNodeName(); if (name.equals("name")) { String value = detail.getFirstChild().getNodeValue().trim(); server.setCurrentState(getServerState(value)); } } } else if (name.equals("privateDnsName")) { if (attr.hasChildNodes()) { String value = attr.getFirstChild().getNodeValue(); RawAddress[] addrs = server.getPrivateAddresses(); server.setPrivateDnsAddress(value); if (addrs == null || addrs.length < 1) { value = guess(value); if (value != null) { server.setPrivateAddresses(new RawAddress(value)); } } } } else if (name.equals("dnsName")) { if (attr.hasChildNodes()) { String value = attr.getFirstChild().getNodeValue(); server.setPublicDnsAddress(value); } } else if (name.equals("privateIpAddress")) { if (attr.hasChildNodes()) { String value = attr.getFirstChild().getNodeValue(); server.setPrivateAddresses(new RawAddress(value)); } } else if (name.equals("ipAddress")) { if (attr.hasChildNodes()) { String value = attr.getFirstChild().getNodeValue(); server.setPublicAddresses(new RawAddress(value)); for (IpAddress addr : addresses) { if (value.equals(addr.getRawAddress().getIpAddress())) { server.setProviderAssignedIpAddressId(addr.getProviderIpAddressId()); break; } } } } else if (name.equals("rootDeviceType")) { if (attr.hasChildNodes()) { server.setPersistent(attr.getFirstChild().getNodeValue().equalsIgnoreCase("ebs")); } } else if (name.equals("tagSet")) { Map<String, String> tags = getProvider().getTagsFromTagSet(attr); if (tags != null && tags.size() > 0) { server.setTags(tags); for (Map.Entry<String, String> entry : tags.entrySet()) { if (entry.getKey().equalsIgnoreCase("name")) { server.setName(entry.getValue()); } else if (entry.getKey().equalsIgnoreCase("description")) { server.setDescription(entry.getValue()); } } } } else if (name.equals("instanceType")) { String value = attr.getFirstChild().getNodeValue().trim(); server.setProductId(value); } else if (name.equals("launchTime")) { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); fmt.setCalendar(UTC_CALENDAR); String value = attr.getFirstChild().getNodeValue().trim(); try { server.setLastBootTimestamp(fmt.parse(value).getTime()); server.setCreationTimestamp(server.getLastBootTimestamp()); } catch (ParseException e) { logger.error(e); throw new CloudException(e); } } else if (name.equals("platform")) { if (attr.hasChildNodes()) { Platform platform = Platform.guess(attr.getFirstChild().getNodeValue()); if (platform.equals(Platform.UNKNOWN)) { platform = Platform.UNIX; } server.setPlatform(platform); } } else if (name.equals("placement")) { NodeList details = attr.getChildNodes(); for (int j = 0; j < details.getLength(); j++) { Node detail = details.item(j); name = detail.getNodeName(); if (name.equals("availabilityZone")) { if (detail.hasChildNodes()) { String value = detail.getFirstChild().getNodeValue().trim(); server.setProviderDataCenterId(value); } } } } else if (name.equals("networkInterfaceSet")) { ArrayList<String> networkInterfaceIds = new ArrayList<String>(); if (attr.hasChildNodes()) { NodeList items = attr.getChildNodes(); for (int j = 0; j < items.getLength(); j++) { Node item = items.item(j); if (item.getNodeName().equals("item") && item.hasChildNodes()) { NodeList parts = item.getChildNodes(); String networkInterfaceId = null; for (int k = 0; k < parts.getLength(); k++) { Node part = parts.item(k); if (part.getNodeName().equalsIgnoreCase("networkInterfaceId")) { if (part.hasChildNodes()) { networkInterfaceId = part.getFirstChild().getNodeValue().trim(); } } } if (networkInterfaceId != null) { networkInterfaceIds.add(networkInterfaceId); } } } } if (networkInterfaceIds.size() > 0) { server.setProviderNetworkInterfaceIds( networkInterfaceIds.toArray(new String[networkInterfaceIds.size()])); } /* [FIXME?] TODO: Really networkInterfaceSet needs to be own type/resource Example: <networkInterfaceSet> <item> <networkInterfaceId>eni-1a2b3c4d</networkInterfaceId> <subnetId>subnet-1a2b3c4d</subnetId> <vpcId>vpc-1a2b3c4d</vpcId> <description>Primary network interface</description> <ownerId>111122223333</ownerId> <status>in-use</status> <macAddress>1b:2b:3c:4d:5e:6f</macAddress> <privateIpAddress>10.0.0.12</privateIpAddress> <sourceDestCheck>true</sourceDestCheck> <groupSet> <item> <groupId>sg-1a2b3c4d</groupId> <groupName>my-security-group</groupName> </item> </groupSet> <attachment> <attachmentId>eni-attach-1a2b3c4d</attachmentId> <deviceIndex>0</deviceIndex> <status>attached</status> <attachTime>YYYY-MM-DDTHH:MM:SS+0000</attachTime> <deleteOnTermination>true</deleteOnTermination> </attachment> <association> <publicIp>198.51.100.63</publicIp> <ipOwnerId>111122223333</ipOwnerId> </association> <privateIpAddressesSet> <item> <privateIpAddress>10.0.0.12</privateIpAddress> <primary>true</primary> <association> <publicIp>198.51.100.63</publicIp> <ipOwnerId>111122223333</ipOwnerId> </association> </item> <item> <privateIpAddress>10.0.0.14</privateIpAddress> <primary>false</primary> <association> <publicIp>198.51.100.177</publicIp> <ipOwnerId>111122223333</ipOwnerId> </association> </item> </privateIpAddressesSet> </item> </networkInterfaceSet> */ } else if (name.equals("keyName")) { server.setProviderKeypairId(AWSCloud.getTextValue(attr)); } else if (name.equals("groupSet")) { ArrayList<String> firewalls = new ArrayList<String>(); if (attr.hasChildNodes()) { NodeList tags = attr.getChildNodes(); for (int j = 0; j < tags.getLength(); j++) { Node tag = tags.item(j); if (tag.getNodeName().equals("item") && tag.hasChildNodes()) { NodeList parts = tag.getChildNodes(); String groupId = null; for (int k = 0; k < parts.getLength(); k++) { Node part = parts.item(k); if (part.getNodeName().equalsIgnoreCase("groupId")) { if (part.hasChildNodes()) { groupId = part.getFirstChild().getNodeValue().trim(); } } } if (groupId != null) { firewalls.add(groupId); } } } } if (firewalls.size() > 0) { server.setProviderFirewallIds(firewalls.toArray(new String[firewalls.size()])); } } else if ("blockDeviceMapping".equals(name) && attr.hasChildNodes()) { List<Volume> volumes = new ArrayList<Volume>(); if (attr.hasChildNodes()) { NodeList blockDeviceMapping = attr.getChildNodes(); for (int j = 0; j < blockDeviceMapping.getLength(); j++) { Node bdmItems = blockDeviceMapping.item(j); if (bdmItems.getNodeName().equals("item") && bdmItems.hasChildNodes()) { NodeList items = bdmItems.getChildNodes(); Volume volume = new Volume(); for (int k = 0; k < items.getLength(); k++) { Node item = items.item(k); String itemNodeName = item.getNodeName(); if ("deviceName".equals(itemNodeName)) { volume.setDeviceId(AWSCloud.getTextValue(item)); } else if ("ebs".equals(itemNodeName)) { NodeList ebsNodeList = item.getChildNodes(); for (int l = 0; l < ebsNodeList.getLength(); l++) { Node ebsNode = ebsNodeList.item(l); String ebsNodeName = ebsNode.getNodeName(); if ("volumeId".equals(ebsNodeName)) { volume.setProviderVolumeId(AWSCloud.getTextValue(ebsNode)); } else if ("status".equals(ebsNodeName)) { volume.setCurrentState(EBSVolume.toVolumeState(ebsNode)); } else if ("deleteOnTermination".equals(ebsNodeName)) { volume.setDeleteOnVirtualMachineTermination( AWSCloud.getBooleanValue(ebsNode)); } } } } if (volume.getDeviceId() != null) { volumes.add(volume); } } } } if (volumes.size() > 0) { server.setVolumes(volumes.toArray(new Volume[volumes.size()])); } } else if ("rootDeviceName".equals(name) && attr.hasChildNodes()) { rootDeviceName = AWSCloud.getTextValue(attr); } else if ("ebsOptimized".equals(name) && attr.hasChildNodes()) { server.setIoOptimized(AWSCloud.getBooleanValue(attr)); } else if ("sourceDestCheck".equals(name) && attr.hasChildNodes()) { /** * note: a value of <sourceDestCheck>true</sourceDestCheck> means this instance cannot * function as a NAT instance, so we negate the value to indicate if it is allowed */ server.setIpForwardingAllowed(!AWSCloud.getBooleanValue(attr)); } else if ("stateReasonMessage".equals(name)) { server.setStateReasonMessage(AWSCloud.getTextValue(attr)); } else if ("iamInstanceProfile".equals(name) && attr.hasChildNodes()) { NodeList details = attr.getChildNodes(); for (int j = 0; j < details.getLength(); j++) { Node detail = details.item(j); name = detail.getNodeName(); if (name.equals("arn")) { if (detail.hasChildNodes()) { String value = detail.getFirstChild().getNodeValue().trim(); server.setProviderRoleId(value); } } } } else if ("instanceLifecycle".equals(name)) { String value = AWSCloud.getTextValue(attr); if (value != null && "spot".equalsIgnoreCase(value)) { server.setLifecycle(VirtualMachineLifecycle.SPOT); } } else if ("spot-instance-request-id".equals(name)) { server.setSpotRequestId(AWSCloud.getTextValue(attr)); } } if (server.getPlatform() == null) { server.setPlatform(Platform.UNKNOWN); } server.setProviderRegionId(ctx.getRegionId()); if (server.getName() == null) { server.setName(server.getProviderVirtualMachineId()); } if (server.getDescription() == null) { server.setDescription(server.getName() + " (" + server.getProductId() + ")"); } if (server.getArchitecture() == null && server.getProductId() != null) { server.setArchitecture(getArchitecture(server.getProductId())); } else if (server.getArchitecture() == null) { server.setArchitecture(Architecture.I64); } // find the root device in the volumes list and set boolean value if (rootDeviceName != null && server.getVolumes() != null) { for (Volume volume : server.getVolumes()) { if (rootDeviceName.equals(volume.getDeviceId())) { volume.setRootVolume(true); break; } } } return server; }
From source file:org.dasein.cloud.aws.identity.IAM.java
private @Nullable CloudPolicy[] getGroupPolicy(@Nonnull CloudGroup group, @Nonnull String policyName) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER: " + IAM.class.getName() + ".getGroupPolicy(" + group + "," + policyName + ")"); }//www . j av a2s . c om try { Map<String, String> parameters = provider.getStandardParameters(provider.getContext(), IAMMethod.GET_GROUP_POLICY, IAMMethod.VERSION); EC2Method method; NodeList blocks; Document doc; parameters.put("GroupName", group.getName()); parameters.put("PolicyName", policyName); if (logger.isDebugEnabled()) { logger.debug("parameters=" + parameters); } method = new IAMMethod(provider, parameters); try { doc = method.invoke(); blocks = doc.getElementsByTagName("GetGroupPolicyResult"); for (int i = 0; i < blocks.getLength(); i++) { Node policyNode = blocks.item(i); if (policyNode.hasChildNodes()) { NodeList attrs = policyNode.getChildNodes(); for (int j = 0; j < attrs.getLength(); j++) { Node attr = attrs.item(j); if (attr.getNodeName().equalsIgnoreCase("PolicyDocument")) { String json = URLDecoder.decode(attr.getFirstChild().getNodeValue().trim(), "utf-8"); JSONObject stmt = new JSONObject(json); if (stmt.has("Statement")) { return toPolicy(policyName, stmt.getJSONArray("Statement")); } } } } } return null; } catch (EC2Exception e) { if (e.getStatus() == 404) { return null; } logger.error(e.getSummary()); throw new CloudException(e); } catch (JSONException e) { logger.error("Failed to parse policy statement: " + e.getMessage()); throw new CloudException(e); } catch (UnsupportedEncodingException e) { logger.error("Unknown encoding in utf-8: " + e.getMessage()); throw new InternalException(e); } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT: " + IAM.class.getName() + ".getGroupPolicy()"); } } }
From source file:org.dasein.cloud.aws.identity.IAM.java
private @Nullable CloudPolicy[] getUserPolicy(@Nonnull CloudUser user, @Nonnull String policyName) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER: " + IAM.class.getName() + ".getUserPolicy(" + user + "," + policyName + ")"); }//from w ww . j av a 2s .com try { Map<String, String> parameters = provider.getStandardParameters(provider.getContext(), IAMMethod.GET_USER_POLICY, IAMMethod.VERSION); EC2Method method; NodeList blocks; Document doc; parameters.put("UserName", user.getUserName()); parameters.put("PolicyName", policyName); if (logger.isDebugEnabled()) { logger.debug("parameters=" + parameters); } method = new IAMMethod(provider, parameters); try { doc = method.invoke(); blocks = doc.getElementsByTagName("GetUserPolicyResult"); for (int i = 0; i < blocks.getLength(); i++) { Node policyNode = blocks.item(i); if (policyNode.hasChildNodes()) { NodeList attrs = policyNode.getChildNodes(); for (int j = 0; j < attrs.getLength(); j++) { Node attr = attrs.item(j); if (attr.getNodeName().equalsIgnoreCase("PolicyDocument")) { String json = URLDecoder.decode(attr.getFirstChild().getNodeValue().trim(), "utf-8"); JSONObject stmt = new JSONObject(json); if (stmt.has("Statement")) { return toPolicy(policyName, stmt.getJSONArray("Statement")); } } } } } return null; } catch (EC2Exception e) { if (e.getStatus() == 404) { return null; } logger.error(e.getSummary()); throw new CloudException(e); } catch (JSONException e) { logger.error("Failed to parse policy statement: " + e.getMessage()); throw new CloudException(e); } catch (UnsupportedEncodingException e) { logger.error("Unknown encoding in utf-8: " + e.getMessage()); throw new InternalException(e); } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT: " + IAM.class.getName() + ".getUserPolicy()"); } } }
From source file:org.dasein.cloud.aws.identity.IAM.java
@Override public @Nonnull Iterable<CloudPolicy> listPoliciesForGroup(@Nonnull String providerGroupId) throws CloudException, InternalException { APITrace.begin(provider, "IAM.listPoliciesForGroup"); try {/*from w w w . j a v a 2 s .c om*/ ProviderContext ctx = provider.getContext(); if (ctx == null) { logger.error("No context was established for this request."); throw new InternalException("No context was established for this request"); } CloudGroup group = getGroup(providerGroupId); if (group == null) { throw new CloudException("No such group: " + providerGroupId); } Map<String, String> parameters = provider.getStandardParameters(provider.getContext(), IAMMethod.LIST_GROUP_POLICIES, IAMMethod.VERSION); EC2Method method; NodeList blocks; Document doc; parameters.put("GroupName", group.getName()); if (logger.isDebugEnabled()) { logger.debug("parameters=" + parameters); } method = new IAMMethod(provider, parameters); try { ArrayList<String> names = new ArrayList<String>(); doc = method.invoke(); blocks = doc.getElementsByTagName("member"); for (int i = 0; i < blocks.getLength(); i++) { Node member = blocks.item(i); if (member.hasChildNodes()) { String name = member.getFirstChild().getNodeValue().trim(); if (name.length() > 0) { names.add(name); } } } ArrayList<CloudPolicy> policies = new ArrayList<CloudPolicy>(); for (String name : names) { Collections.addAll(policies, getGroupPolicy(group, name)); } if (logger.isDebugEnabled()) { logger.debug("policies=" + policies); } return policies; } catch (EC2Exception e) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } }
From source file:org.dasein.cloud.aws.identity.IAM.java
@Override public @Nonnull Iterable<CloudPolicy> listPoliciesForUser(@Nonnull String providerUserId) throws CloudException, InternalException { APITrace.begin(provider, "IAM.listPoliciesForUser"); try {/*from www . ja v a 2 s . c om*/ ProviderContext ctx = provider.getContext(); if (ctx == null) { logger.error("No context was established for this request."); throw new InternalException("No context was established for this request"); } CloudUser user = getUser(providerUserId); if (user == null) { throw new CloudException("No such user: " + providerUserId); } Map<String, String> parameters = provider.getStandardParameters(provider.getContext(), IAMMethod.LIST_USER_POLICIES, IAMMethod.VERSION); EC2Method method; NodeList blocks; Document doc; parameters.put("UserName", user.getUserName()); if (logger.isDebugEnabled()) { logger.debug("parameters=" + parameters); } method = new IAMMethod(provider, parameters); try { ArrayList<String> names = new ArrayList<String>(); doc = method.invoke(); blocks = doc.getElementsByTagName("member"); for (int i = 0; i < blocks.getLength(); i++) { Node member = blocks.item(i); if (member.hasChildNodes()) { String name = member.getFirstChild().getNodeValue().trim(); if (name.length() > 0) { names.add(name); } } } ArrayList<CloudPolicy> policies = new ArrayList<CloudPolicy>(); for (String name : names) { Collections.addAll(policies, getUserPolicy(user, name)); } if (logger.isDebugEnabled()) { logger.debug("policies=" + policies); } return policies; } catch (EC2Exception e) { logger.error(e.getSummary()); throw new CloudException(e); } } finally { APITrace.end(); } }
From source file:org.dasein.cloud.aws.identity.IAM.java
private @Nullable AccessKey toAccessKey(@Nonnull ProviderContext ctx, @Nullable Node node) throws CloudException, InternalException { if (node == null) { return null; }/*from w w w .ja v a 2 s . c o m*/ NodeList attributes = node.getChildNodes(); AccessKey key = new AccessKey(); key.setProviderOwnerId(ctx.getAccountNumber()); String userName = null; for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); String attrName = attribute.getNodeName(); if (attrName.equalsIgnoreCase("UserName") && attribute.hasChildNodes()) { userName = attribute.getFirstChild().getNodeValue().trim(); } else if (attrName.equalsIgnoreCase("AccessKeyId") && attribute.hasChildNodes()) { key.setSharedPart(attribute.getFirstChild().getNodeValue().trim()); } else if (attrName.equalsIgnoreCase("SecretAccessKey") && attribute.hasChildNodes()) { try { key.setSecretPart(attribute.getFirstChild().getNodeValue().trim().getBytes("utf-8")); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } } else if (attrName.equalsIgnoreCase("Status")) { if (!attribute.hasChildNodes() || !attribute.getFirstChild().getNodeValue().trim().equalsIgnoreCase("Active")) { return null; } } } if (userName != null) { CloudUser user = getUserByName(userName); if (user == null) { logger.warn("Found key " + key.getSharedPart() + " belonging to " + userName + ", but no matching user"); return null; } String userId = user.getProviderUserId(); if (userId == null) { logger.warn("Found key " + key.getSharedPart() + " belonging to " + userName + ", but no matching user"); return null; } key.setProviderUserId(userId); } if (key.getSharedPart() == null || key.getSecretPart() == null) { return null; } return key; }
From source file:org.dasein.cloud.aws.identity.IAM.java
private @Nullable CloudGroup toGroup(@Nonnull ProviderContext ctx, @Nullable Node node) throws CloudException, InternalException { if (node == null) { return null; }//from w w w .jav a 2s . c o m NodeList attributes = node.getChildNodes(); CloudGroup group = new CloudGroup(); group.setPath("/"); group.setProviderOwnerId(ctx.getAccountNumber()); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); String attrName = attribute.getNodeName(); if (attrName.equalsIgnoreCase("Path") && attribute.hasChildNodes()) { group.setPath(attribute.getFirstChild().getNodeValue().trim()); } else if (attrName.equalsIgnoreCase("GroupId") && attribute.hasChildNodes()) { group.setProviderGroupId(attribute.getFirstChild().getNodeValue().trim()); } else if (attrName.equalsIgnoreCase("GroupName") && attribute.hasChildNodes()) { group.setName(attribute.getFirstChild().getNodeValue().trim()); } } if (group.getName() == null || group.getProviderGroupId() == null) { return null; } return group; }
From source file:org.dasein.cloud.aws.identity.IAM.java
private @Nullable CloudUser toUser(@Nonnull ProviderContext ctx, @Nullable Node node) throws CloudException, InternalException { if (node == null) { return null; }//from w ww .jav a2s .co m NodeList attributes = node.getChildNodes(); CloudUser user = new CloudUser(); user.setPath("/"); user.setProviderOwnerId(ctx.getAccountNumber()); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); String attrName = attribute.getNodeName(); if (attrName.equalsIgnoreCase("Path") && attribute.hasChildNodes()) { user.setPath(attribute.getFirstChild().getNodeValue().trim()); } else if (attrName.equalsIgnoreCase("UserId") && attribute.hasChildNodes()) { user.setProviderUserId(attribute.getFirstChild().getNodeValue().trim()); } else if (attrName.equalsIgnoreCase("UserName") && attribute.hasChildNodes()) { user.setUserName(attribute.getFirstChild().getNodeValue().trim()); } } if (user.getUserName() == null || user.getProviderUserId() == null) { return null; } return user; }
From source file:org.dasein.cloud.aws.storage.S3Method.java
S3Response invoke(@Nullable String bucket, @Nullable String object, @Nullable String temporaryEndpoint) throws S3Exception, CloudException, InternalException { if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("----------------------------------------------------------------------------------"); }//from w ww. jav a 2s . c o m HttpClient client = null; boolean leaveOpen = false; try { StringBuilder url = new StringBuilder(); HttpRequestBase method; int status; // Sanitise the parameters as they may have spaces and who knows what else if (bucket != null) { bucket = AWSCloud.encode(bucket, false); } if (object != null && !"?location".equalsIgnoreCase(object) && !"?acl".equalsIgnoreCase(object) && !"?tagging".equalsIgnoreCase(object)) { object = AWSCloud.encode(object, false); } if (temporaryEndpoint != null) { temporaryEndpoint = AWSCloud.encode(temporaryEndpoint, false); } if (provider.getEC2Provider().isAWS()) { url.append("https://"); String regionId = provider.getContext().getRegionId(); if (temporaryEndpoint == null) { boolean validDomainName = isValidDomainName(bucket); if (bucket != null && validDomainName) { url.append(bucket); if (regionId != null && !regionId.isEmpty() && !"us-east-1".equals(regionId)) { url.append(".s3-"); url.append(regionId); url.append(".amazonaws.com/"); } else { url.append(".s3.amazonaws.com/"); } } else { if (regionId != null && !regionId.isEmpty() && !"us-east-1".equals(regionId)) { url.append("s3-"); url.append(regionId); url.append(".amazonaws.com/"); } else { url.append("s3.amazonaws.com/"); } } if (bucket != null && !validDomainName) { url.append(bucket); url.append("/"); } } else { url.append(temporaryEndpoint); url.append("/"); } } else if (provider.getEC2Provider().isStorage() && "google".equalsIgnoreCase(provider.getProviderName())) { url.append("https://"); if (temporaryEndpoint == null) { if (bucket != null) { url.append(bucket); url.append("."); } url.append("commondatastorage.googleapis.com/"); } else { url.append(temporaryEndpoint); url.append("/"); } } else { int idx = 0; if (!provider.getContext().getEndpoint().startsWith("http")) { url.append("https://"); } else { idx = provider.getContext().getEndpoint().indexOf("https://"); if (idx == -1) { idx = "http://".length(); url.append("http://"); } else { idx = "https://".length(); url.append("https://"); } } String service = ""; if (provider.getEC2Provider().isEucalyptus()) { service = "Walrus/"; } if (temporaryEndpoint == null) { url.append(provider.getContext().getEndpoint().substring(idx)); if (!provider.getContext().getEndpoint().endsWith("/")) { url.append("/").append(service); } else { url.append(service); } } else { url.append(temporaryEndpoint); url.append("/"); url.append(service); } if (bucket != null) { url.append(bucket); url.append("/"); } } if (object != null) { url.append(object); } else if (parameters != null) { boolean first = true; if (object != null && object.indexOf('?') != -1) { first = false; } for (Map.Entry<String, String> entry : parameters.entrySet()) { String key = entry.getKey(); String val = entry.getValue(); if (first) { url.append("?"); first = false; } else { url.append("&"); } if (val != null) { url.append(AWSCloud.encode(key, false)); url.append("="); url.append(AWSCloud.encode(val, false)); } else { url.append(AWSCloud.encode(key, false)); } } } if (provider.getEC2Provider().isStorage() && provider.getProviderName().equalsIgnoreCase("Google")) { headers.put(AWSCloud.P_GOOG_DATE, getDate()); } else { headers.put(AWSCloud.P_AWS_DATE, provider.getV4HeaderDate(null)); } if (contentType == null && body != null) { contentType = "application/xml"; headers.put("Content-Type", contentType); } else if (contentType != null) { headers.put("Content-Type", contentType); } method = action.getMethod(url.toString()); String host = method.getURI().getHost(); headers.put("host", host); if (action.equals(S3Action.PUT_BUCKET_TAG)) try { headers.put("Content-MD5", toBase64(computeMD5Hash(body))); } catch (NoSuchAlgorithmException e) { logger.error(e); } catch (IOException e) { logger.error(e); } if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { method.addHeader(entry.getKey(), entry.getValue()); } } if (body != null) { ((HttpEntityEnclosingRequestBase) method).setEntity(new StringEntity(body, APPLICATION_XML)); } else if (uploadFile != null) { ((HttpEntityEnclosingRequestBase) method).setEntity(new FileEntity(uploadFile, contentType)); } try { String hash = null; if (method instanceof HttpEntityEnclosingRequestBase) { try { hash = provider.getRequestBodyHash( EntityUtils.toString(((HttpEntityEnclosingRequestBase) method).getEntity())); } catch (IOException e) { throw new InternalException(e); } } else { hash = provider.getRequestBodyHash(""); } String signature; if (provider.getEC2Provider().isAWS()) { // Sign v4 for AWS signature = provider.getV4Authorization(new String(provider.getAccessKey()[0]), new String(provider.getAccessKey()[1]), method.getMethod(), url.toString(), SERVICE_ID, headers, hash); if (hash != null) { method.addHeader(AWSCloud.P_AWS_CONTENT_SHA256, hash); } } else { // Eucalyptus et al use v2 signature = provider.signS3(new String(provider.getAccessKey()[0], "utf-8"), provider.getAccessKey()[1], method.getMethod(), null, contentType, headers, bucket, object); } method.addHeader(AWSCloud.P_CFAUTH, signature); } catch (UnsupportedEncodingException e) { logger.error(e); } if (wire.isDebugEnabled()) { wire.debug("[" + url.toString() + "]"); wire.debug(method.getRequestLine().toString()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { try { wire.debug(EntityUtils.toString(((HttpEntityEnclosingRequestBase) method).getEntity())); } catch (IOException ignore) { } wire.debug(""); } else if (uploadFile != null) { wire.debug("-- file upload --"); wire.debug(""); } } attempts++; client = provider.getClient(body == null && uploadFile == null); S3Response response = new S3Response(); HttpResponse httpResponse; try { APITrace.trace(provider, action.toString()); httpResponse = client.execute(method); if (wire.isDebugEnabled()) { wire.debug(httpResponse.getStatusLine().toString()); for (Header header : httpResponse.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } status = httpResponse.getStatusLine().getStatusCode(); } catch (IOException e) { logger.error(url + ": " + e.getMessage()); throw new InternalException(e); } response.headers = httpResponse.getAllHeaders(); HttpEntity entity = httpResponse.getEntity(); InputStream input = null; if (entity != null) { try { input = entity.getContent(); } catch (IOException e) { throw new CloudException(e); } } try { if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_ACCEPTED) { Header clen = httpResponse.getFirstHeader("Content-Length"); long len = -1L; if (clen != null) { len = Long.parseLong(clen.getValue()); } if (len != 0L) { try { Header ct = httpResponse.getFirstHeader("Content-Type"); if ((ct != null && (ct.getValue().startsWith("application/xml") || ct.getValue().startsWith("text/xml"))) || (action.equals(S3Action.GET_BUCKET_TAG) && input != null)) { try { response.document = parseResponse(input); return response; } finally { input.close(); } } else if (ct != null && ct.getValue().startsWith("application/octet-stream") && len < 1) { return null; } else { response.contentLength = len; if (ct != null) { response.contentType = ct.getValue(); } response.input = input; response.method = method; leaveOpen = true; return response; } } catch (IOException e) { logger.error(e); throw new CloudException(e); } } else { return response; } } else if (status == HttpStatus.SC_NO_CONTENT) { return response; } if (status == HttpStatus.SC_FORBIDDEN) { throw new S3Exception(status, "", "AccessForbidden", "Access was denied : " + (url != null ? url.toString() : "")); } else if (status == HttpStatus.SC_NOT_FOUND) { throw new S3Exception(status, null, null, "Object not found."); } else { if (status == HttpStatus.SC_SERVICE_UNAVAILABLE || status == HttpStatus.SC_INTERNAL_SERVER_ERROR) { if (attempts >= 5) { String msg; if (status == HttpStatus.SC_SERVICE_UNAVAILABLE) { msg = "Cloud service is currently unavailable."; } else { msg = "The cloud service encountered a server error while processing your request."; } logger.error(msg); throw new CloudException(msg); } else { leaveOpen = true; if (input != null) { try { input.close(); } catch (IOException ignore) { } } try { Thread.sleep(5000L); } catch (InterruptedException ignore) { } return invoke(bucket, object); } } try { Document doc; try { logger.warn("Received error code: " + status); doc = parseResponse(input); } finally { if (input != null) { input.close(); } } if (doc != null) { String endpoint = null, code = null, message = null, requestId = null; NodeList blocks = doc.getElementsByTagName("Error"); if (blocks.getLength() > 0) { Node error = blocks.item(0); NodeList attrs; attrs = error.getChildNodes(); for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); if (attr.getNodeName().equals("Code") && attr.hasChildNodes()) { code = attr.getFirstChild().getNodeValue().trim(); } else if (attr.getNodeName().equals("Message") && attr.hasChildNodes()) { message = attr.getFirstChild().getNodeValue().trim(); } else if (attr.getNodeName().equals("RequestId") && attr.hasChildNodes()) { requestId = attr.getFirstChild().getNodeValue().trim(); } else if (attr.getNodeName().equals("Endpoint") && attr.hasChildNodes()) { endpoint = attr.getFirstChild().getNodeValue().trim(); } } } if (endpoint != null && code.equals("TemporaryRedirect")) { if (temporaryEndpoint != null) { throw new CloudException("Too deep redirect to " + endpoint); } else { return invoke(bucket, object, endpoint); } } else { if (message == null) { throw new CloudException("Unable to identify error condition: " + status + "/" + requestId + "/" + code); } throw new S3Exception(status, requestId, code, message); } } else { throw new CloudException("Unable to parse error."); } } catch (IOException e) { if (status == HttpStatus.SC_FORBIDDEN) { throw new S3Exception(status, "", "AccessForbidden", "Access was denied without explanation."); } throw new CloudException(e); } catch (RuntimeException e) { throw new CloudException(e); } catch (Error e) { throw new CloudException(e); } } } finally { if (!leaveOpen) { if (input != null) { try { input.close(); } catch (IOException ignore) { } } } } } finally { if (!leaveOpen && client != null) { client.getConnectionManager().shutdown(); } if (wire.isDebugEnabled()) { wire.debug("----------------------------------------------------------------------------------"); wire.debug(""); } } }
From source file:org.dasein.cloud.azure.AzureLocation.java
public boolean isSubscribed(AzureService toService) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new AzureConfigException("No context was specified for this request"); }// w w w.ja v a2 s . c o m AzureMethod method = new AzureMethod(provider); Document doc = method.getAsXML(ctx.getAccountNumber(), LOCATIONS); if (doc == null) { return false; } NodeList entries = doc.getElementsByTagName("Location"); for (int i = 0; i < entries.getLength(); i++) { Node entry = entries.item(i); if (entry != null) { NodeList attributes = entry.getChildNodes(); String regionId = null; boolean subscribed = false; for (int j = 0; j < attributes.getLength(); j++) { Node attribute = attributes.item(j); if (attribute.getNodeName().equalsIgnoreCase("name") && attribute.hasChildNodes()) { regionId = attribute.getFirstChild().getNodeValue().trim(); } else if (attribute.getNodeName().equalsIgnoreCase("availableservices") && attribute.hasChildNodes()) { NodeList services = attribute.getChildNodes(); for (int k = 0; k < services.getLength(); k++) { Node service = services.item(k); if (service != null && service.getNodeName().equalsIgnoreCase("availableservice") && service.hasChildNodes()) { String serviceName = service.getFirstChild().getNodeValue().trim(); if (toService.toString().equalsIgnoreCase(serviceName)) { subscribed = true; break; } } } } } if (regionId != null && regionId.equalsIgnoreCase(ctx.getRegionId())) { return subscribed; } } } return false; }