Example usage for org.apache.commons.lang BooleanUtils toStringYesNo

List of usage examples for org.apache.commons.lang BooleanUtils toStringYesNo

Introduction

In this page you can find the example usage for org.apache.commons.lang BooleanUtils toStringYesNo.

Prototype

public static String toStringYesNo(boolean bool) 

Source Link

Document

Converts a boolean to a String returning 'yes' or 'no'.

 BooleanUtils.toStringYesNo(true)   = "yes" BooleanUtils.toStringYesNo(false)  = "no" 

Usage

From source file:com.facultyshowcase.app.ui.UIUtil.java

public static void writeProperty(EntityUtilWriter writer, String htmlClass, String label, boolean bool) {
    writeContainerBeginning(writer, htmlClass);

    writeLabel(writer, htmlClass, label);

    writer.append("<span ");
    writer.appendEscapedAttribute(CLASS, CmsHTMLClassNames.convertClassName(PROP + " " + htmlClass));
    writer.append(">");
    writer.appendEscapedData(BooleanUtils.toStringYesNo(bool));
    writer.append("</span>");

    writeContainerEnd(writer);/*from  w  ww  .  ja  v  a 2  s .  co  m*/
}

From source file:edu.cornell.med.icb.goby.modes.AbstractCommandLineMode.java

/**
 * Print the usage for a mode in the format appropriate for a
 * <a href="http://www.wikimedia.org/">Wikimedia</a> table.
 *
 * @param jsap The parameters for the mode
 *///  w w w  .ja v  a 2  s.  c  o  m
public void printUsageAsWikiTable(final JSAP jsap) {
    final PrintStream stream = System.out;

    // Table definition/header
    stream.println(
            "{| class=\"wikitable\" style=\"margin: 1em auto 1em auto; background:#efefef;\" valign=\"top\" align=\"center\" border=\"1\" cellpadding=\"5\" width=\"80%\"");
    stream.println("|- valign=\"bottom\" align=\"left\" style=\"background:#ffdead;\"");
    stream.println("!width=\"15%\"| Flag");
    stream.println("!width=\"10%\" | Arguments");
    stream.println("!width=\"5%\"| Required");
    stream.println("! Description");
    stream.println();

    // iterate through help entries for the mode
    final IDMap idMap = jsap.getIDMap();
    final Iterator iterator = idMap.idIterator();
    while (iterator.hasNext()) {
        final String id = (String) iterator.next();
        if (!"mode".equals(id) && !isJSAPHelpId(id)) { // skip the mode and help ids
            final Parameter parameter = jsap.getByID(id);
            stream.println("|- valign=\"top\" align=\"left\"");
            stream.print("| <nowiki>");
            if (parameter instanceof Flagged) {
                final Flagged flagged = (Flagged) parameter;
                final Character characterFlag = flagged.getShortFlagCharacter();
                final String longFlag = flagged.getLongFlag();
                if (characterFlag != null && StringUtils.isNotBlank(longFlag)) {
                    stream.print("(-" + characterFlag + "|--" + longFlag + ")");
                } else if (characterFlag != null) {
                    stream.print("-" + characterFlag);
                } else if (StringUtils.isNotBlank(longFlag)) {
                    stream.print("--" + longFlag);
                }
            } else {
                stream.print("n/a");
            }
            stream.println("</nowiki>");
            stream.print("| ");
            if (parameter instanceof Switch) {
                stream.println("n/a");
            } else {
                stream.println(id);
            }

            final boolean required;
            if (parameter instanceof Option) {
                final Option option = (Option) parameter;
                required = option.required();
            } else {
                required = !(parameter instanceof Switch);
            }
            stream.println("| " + BooleanUtils.toStringYesNo(required));
            stream.println("| " + parameter.getHelp());
            if (parameter.getDefault() != null) {
                stream.print("Default value: ");
                for (final String defaultValue : parameter.getDefault()) {
                    stream.print(" ");
                    stream.print(defaultValue);
                }
            }
            stream.println();
        }
    }

    // table close
    stream.println("|}");
}

From source file:com.adaptris.core.ftp.SftpConnectionTest.java

public static File createOpenSshConfig(boolean strict) throws Exception {
    File tempDir = new File(PROPERTIES.getProperty(CFG_TEMP_HOSTS_FILE));
    tempDir.mkdirs();//from w w  w.jav a  2  s  .c o  m
    File tempFile = File.createTempFile(SftpConnectionTest.class.getSimpleName(), "", tempDir);
    try (PrintStream out = new PrintStream(new FileOutputStream(tempFile))) {
        out.println("Host *");
        out.println("  StrictHostKeyChecking " + BooleanUtils.toStringYesNo(strict));
        out.println("  " + SftpClient.SSH_PREFERRED_AUTHENTICATIONS + " " + SftpClient.NO_KERBEROS_AUTH);
    }
    return tempFile;
}

From source file:edu.cornell.med.icb.goby.modes.AbstractCommandLineMode.java

/**
 * Print the usage for a mode in the format appropriate for a table in HTML.
 *
 * @param jsap The parameters for the mode
 *//*from  w w w.j  a v a  2s .c  o  m*/
public void printUsageAsHtmlTable(final JSAP jsap) {
    final PrintStream writer = System.out;

    // Table definition/header
    writer.println("<table style=\"background: #efefef;\" border=\"1\" cellpadding=\"5\">");
    writer.println("<tbody>");
    writer.println("<tr style=\"background: #ffdead;\" align=\"left\" valign=\"bottom\">");
    writer.println("<th style=\"width: 15%\">Flag</th>");
    writer.println("<th style=\"width: 10%\">Arguments</th>");
    writer.println("<th style=\"width: 5%\">Required</th>");
    writer.println("<th>Description</th>");
    writer.println("</tr>");

    // iterate through help entries for the mode
    final IDMap idMap = jsap.getIDMap();
    final Iterator iterator = idMap.idIterator();
    while (iterator.hasNext()) {
        final String id = (String) iterator.next();
        if (!"mode".equals(id) && !isJSAPHelpId(id)) { // skip the mode and help ids
            final Parameter parameter = jsap.getByID(id);
            writer.println("<tr align=\"left\" valign=\"top\">");
            writer.print("<td><code>");
            if (parameter instanceof Flagged) {
                final Flagged flagged = (Flagged) parameter;
                final Character characterFlag = flagged.getShortFlagCharacter();
                final String longFlag = flagged.getLongFlag();
                if (characterFlag != null && StringUtils.isNotBlank(longFlag)) {
                    writer.print("(-" + characterFlag + "|--" + longFlag + ")");
                } else if (characterFlag != null) {
                    writer.print("-" + characterFlag);
                } else if (StringUtils.isNotBlank(longFlag)) {
                    writer.print("--" + longFlag);
                }
            } else {
                writer.print("n/a");
            }
            writer.println("</code></td>");
            writer.print("<td>");
            if (parameter instanceof Switch) {
                writer.print("n/a");
            } else {
                writer.print(id);
            }
            writer.println("</td>");
            final boolean required;
            if (parameter instanceof Option) {
                final Option option = (Option) parameter;
                required = option.required();
            } else {
                required = !(parameter instanceof Switch);
            }
            writer.println("<td>" + BooleanUtils.toStringYesNo(required) + "</td>");
            writer.print("<td>");

            // convert any strange characters to html codes
            final String htmlHelpString = StringEscapeUtils.escapeHtml(parameter.getHelp());
            // and also convert "-" to the hyphen character code
            writer.print(StringUtils.replace(htmlHelpString, "-", "&#45;"));
            if (parameter.getDefault() != null) {
                writer.print(" Default value: ");
                for (final String defaultValue : parameter.getDefault()) {
                    writer.print(" ");
                    writer.print(StringUtils.replace(defaultValue, "-", "&#45;"));
                }
            }
            writer.println("</td>");
            writer.println("</tr>");
        }
    }

    // table close
    writer.println("</tbody>");
    writer.println("</table>");
}

From source file:com.facultyshowcase.app.ui.ProfessorProfileViewer.java

@Override
public void init() {
    // Make sure you call super.init() at the top of this method.
    /// See the Javadoc for #init() for more information about what it does.
    super.init();

    // Set HTML element type and class names for presentation use on this Container component.
    setHTMLElement(HTMLElement.section);
    addClassName("user-profile-viewer");
    // property_viewer is a standard class name.
    addClassName(UIUtil.PROP + "erty-viewer");
    // Add microdata for programmatic / SEO use
    /// OR use RDFa support
    /// You typically only do this in viewers - not editors.
    setAttribute("itemscope", "");
    setAttribute("itemtype", "http://schema.org/Person");
    // setAttribute allows you to set any attribute as long as it will not interfere with a component's
    /// native HTML. For example, you cannot set the "value" attribute on a Field since
    /// it uses that attribute.

    // It's a good idea to *not* mark variables final that you don't want in the scope of event listeners.
    /// Hibernate/JPA entities are a great example of this pattern. You always need to re-attach
    /// entities before using them, so we should always call getProfessorProfile() in the context
    /// of handling an event. Note: our getProfessorProfile() method re-attaches the entity.
    ProfessorProfile ProfessorProfile = getProfessorProfile();

    Name name = ProfessorProfile.getName();
    // You can use a Field for displaying non-internationalized content.
    /// It is desirable to do this since you don't need to create a LocalizedText.
    /// However, you cannot change the HTMLElement of a Field at this time,
    /// so some of the following code uses a Label which does allow
    /// specification of the HTMLElement.
    final Field slug = new Field(ProfessorProfile.getSlug(), false);
    final Field namePrefix = new Field(name.getFormOfAddress(), false);
    final Field nameGiven = new Field(name.getFirst(), false);
    final Field nameFamily = new Field(name.getLast(), false);
    final Field nameSuffix = new Field(name.getSuffix(), false);
    // Sometimes it is easier and less error prone to make a component non-visible
    /// than checking for null on each use. Use this pattern with care. You don't
    /// want to consume a lot of resource unnecessarily.
    if (StringFactory.isEmptyString(namePrefix.getText()))
        namePrefix.setVisible(false);// w  ww  .  ja v a2 s .  com
    if (StringFactory.isEmptyString(nameSuffix.getText()))
        nameSuffix.setVisible(false);

    // Address
    Address address = ProfessorProfile.getPostalAddress();
    // Address lines are always on their own line so we make sure they are enclosed by a block element like a DIV..
    final Label addressLine1 = new Label();
    addressLine1.setHTMLElement(HTMLElement.div).addClassName(UIUtil.PROP).addClassName(UIUtil.ADDRESS_LINE);
    final Label addressLine2 = new Label();
    addressLine2.setHTMLElement(HTMLElement.div).addClassName(UIUtil.PROP).addClassName(UIUtil.ADDRESS_LINE);
    if (address.getAddressLines().length > 0)
        addressLine1.setText(TextSources.create(address.getAddressLines()[0]));
    if (address.getAddressLines().length > 1)
        addressLine2.setText(TextSources.create(address.getAddressLines()[1]));
    final HTMLComponent city = new HTMLComponent();
    // The "prop" class name is part of the standard HTML structure. It is always a good idea to also
    /// add a specific class name like "city" in this example. Please be consistent when using class names.
    /// For example, if everyone else is using "city", please use "city" too. Don't come up with another class name
    /// that means something similar like "town" or "locality". Consistency has a big impact on
    /// the time required to style HTML as well as the ability to reuse CSS.
    city.setHTMLElement(HTMLElement.span).addClassName(UIUtil.PROP).addClassName(UIUtil.CITY);
    if (!StringFactory.isEmptyString(address.getCity())) {
        // Our microdata for the city shouldn't include the comma, so this is a bit more complicated than the other examples.
        city.setText(TextSources.create("<span item" + UIUtil.PROP + "=\"" + UIUtil.ADDRESS + "Locality\">"
                + address.getCity() + "</span><span class=\"delimiter\">,</span>"));
    } else
        city.setVisible(false);
    final Label state = new Label(TextSources.create(address.getState()));
    state.addClassName(UIUtil.PROP).addClassName(UIUtil.STATE);
    final Label postalCode = new Label(TextSources.create(address.getPostalCode()));
    postalCode.addClassName(UIUtil.PROP).addClassName(UIUtil.POSTAL_CODE);

    // Other Contact
    final Field phoneNumber = new Field(ProfessorProfile.getPhoneNumber(), false);
    final Field emailAddress = new Field(ProfessorProfile.getEmailAddress(), false);

    // Social Contact
    final URILink twitterLink = ProfessorProfile.getTwitterLink() != null
            ? new URILink(_ProfessorProfileDAO.toURI(ProfessorProfile.getTwitterLink(), null))
            : null;
    final URILink facebookLink = ProfessorProfile.getFacebookLink() != null
            ? new URILink(_ProfessorProfileDAO.toURI(ProfessorProfile.getFacebookLink(), null))
            : null;
    final URILink linkedInLink = ProfessorProfile.getLinkedInLink() != null
            ? new URILink(_ProfessorProfileDAO.toURI(ProfessorProfile.getLinkedInLink(), null))
            : null;

    // We are going to output HTML received from the outside, so we need to sanitize it first for security reasons.
    /// Sometimes you'll do this sanitation prior to persisting the data. It depends on whether or not you need to
    /// keep the original unsanitized HTML around.
    final HTMLComponent aboutMeProse = new HTMLComponent(
            UIUtil.scrubHtml(ProfessorProfile.getAboutMeProse(), Event.getRequest(), Event.getResponse()));
    Component aboutMeVideo = null;
    URL videoLink = ProfessorProfile.getAboutMeVideoLink();
    if (videoLink != null) {
        // There are several ways to link to media (Youtube video URL, Vimeo video URL, Flickr URL, internally hosted media file, etc).
        /// You can link to it.
        /// You can embed it. See http://oembed.com/ for a common protocol for doing this.
        /// If the link is to the media itself, you can create a player for it.
        /// Below is an example of creating a link to the video as well as a player.
        final URI videoLinkURI = _ProfessorProfileDAO.toURI(videoLink, null);
        URILink videoLinkComponent = new URILink(videoLinkURI, TextSources.create("My Video"));
        videoLinkComponent.setTarget("_blank");
        IMediaUtility util = MediaUtilityFactory.getUtility();
        try {
            // Check if we can parse the media and it has a stream we like.
            /// In our made up example, we're only accepting H.264 video. We don't care about the audio in this example.
            IMediaMetaData mmd;
            if (util.isEnabled() && videoLinkURI != null
                    && (mmd = util.getMetaData(videoLinkURI.toString())).getStreams().length > 0) {
                int width = 853, height = 480; // 480p default
                boolean hasVideo = false;
                for (IMediaStream stream : mmd.getStreams()) {
                    if (stream.getCodec().getType() == ICodec.Type.video
                            && "H264".equals(stream.getCodec().name())) {
                        hasVideo = true;
                        if (stream.getWidth() > 0) {
                            width = stream.getWidth();
                            height = stream.getHeight();
                        }
                        break;
                    }
                }
                if (hasVideo) {
                    Media component = new Media();
                    component.setMediaType(Media.MediaType.video);
                    component.addSource(new MediaSource(videoLinkURI));
                    component.setFallbackContent(videoLinkComponent);
                    component.setSize(new PixelMetric(width), new PixelMetric(height));
                    aboutMeVideo = component;
                }
            }
        } catch (IllegalArgumentException | RemoteException e) {
            _logger.error("Unable to get media information for " + videoLink, e);
        }
        if (aboutMeVideo == null) {
            // We could check for oEmbed support in case link was to youtube, vimeo, etc - http://oembed.com/
            // Since this is an example, we'll just output the link.
            aboutMeVideo = videoLinkComponent;
        }
    }
    ImageComponent picture = null;
    final FileEntity ProfessorProfilePicture = ProfessorProfile.getPicture();
    if (ProfessorProfilePicture != null) {
        picture = new ImageComponent(new Image(ProfessorProfilePicture));
        picture.setImageCaching(ProfessorProfilePicture.getLastModifiedTime()
                .before(new Date(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(60))));
    }

    // Professional Information

    // We are going to output HTML received from the outside, so we need to sanitize it first for security reasons.
    /// Sometimes you'll do this sanitation prior to persisting the data. It depends on whether or not you need to
    /// keep the original unsanitized HTML around.
    final HTMLComponent researchSpecialty = new HTMLComponent(
            UIUtil.scrubHtml(ProfessorProfile.getAboutMeProse(), Event.getRequest(), Event.getResponse()));

    final Field rank = ProfessorProfile.getProfessorRank() != null
            ? new Field(ObjectUtils.toString(ProfessorProfile.getProfessorRank()), false)
            : null;
    final DateFormat parser = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
    final Field dateJoined = ProfessorProfile.getDateJoined() != null
            ? new Field(parser.format(ProfessorProfile.getDateJoined()), false)
            : null;
    final Field onSabbatical = new Field(BooleanUtils.toStringYesNo(ProfessorProfile.isOnSabbatical()), false);

    // Now that we've initialized most of the content, we'll add all the components to this View
    /// using the standard HTML structure for a property viewer.
    add(of(HTMLElement.section, UIUtil.PROP + "-group " + UIUtil.NAME,
            new Label(TextSources.create("Name")).setHTMLElement(HTMLElement.h1),
            slug.setAttribute("item" + UIUtil.PROP, UIUtil.USER_ID).addClassName(UIUtil.PROP)
                    .addClassName(UIUtil.USER_ID),
            namePrefix.setAttribute("item" + UIUtil.PROP, "honorificPrefix").addClassName(UIUtil.PROP)
                    .addClassName(UIUtil.PREFIX),
            nameGiven.setAttribute("item" + UIUtil.PROP, "givenName").addClassName(UIUtil.PROP)
                    .addClassName(UIUtil.FIRST_NAME),
            nameFamily.setAttribute("item" + UIUtil.PROP, "familyName").addClassName(UIUtil.PROP)
                    .addClassName(UIUtil.LAST_NAME),
            nameSuffix.setAttribute("item" + UIUtil.PROP, "honorificSuffix").addClassName(UIUtil.PROP)
                    .addClassName(UIUtil.SUFFIX)));

    // Add wrapping DIV to group address lines if necessary.
    Component streetAddress = (!StringFactory.isEmptyString(addressLine1.getText())
            && !StringFactory.isEmptyString(addressLine2.getText())
                    ? of(HTMLElement.div, UIUtil.ADDRESS_LINES, addressLine1, addressLine2)
                    : (StringFactory.isEmptyString(addressLine1.getText()) ? addressLine2 : addressLine1)
                            .setHTMLElement(HTMLElement.div));
    streetAddress.setAttribute("item" + UIUtil.PROP, "streetAddress");
    boolean hasAddress = (!StringFactory.isEmptyString(addressLine1.getText())
            || !StringFactory.isEmptyString(addressLine2.getText())
            || !StringFactory.isEmptyString(city.getText()) || !StringFactory.isEmptyString(state.getText())
            || !StringFactory.isEmptyString(postalCode.getText()));
    boolean hasPhone = !StringFactory.isEmptyString(phoneNumber.getText());
    boolean hasEmail = !StringFactory.isEmptyString(emailAddress.getText());
    // We only want to output the enclosing HTML if we have content to display.
    if (hasAddress || hasPhone || hasEmail) {
        Container contactContainer = of(HTMLElement.section, "contact",
                new Label(TextSources.create("Contact Information")).setHTMLElement(HTMLElement.h1));
        add(contactContainer);
        if (hasAddress) {
            contactContainer.add(of(HTMLElement.div, UIUtil.PROP_GROUP + " " + UIUtil.ADDRESS,
                    // We are using an H2 here because are immediate ancestor is a DIV. If it was a SECTION,
                    /// then we would use an H1. See the ProfessorProfileViewer for a comparison.
                    new Label(TextSources.create("Address")).setHTMLElement(HTMLElement.h2), streetAddress,
                    of(HTMLElement.div, UIUtil.PLACE, city,
                            state.setAttribute("item" + UIUtil.PROP, UIUtil.ADDRESS + "Region"),
                            postalCode.setAttribute("item" + UIUtil.PROP, "postalCode")))
                                    .setAttribute("item" + UIUtil.PROP, UIUtil.ADDRESS)
                                    .setAttribute("itemscope", "")
                                    .setAttribute("itemtype", "http://schema.org/PostalAddress"));
        }
        if (hasPhone) {
            contactContainer.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.PHONE,
                    new Label(TextSources.create("Phone")).setHTMLElement(HTMLElement.h2),
                    phoneNumber.setAttribute("item" + UIUtil.PROP, "telephone")));
        }
        if (hasEmail) {
            contactContainer.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.EMAIL,
                    new Label(TextSources.create("Email")).setHTMLElement(HTMLElement.h2),
                    emailAddress.setAttribute("item" + UIUtil.PROP, UIUtil.EMAIL)));
        }
    }

    if (twitterLink != null || facebookLink != null || linkedInLink != null) {
        Container social = of(HTMLElement.section, UIUtil.SOCIAL,
                new Label(TextSources.create("Social Media Links")).setHTMLElement(HTMLElement.h1));
        add(social);
        if (twitterLink != null) {
            twitterLink.setTarget("_blank");
            twitterLink.setText(TextSources.create("Twitter Link"));
            social.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.TWITTER, TextSources.create("Twitter"),
                    twitterLink));
        }
        if (facebookLink != null) {
            facebookLink.setTarget("_blank");
            facebookLink.setText(TextSources.create("Facebook Link"));
            social.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.FACEBOOK, TextSources.create("Facebook"),
                    facebookLink));
        }
        if (linkedInLink != null) {
            linkedInLink.setTarget("_blank");
            linkedInLink.setText(TextSources.create("LinkedIn Link"));
            social.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.LINKEDIN, TextSources.create("LinkedIn"),
                    linkedInLink));
        }
    }

    final boolean hasAboutMeProse = StringFactory.isEmptyString(aboutMeProse.getText());
    if (!hasAboutMeProse || aboutMeVideo != null) {
        Container aboutMe = of(HTMLElement.section, UIUtil.ABOUT_ME,
                new Label(TextSources.create("About Me")).setHTMLElement(HTMLElement.h1));
        add(aboutMe);
        if (picture != null) {
            aboutMe.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.PICTURE, TextSources.create("Picture"),
                    picture));
        }
        if (hasAboutMeProse) {
            aboutMe.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.PROSE,
                    TextSources.create("Hobbies, Interests..."), aboutMeProse));
        }
        if (aboutMeVideo != null) {
            Label label = new Label(TextSources.create("Video")).setHTMLElement(HTMLElement.label);
            label.addClassName("vl");
            aboutMe.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.VIDEO, label, aboutMeVideo));
        }

    }

    final boolean hasResearchSpecialty = StringFactory.isEmptyString(researchSpecialty.getText());
    if (!hasResearchSpecialty || rank != null || dateJoined != null || onSabbatical != null) {
        Container professionalInformation = of(HTMLElement.section, UIUtil.PROFESSIONAL_INFORMATION,
                new Label(TextSources.create("Professional Information")).setHTMLElement(HTMLElement.h1));
        add(professionalInformation);
        if (rank != null) {
            professionalInformation.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.RANK,
                    TextSources.create("Professor Rank"), rank));
        }
        if (dateJoined != null) {
            Label label = new Label(TextSources.create("Date Joined")).setHTMLElement(HTMLElement.label);
            professionalInformation
                    .add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.DATE_JOINED, label, dateJoined));
        }
        if (onSabbatical != null) {
            Label label = new Label(TextSources.create("On Sabbatical")).setHTMLElement(HTMLElement.label);
            professionalInformation
                    .add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.ON_SABBATICAL, label, onSabbatical));
        }
        if (hasResearchSpecialty) {
            professionalInformation.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.PROSE,
                    TextSources.create("Research Specialty"), aboutMeProse));
        }
    }
}

From source file:org.bdval.BDVModel.java

/**
 * Loads a BDVal model from disk. BDVal models are generated with the
 * {@link org.bdval.DiscoverAndValidate} tools (BDVal).
 *
 * @param options specific options to use when loading the model
 * @throws IOException            if there is a problem accessing the model
 * @throws ClassNotFoundException if the type of the model is not recognized
 */// w  ww  .  j a  v  a  2  s . c o m
public void load(final DAVOptions options) throws IOException, ClassNotFoundException {
    final boolean zipExists = new File(zipFilename).exists();
    if (LOG.isDebugEnabled()) {
        LOG.debug("model zip file exists: " + BooleanUtils.toStringYesNo(zipExists));
    }
    properties.clear();
    properties.setDelimiterParsingDisabled(true);
    // check to see if a zip file exists - if it doesn't we assume it's an old binary format
    if (zipModel && zipExists) {
        LOG.info("Reading model from filename: " + zipFilename);

        final ZipFile zipFile = new ZipFile(zipFilename);
        try {
            final ZipEntry propertyEntry = zipFile.getEntry(FilenameUtils.getName(modelPropertiesFilename));
            // load properties
            properties.clear();
            properties.addAll(loadProperties(zipFile.getInputStream(propertyEntry), options));

            // the platform is more than one entry in the zip, so here we pass the whole zip
            trainingPlatform = options.trainingPlatform = loadPlatform(zipFile);

            if (isConsensusModel()) {
                int index = 0;
                final ObjectList<String> modelJurorFilePrefixes = new ObjectArrayList<String>();
                String nextFilename;
                while ((nextFilename = (String) properties
                        .getProperty("bdval.consensus.model." + Integer.toString(index))) != null) {
                    modelJurorFilePrefixes.add(nextFilename);
                    index++;
                }

                delegate = new ConsensusBDVModel(modelFilenamePrefix,
                        modelJurorFilePrefixes.toArray(new String[modelJurorFilePrefixes.size()]));
                delegate.load(options);
                setGeneList(convertTrainingPlatformToGeneList(options));
                return;
            } else {
                probesetScaleMeanMap = options.probesetScaleMeanMap = loadMeansMap(
                        zipFile.getInputStream(zipFile.getEntry(FilenameUtils.getName(meansMapFilename))));
                probesetScaleRangeMap = options.probesetScaleRangeMap = loadRangeMap(
                        zipFile.getInputStream(zipFile.getEntry(FilenameUtils.getName(rangeMapFilename))));
                setGeneList(convertTrainingPlatformToGeneList(options));
            }

            final String modelParameters = properties.getString("training.classifier.parameters");

            LOG.info("Loading model " + modelFilename);
            final InputStream modelStream = zipFile
                    .getInputStream(zipFile.getEntry(FilenameUtils.getName(modelFilename)));
            helper = ClassificationModel.load(modelStream, modelParameters);
            LOG.info("Model loaded.");

            options.classiferClass = helper.classifier.getClass();
            // we don't have a way to inspect the saved model for parameters used during training:
            options.classifierParameters = ClassificationModel.splitModelParameters(modelParameters);
        } finally {
            try {
                zipFile.close();
            } catch (IOException e) { // NOPMD
                // ignore since there is not much we can do anyway
            }
        }
    } else {
        final File propertyFile = new File(modelFilenamePrefix + "." + ModelFileExtension.props.toString());
        LOG.debug("Loading properties from " + propertyFile.getAbsolutePath());
        final Properties properties = loadProperties(FileUtils.openInputStream(propertyFile), options);

        trainingPlatform = options.trainingPlatform = (GEOPlatformIndexed) BinIO.loadObject(platformFilename);

        if (isConsensusModel()) {
            int index = 0;
            final ObjectList<String> modelJurorFilePrefixes = new ObjectArrayList<String>();
            String nextFilename = null;
            while ((nextFilename = (String) properties
                    .getProperty("bdval.consensus.model." + Integer.toString(index))) != null) {
                modelJurorFilePrefixes.add(nextFilename);
                index++;
            }

            delegate = new ConsensusBDVModel(modelFilenamePrefix,
                    modelJurorFilePrefixes.toArray(new String[modelJurorFilePrefixes.size()]));
            delegate.load(options);
            setGeneList(convertTrainingPlatformToGeneList(options));
            return;
        } else {
            probesetScaleMeanMap = options.probesetScaleMeanMap = (Object2DoubleMap<MutableString>) BinIO
                    .loadObject(modelFilenamePrefix + ".means");
            if (LOG.isDebugEnabled()) {
                LOG.debug("Number of entries in means map = " + probesetScaleMeanMap.size());
            }
            probesetScaleRangeMap = options.probesetScaleRangeMap = (Object2DoubleMap<MutableString>) BinIO
                    .loadObject(modelFilenamePrefix + ".ranges");
            if (LOG.isDebugEnabled()) {
                LOG.debug("Number of entries in range map = " + probesetScaleRangeMap.size());
            }
            setGeneList(convertTrainingPlatformToGeneList(options));
        }

        final String modelParameters = properties.getString("training.classifier.parameters");

        LOG.info("Loading model " + modelFilename);
        helper = ClassificationModel.load(modelFilename, modelParameters);
        LOG.info("Model loaded.");

        options.classiferClass = helper.classifier.getClass();
        // we don't have a way to inspect the saved model for parameters used during training:
        options.classifierParameters = ClassificationModel.splitModelParameters(modelParameters);
    }
}

From source file:org.bdval.BDVModel.java

private GEOPlatformIndexed loadPlatform() throws ClassNotFoundException, IOException {
    final GEOPlatformIndexed platform;
    final boolean zipExists = new File(zipFilename).exists();
    if (LOG.isDebugEnabled()) {
        LOG.debug("model zip file exists: " + BooleanUtils.toStringYesNo(zipExists));
    }/*ww w  .j ava  2s .  com*/
    if (zipModel && zipExists) {
        platform = loadPlatform(new ZipFile(zipFilename));
    } else {
        platform = (GEOPlatformIndexed) BinIO.loadObject(platformFilename);
    }
    return platform;
}

From source file:org.bdval.ConsensusBDVModel.java

/**
 * @param options specific options to use when loading the properties
 * @throws IOException if there is a problem accessing the properties
 *///from  www  .  j ava 2  s. c o  m
private void loadProperties(final DAVOptions options) throws IOException {
    final boolean zipExists = new File(zipFilename).exists();
    if (LOG.isDebugEnabled()) {
        LOG.debug("model zip file exists: " + BooleanUtils.toStringYesNo(zipExists));
    }

    properties.clear();

    // check to see if a zip file exists - if it doesn't we assume it's an old binary format
    if (zipModel && zipExists) {
        LOG.info("Reading model from filename: " + zipFilename);

        final ZipFile zipFile = new ZipFile(zipFilename);
        try {
            final ZipEntry propertyEntry = zipFile.getEntry(FilenameUtils.getName(modelPropertiesFilename));
            // load properties
            properties.clear();
            properties.addAll(loadProperties(zipFile.getInputStream(propertyEntry), options));
        } finally {
            try {
                zipFile.close();
            } catch (IOException e) { // NOPMD
                // ignore since there is not much we can do anyway
            }
        }
    } else {
        final File propertyFile = new File(modelFilenamePrefix + "." + ModelFileExtension.props.toString());
        if (propertyFile.exists() && propertyFile.canRead()) {
            LOG.debug("Loading properties from " + propertyFile.getAbsolutePath());
            properties.addAll(loadProperties(FileUtils.openInputStream(propertyFile), options));
        }
    }
}

From source file:org.kuali.student.cm.course.service.impl.CourseMaintainableImpl.java

/**
 * Updates the ReviewProposalDisplay object for the Course Proposal and refreshes remote data elements based on passed in @shouldRepopulateRemoteData param
 *
 * @param shouldRepopulateRemoteData identifies whether remote data elements like Collaborators should be refreshed
 *//*from   w  w  w . j  av a  2  s.c o  m*/
@Override
protected void updateReview(ProposalElementsWrapper proposalElementsWrapper,
        boolean shouldRepopulateRemoteData) {

    CourseInfoWrapper courseInfoWrapper = (CourseInfoWrapper) proposalElementsWrapper;
    CourseInfo savedCourseInfo = courseInfoWrapper.getCourseInfo();

    // Update course section
    ReviewProposalDisplay reviewData = courseInfoWrapper.getReviewProposalDisplay();
    if (reviewData == null) {
        reviewData = new ReviewProposalDisplay();
        courseInfoWrapper.setReviewProposalDisplay(reviewData);
    }
    if (StringUtils.isBlank(courseInfoWrapper.getPreviousSubjectCode())
            && StringUtils.isNotBlank(savedCourseInfo.getSubjectArea())) {
        courseInfoWrapper.setPreviousSubjectCode(savedCourseInfo.getSubjectArea());
    }

    reviewData.getCourseSection().setCourseTitle(savedCourseInfo.getCourseTitle());
    reviewData.getCourseSection().setTranscriptTitle(savedCourseInfo.getTranscriptTitle());
    reviewData.getCourseSection().setSubjectArea(savedCourseInfo.getSubjectArea());
    reviewData.getCourseSection().setCourseNumberSuffix(savedCourseInfo.getCourseNumberSuffix());

    if (StringUtils.isNotBlank(courseInfoWrapper.getProposalInfo().getId())) {
        Date updateTime = courseInfoWrapper.getProposalInfo().getMeta().getUpdateTime();
        if (updateTime != null) {
            courseInfoWrapper
                    .setLastUpdated(CurriculumManagementConstants.CM_DATE_FORMATTER.format(updateTime));
        }
    }

    if (savedCourseInfo.getDescr() != null) {
        reviewData.getCourseSection().setDescription(savedCourseInfo.getDescr().getPlain());
    }

    reviewData.getCourseSection().getInstructors().clear();
    for (CluInstructorInfoWrapper insturctorWrappers : courseInfoWrapper.getInstructorWrappers()) {
        reviewData.getCourseSection().getInstructors().add(insturctorWrappers.getDisplayName());
    }

    reviewData.getCourseSection().getCrossListings().clear();
    if (!savedCourseInfo.getCrossListings().isEmpty()) {
        for (CourseCrossListingInfo crossListingInfo : savedCourseInfo.getCrossListings()) {
            reviewData.getCourseSection().getCrossListings().add(crossListingInfo.getCode());
        }
    }

    reviewData.getCourseSection().getJointlyOfferedCourses().clear();
    if (!savedCourseInfo.getJoints().isEmpty()) {
        for (CourseJointInfo jointInfo : savedCourseInfo.getJoints()) {
            reviewData.getCourseSection().getJointlyOfferedCourses()
                    .add(jointInfo.getSubjectArea() + jointInfo.getCourseNumberSuffix());
        }
    }

    reviewData.getCourseSection().getVariations().clear();
    if (!savedCourseInfo.getVariations().isEmpty()) {
        for (CourseVariationInfo variationInfo : savedCourseInfo.getVariations()) {
            if (variationInfo.getVariationCode() == null && variationInfo.getVariationTitle() == null) {
                reviewData.getCourseSection().getVariations().add("");
            } else if (variationInfo.getVariationCode() == null) {
                reviewData.getCourseSection().getVariations()
                        .add("" + ": " + variationInfo.getVariationTitle());
            } else {
                reviewData.getCourseSection().getVariations()
                        .add(variationInfo.getVariationCode() + ": " + variationInfo.getVariationTitle());
            }
        }
    }

    // Update governance section
    reviewData.getGovernanceSection().getCampusLocations().clear();
    reviewData.getGovernanceSection().getCampusLocations()
            .addAll(updateCampusLocations(savedCourseInfo.getCampusLocations()));
    reviewData.getGovernanceSection().setCurriculumOversight(buildCurriculumOversightList(
            savedCourseInfo.getSubjectArea(), savedCourseInfo.getUnitsContentOwner()));

    reviewData.getGovernanceSection().getAdministeringOrganization().clear();
    for (OrganizationInfoWrapper organizationInfoWrapper : courseInfoWrapper.getAdministeringOrganizations()) {
        if (organizationInfoWrapper.isUserEntered()) {
            reviewData.getGovernanceSection().getAdministeringOrganization()
                    .add(organizationInfoWrapper.getOrganizationName());
        }
    }

    // update course logistics section
    reviewData.getCourseLogisticsSection().getTerms().clear();
    try {
        for (String termType : savedCourseInfo.getTermsOffered()) {
            TypeInfo term = getTypeService().getType(termType, ContextUtils.createDefaultContextInfo());
            reviewData.getCourseLogisticsSection().getTerms().add(term.getName());
        }
    } catch (Exception e) {
        throw new RiceIllegalStateException(e);
    }

    if (savedCourseInfo.getDuration() != null
            && StringUtils.isNotBlank(savedCourseInfo.getDuration().getAtpDurationTypeKey())) {
        try {
            TypeInfo type = getTypeService().getType(savedCourseInfo.getDuration().getAtpDurationTypeKey(),
                    ContextUtils.createDefaultContextInfo());
            reviewData.getCourseLogisticsSection().setAtpDurationType(type.getName());
        } catch (Exception e) {
            throw new RiceIllegalStateException(e);
        }
    }

    if (savedCourseInfo.getDuration() != null) {
        reviewData.getCourseLogisticsSection().setTimeQuantity(savedCourseInfo.getDuration().getTimeQuantity());
    }

    reviewData.getCourseLogisticsSection().setAudit(BooleanUtils.toStringYesNo(courseInfoWrapper.isAudit()));
    reviewData.getCourseLogisticsSection()
            .setPassFail(BooleanUtils.toStringYesNo(courseInfoWrapper.isPassFail()));
    reviewData.getCourseLogisticsSection().setGradingOptions(buildGradingOptionsList());
    reviewData.getCourseLogisticsSection().setFinalExamStatus(getFinalExamString());
    reviewData.getCourseLogisticsSection()
            .setFinalExamStatusRationale(courseInfoWrapper.getFinalExamRationale());

    reviewData.getCourseLogisticsSection().getOutcomes().clear();

    for (ResultValuesGroupInfoWrapper rvg : courseInfoWrapper.getCreditOptionWrappers()) {
        if (StringUtils.isNotBlank(rvg.getTypeKey())) {
            String creditOptionType = "";
            String creditOptionValue = rvg.getUiHelper().getResultValue();
            if (StringUtils.equals(rvg.getTypeKey(), LrcServiceConstants.RESULT_VALUES_GROUP_TYPE_KEY_FIXED)) {
                creditOptionType = "Fixed";
                if (StringUtils.contains(rvg.getResultValueRange().getMinValue(), "degree.")) {
                    creditOptionValue = StringUtils.substringAfterLast(rvg.getUiHelper().getResultValue(),
                            "degree.");
                } else {
                    creditOptionValue = rvg.getUiHelper().getResultValue();
                }
            } else if (StringUtils.equals(rvg.getTypeKey(),
                    LrcServiceConstants.RESULT_VALUES_GROUP_TYPE_KEY_MULTIPLE)) {
                creditOptionType = "Multiple";
            } else if (StringUtils.equals(rvg.getTypeKey(),
                    LrcServiceConstants.RESULT_VALUES_GROUP_TYPE_KEY_RANGE)) {
                creditOptionType = "Range";
            }
            reviewData.getCourseLogisticsSection().getOutcomes()
                    .add(new OutcomeReviewSection(creditOptionType, creditOptionValue));
        }
    }

    List<FormatInfoWrapper> formatInfoWrappers = new ArrayList<FormatInfoWrapper>();
    for (FormatInfo formatInfo : savedCourseInfo.getFormats()) {

        List<ActivityInfoWrapper> activityInfoWrapperList = new ArrayList<ActivityInfoWrapper>();
        for (ActivityInfo activityInfo : formatInfo.getActivities()) {

            Integer anticipatedClassSize = activityInfo.getDefaultEnrollmentEstimate();
            String activityType = activityInfo.getTypeKey();

            String contactHours = "";
            String durationCount = "";

            if (activityInfo.getDuration() != null) {
                String durationType = null;
                if (StringUtils.isNotBlank(activityInfo.getDuration().getAtpDurationTypeKey())) {
                    try {
                        TypeInfo duration = getTypeService().getType(
                                activityInfo.getDuration().getAtpDurationTypeKey(), createContextInfo());
                        durationType = duration.getName();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }

                if (activityInfo.getDuration().getTimeQuantity() != null) {
                    durationCount = activityInfo.getDuration().getTimeQuantity().toString();
                }
                if (StringUtils.isNotBlank(durationType)) {
                    durationCount = durationCount + " " + durationType
                            + CurriculumManagementConstants.COLLECTION_ITEM_PLURAL_END;
                }
            }

            if (activityInfo.getContactHours() != null) {

                String contactType = activityInfo.getContactHours().getUnitTypeKey();
                contactType = StringUtils.substringAfterLast(contactType, ".");

                if (activityInfo.getContactHours().getUnitQuantity() != null) {
                    contactHours = activityInfo.getContactHours().getUnitQuantity();
                }
                if (StringUtils.isNotBlank(contactType)) {
                    contactHours = contactHours + " per " + StringUtils.lowerCase(contactType);
                }
            }

            ActivityInfoWrapper activityInfoWrapper = new ActivityInfoWrapper(anticipatedClassSize,
                    activityType, durationCount, contactHours);
            activityInfoWrapperList.add(activityInfoWrapper);
        }
        FormatInfoWrapper formatInfoWrapper = new FormatInfoWrapper(activityInfoWrapperList);
        formatInfoWrappers.add(formatInfoWrapper);
    }
    if (!formatInfoWrappers.isEmpty()) {
        reviewData.getCourseLogisticsSection().setFormatInfoWrappers(formatInfoWrappers);
    }

    /**
     * Active Dates section
     */
    reviewData.getActiveDatesSection()
            .setStartTerm(getTermDesc(courseInfoWrapper.getCourseInfo().getStartTerm()));
    reviewData.getActiveDatesSection().setEndTerm(getTermDesc(courseInfoWrapper.getCourseInfo().getEndTerm()));
    reviewData.getActiveDatesSection()
            .setPilotCourse(BooleanUtils.toStringYesNo(courseInfoWrapper.getCourseInfo().isPilotCourse()));

    /**
     * Financials section
     */
    //        reviewData.getFinancialsSection().setFee();
    //        reviewData.getFinancialsSection().setExpendingOrganization();
    //        reviewData.getFinancialsSection().setRevenueSource();
    if (savedCourseInfo.getFeeJustification() != null) {
        reviewData.getFinancialsSection()
                .setJustificationOfFees(savedCourseInfo.getFeeJustification().getPlain());
    }

    /**
     * Populate 'Proposal' specific model
     */
    if (courseInfoWrapper.isProposalDataUsed()) {
        updateSupportingDocumentsForReviewPages(courseInfoWrapper);
        updateProposalDataForReviewPages(reviewData, shouldRepopulateRemoteData);
    }
}

From source file:org.kuali.student.enrollment.class2.acal.dto.HolidayWrapper.java

public String getIsNonInstructional() {
    if (holidayInfo != null) {
        return StringUtils.capitalize(BooleanUtils.toStringYesNo(!holidayInfo.getIsInstructionalDay()));
    }//w  w w .  j  a v a 2s .  com
    return StringUtils.capitalize(BooleanUtils.toStringYesNo(true));
}