List of usage examples for org.apache.commons.lang3 StringUtils removeEnd
public static String removeEnd(final String str, final String remove)
Removes a substring only if it is at the end of a source string, otherwise returns the source string.
A null source string will return null .
From source file:com.norconex.commons.lang.url.URLNormalizer.java
/** * <p>Removes trailing question mark ("?").</p> * <code>http://www.example.com/display? → * http://www.example.com/display </code> * @return this instance//from w ww . j a va2 s . c o m */ public URLNormalizer removeTrailingQuestionMark() { if (url.endsWith("?") && StringUtils.countMatches(url, "?") == 1) { url = StringUtils.removeEnd(url, "?"); } return this; }
From source file:fusion.Fusion.java
private static void getINASameAsLinks(File file) throws FileNotFoundException, IOException, URISyntaxException { try (BufferedReader br = new BufferedReader(new FileReader(file))) { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { if (line.contains("owl:sameAs")) { sb.append(line);/*from w w w. ja v a2 s . c om*/ sb.append(System.lineSeparator()); } line = br.readLine(); } String linksString = sb.toString(); String[] linksArray = linksString.split("\n"); for (int i = 0; i < linksArray.length; i++) { String value1 = linksArray[i].substring(0, linksArray[i].indexOf(" owl:sameAs")); String value2 = linksArray[i].substring(linksArray[i].lastIndexOf("owl:sameAs ") + 11, linksArray[i].length() - 1); value1 = StringUtils.removeStart(value1, "<"); value2 = StringUtils.removeStart(value2, "<"); value1 = StringUtils.removeStart(value1, "http://www.ina.fr/thesaurus/pp/"); value2 = StringUtils.removeStart(value2, "http://www.ina.fr/thesaurus/pp/"); value1 = StringUtils.removeStart(value1, "http://fr.dbpedia.org/resource/"); // value2 = StringUtils.removeStart(value2, "http://fr.dbpedia.org/resource/"); // value1 = StringUtils.removeEnd(value1, "."); value2 = StringUtils.removeEnd(value2, "."); value1 = StringUtils.removeEnd(value1, ">"); value2 = StringUtils.removeEnd(value2, ">"); if (!distinctURLs.containsKey(value1.hashCode())) distinctURLs.put(value1.hashCode(), new URI(value1)); if (!distinctURLs.containsKey(value2.hashCode())) distinctURLs.put(value2.hashCode(), new URI(value2)); links.add(new SameAsLink(distinctURLs.get(value1.hashCode()), distinctURLs.get(value2.hashCode()))); // adding same as links } for (Integer name : distinctURLs.keySet()) { Instance instance = new Instance(distinctURLs.get(name), null); if (distinctURLs.get(name).toString().contains("dbpedia")) instance.setSource(sources.get("fr.dbpedia.org")); else instance.setSource(sources.get("www.ina.fr")); instances.put(instance.getUri(), instance); } } }
From source file:com.moscona.dataSpace.persistence.DirectoryDataStore.java
@Override public void moveAllSegments(IVector vector, boolean fromTemporary, boolean toTemporary) throws DataSpaceException { stats.startTimerFor(TIMING_MOVE_ALL_SEGMENTS); try {/* ww w. j a va2 s . c om*/ if (fromTemporary == toTemporary) { return; // nothing to do } if (!AbstractVector.class.isAssignableFrom(vector.getClass())) { throw new DataSpaceException( "This implementation only knows how to deal with AbstractVector instances. Got " + vector.getClass().getName()); } AbstractVector.SegmentIterator iterator = ((AbstractVector) vector).segmentIterator(); while (iterator.hasNext()) { AbstractVector.SegmentInfo segment = iterator.next(); String location = ((AbstractVectorSegment) segment.getSegment()).getBackingArrayStorageLocation(); if (location == null) { throw new DataSpaceException( "Found a segment with no existing file location in moveAllSegments()! Segment #" + segment.getSegmentNumber() + " Assume that the vector storage is now corrupt!"); } String newLocation = toTemporary ? location + TEMPORARY_SEGMENT_EXT : StringUtils.removeEnd(location, TEMPORARY_SEGMENT_EXT); boolean success = new File(location).renameTo(new File(newLocation)); if (!success) { throw new DataSpaceException("Failed to rename segment file in moveAllSegments()! Segment #" + segment.getSegmentNumber() + " Assume that the vector storage is now corrupt! Segment file: " + location); } ((AbstractVectorSegment) segment.getSegment()).setBackingArrayStorageLocation(newLocation); } } finally { stopTimerFor(TIMING_MOVE_ALL_SEGMENTS); } }
From source file:de.crowdcode.kissmda.core.uml.UmlHelper.java
/** * Check for parameterized type to get the template parameter substitution. * //ww w. j a v a 2s . c o m * @param type * UML2 type * @return Map of umlTypeName and umlQualifiedTypeName */ public Map<String, String> checkParameterizedTypeForTemplateParameterSubstitution(Type type) { Map<String, String> results = new HashMap<String, String>(); String umlTypeName = type.getName(); String umlQualifiedTypeName = type.getQualifiedName(); List<String> templateSubstitutions = getTemplateParameterSubstitution(type); if (templateSubstitutions.size() != 0) { int index = 0; String paramTypeNames = StringUtils.substringAfter(umlTypeName, "<"); paramTypeNames = StringUtils.removeEnd(paramTypeNames, ">"); EList<String> paramTypeNameList = convertStringToList(paramTypeNames, ","); for (String paramTypeName : paramTypeNameList) { umlTypeName = StringUtils.replace(umlTypeName, paramTypeName, templateSubstitutions.get(index)); umlQualifiedTypeName = StringUtils.replace(umlQualifiedTypeName, paramTypeName, templateSubstitutions.get(index)); index = index + 1; } } results.put("umlTypeName", umlTypeName); results.put("umlQualifiedTypeName", umlQualifiedTypeName); return results; }
From source file:com.evolveum.midpoint.web.component.wizard.resource.SynchronizationStep.java
private static String getTypeDisplayName(@NotNull QName name) { return StringUtils.removeEnd(name.getLocalPart(), "Type"); }
From source file:com.moscona.dataSpace.persistence.DirectoryDataStore.java
private String getBackingArrayPathForSegment(int num, String suffix) { String str = Integer.toString(num); ArrayList<String> parts = new ArrayList<String>(); while (str.length() > 2) { String head = StringUtils.left(str, 2); str = StringUtils.removeStart(str, head); parts.add(head);// w w w .j a va2s . co m } return StringUtils.removeEnd(segmentsDirName() + StringUtils.join(parts, "/"), "/") + "/" + Integer.toString(num) + "." + suffix.trim(); }
From source file:in.mycp.remote.EucalyptusService.java
@RemoteMethod public void syncDataFromEuca(Infra infra) { User currentUser = null;//from w ww . j a v a 2s . co m Company company = null; currentUser = Commons.getCurrentUser(); company = Company.findCompany(Commons.getCurrentSession().getCompanyId()); AssetType assetTypeIpAddress = AssetType.findAssetTypesByNameEquals("IpAddress").getSingleResult(); AssetType assetTypeSecurityGroup = AssetType.findAssetTypesByNameEquals("SecurityGroup").getSingleResult(); AssetType assetTypeVolume = AssetType.findAssetTypesByNameEquals("Volume").getSingleResult(); AssetType assetTypeVolumeSnapshot = AssetType.findAssetTypesByNameEquals("VolumeSnapshot") .getSingleResult(); AssetType assetTypeComputeImage = AssetType.findAssetTypesByNameEquals("ComputeImage").getSingleResult(); AssetType assetTypeComputeInstance = AssetType.findAssetTypesByNameEquals("ComputeInstance") .getSingleResult(); AssetType assetTypeKeyPair = AssetType.findAssetTypesByNameEquals("KeyPair").getSingleResult(); ProductCatalog ipaddressProduct = null; ProductCatalog secGroupProduct = null; ProductCatalog volumeProduct = null; ProductCatalog snapshotProduct = null; ProductCatalog computeProduct = null; ProductCatalog imageProduct = null; ProductCatalog keypairProduct = null; Set<ProductCatalog> products = infra.getProductCatalogs(); if (products != null && products.size() > 0) { } else { logger.error("Please set up products for this Cloud before synchronizing."); return; } for (Iterator iterator = products.iterator(); iterator.hasNext();) { ProductCatalog productCatalog = (ProductCatalog) iterator.next(); if (productCatalog.getProductType().equals(Commons.ProductType.ComputeImage.getName())) { imageProduct = productCatalog; } else if (productCatalog.getProductType().equals(Commons.ProductType.ComputeInstance.getName())) { computeProduct = productCatalog; } else if (productCatalog.getProductType().equals(Commons.ProductType.IpAddress.getName())) { ipaddressProduct = productCatalog; } else if (productCatalog.getProductType().equals(Commons.ProductType.KeyPair.getName())) { keypairProduct = productCatalog; } else if (productCatalog.getProductType().equals(Commons.ProductType.SecurityGroup.getName())) { secGroupProduct = productCatalog; } else if (productCatalog.getProductType().equals(Commons.ProductType.Volume.getName())) { volumeProduct = productCatalog; } else if (productCatalog.getProductType().equals(Commons.ProductType.VolumeSnapshot.getName())) { snapshotProduct = productCatalog; } } if (ipaddressProduct == null) { logger.error("Please set up ipaddress Product for this Cloud before synchronizing."); return; } else if (secGroupProduct == null) { logger.error("Please set up Security Group Product for this Cloud before synchronizing."); return; } else if (volumeProduct == null) { logger.error("Please set up Volume Product for this Cloud before synchronizing."); return; } else if (snapshotProduct == null) { logger.error("Please set up Snapshot Product for this Cloud before synchronizing."); return; } else if (computeProduct == null) { logger.error("Please set up Compute Product for this Cloud before synchronizing."); return; } else if (imageProduct == null) { logger.error("Please set up Image Product for this Cloud before synchronizing."); return; } else if (keypairProduct == null) { logger.error("Please set up Key Pair Product for this Cloud before synchronizing."); return; } Date start = new Date(); logger.info("Connect Start:" + new Date()); Jec2 ec2 = getNewJce2(infra); String ownerId = ""; List<String> params = new ArrayList<String>(); try { params = new ArrayList<String>(); List<GroupDescription> groupDescs = ec2.describeSecurityGroups(params); logger.info("Available Security groups @" + (new Date().getTime() - start.getTime()) / 1000 + " S"); for (Iterator iterator = groupDescs.iterator(); iterator.hasNext();) { GroupDescription groupDescription = (GroupDescription) iterator.next(); logger.info(groupDescription); GroupDescriptionP descriptionP = null; try { List<GroupDescriptionP> groups = GroupDescriptionP .findGroupDescriptionPsByNameEqualsAndCompanyEquals(groupDescription.getName(), company) .getResultList(); inner: for (Iterator iterator2 = groups.iterator(); iterator2.hasNext();) { GroupDescriptionP groupDescriptionP = (GroupDescriptionP) iterator2.next(); //check if this security group is for this cloud or for some other in teh same account. //if same , then we do an update below.if not, we will create new. if (groupDescriptionP.getAsset().getProductCatalog().getInfra().getId() == infra.getId()) { descriptionP = groupDescriptionP; break inner; } } } catch (Exception e) { //logger.error(e.getMessage());// descriptionP = null; e.printStackTrace(); } if (descriptionP != null) { descriptionP.setDescripton(groupDescription.getDescription()); descriptionP.setOwner(groupDescription.getOwner()); } else { descriptionP = new GroupDescriptionP(); descriptionP.setName(groupDescription.getName()); descriptionP.setDescripton(groupDescription.getDescription()); descriptionP.setOwner(groupDescription.getOwner()); Asset asset = Commons.getNewAsset(assetTypeSecurityGroup, currentUser, secGroupProduct); descriptionP.setStatus(Commons.secgroup_STATUS.active + ""); descriptionP.setAsset(asset); } //needed for other work in snapshot import ownerId = groupDescription.getOwner(); descriptionP = descriptionP.merge(); List<IpPermission> ipPermissions = groupDescription.getPermissions(); Set<IpPermissionP> ipPermissionPs = new HashSet<IpPermissionP>(); for (Iterator iterator2 = ipPermissions.iterator(); iterator2.hasNext();) { IpPermission ipPermission = (IpPermission) iterator2.next(); logger.info(ipPermission.getFromPort() + ipPermission.getProtocol() + ipPermission.getToPort() + ipPermission.getIpRanges()); IpPermissionP ipPermissionP = null; try { // .findIpPermissionPsByProtocolEqualsAndToPortEqualsAndFromPortEquals( ipPermissionP = IpPermissionP .findIpPermissionPsByGroupDescriptionAndProtocolEqualsAndFromPortEquals( descriptionP, ipPermission.getProtocol(), ipPermission.getFromPort()) .getSingleResult(); // ipPermission.getProtocol(), ipPermission.getToPort(), // ipPermission.getFromPort()).getSingleResult(); } catch (Exception e) { //logger.error(e.getMessage()); e.printStackTrace(); } if (ipPermissionP != null) { // do not create a new object } else { ipPermissionP = new IpPermissionP(); } List<String> cidrIps = ipPermission.getIpRanges(); String cidrIps_str = ""; for (Iterator iterator3 = cidrIps.iterator(); iterator3.hasNext();) { String string = (String) iterator3.next(); cidrIps_str = cidrIps_str + string + ","; } cidrIps_str = StringUtils.removeEnd(cidrIps_str, ","); List<String[]> uidGroupPairs = ipPermission.getUidGroupPairs(); String uidGroupPairs_str = ""; for (Iterator iterator3 = uidGroupPairs.iterator(); iterator3.hasNext();) { String[] strArray = (String[]) iterator3.next(); String strArray_str = ""; for (int i = 0; i < strArray.length; i++) { strArray_str = strArray_str + strArray[i] + ","; } strArray_str = StringUtils.removeEnd(strArray_str, ","); uidGroupPairs_str = uidGroupPairs_str + strArray_str + ","; } uidGroupPairs_str = StringUtils.removeEnd(uidGroupPairs_str, ","); ipPermissionP.setCidrIps(cidrIps_str); ipPermissionP.setUidGroupPairs(uidGroupPairs_str); ipPermissionP.setFromPort(ipPermission.getFromPort()); ipPermissionP.setGroupDescription(descriptionP); ipPermissionP.setProtocol(ipPermission.getProtocol()); ipPermissionP.setToPort(ipPermission.getToPort()); descriptionP = descriptionP.merge(); ipPermissionP.setGroupDescription(descriptionP); ipPermissionP = ipPermissionP.merge(); if (descriptionP.getIpPermissionPs() != null) { descriptionP.getIpPermissionPs().add(ipPermissionP); } else { Set<IpPermissionP> ipPermissionPsNew = new HashSet<IpPermissionP>(); ipPermissionPsNew.add(ipPermissionP); descriptionP.setIpPermissionPs(ipPermissionPsNew); } descriptionP = descriptionP.merge(); } /* * GroupDescriptionP descriptionP = new GroupDescriptionP(null, * groupDescription.getName(), * groupDescription.getDescription(), * groupDescription.getOwner(), null); */ } // end of for groupDescs.iterator() //clean up the security groups which are just hanging around just getting created for the last 1 hour List<GroupDescriptionP> secGroups = GroupDescriptionP.findAllGroupDescriptionPs(); for (Iterator secGroupiterator = secGroups.iterator(); secGroupiterator.hasNext();) { GroupDescriptionP groupDescriptionP = (GroupDescriptionP) secGroupiterator.next(); try { if (groupDescriptionP.getStatus().equals(Commons.secgroup_STATUS.starting + "") && (new Date().getTime() - groupDescriptionP.getAsset().getStartTime().getTime() > (1000 * 60 * 60))) { groupDescriptionP.getAsset().setEndTime(groupDescriptionP.getAsset().getStartTime()); groupDescriptionP.setStatus(Commons.secgroup_STATUS.failed + ""); groupDescriptionP.merge(); } } catch (Exception e) { //e.printStackTrace(); logger.error(e); } } } catch (Exception e) { e.printStackTrace(); } try { List<AddressInfo> addressInfos = ec2.describeAddresses(params); logger.info("Available addresses @ " + (new Date().getTime() - start.getTime()) / 1000 + " S"); for (Iterator iterator = addressInfos.iterator(); iterator.hasNext();) { AddressInfo addressInfo = (AddressInfo) iterator.next(); logger.info(addressInfo.getInstanceId() + "-----" + addressInfo.getPublicIp()); if (addressInfo.getInstanceId() == null || addressInfo.getInstanceId().startsWith("nobody")) { // do not import free IPs continue; } AddressInfoP addressInfoP = null; try { addressInfoP = AddressInfoP .findAddressInfoPsByPublicIpEqualsAndCompanyEquals(addressInfo.getPublicIp(), company) .getSingleResult(); } catch (Exception e) { //logger.error(e.getMessage());//e.printStackTrace(); } if (addressInfoP == null) { addressInfoP = new AddressInfoP(); Asset asset = Commons.getNewAsset(assetTypeIpAddress, currentUser, ipaddressProduct); addressInfoP.setAsset(asset); addressInfoP.setStatus(Commons.ipaddress_STATUS.available + ""); addressInfoP = addressInfoP.merge(); } addressInfoP.setInstanceId(addressInfo.getInstanceId()); addressInfoP.setPublicIp(addressInfo.getPublicIp()); addressInfoP = addressInfoP.merge(); } List<AddressInfoP> addresses = AddressInfoP.findAllAddressInfoPs(); for (Iterator iterator = addresses.iterator(); iterator.hasNext();) { AddressInfoP addressInfoP = (AddressInfoP) iterator.next(); try { if (addressInfoP.getStatus().equals(Commons.ipaddress_STATUS.starting + "") && (new Date().getTime() - addressInfoP.getAsset().getStartTime().getTime() > (1000 * 60 * 60))) { addressInfoP.getAsset().setEndTime(addressInfoP.getAsset().getStartTime()); addressInfoP.setStatus(Commons.ipaddress_STATUS.failed + ""); addressInfoP.merge(); } } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } /* params = new ArrayList<String>(); List<RegionInfo> regions = ec2.describeRegions(params); for (Iterator iterator = regions.iterator(); iterator.hasNext();) { RegionInfo regionInfo = (RegionInfo) iterator.next(); logger.info("regionInfo = " + regionInfo); RegionP regionP = null; try { regionP = RegionP.findRegionPsByNameEquals(regionInfo.getName()).getSingleResult(); } catch (Exception e) { logger.error(e.getMessage());//e.printStackTrace(); } if (regionP != null) { } else { regionP = new RegionP(); } regionP.setName(regionInfo.getName()); regionP.setUrl(regionInfo.getUrl()); regionP = regionP.merge(); } */ try { params = new ArrayList<String>(); List<AvailabilityZone> zones = ec2.describeAvailabilityZones(params); for (Iterator iterator = zones.iterator(); iterator.hasNext();) { AvailabilityZone availabilityZone = (AvailabilityZone) iterator.next(); logger.info("availabilityZone = " + availabilityZone); AvailabilityZoneP availabilityZoneP = null; try { availabilityZoneP = AvailabilityZoneP .findAvailabilityZonePsByNameEquals(availabilityZone.getName()).getSingleResult(); } catch (Exception e) { //logger.error(e.getMessage());//e.printStackTrace(); } if (availabilityZoneP != null) { } else { availabilityZoneP = new AvailabilityZoneP(); } availabilityZoneP.setName(availabilityZone.getName()); availabilityZoneP.setRegionName(availabilityZone.getRegionName()); availabilityZoneP.setState(availabilityZone.getState()); availabilityZoneP.setInfraId(infra); infra.setZone(availabilityZone.getName()); availabilityZoneP = availabilityZoneP.merge(); } } catch (Exception e) { e.printStackTrace(); } try { params = new ArrayList<String>(); List<VolumeInfo> volumes = ec2.describeVolumes(params); logger.info("Available Volumes"); for (Iterator iterator = volumes.iterator(); iterator.hasNext();) { VolumeInfo volumeInfo = (VolumeInfo) iterator.next(); logger.info(volumeInfo.getSize() + volumeInfo.getVolumeId() + volumeInfo.getCreateTime().getTime()); VolumeInfoP volumeInfoP = null; try { volumeInfoP = VolumeInfoP .findVolumeInfoPsByVolumeIdEqualsAndCompanyEquals(volumeInfo.getVolumeId(), company) .getSingleResult(); } catch (Exception e) { //logger.error(e.getMessage());//e.printStackTrace(); } if (volumeInfoP != null) { } else { volumeInfoP = new VolumeInfoP(); Asset asset = Commons.getNewAsset(assetTypeVolume, currentUser, volumeProduct); volumeInfoP.setAsset(asset); } volumeInfoP.setSize(Integer.parseInt(volumeInfo.getSize())); volumeInfoP.setVolumeId(volumeInfo.getVolumeId()); volumeInfoP.setCreateTime(volumeInfo.getCreateTime().getTime()); volumeInfoP.setZone(volumeInfo.getZone()); volumeInfoP.setStatus(volumeInfo.getStatus()); volumeInfoP.setSnapshotId(volumeInfo.getSnapshotId()); volumeInfoP = volumeInfoP.merge(); List<AttachmentInfoP> existingAttachments = AttachmentInfoP .findAttachmentInfoPsByVolumeIdEquals(volumeInfoP.getVolumeId()).getResultList(); if (existingAttachments != null) { for (Iterator iterator2 = existingAttachments.iterator(); iterator2.hasNext();) { AttachmentInfoP attachmentInfoP = (AttachmentInfoP) iterator2.next(); attachmentInfoP.remove(); } } List<AttachmentInfo> attachments = volumeInfo.getAttachmentInfo(); Set<AttachmentInfoP> attachments4Store = new HashSet<AttachmentInfoP>(); if (attachments != null && attachments.size() > 0) { for (Iterator iterator2 = attachments.iterator(); iterator2.hasNext();) { AttachmentInfo attachmentInfo = (AttachmentInfo) iterator2.next(); AttachmentInfoP attachmentInfoP = new AttachmentInfoP(); attachmentInfoP.setAttachTime(attachmentInfo.getAttachTime().getTime()); attachmentInfoP.setDevice(attachmentInfo.getDevice()); attachmentInfoP.setInstanceId(attachmentInfo.getInstanceId()); attachmentInfoP.setVolumeId(attachmentInfo.getVolumeId()); attachmentInfoP.setStatus(attachmentInfo.getStatus()); attachmentInfoP.setVolumeInfo(volumeInfoP); volumeInfoP.setDevice(attachmentInfo.getDevice()); volumeInfoP.setInstanceId(attachmentInfo.getInstanceId()); volumeInfoP.setStatus(Commons.VOLUME_STATUS_ATTACHED); attachmentInfoP = attachmentInfoP.merge(); attachments4Store.add(attachmentInfoP); } } volumeInfoP.setAttachmentInfoPs(attachments4Store); volumeInfoP = volumeInfoP.merge(); } // end of for volumes.iterator() } catch (Exception e) { e.printStackTrace(); } List<VolumeInfoP> vols = VolumeInfoP.findAllVolumeInfoPs(); for (Iterator volIterator = vols.iterator(); volIterator.hasNext();) { VolumeInfoP volumeInfo2 = (VolumeInfoP) volIterator.next(); try { if (volumeInfo2.getStatus().equals(Commons.VOLUME_STATUS_CREATING) && (new Date().getTime() - volumeInfo2.getAsset().getStartTime().getTime() > (1000 * 60 * 60))) { volumeInfo2.getAsset().setEndTime(volumeInfo2.getAsset().getStartTime()); volumeInfo2.setStatus(Commons.VOLUME_STATUS_FAILED); volumeInfo2.merge(); } } catch (Exception e) { e.printStackTrace(); } } try { params = new ArrayList<String>(); List<SnapshotInfo> snapshots = ec2.describeSnapshots(params); logger.info("Available Snapshots"); for (Iterator iterator = snapshots.iterator(); iterator.hasNext();) { SnapshotInfo snapshotInfo = (SnapshotInfo) iterator.next(); if (snapshotInfo.getOwnerId() != null && snapshotInfo.getOwnerId().equals(ownerId)) { logger.info("importing owned snapshot " + snapshotInfo.toString()); } else { logger.info("not importing snapshot since you are not the owner: " + snapshotInfo.toString()); continue; } SnapshotInfoP snapshotInfoP = null; try { snapshotInfoP = SnapshotInfoP.findSnapshotInfoPsBySnapshotIdEqualsAndCompanyEquals( snapshotInfo.getSnapshotId(), company).getSingleResult(); } catch (Exception e) { logger.error(e.getMessage());//e.printStackTrace(); } if (snapshotInfoP != null) { } else { snapshotInfoP = new SnapshotInfoP(); Asset asset = Commons.getNewAsset(assetTypeVolumeSnapshot, currentUser, snapshotProduct); snapshotInfoP.setAsset(asset); snapshotInfoP = snapshotInfoP.merge(); } snapshotInfoP.setDescription(snapshotInfo.getDescription()); snapshotInfoP.setProgress(snapshotInfo.getProgress()); snapshotInfoP.setVolumeId(snapshotInfo.getVolumeId()); snapshotInfoP.setStartTime(snapshotInfo.getStartTime().getTime()); snapshotInfoP.setSnapshotId(snapshotInfo.getSnapshotId()); snapshotInfoP.setStatus(snapshotInfo.getStatus()); snapshotInfoP.setOwnerId(snapshotInfo.getOwnerId()); snapshotInfoP.setVolumeSize(snapshotInfo.getVolumeSize()); snapshotInfoP.setOwnerAlias(snapshotInfo.getOwnerAlias()); snapshotInfoP = snapshotInfoP.merge(); } // end of for snapshots.iterator() List<SnapshotInfoP> snaps = SnapshotInfoP.findAllSnapshotInfoPs(); for (Iterator iterator = snaps.iterator(); iterator.hasNext();) { SnapshotInfoP snapshotInfoP = (SnapshotInfoP) iterator.next(); try { if (snapshotInfoP.getStatus() != null && snapshotInfoP.getStatus().equals(Commons.SNAPSHOT_STATUS.pending + "") && (new Date().getTime() - snapshotInfoP.getAsset().getStartTime().getTime() > (1000 * 60 * 60 * 3))) { snapshotInfoP.getAsset().setEndTime(snapshotInfoP.getAsset().getStartTime()); snapshotInfoP.setStatus(Commons.SNAPSHOT_STATUS.inactive + ""); snapshotInfoP.merge(); } } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } try { List<ImageDescription> images = ec2.describeImages(params); logger.info("Available Images"); int imageCount = 0; outer: for (ImageDescription img : images) { try { if (img.getImageState().equals("available")) { if (infra.getServer() != null && infra.getServer().contains("ec2.amazon")) { //if syncing from ec2, just load 100 bitnami ubuntu images // and check if they are public ones. if (!img.isPublic()) { continue; } if (img.getName() != null && (img.getName().contains("bitnami") && img.getName().contains("ubuntu"))) { imageCount = imageCount + 1; if (imageCount > 100) { logger.info("more than 100 images, cutting short the import process."); break outer; } } else { continue; } } logger.info( img.getImageId() + "\t" + img.getImageLocation() + "\t" + img.getImageOwnerId()); ImageDescriptionP imageDescriptionP = null; try { imageDescriptionP = ImageDescriptionP .findImageDescriptionPsByImageIdEqualsAndCompanyEquals(img.getImageId(), company) .getSingleResult(); } catch (Exception e) { //logger.error(e.getMessage());//e.printStackTrace(); } if (imageDescriptionP != null) { } else { imageDescriptionP = new ImageDescriptionP(); Asset asset = Commons.getNewAsset(assetTypeComputeImage, currentUser, imageProduct); imageDescriptionP.setAsset(asset); imageDescriptionP = imageDescriptionP.merge(); } imageDescriptionP.setImageId(img.getImageId()); imageDescriptionP.setImageLocation(img.getImageLocation()); imageDescriptionP.setImageOwnerId(img.getImageOwnerId()); imageDescriptionP.setImageState(img.getImageState()); imageDescriptionP.setIsPublic(img.isPublic()); List<String> prodCodes = img.getProductCodes(); String prodCodes_str = ""; for (Iterator iterator = prodCodes.iterator(); iterator.hasNext();) { String prodCode = (String) iterator.next(); prodCodes_str = prodCodes_str + prodCode + ","; } prodCodes_str = StringUtils.removeEnd(prodCodes_str, ","); imageDescriptionP.setProductCodes(prodCodes_str); imageDescriptionP.setArchitecture(img.getArchitecture()); imageDescriptionP.setImageType(img.getImageType()); imageDescriptionP.setKernelId(img.getKernelId()); imageDescriptionP.setRamdiskId(img.getRamdiskId()); imageDescriptionP.setPlatform(img.getPlatform()); imageDescriptionP.setReason(img.getReason()); imageDescriptionP.setImageOwnerAlias(img.getImageOwnerAlias()); imageDescriptionP.setName(img.getName()); imageDescriptionP.setDescription(img.getDescription()); imageDescriptionP.setRootDeviceType(img.getRootDeviceType()); imageDescriptionP.setRootDeviceName(img.getRootDeviceName()); imageDescriptionP.setVirtualizationType(img.getVirtualizationType()); imageDescriptionP.merge(); } } catch (Exception e) { e.printStackTrace(); } } // end of for ImageDescription img : images } catch (Exception e) { e.printStackTrace(); } try { params = new ArrayList<String>(); List<ReservationDescription> instances = ec2.describeInstances(params); logger.info("Instances"); String instanceId = ""; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss"); Date now = new Date(); for (ReservationDescription res : instances) { logger.info(res.getOwner() + "\t" + res.getReservationId()); if (res.getInstances() != null) { HashSet<InstanceP> instancesP = new HashSet<InstanceP>(); for (Instance inst : res.getInstances()) { Date then = inst.getLaunchTime().getTime(); long timediff = now.getTime() - then.getTime(); long hours = timediff / (1000 * 60 * 60); // inst.get // c.getTimeInMillis(); logger.info("\t" + inst.getImageId() + "\t" + inst.getDnsName() + "\t" + inst.getState() + "\t" + inst.getKeyName() + "\t" + formatter.format(then) + "\t(H)" + hours + "\t" + inst.getInstanceType().getTypeId() + inst.getPlatform()); InstanceP instanceP = null; try { instanceP = InstanceP .findInstancePsByInstanceIdEqualsAndCompanyEquals(inst.getInstanceId(), company) .getSingleResult(); } catch (Exception e) { //logger.error(e.getMessage());//e.printStackTrace(); } if (instanceP != null) { } else { instanceP = new InstanceP(); Asset asset = Commons.getNewAsset(assetTypeComputeInstance, currentUser, computeProduct); instanceP.setAsset(asset); } instanceP.setInstanceId(inst.getInstanceId()); instanceP.setImageId(inst.getImageId()); instanceP.setDnsName(inst.getDnsName()); instanceP.setState(inst.getState()); instanceP.setKeyName(inst.getKeyName()); instanceP.setInstanceType(inst.getInstanceType().getTypeId()); instanceP.setPlatform(inst.getPlatform()); instanceP.setPrivateDnsName(inst.getPrivateDnsName()); instanceP.setReason(inst.getReason()); instanceP.setLaunchIndex(inst.getLaunchIndex()); List<String> prodCodes = inst.getProductCodes(); String prodCodes_str = ""; for (Iterator iterator = prodCodes.iterator(); iterator.hasNext();) { String prodCode = (String) iterator.next(); prodCodes_str = prodCodes_str + prodCode + ","; } prodCodes_str = StringUtils.removeEnd(prodCodes_str, ","); instanceP.setProductCodes(prodCodes_str); instanceP.setLaunchTime(inst.getLaunchTime().getTime()); instanceP.setAvailabilityZone(inst.getAvailabilityZone()); instanceP.setKernelId(inst.getKernelId()); instanceP.setRamdiskId(inst.getRamdiskId()); instanceP.setStateCode(inst.getStateCode()); // instanceP.setMonitoring(inst.get) instanceP.setSubnetId(inst.getSubnetId()); instanceP.setVpcId(inst.getVpcId()); instanceP.setPrivateIpAddress(inst.getPrivateIpAddress()); instanceP.setIpAddress(inst.getIpAddress()); instanceP.setArchitecture(inst.getArchitecture()); instanceP.setRootDeviceType(inst.getRootDeviceType()); instanceP.setRootDeviceName(inst.getRootDeviceName()); instanceP.setInstanceLifecycle(inst.getInstanceLifecycle()); instanceP.setSpotInstanceRequestId(inst.getSpotInstanceRequestId()); instanceP.setVirtualizationType(inst.getVirtualizationType()); //instanceP.setState(Commons.REQUEST_STATUS.running+""); // instanceP.setClientToken(inst.get) //instanceP.setReservationDescription(reservationDescriptionP); instanceP = instanceP.merge(); instancesP.add(instanceP); } /* * reservationDescriptionP.setInstancePs(instancesP); * reservationDescriptionP = * reservationDescriptionP.merge(); */ } } // end of ReservationDescription res : instances List<InstanceP> insts = InstanceP.findAllInstancePs(); for (Iterator iterator = insts.iterator(); iterator.hasNext();) { InstanceP instanceP2 = (InstanceP) iterator.next(); try { if (instanceP2.getState().equals(Commons.REQUEST_STATUS.STARTING + "") && (new Date().getTime() - instanceP2.getAsset().getStartTime().getTime() > (1000 * 60 * 60 * 3))) { instanceP2.getAsset().setEndTime(instanceP2.getAsset().getStartTime()); instanceP2.setState(Commons.REQUEST_STATUS.FAILED + ""); instanceP2.merge(); } } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } try { List<KeyPairInfo> info = ec2.describeKeyPairs(new String[] {}); logger.info("keypair list"); for (KeyPairInfo keypairinfo : info) { logger.info("keypair : " + keypairinfo.getKeyName() + ", " + keypairinfo.getKeyFingerprint()); KeyPairInfoP keyPairInfoP = null; try { keyPairInfoP = KeyPairInfoP .findKeyPairInfoPsByKeyNameEqualsAndCompanyEquals(keypairinfo.getKeyName(), company) .getSingleResult(); } catch (Exception e) { //logger.error(e);//e.printStackTrace(); } if (keyPairInfoP != null) { } else { keyPairInfoP = new KeyPairInfoP(); Asset asset = Commons.getNewAsset(assetTypeKeyPair, currentUser, keypairProduct); keyPairInfoP.setAsset(asset); keyPairInfoP = keyPairInfoP.merge(); } keyPairInfoP.setKeyName(keypairinfo.getKeyName()); keyPairInfoP.setKeyFingerprint(keypairinfo.getKeyFingerprint()); keyPairInfoP.setKeyMaterial(keypairinfo.getKeyMaterial()); keyPairInfoP.setStatus(Commons.keypair_STATUS.active + ""); keyPairInfoP = keyPairInfoP.merge(); } // end of for KeyPairInfo i : info) List<KeyPairInfoP> keys = KeyPairInfoP.findAllKeyPairInfoPs(); for (Iterator iterator = keys.iterator(); iterator.hasNext();) { KeyPairInfoP keyPairInfoP = (KeyPairInfoP) iterator.next(); try { if (keyPairInfoP.getStatus().equals(Commons.keypair_STATUS.starting + "") && (new Date().getTime() - keyPairInfoP.getAsset().getStartTime().getTime() > (1000 * 60 * 60 * 3))) { keyPairInfoP.getAsset().setEndTime(keyPairInfoP.getAsset().getStartTime()); keyPairInfoP.setStatus(Commons.keypair_STATUS.failed + ""); keyPairInfoP.merge(); } } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.gp.cong.logisoft.bc.fcl.SedFilingBC.java
public void readRespResponseFile(InputStream is, String aesFilesFolder, String aesResponseFileName) throws Exception { List<String> contents = FileUtils.readLines(new File(aesFilesFolder + aesResponseFileName)); // Iterate the result to print each line of the file. String itn = ""; String shipmentNumber = ""; String status = ""; String exception = ""; if (null != contents && contents.size() > 0) { contents.remove(0);/*www.j a v a 2s . c o m*/ } for (String line : contents) { if (null != line && line.length() > 0) { String key = StringUtils.substringBefore(line, " "); shipmentNumber = StringUtils.substringBefore(key, "-") + "-" + (StringUtils.substringAfterLast(key, "-").substring(0, 2)); status += StringUtils.substringAfterLast(line, key).trim() + " "; } } status = StringUtils.removeEnd(status, " "); if (CommonUtils.isNotEmpty(shipmentNumber)) { FclBlDAO fclBlDAO = new FclBlDAO(); String fileNo = shipmentNumber.contains("-") ? shipmentNumber.substring(0, shipmentNumber.indexOf("-")) : shipmentNumber; if (fileNo.length() > 6) { fileNo = fileNo.substring(2); } //String fileNo = shipmentNumber.contains("-") && shipmentNumber.length() > 2 ? shipmentNumber.substring(2, shipmentNumber.indexOf("-")) : shipmentNumber; FclBl fclBl = fclBlDAO.getFileNoObject(fileNo); LclFileNumber lclFileNumber = null; if (null == fclBl) { lclFileNumber = new LclFileNumberDAO().getByProperty("fileNumber", fileNo); } FclAESDetails fclAESDetails = new FclAESDetails(); SedFilingsDAO sedFilingsDAO = new SedFilingsDAO(); boolean hasAes = false; SedFilings sedFilings = sedFilingsDAO.findByTrnref(shipmentNumber.trim()); if (null != sedFilings) { sedFilings.setItn(itn); if (status.contains("SUCCESSFULLY PROCESSED")) { sedFilings.setStatus("P"); } else { sedFilings.setStatus("E"); } AesHistory aesHistory = new AesHistory(); if (null != fclBl) { aesHistory.setBolId(fclBl.getBol()); aesHistory.setFclBlNo(fclBl.getBolId()); for (Object object : fclBl.getFclAesDetails()) { FclAESDetails aes = (FclAESDetails) object; if (null != aes.getAesDetails() && aes.getAesDetails().equalsIgnoreCase(itn)) { hasAes = true; break; } } if (!hasAes && CommonUtils.isNotEmpty(itn)) { fclAESDetails.setAesDetails(itn); fclAESDetails.setFileNo(fileNo); fclAESDetails.setTrailerNoId(fclBl.getBol()); fclBl.getFclAesDetails().add(fclAESDetails); fclBlDAO.update(fclBl); } } else if (null != lclFileNumber) { //aesHistory.setBolId(lclFileNumber.getId()); aesHistory.setFclBlNo(lclFileNumber.getFileNumber()); } aesHistory.setFileNumber(shipmentNumber); aesHistory.setAesException(exception); aesHistory.setFileNo(fileNo); aesHistory.setItn(itn); aesHistory.setStatus(status); aesHistory.setProcessedDate(new Date()); byte[] bs = IOUtils.toByteArray(is); Blob blob = fclBlDAO.getSession().getLobHelper().createBlob(bs); aesHistory.setResponseFile(blob); new AesHistoryDAO().save(aesHistory); sedFilingsDAO.update(sedFilings); } } }
From source file:com.alliander.osgp.acceptancetests.configurationmanagement.GetConfigurationDataSteps.java
private String convertIndexAddressMapToString(final List<IndexAddressMap> indexAddressMapList) { String result = ""; for (final IndexAddressMap indexAddressMap : indexAddressMapList) { result += indexAddressMap.getIndex() + "," + indexAddressMap.getAddress() + ";"; }/* ww w . j a va 2s. c om*/ result = StringUtils.removeEnd(result, ";"); return result; }
From source file:com.alliander.osgp.acceptancetests.configurationmanagement.GetConfigurationDataSteps.java
private String convertRelayMapToString(final List<RelayMap> relayMapList) { String result = ""; for (final RelayMap relayMap : relayMapList) { result += relayMap.getIndex() + "," + relayMap.getAddress() + ";"; }//from ww w . j a va2 s . c o m result = StringUtils.removeEnd(result, ";"); return result; }