Example usage for org.apache.commons.lang3 StringUtils removeEnd

List of usage examples for org.apache.commons.lang3 StringUtils removeEnd

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils removeEnd.

Prototype

public static String removeEnd(final String str, final String remove) 

Source Link

Document

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 .

Usage

From source file:com.sonicle.webtop.core.app.WebTopSession.java

private void fillExtJsReferences(JsWTS js, Locale locale, String theme, boolean rtl) {
    js.appManifest.framework = "ext";
    js.appManifest.toolkit = "classic";

    //TODO: rendere dinamico il caricamento delle librerie, permettendo ai servizi di aggiungere le loro

    // Do not replace 0.0.0 with the real version, it limits server traffic.
    final String VENDOR_PATH = "resources/com.sonicle.webtop.core/0.0.0/resources/vendor";
    final String LIBS_PATH = "resources/com.sonicle.webtop.core/0.0.0/resources/libs";

    // Include external libraries references
    js.appManifest.addJs(VENDOR_PATH + "/jquery/3.3.1/" + "jquery.min.js");
    js.appManifest.addJs(VENDOR_PATH + "/spark-md5/3.0.0/" + "spark-md5.min.js");
    js.appManifest.addJs(VENDOR_PATH + "/js-emoji/3.4.1/" + "emoji.min.js");
    js.appManifest.addJs(VENDOR_PATH + "/ion.sound/3.0.7/" + "ion.sound.min.js");
    js.appManifest.addJs(VENDOR_PATH + "/linkify/2.1.6/" + "linkify.min.js");
    js.appManifest.addJs(VENDOR_PATH + "/linkify/2.1.6/" + "linkify-string.min.js");
    js.appManifest.addJs(VENDOR_PATH + "/screenfull/3.3.2/" + "screenfull.min.js");
    js.appManifest.addJs(VENDOR_PATH + "/atmosphere/2.3.5/" + "atmosphere.min.js");
    js.appManifest.addJs(VENDOR_PATH + "/jsxc/3.4.0/" + "jsxc.dep.js");
    js.appManifest.addJs(VENDOR_PATH + "/tinymce/4.3.12/" + "tinymce.min.js");
    js.appManifest.addJs(VENDOR_PATH + "/plupload/2.3.6/" + "plupload.full.min.js"); // Remember to update paths in Factory.js
    js.appManifest.addJs(VENDOR_PATH + "/rrule/2.1.0/" + "rrule.min.js");
    js.appManifest.addJs(VENDOR_PATH + "/markjs/8.11.1/" + "mark.min.js");
    js.appManifest.addJs(VENDOR_PATH + "/search-string/3.1.0/" + "search-string.min.js");

    // Uncomment these lines to load debug versions of the libraries ----->
    //js.appManifest.addJs(VENDOR_PATH + "/jsxc/3.4.0/" + "jsxc.dep.js");
    //js.appManifest.addJs(VENDOR_PATH + "/tinymce/4.3.12/" + "tinymce.js");
    //js.appManifest.addJs(VENDOR_PATH + "/plupload/2.3.6/" + "moxie.js");
    //js.appManifest.addJs(VENDOR_PATH + "/plupload/2.3.6/" + "plupload.dev.js");
    // <-------------------------------------------------------------------
    //js.appManifest.addJs(VENDOR_PATH + "/ckeditor/" + "ckeditor.js");

    // Include ExtJs references
    final String EXTJS_PATH = "resources/client/extjs/";
    String extRtl = rtl ? "-rtl" : "";
    String extDebug = WebTopProps.getExtJsDebug() ? "-debug" : "";
    String extTheme = theme;/*from   www  .  java 2  s  .  com*/
    String extBaseTheme = StringUtils.removeEnd(theme, "-touch");
    String extLang = "-" + locale.getLanguage();
    js.appManifest.addJs(EXTJS_PATH + "ext-all" + extRtl + extDebug + ".js");
    js.appManifest
            .addJs(EXTJS_PATH + js.appManifest.toolkit + "/locale/" + "locale" + extLang + extDebug + ".js");
    //js.appManifest.addJs(EXTJS_PATH + "packages/ext-locale/build/" + "ext-locale" + extLang + extDebug + ".js"); // ExtJs library localization
    js.appManifest.addJs(EXTJS_PATH + js.appManifest.toolkit + "/" + "theme-" + extTheme + "/" + "theme-"
            + extTheme + extDebug + ".js");
    js.appManifest.addCss(EXTJS_PATH + js.appManifest.toolkit + "/" + "theme-" + extTheme + "/resources/"
            + "theme-" + extTheme + "-all" + extRtl + extDebug + ".css");
    //js.appManifest.addJs(EXTJS_PATH + "packages/" + "ext-theme-" + extTheme + "/build/" + "ext-theme-" + extTheme + extDebug + ".js"); // ExtJs theme overrides
    //js.appManifest.addCss(EXTJS_PATH + "packages/" + "ext-theme-" + extTheme + "/build/resources/" + "ext-theme-" + extTheme + "-all" + extRtl + extDebug + ".css");
    js.appManifest.addJs(
            EXTJS_PATH + "packages/charts/" + js.appManifest.toolkit + "/" + "charts" + extDebug + ".js");
    js.appManifest.addCss(EXTJS_PATH + "packages/charts/" + js.appManifest.toolkit + "/" + extBaseTheme
            + "/resources/" + "charts-all" + extRtl + extDebug + ".css");
    //js.appManifest.addCss(EXTJS_PATH + "packages/sencha-charts/build/" + extBaseTheme + "/resources/" + "sencha-charts-all" + extRtl + extDebug + ".css");   
    js.appManifest.addJs(EXTJS_PATH + "packages/ux/" + js.appManifest.toolkit + "/" + "ux" + extDebug + ".js");
    js.appManifest.addCss(EXTJS_PATH + "packages/ux/" + js.appManifest.toolkit + "/" + extBaseTheme
            + "/resources/" + "ux-all" + extRtl + extDebug + ".css");

    // Include Sonicle ExtJs Extensions references
    if (WebTopProps.getSoExtJsExtensionsDevMode()) {
        js.appManifest.addPath("Sonicle", EXTJS_PATH + "packages/sonicle-extensions/src");
    } else {
        js.appManifest
                .addJs(EXTJS_PATH + "packages/sonicle-extensions/" + "sonicle-extensions" + extDebug + ".js");
    }
    js.appManifest.addCss(EXTJS_PATH + "packages/sonicle-extensions/" + extBaseTheme + "/resources/"
            + "sonicle-extensions-all" + extRtl + extDebug + ".css");

    // Override default Ext error handling in order to avoid application hang.
    // NB: This is only necessary when using ExtJs debug file!
    if (WebTopProps.getExtJsDebug())
        js.appManifest.addJs(LIBS_PATH + "/" + "ext-override-errors.js");
}

From source file:alfio.manager.EventManager.java

public String getEventUrl(Event event) {
    return StringUtils.removeEnd(
            configurationManager.getRequiredValue(
                    Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.BASE_URL)),
            "/") + "/event/" + event.getShortName() + "/";
}

From source file:alfio.manager.TicketReservationManager.java

public String reservationUrl(String reservationId, Event event) {
    TicketReservation reservation = ticketReservationRepository.findReservationById(reservationId);
    return StringUtils.removeEnd(
            configurationManager.getRequiredValue(
                    Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.BASE_URL)),
            "/") + "/event/" + event.getShortName() + "/reservation/" + reservationId + "?lang="
            + reservation.getUserLanguage();
}

From source file:alfio.manager.TicketReservationManager.java

String ticketUrl(Event event, String ticketId) {
    Ticket ticket = ticketRepository.findByUUID(ticketId);
    return StringUtils.removeEnd(
            configurationManager.getRequiredValue(
                    Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.BASE_URL)),
            "/") + "/event/" + event.getShortName() + "/ticket/" + ticketId + "?lang="
            + ticket.getUserLanguage();//from  w  ww .j a  v a2s  . c  o  m
}

From source file:alfio.manager.TicketReservationManager.java

public String ticketUpdateUrl(Event event, String ticketId) {
    Ticket ticket = ticketRepository.findByUUID(ticketId);
    return StringUtils.removeEnd(
            configurationManager.getRequiredValue(
                    Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.BASE_URL)),
            "/") + "/event/" + event.getShortName() + "/ticket/" + ticketId + "/update?lang="
            + ticket.getUserLanguage();/*w ww. java  2  s .c om*/
}

From source file:in.mycp.remote.EucalyptusService.java

@RemoteMethod
public void syncDataFromMycp(Infra infra) {
    try {//from   ww w.ja  v a 2  s.c  o  m
        Date start = new Date();
        logger.info("Connect Start:" + new Date());
        Jec2 ec2 = getNewJce2(infra);

        List<String> params = new ArrayList<String>();
        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.findAddressInfoPsByPublicIpEquals(addressInfo.getPublicIp())
                        .getSingleResult();
                addressInfoP.setInstanceId(addressInfo.getInstanceId());
                addressInfoP.setPublicIp(addressInfo.getPublicIp());
                addressInfoP = addressInfoP.merge();
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        }

        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();
            }
        }

        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 {
                descriptionP = GroupDescriptionP.findGroupDescriptionPsByNameEquals(groupDescription.getName())
                        .getSingleResult();
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }

            if (descriptionP != null) {
                descriptionP.setDescripton(groupDescription.getDescription());
                descriptionP.setOwner(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 {
                        ipPermissionP = IpPermissionP
                                .findIpPermissionPsByGroupDescriptionAndProtocolEqualsAndFromPortEquals(
                                        descriptionP, ipPermission.getProtocol(), ipPermission.getFromPort())
                                .getSingleResult();
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }

                    if (ipPermissionP != null) {
                        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();
                    }

                }
            } //end of if 

        } // end of for groupDescs.iterator()

        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();
            }
        }

        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.findVolumeInfoPsByVolumeIdEquals(volumeInfo.getVolumeId())
                        .getSingleResult();
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
            if (volumeInfoP != null) {
                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);
                        attachmentInfoP = attachmentInfoP.merge();
                        attachments4Store.add(attachmentInfoP);
                    }
                }

                volumeInfoP.setAttachmentInfoPs(attachments4Store);
                volumeInfoP = volumeInfoP.merge();
            } //if volume !=null
        } // end of for volumes.iterator()

        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();
            }

        }

        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();
            logger.info(snapshotInfo.getDescription() + snapshotInfo.getProgress() + snapshotInfo.getStatus()
                    + snapshotInfo.getVolumeId() + snapshotInfo.getStartTime().getTime());
            SnapshotInfoP snapshotInfoP = null;
            try {
                snapshotInfoP = SnapshotInfoP.findSnapshotInfoPsBySnapshotIdEquals(snapshotInfo.getSnapshotId())
                        .getSingleResult();
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }

            if (snapshotInfoP != null) {
                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().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();
            }
        }

        List<ImageDescription> images = ec2.describeImages(params);
        logger.info("Available Images");
        for (ImageDescription img : images) {
            if (img.getImageState().equals("available")) {
                logger.info(img.getImageId() + "\t" + img.getImageLocation() + "\t" + img.getImageOwnerId());
                ImageDescriptionP imageDescriptionP = null;
                try {
                    imageDescriptionP = ImageDescriptionP
                            .findImageDescriptionPsByImageIdEquals(img.getImageId()).getSingleResult();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }
                if (imageDescriptionP != null) {
                    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 = imageDescriptionP.merge();
                }
            }
        } // end of for ImageDescription img : images

        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) {
                for (Instance inst : res.getInstances()) {
                    Date then = inst.getLaunchTime().getTime();
                    long timediff = now.getTime() - then.getTime();
                    long hours = timediff / (1000 * 60 * 60);
                    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.findInstancePsByInstanceIdEquals(inst.getInstanceId())
                                .getSingleResult();
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }

                    if (instanceP != null) {

                        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.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 = instanceP.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();
            }
        }

        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.findKeyPairInfoPsByKeyNameEquals(keypairinfo.getKeyName())
                        .getSingleResult();
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }

            if (keyPairInfoP != null) {
                keyPairInfoP.setKeyName(keypairinfo.getKeyName());
                keyPairInfoP.setKeyFingerprint(keypairinfo.getKeyFingerprint());
                keyPairInfoP.setKeyMaterial(keypairinfo.getKeyMaterial());
                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) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

}

From source file:com.gp.cong.logisoft.lcl.report.LclAllBLPdfCreator.java

public PdfPTable appendChargesAndCommodity() throws Exception {
    LclBlAcDAO lclBlAcDAO = new LclBlAcDAO();
    List<LclBlPiece> lclBlPiecesList = lclbl.getLclFileNumber().getLclBlPieceList();
    List<LclBlAc> chargeList = lclBlAcDAO.getLclCostByFileNumberAsc(lclbl.getFileNumberId());
    PdfPTable chargeTable = new PdfPTable(6);
    PdfPCell chargeCell = null;//from  ww w . j a  v  a2  s.co m
    chargeTable.setWidths(new float[] { 3.8f, 1.5f, .8f, 3.8f, 1.5f, .8f });
    chargeTable.setWidthPercentage(100f);
    Paragraph p = null;

    this.total_ar_amount = 0.00;
    this.total_ar_col_amount = 0.00;
    this.total_ar_ppd_amount = 0.00;

    List<LinkedHashMap<String, PdfPCell>> listChargeMap = null;
    LinkedHashMap<String, PdfPCell> chargeMap = null;
    if ("BOTH".equalsIgnoreCase(billType)) {
        listChargeMap = this.getTotalChargesList(chargeList, lclBlPiecesList);
    } else {
        chargeMap = this.getTotalCharges(chargeList, lclBlPiecesList);
    }

    LclBlAc blAC = lclBlAcDAO.manualChargeValidate(lclbl.getFileNumberId(), "OCNFRT", false);
    if (lclBlPiecesList != null && lclBlPiecesList.size() > 0 && blAC != null) {
        BigDecimal CFT = BigDecimal.ZERO, LBS = BigDecimal.ZERO;
        LclBlPiece lclBlPiece = (LclBlPiece) lclBlPiecesList.get(0);
        if (blAC.getRatePerUnitUom() != null) {
            CFT = blAC.getRatePerUnitUom().equalsIgnoreCase("FRV") ? blAC.getRatePerVolumeUnit()
                    : BigDecimal.ZERO;
            LBS = blAC.getRatePerUnitUom().equalsIgnoreCase("FRW") ? blAC.getRatePerWeightUnit()
                    : BigDecimal.ZERO;
        }
        if (CFT != BigDecimal.ZERO || LBS != BigDecimal.ZERO) {
            StringBuilder cbmValues = new StringBuilder();
            if (CFT != BigDecimal.ZERO && lclBlPiece.getActualVolumeImperial() != null) {
                cbmValues.append(NumberUtils
                        .convertToThreeDecimalhash(lclBlPiece.getActualVolumeImperial().doubleValue()));
            }
            if (LBS != BigDecimal.ZERO && lclBlPiece.getActualWeightImperial() != null) {
                cbmValues.append(NumberUtils
                        .convertToThreeDecimalhash(lclBlPiece.getActualWeightImperial().doubleValue()));
            }
            if (null != blAC.getArAmount() && blAC.getArAmount().toString().equalsIgnoreCase(OCNFRT_Total)) {
                if (CFT == BigDecimal.ZERO) {
                    cbmValues.append(" LBS @ ").append(LBS).append(" PER 100 LBS @ ")
                            .append(blAC.getArAmount());
                } else {
                    cbmValues.append(" CFT @ ").append(CFT).append(" PER CFT @").append(blAC.getArAmount());
                }
                chargeCell = new PdfPCell();
                chargeCell.setBorder(0);
                chargeCell.setColspan(6);
                chargeTable.addCell(chargeCell);

                chargeCell = new PdfPCell();
                chargeCell.setBorder(0);
                chargeCell.setColspan(6);
                p = new Paragraph(2f, "" + cbmValues.toString().toUpperCase(), totalFontQuote);
                p.add(new Paragraph(2f,
                        null != lclBlPiece && null != lclBlPiece.getCommodityType()
                                ? "   Commodity# " + lclBlPiece.getCommodityType().getCode()
                                : "   Commodity#",
                        totalFontQuote));
                p.setAlignment(Element.ALIGN_LEFT);
                chargeCell.addElement(p);
                chargeTable.addCell(chargeCell);
            }
        }
    }
    this.OCNFRT_Total = "";
    LinkedHashMap<String, PdfPCell> left_chargeMap = new LinkedHashMap<String, PdfPCell>();
    LinkedHashMap<String, PdfPCell> right_chargeMap = new LinkedHashMap<String, PdfPCell>();
    if ("BOTH".equalsIgnoreCase(billType) && listChargeMap != null && !listChargeMap.isEmpty()) {
        if (listChargeMap.size() > 1) {
            if (listChargeMap.get(0).size() > 6 || listChargeMap.get(1).size() > 6) {
                chargeMap = new LinkedHashMap<String, PdfPCell>();
                chargeMap.putAll(listChargeMap.get(0));
                chargeMap.putAll(listChargeMap.get(1));
                int count = 0, size = chargeMap.size() / 2 <= 6 ? 6 : chargeMap.size() / 2;
                for (String key : chargeMap.keySet()) {
                    if (count++ < size) {
                        left_chargeMap.put(key, chargeMap.get(key));
                    } else {
                        right_chargeMap.put(key, chargeMap.get(key));
                    }
                }
            } else {
                left_chargeMap.putAll(listChargeMap.get(0));
                right_chargeMap.putAll(listChargeMap.get(1));
            }
        } else {
            int count = 0, size = listChargeMap.get(0).size() / 2 <= 6 ? 6 : listChargeMap.get(0).size() / 2;
            for (String key : listChargeMap.get(0).keySet()) {
                if (count++ < size) {
                    left_chargeMap.put(key, listChargeMap.get(0).get(key));
                } else {
                    right_chargeMap.put(key, listChargeMap.get(0).get(key));
                }
            }
        }
    } else if (chargeMap != null && !chargeMap.isEmpty()) {
        int count = 0, size = chargeMap.size() / 2 <= 6 ? 6 : chargeMap.size() / 2;
        for (String key : chargeMap.keySet()) {
            if (count++ < size) {
                left_chargeMap.put(key, chargeMap.get(key));
            } else {
                right_chargeMap.put(key, chargeMap.get(key));
            }
        }
    }

    if (!left_chargeMap.isEmpty()) {
        String chargeDesc = null;
        PdfPTable innner_chargeTable = new PdfPTable(2);
        innner_chargeTable.setWidthPercentage(100f);
        PdfPCell inner_chargeCell = null;

        chargeCell = new PdfPCell();
        chargeCell.setBorder(0);
        chargeCell.setColspan(3);
        chargeCell.setBorderWidthRight(0.6f);
        chargeCell.setPadding(0);
        innner_chargeTable = new PdfPTable(2);
        innner_chargeTable.setWidths(new float[] { 5f, 3f });
        if (!left_chargeMap.isEmpty()) {
            for (String key : left_chargeMap.keySet()) {
                inner_chargeCell = new PdfPCell();
                inner_chargeCell.setBorder(0);
                inner_chargeCell.setPaddingLeft(-15);
                chargeDesc = key.substring(key.indexOf("#") + 1, key.indexOf("$"));
                inner_chargeCell.addElement(new Paragraph(7f, "" + chargeDesc, totalFontQuote));
                innner_chargeTable.addCell(inner_chargeCell);

                inner_chargeCell = new PdfPCell();
                inner_chargeCell.setBorder(0);
                inner_chargeCell = left_chargeMap.get(key);
                innner_chargeTable.addCell(inner_chargeCell);
            }
        }
        chargeCell.addElement(innner_chargeTable);
        chargeTable.addCell(chargeCell);

        chargeCell = new PdfPCell();
        chargeCell.setBorder(0);
        chargeCell.setColspan(3);
        chargeCell.setPadding(0);
        innner_chargeTable = new PdfPTable(2);
        innner_chargeTable.setWidths(new float[] { 5f, 3f });
        if (!left_chargeMap.isEmpty()) {
            for (String key : right_chargeMap.keySet()) {
                inner_chargeCell = new PdfPCell();
                inner_chargeCell.setBorder(0);
                inner_chargeCell.setPaddingLeft(-15);
                chargeDesc = key.substring(key.indexOf("#") + 1, key.indexOf("$"));
                inner_chargeCell.addElement(new Paragraph(7f, "" + chargeDesc, totalFontQuote));
                innner_chargeTable.addCell(inner_chargeCell);

                inner_chargeCell = new PdfPCell();
                inner_chargeCell.setBorder(0);
                inner_chargeCell = right_chargeMap.get(key);
                innner_chargeTable.addCell(inner_chargeCell);
            }
        }
        chargeCell.addElement(innner_chargeTable);
        chargeTable.addCell(chargeCell);
    } else {
        this.total_ar_amount = 0.00;
        this.total_ar_ppd_amount = 0.00;
        this.total_ar_col_amount = 0.00;
    }
    String acctNo = "";
    String billToParty = "";
    if (CommonFunctions.isNotNull(lclbl.getBillToParty()) && CommonUtils.isNotEmpty(lclbl.getBillToParty())) {
        if (lclbl.getBillToParty().equalsIgnoreCase("T")
                && CommonFunctions.isNotNull(lclbl.getThirdPartyAcct())) {
            billToParty = "THIRD PARTY";
            acctNo = lclbl.getThirdPartyAcct().getAccountno();
        } else if (lclbl.getBillToParty().equalsIgnoreCase("S")
                && CommonFunctions.isNotNull(lclbl.getShipAcct())) {
            billToParty = "SHIPPER";
            acctNo = lclbl.getShipAcct().getAccountno();
        } else if (lclbl.getBillToParty().equalsIgnoreCase("F")
                && CommonFunctions.isNotNull(lclbl.getFwdAcct())) {
            billToParty = "FORWARDER";
            acctNo = lclbl.getFwdAcct().getAccountno();
        } else if (lclbl.getBillToParty().equalsIgnoreCase("A")
                && CommonFunctions.isNotNull(lclbl.getAgentAcct())) {
            billToParty = "AGENT";
            if (lclBooking.getBookingType().equals("T")
                    && lclbl.getLclFileNumber().getLclBookingImport().getExportAgentAcctNo() != null) {
                acctNo = lclbl.getLclFileNumber().getLclBookingImport().getExportAgentAcctNo().getAccountno();
            } else if (lclBooking.getAgentAcct() != null) {
                acctNo = lclBooking.getAgentAcct().getAccountno();
            } else {
                acctNo = lclbl.getAgentAcct().getAccountno();
            }
        }
    }

    if ("BOTH".equalsIgnoreCase(billType)) {
        if (this.total_ar_ppd_amount != 0.00 || this.total_ar_col_amount != 0.00) {
            if (this.total_ar_ppd_amount != 0.00) {
                if (CommonFunctions.isNotNullOrNotEmpty(ppdBillToSet) && ppdBillToSet.size() == 1) {
                    for (String billTo : ppdBillToSet) {
                        arBillToParty = billTo;
                        break;
                    }
                    if (arBillToParty.equalsIgnoreCase("T")) {
                        billToParty = "THIRD PARTY";
                        acctNo = null != lclbl.getThirdPartyAcct() ? lclbl.getThirdPartyAcct().getAccountno()
                                : acctNo;
                    } else if (arBillToParty.equalsIgnoreCase("S")) {
                        acctNo = null != lclbl.getShipAcct() ? lclbl.getShipAcct().getAccountno() : acctNo;
                        billToParty = "SHIPPER";
                    } else if (arBillToParty.equalsIgnoreCase("F")) {
                        billToParty = "FORWARDER";
                        acctNo = null != lclbl.getFwdAcct() ? lclbl.getFwdAcct().getAccountno() : acctNo;
                    }
                } else {
                    acctNo = null;
                }
                chargeCell = new PdfPCell();
                chargeCell.setBorder(0);
                chargeCell.setColspan(2);
                p = new Paragraph(7f, "T O T A L (USA)", totalFontQuote);
                p.setAlignment(Element.ALIGN_LEFT);
                chargeCell.addElement(p);
                chargeTable.addCell(chargeCell);

                chargeCell = new PdfPCell();
                chargeCell.setColspan(4);
                chargeCell.setBorder(0);
                if (null != acctNo) {
                    p = new Paragraph(7f, "$" + NumberUtils.convertToTwoDecimal(this.total_ar_ppd_amount)
                            + " PPD " + billToParty + "-" + acctNo, totalFontQuote);
                } else {
                    p = new Paragraph(7f,
                            "$" + NumberUtils.convertToTwoDecimal(this.total_ar_ppd_amount) + " PPD ",
                            totalFontQuote);
                }
                p.setAlignment(Element.ALIGN_LEFT);
                chargeCell.addElement(p);
                chargeTable.addCell(chargeCell);
            }

            if (this.total_ar_col_amount != 0.00) {
                String colAcctNo = "";
                if (lclBooking.getBookingType().equals("T")
                        && lclbl.getLclFileNumber().getLclBookingImport().getExportAgentAcctNo() != null) {
                    colAcctNo = lclbl.getLclFileNumber().getLclBookingImport().getExportAgentAcctNo()
                            .getAccountno();
                } else if (lclBooking.getAgentAcct() != null) {
                    colAcctNo = lclBooking.getAgentAcct().getAccountno();
                } else if (lclbl.getAgentAcct() != null) {
                    colAcctNo = lclbl.getAgentAcct().getAccountno();
                }
                chargeCell = new PdfPCell();
                chargeCell.setBorder(0);
                chargeCell.setColspan(2);
                if (this.total_ar_ppd_amount == 0.00) {
                    p = new Paragraph(7f, "T O T A L (USA)", totalFontQuote);
                } else {
                    p = new Paragraph(7f, "", totalFontQuote);
                }
                p.setAlignment(Element.ALIGN_LEFT);
                chargeCell.addElement(p);
                chargeTable.addCell(chargeCell);

                chargeCell = new PdfPCell();
                chargeCell.setColspan(4);
                chargeCell.setBorder(0);
                p = new Paragraph(7f, "$" + NumberUtils.convertToTwoDecimal(this.total_ar_col_amount)
                        + " COL AGENT-" + colAcctNo, totalFontQuote);
                p.setAlignment(Element.ALIGN_LEFT);
                chargeCell.addElement(p);
                chargeTable.addCell(chargeCell);
            }

            NumberFormat numberFormat = new DecimalFormat("###,###,##0.000");
            if (this.total_ar_ppd_amount != 0.00) {
                String totalString1 = numberFormat.format(this.total_ar_ppd_amount).replaceAll(",", "");
                int indexdot = totalString1.indexOf(".");
                String beforeDecimal = totalString1.substring(0, indexdot);
                String afterDecimal = totalString1.substring(indexdot + 1, totalString1.length());
                chargeCell = new PdfPCell();
                chargeCell.setColspan(6);
                chargeCell.setBorder(0);
                p = new Paragraph(7f, "" + ConvertNumberToWords.convert(Integer.parseInt(beforeDecimal))
                        + " DOLLARS AND " + StringUtils.removeEnd(afterDecimal, "0") + " CENTS",
                        totalFontQuote);
                chargeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                chargeCell.addElement(p);
                chargeTable.addCell(chargeCell);
            }
            if (this.total_ar_col_amount != 0.00) {
                String totalString1 = numberFormat.format(this.total_ar_col_amount).replaceAll(",", "");
                int indexdot = totalString1.indexOf(".");
                String beforeDecimal = totalString1.substring(0, indexdot);
                String afterDecimal = totalString1.substring(indexdot + 1, totalString1.length());
                chargeCell = new PdfPCell();
                chargeCell.setColspan(6);
                chargeCell.setBorder(0);
                p = new Paragraph(7f, "" + ConvertNumberToWords.convert(Integer.parseInt(beforeDecimal))
                        + " DOLLARS AND " + StringUtils.removeEnd(afterDecimal, "0") + " CENTS",
                        totalFontQuote);
                chargeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                chargeCell.addElement(p);
                chargeTable.addCell(chargeCell);
            }
        }
    } else if (this.total_ar_amount != 0.00) {
        chargeCell = new PdfPCell();
        chargeCell.setBorder(0);
        chargeCell.setColspan(2);
        chargeCell.setPaddingTop(8f);
        p = new Paragraph(7f, "T O T A L (USA)", totalFontQuote);
        p.setAlignment(Element.ALIGN_LEFT);
        chargeCell.addElement(p);
        chargeTable.addCell(chargeCell);

        chargeCell = new PdfPCell();
        chargeCell.setColspan(4);
        chargeCell.setBorder(0);
        chargeCell.setPaddingTop(8f);
        p = new Paragraph(7f, "$" + NumberUtils.convertToTwoDecimal(this.total_ar_amount) + " " + billType + " "
                + billToParty + "-" + acctNo, totalFontQuote);
        p.setAlignment(Element.ALIGN_LEFT);
        chargeCell.addElement(p);
        chargeTable.addCell(chargeCell);

        NumberFormat numberFormat = new DecimalFormat("###,###,##0.000");

        String totalString1 = numberFormat.format(this.total_ar_amount).replaceAll(",", "");
        int indexdot = totalString1.indexOf(".");
        String beforeDecimal = totalString1.substring(0, indexdot);
        String afterDecimal = totalString1.substring(indexdot + 1, totalString1.length());
        chargeCell = new PdfPCell();
        chargeCell.setColspan(6);
        chargeCell.setBorder(0);
        p = new Paragraph(7f, "" + ConvertNumberToWords.convert(Integer.parseInt(beforeDecimal))
                + " DOLLARS AND " + StringUtils.removeEnd(afterDecimal, "0") + " CENTS", totalFontQuote);
        chargeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        chargeCell.addElement(p);
        chargeTable.addCell(chargeCell);
    }

    chargeCell = new PdfPCell();
    chargeCell.setBorder(0);
    chargeCell.setColspan(4);
    p = new Paragraph(5f, "" + sailDateFormat, totalFontQuote);
    p.setAlignment(Element.ALIGN_LEFT);
    chargeCell.addElement(p);
    chargeTable.addCell(chargeCell);

    chargeCell = new PdfPCell();
    chargeCell.setColspan(5);
    chargeCell.setBorder(0);
    chargeTable.addCell(chargeCell);

    chargeCell = new PdfPCell();
    chargeCell.setColspan(3);
    chargeCell.setBorder(0);
    chargeCell.setRowspan(3);
    String fdPodValue = null;
    if (agencyInfo != null && CommonUtils.isNotEmpty(agencyInfo[2])) {
        fdPodValue = agencyInfo[2];
    } else if (CommonFunctions.isNotNull(lclbl.getFinalDestination())
            && CommonFunctions.isNotNull(lclbl.getFinalDestination().getCountryId())
            && CommonFunctions.isNotNull(lclbl.getFinalDestination().getCountryId().getCodedesc())) {
        fdPodValue = lclbl.getFinalDestination().getUnLocationName() + ","
                + lclbl.getFinalDestination().getCountryId().getCodedesc();
    }
    p = new Paragraph(7f, fdPodValue != null ? fdPodValue.toUpperCase() : podValues.toUpperCase(),
            totalFontQuote);
    p.setAlignment(Element.ALIGN_LEFT);
    chargeCell.addElement(p);
    chargeTable.addCell(chargeCell);

    chargeCell = new PdfPCell();
    chargeCell.setBorder(0);
    chargeCell.setColspan(3);
    p = new Paragraph(5f, "UNIT# " + unitNumber, headingblackBoldFont);
    p.setAlignment(Element.ALIGN_LEFT);
    chargeCell.addElement(p);
    chargeTable.addCell(chargeCell);

    chargeCell = new PdfPCell();
    chargeCell.setBorder(0);
    chargeCell.setColspan(3);
    chargeCell.setPaddingTop(2f);
    p = new Paragraph(5f, "SEAL# " + sealOut, headingblackBoldFont);
    p.setAlignment(Element.ALIGN_LEFT);
    chargeCell.addElement(p);
    chargeTable.addCell(chargeCell);

    chargeCell = new PdfPCell();
    chargeCell.setBorder(0);
    chargeCell.setColspan(3);
    chargeCell.setPaddingTop(2f);
    p = new Paragraph(5f, "CONTROL-VOY# " + voyageNumber, totalFontQuote);
    p.setAlignment(Element.ALIGN_LEFT);
    chargeCell.addElement(p);
    chargeTable.addCell(chargeCell);

    String emailId = "";
    StringBuilder agentDetails = new StringBuilder();
    //Agent Details
    String agentAcctNo = "";
    if ("Y".equalsIgnoreCase(altAgentKey)) {
        agentAcctNo = CommonUtils.isNotEmpty(altAgentValue) ? altAgentValue : "";
    } else if (lclbl.getAgentAcct() != null) {
        agentAcctNo = (agencyInfo != null && CommonUtils.isNotEmpty(agencyInfo[0])) ? agencyInfo[0]
                : lclbl.getAgentAcct().getAccountno();
    }
    if (CommonUtils.isNotEmpty(agentAcctNo)) {
        CustAddress custAddress = new CustAddressDAO().findPrimeContact(agentAcctNo);
        if (CommonFunctions.isNotNull(custAddress)) {
            if (CommonFunctions.isNotNull(custAddress.getAcctName())) {
                agentDetails.append(custAddress.getAcctName()).append("  ");
            }
            if (CommonFunctions.isNotNull(custAddress.getPhone())) {
                agentDetails.append("Phone: ").append(custAddress.getPhone()).append("\n");
            } else {
                agentDetails.append("\n");
            }
            if (CommonFunctions.isNotNull(custAddress.getCoName())) {
                agentDetails.append(custAddress.getCoName()).append("\n");
            }
            if (CommonFunctions.isNotNull(custAddress.getAddress1())) {
                agentDetails.append(custAddress.getAddress1().replace(", ", "\n")).append("\n");
            }
            if (CommonFunctions.isNotNull(custAddress.getCity1())) {
                agentDetails.append(custAddress.getCity1());
            }
            if (CommonFunctions.isNotNull(custAddress.getState())) {
                agentDetails.append("  ").append(custAddress.getState());
            }
            if (CommonFunctions.isNotNull(custAddress.getEmail1())) {
                emailId = custAddress.getEmail1();
            }
        }
    }
    BigDecimal PrintInvoiceValue = null;
    if (lclbl.getPortOfDestination() != null) {
        boolean schnum = new LCLPortConfigurationDAO().getSchnumValue(lclbl.getPortOfDestination().getId());
        if (schnum) {
            BigDecimal printInvoice = lclbl.getInvoiceValue();
            Long fileId = lclbl.getFileNumberId();
            if (!CommonUtils.isEmpty(printInvoice) && !CommonUtils.isEmpty(fileId)) {
                PrintInvoiceValue = printInvoice;
            }
        }
    }

    chargeCell = new PdfPCell();
    chargeCell.setBorder(2);
    chargeCell.setColspan(6);
    chargeCell.setPadding(0f);
    PdfPTable agent_Contact_Table = new PdfPTable(3);
    agent_Contact_Table.setWidthPercentage(100f);
    agent_Contact_Table.setWidths(new float[] { 2.3f, 1.7f, 1.8f });
    PdfPCell agent_Contact_cell = new PdfPCell();
    agent_Contact_cell.setBorder(0);
    agent_Contact_cell.setBorderWidthTop(1f);
    agent_Contact_cell.setBorderWidthLeft(1f);
    agent_Contact_cell.setBorderWidthBottom(0.06f);
    agent_Contact_cell.setBorderWidthRight(1f);
    p = new Paragraph(7f, "To Pick Up Freight Please Contact: ", blackContentNormalFont);
    p.setAlignment(Element.ALIGN_LEFT);
    agent_Contact_cell.addElement(p);
    agent_Contact_Table.addCell(agent_Contact_cell);

    agent_Contact_cell = new PdfPCell();
    agent_Contact_cell.setBorder(0);
    agent_Contact_cell.setColspan(2);
    agent_Contact_cell.setBorderWidthTop(1f);
    agent_Contact_cell.setPaddingBottom(2f);
    p = new Paragraph(7f, "Email: " + emailId.toLowerCase(), totalFontQuote);
    p.setAlignment(Element.ALIGN_LEFT);
    agent_Contact_cell.addElement(p);
    agent_Contact_Table.addCell(agent_Contact_cell);

    agent_Contact_cell = new PdfPCell();
    agent_Contact_cell.setColspan(2);
    agent_Contact_cell.setBorder(0);
    agent_Contact_cell.setBorderWidthLeft(1f);
    p = new Paragraph(7f, "" + agentDetails.toString(), totalFontQuote);
    p.setAlignment(Element.ALIGN_LEFT);
    agent_Contact_cell.addElement(p);
    agent_Contact_Table.addCell(agent_Contact_cell);

    agent_Contact_cell = new PdfPCell();
    agent_Contact_cell.setBorder(0);
    agent_Contact_cell.setPaddingTop(27f);
    p = new Paragraph(7f, "" + agentAcctNo, totalFontQuote);
    p.setAlignment(Element.ALIGN_RIGHT);
    agent_Contact_cell.addElement(p);
    agent_Contact_Table.addCell(agent_Contact_cell);

    agent_Contact_cell = new PdfPCell();
    agent_Contact_cell.setBorder(0);
    agent_Contact_cell.setColspan(3);
    agent_Contact_cell.setBorderWidthLeft(1f);
    StringBuilder builder = new StringBuilder();
    builder.append(PrintInvoiceValue != null ? "Value of Goods:USD $" + PrintInvoiceValue : "");
    p = new Paragraph(3f, "" + builder.toString(), totalFontQuote);
    p.setAlignment(Element.ALIGN_RIGHT);
    agent_Contact_cell.addElement(p);
    agent_Contact_Table.addCell(agent_Contact_cell);
    chargeCell.addElement(agent_Contact_Table);
    chargeTable.addCell(chargeCell);

    return chargeTable;
}

From source file:net.turnbig.pandora.web.Servlets.java

/**
 * http://domain:port/context/related-path
 * //from ww w . j  a v  a  2 s  .c om
 * @param request
 * @return http://domain:port/context
 */
public static String getBasePath(HttpServletRequest request) {
    String requestURL = request.getRequestURL().toString(); // whole URL
    String requestURI = request.getRequestURI(); // context-path + path
    String host = StringUtils.substringBeforeLast(requestURL, requestURI);
    String contextPath = request.getContextPath();
    return StringUtils.removeEnd(host + contextPath, "/");
}

From source file:nl.sidn.dnslib.util.IPUtil.java

public static String expandIPv6(String ip) {
    String[] sections = StringUtils.splitByWholeSeparatorPreserveAllTokens(ip, ":");
    StringBuilder sb = new StringBuilder();
    for (String section : sections) {
        if (section.length() == 0) {
            int missing = (8 - sections.length) + 1;
            for (int i = 0; i < missing; i++) {
                sb.append("0000:");
            }/* w  ww  .j a  va2  s .  c o  m*/
        } else if (section.length() < 4) {
            String paddedSection = StringUtils.leftPad(section, 4, "0");
            sb.append(paddedSection + ":");
        } else {
            sb.append(section + ":");
        }
    }
    String expanded = sb.toString();
    return StringUtils.removeEnd(expanded, ":");
}

From source file:nl.sidn.pcap.util.Settings.java

public static void createTldSuffixes(String value) {
    if (StringUtils.isEmpty(value)) {
        //no value found, do nothing
        return;//from  w w w . j  a  v  a  2 s.c om
    }

    String[] tlds = StringUtils.split(value, ",");
    //create list of DomainParents
    for (int i = 0; i < tlds.length; i++) {
        String parent = tlds[i];
        if (parent == null) {
            //skip nulls
            continue;
        }
        //start and end with a dot.
        if (!StringUtils.startsWith(parent, ".")) {
            parent = "." + parent;
        }

        int labelCount = StringUtils.split(parent, '.').length;
        if (StringUtils.endsWith(parent, ".")) {
            //remove last dot (will become the used tld suffix
            tldSuffixes.add(new DomainParent(parent, StringUtils.removeEnd(parent, "."), labelCount));
        } else {
            tldSuffixes.add(new DomainParent(parent + ".", parent, labelCount));
        }
    }

}