Example usage for org.apache.commons.lang StringUtils defaultString

List of usage examples for org.apache.commons.lang StringUtils defaultString

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils defaultString.

Prototype

public static String defaultString(String str) 

Source Link

Document

Returns either the passed in String, or if the String is null, an empty String ("").

Usage

From source file:com.opengamma.master.position.impl.MasterPositionSource.java

/**
 * Converts a position/trade unique identifier to one unique to the node.
 * /*from www.j  a v a 2 s. c  om*/
 * @param positionOrTradeId  the unique identifier to convert, not null
 * @param nodeId  the node unique identifier, not null
 * @return the combined unique identifier, not null
 */
protected UniqueId convertId(final UniqueId positionOrTradeId, final UniqueId nodeId) {
    return UniqueId.of(nodeId.getScheme() + '-' + positionOrTradeId.getScheme(),
            nodeId.getValue() + '-' + positionOrTradeId.getValue(),
            StringUtils.defaultString(nodeId.getVersion()) + '-'
                    + StringUtils.defaultString(positionOrTradeId.getVersion()));
}

From source file:gtu._work.ui.ObnfInsertCreaterUI.java

private void executeBtnAction() {
    try {// w  w w  . j a  v a  2 s .  co  m
        tableName = StringUtils.trimToEmpty(tableNameText.getText());
        String obnfStr = obnfArea.getText();
        if (StringUtils.isBlank(tableName)) {
            JCommonUtil._jOptionPane_showMessageDialog_error("tableName");
            return;
        }
        if (StringUtils.isBlank(obnfStr)) {
            JCommonUtil._jOptionPane_showMessageDialog_error("obnfStr");
            return;
        }

        Map<String, String> columnMap = new HashMap<String, String>();
        Map<String, String> pkMap = new HashMap<String, String>();

        Pattern objPattern2 = Pattern.compile("(\\w+)\\s*\\=\\s*'([^']*)'");
        Matcher matcher = objPattern2.matcher(obnfStr);
        while (matcher.find()) {
            String dbField = StringUtils.trim(matcher.group(1)).toLowerCase();
            String value = StringUtils.defaultString(matcher.group(2));
            System.out.println("SQL:[" + dbField + "] = [" + value + "]");
            this.addToColumnMap(dbField, value, columnMap, pkMap);
        }

        Pattern objPattern = Pattern.compile("(\\w+)\\=([^\\,\\{\\}\\[\\]]*)");
        matcher = objPattern.matcher(obnfStr);
        while (matcher.find()) {
            String g1 = StringUtils.trim(matcher.group(1));
            if (g1.indexOf("_") != -1) {
                continue;
            }
            String dbField = StringUtils.trim(StringUtilForDb.javaToDbField(g1)).toLowerCase();
            String value = StringUtils.defaultString(matcher.group(2));
            String tmpVal = StringUtils.trimToEmpty(value);
            if (tmpVal.startsWith("'") && tmpVal.endsWith("'")) {
                continue;
            }
            System.out.println("JAVA:[" + dbField + "] = [" + value + "]");
            this.addToColumnMap(dbField, value, columnMap, pkMap);
        }

        this.putToDbFieldList(pkMap, columnMap);
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}

From source file:com.flexive.ejb.beans.workflow.WorkflowEngineBean.java

/**
 * {@inheritDoc}//from   w ww .  jav a2s .c  o  m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long create(Workflow workflow) throws FxApplicationException {
    UserTicket ticket = FxContext.getUserTicket();
    // Permission checks
    FxPermissionUtils.checkRole(ticket, Role.WorkflowManagement);

    // Do work ..
    Connection con = null;
    PreparedStatement stmt = null;
    String sCurSql = null;
    boolean success = false;
    long id = -1;
    try {
        // Sanity checks
        checkIfValid(workflow);

        // Obtain a database connection
        con = Database.getDbConnection();

        // Create the new workflow instance
        sCurSql = "INSERT INTO " + TBL_WORKFLOW + " (ID,NAME,DESCRIPTION) VALUES (?,?,?)";
        stmt = con.prepareStatement(sCurSql);
        id = seq.getId(FxSystemSequencer.WORKFLOW);
        stmt.setLong(1, id);
        stmt.setString(2, workflow.getName());
        stmt.setString(3, StringUtils.defaultString(workflow.getDescription()));
        stmt.executeUpdate();

        // create step(s)
        final Map<Long, Step> createdSteps = new HashMap<Long, Step>();
        for (Step step : workflow.getSteps()) {
            final Step wfstep = new Step(-1, step.getStepDefinitionId(), id, step.getAclId());
            final long newStepId = stepEngine.createStep(wfstep);
            createdSteps.put(step.getId(), new Step(newStepId, wfstep));
        }

        // create route(s)
        for (Route route : workflow.getRoutes()) {
            routeEngine.create(resolveTemporaryStep(createdSteps, route.getFromStepId()),
                    resolveTemporaryStep(createdSteps, route.getToStepId()), route.getGroupId());
        }
        success = true;
    } catch (Exception exc) {
        if (StorageManager.isUniqueConstraintViolation(exc)) {
            throw new FxEntryExistsException("ex.workflow.exists", workflow.getName());
        } else {
            throw new FxCreateException(LOG, "ex.workflow.create", exc, exc.getMessage());
        }
    } finally {
        Database.closeObjects(WorkflowEngineBean.class, con, stmt);
        if (!success) {
            EJBUtils.rollback(ctx);
        } else {
            StructureLoader.reloadWorkflows(FxContext.get().getDivisionId());
        }
    }
    return id;
}

From source file:com.fiveamsolutions.nci.commons.util.HibernateHelper.java

/**
 * @param entity the entity to validate/*from www . ja  va  2s .c om*/
 * @return a map of validation messages keyed by the property path. The keys represent the field/property validation
 *         errors however, when key is null it means the validation is a type/class validation error
 */
public static Map<String, String[]> validate(PersistentObject entity) {
    Map<String, List<String>> messageMap = new HashMap<String, List<String>>();
    ClassValidator<PersistentObject> classValidator = getClassValidator(entity);
    InvalidValue[] validationMessages = classValidator.getInvalidValues(entity);
    for (InvalidValue validationMessage : validationMessages) {
        String path = StringUtils.defaultString(validationMessage.getPropertyPath());
        List<String> m = messageMap.get(path);
        if (m == null) {
            m = new ArrayList<String>();
            messageMap.put(path, m);
        }
        String msg = validationMessage.getMessage();
        msg = msg.replace("(fieldName)", "").trim();
        if (!m.contains(msg)) {
            m.add(msg);
        }
    }

    return convertMapListToMapArray(messageMap);
}

From source file:com.atlassian.plugins.project.ConfigActionSupport.java

/**
 * For a given custom field name, either return the already set value or set
 * it to its initial value and return it. Note that null values mean the
 * name has not yet been set./* w w w . ja  v  a2  s.co  m*/
 * 
 * @param cfName
 *            the custom field name
 * @param customField
 *            the custom field
 * @param defaultVal
 *            the default value
 * @return the custom field name
 */
private String getCFName(String cfName, CustomField customField, String defaultVal) {
    if (cfName == null) {
        cfName = (customField != null ? customField.getName() : defaultVal);
        cfName = StringUtils.defaultString(cfName); // Ensure the value is
        // never set to null
        // (null means
        // uninitialized)
    }
    return cfName;
}

From source file:info.magnolia.module.admininterface.AdminTreeMVCHandler.java

/**
 * Saves a value edited directly inside the tree. This can also be a lable
 * @return name of the view// w  w  w . j a  v a2s  .c o m
 */
public String saveValue() {
    String saveName = this.getRequest().getParameter("saveName"); //$NON-NLS-1$
    Tree tree = getTree();

    // value to save is a node data's value (config admin)
    boolean isNodeDataValue = "true".equals(this.getRequest().getParameter("isNodeDataValue")); //$NON-NLS-1$ //$NON-NLS-2$

    // value to save is a node data's type (config admin)
    boolean isNodeDataType = "true".equals(this.getRequest().getParameter("isNodeDataType")); //$NON-NLS-1$ //$NON-NLS-2$

    String value = StringUtils.defaultString(this.getRequest().getParameter("saveValue")); //$NON-NLS-1$
    displayValue = StringUtils.EMPTY;
    // value to save is a content's meta information
    boolean isMeta = "true".equals(this.getRequest().getParameter("isMeta")); //$NON-NLS-1$ //$NON-NLS-2$
    // value to save is a label (name of page, content node or node data)
    boolean isLabel = "true".equals(this.getRequest().getParameter("isLabel")); //$NON-NLS-1$ //$NON-NLS-2$

    if (isNodeDataValue || isNodeDataType) {
        tree.setPath(StringUtils.substringBeforeLast(path, "/")); //$NON-NLS-1$
        saveName = StringUtils.substringAfterLast(path, "/"); //$NON-NLS-1$
    } else {
        // "/modules/templating/Templates/x"
        tree.setPath(path);
    }

    if (isLabel) {
        displayValue = rename(value);
    } else if (isNodeDataType) {
        int type = Integer.valueOf(value).intValue();
        synchronized (ExclusiveWrite.getInstance()) {
            displayValue = tree.saveNodeDataType(saveName, type);
        }
    } else {
        synchronized (ExclusiveWrite.getInstance()) {
            displayValue = tree.saveNodeData(saveName, value, isMeta);
        }
    }

    // if there was a displayValue passed show it instead of the written value
    displayValue = StringUtils.defaultString(this.getRequest().getParameter("displayValue"), value); //$NON-NLS-1$

    // @todo should be handled in a better way but, at the moment, this is better than nothing
    if (path.startsWith("/subscribers/")) { //$NON-NLS-1$
        Subscriber.reload();
    } else if (path.startsWith("/server/MIMEMapping")) { //$NON-NLS-1$
        MIMEMapping.reload();
    }

    return VIEW_VALUE;
}

From source file:mitm.common.pdf.MessagePDFBuilder.java

public void buildPDF(MimeMessage message, String replyURL, OutputStream pdfStream)
        throws DocumentException, MessagingException, IOException {
    Document document = createDocument();

    PdfWriter pdfWriter = createPdfWriter(document, pdfStream);

    document.open();/*from w  w w  .j  a va2  s.  co m*/

    String[] froms = null;

    try {
        froms = EmailAddressUtils.addressesToStrings(message.getFrom(), true /* mime decode */);
    } catch (MessagingException e) {
        logger.warn("From address is not a valid email address.");
    }

    if (froms != null) {
        for (String from : froms) {
            document.addAuthor(from);
        }
    }

    String subject = null;

    try {
        subject = message.getSubject();
    } catch (MessagingException e) {
        logger.error("Error getting subject.", e);
    }

    if (subject != null) {
        document.addSubject(subject);
        document.addTitle(subject);
    }

    String[] tos = null;

    try {
        tos = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.TO),
                true /* mime decode */);
    } catch (MessagingException e) {
        logger.warn("To is not a valid email address.");
    }

    String[] ccs = null;

    try {
        ccs = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.CC),
                true /* mime decode */);
    } catch (MessagingException e) {
        logger.warn("CC is not a valid email address.");
    }

    Date sentDate = null;

    try {
        sentDate = message.getSentDate();
    } catch (MessagingException e) {
        logger.error("Error getting sent date.", e);
    }

    Collection<Part> attachments = new LinkedList<Part>();

    String body = BodyPartUtils.getPlainBodyAndAttachments(message, attachments);

    attachments = preprocessAttachments(attachments);

    if (body == null) {
        body = MISSING_BODY;
    }

    /*
     * PDF does not have tab support so we convert tabs to spaces
     */
    body = StringReplaceUtils.replaceTabsWithSpaces(body, tabWidth);

    PdfPTable headerTable = new PdfPTable(2);

    headerTable.setHorizontalAlignment(Element.ALIGN_LEFT);
    headerTable.setWidthPercentage(100);
    headerTable.setWidths(new int[] { 1, 6 });
    headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);

    Font headerFont = createHeaderFont();

    FontSelector headerFontSelector = createHeaderFontSelector();

    PdfPCell cell = new PdfPCell(new Paragraph("From:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);

    String decodedFroms = StringUtils.defaultString(StringUtils.join(froms, ", "));

    headerTable.addCell(headerFontSelector.process(decodedFroms));

    cell = new PdfPCell(new Paragraph("To:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(tos, ", "))));

    cell = new PdfPCell(new Paragraph("CC:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(ccs, ", "))));

    cell = new PdfPCell(new Paragraph("Subject:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(subject)));

    cell = new PdfPCell(new Paragraph("Date:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(ObjectUtils.toString(sentDate));

    cell = new PdfPCell(new Paragraph("Attachments:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable
            .addCell(headerFontSelector.process(StringUtils.defaultString(getAttachmentHeader(attachments))));

    document.add(headerTable);

    if (replyURL != null) {
        addReplyLink(document, replyURL);
    }

    /*
     * Body table will contain the body of the message
     */
    PdfPTable bodyTable = new PdfPTable(1);
    bodyTable.setWidthPercentage(100f);

    bodyTable.setSplitLate(false);

    bodyTable.setSpacingBefore(15f);
    bodyTable.setHorizontalAlignment(Element.ALIGN_LEFT);

    addBodyAndAttachments(pdfWriter, document, bodyTable, body, attachments);

    Phrase footer = new Phrase(FOOTER_TEXT);

    PdfContentByte cb = pdfWriter.getDirectContent();

    ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, footer, document.right(), document.bottom(), 0);

    document.close();
}

From source file:hudson.cli.CLI.java

public static int _main(String[] _args) throws Exception {
    List<String> args = Arrays.asList(_args);
    PrivateKeyProvider provider = new PrivateKeyProvider();
    boolean sshAuthRequestedExplicitly = false;
    String httpProxy = null;//from   www . j  av a2s.  com

    String url = System.getenv("JENKINS_URL");

    if (url == null)
        url = System.getenv("HUDSON_URL");

    boolean tryLoadPKey = true;

    Mode mode = null;

    String user = null;
    String auth = null;

    String userIdEnv = System.getenv("JENKINS_USER_ID");
    String tokenEnv = System.getenv("JENKINS_API_TOKEN");

    boolean strictHostKey = false;

    while (!args.isEmpty()) {
        String head = args.get(0);
        if (head.equals("-version")) {
            System.out.println("Version: " + computeVersion());
            return 0;
        }
        if (head.equals("-http")) {
            if (mode != null) {
                printUsage("-http clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.HTTP;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-ssh")) {
            if (mode != null) {
                printUsage("-ssh clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.SSH;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-remoting")) {
            if (mode != null) {
                printUsage("-remoting clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.REMOTING;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-s") && args.size() >= 2) {
            url = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-noCertificateCheck")) {
            LOGGER.info("Skipping HTTPS certificate checks altogether. Note that this is not secure at all.");
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
            // bypass host name check, too.
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-noKeyAuth")) {
            tryLoadPKey = false;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-i") && args.size() >= 2) {
            File f = new File(args.get(1));
            if (!f.exists()) {
                printUsage(Messages.CLI_NoSuchFileExists(f));
                return -1;
            }

            provider.readFrom(f);

            args = args.subList(2, args.size());
            sshAuthRequestedExplicitly = true;
            continue;
        }
        if (head.equals("-strictHostKey")) {
            strictHostKey = true;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-user") && args.size() >= 2) {
            user = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-auth") && args.size() >= 2) {
            auth = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-p") && args.size() >= 2) {
            httpProxy = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-logger") && args.size() >= 2) {
            Level level = parse(args.get(1));
            for (Handler h : Logger.getLogger("").getHandlers()) {
                h.setLevel(level);
            }
            for (Logger logger : new Logger[] { LOGGER, FullDuplexHttpStream.LOGGER, PlainCLIProtocol.LOGGER,
                    Logger.getLogger("org.apache.sshd") }) { // perhaps also Channel
                logger.setLevel(level);
            }
            args = args.subList(2, args.size());
            continue;
        }
        break;
    }

    if (url == null) {
        printUsage(Messages.CLI_NoURL());
        return -1;
    }

    if (auth == null) {
        // -auth option not set
        if (StringUtils.isNotBlank(userIdEnv) && StringUtils.isNotBlank(tokenEnv)) {
            auth = StringUtils.defaultString(userIdEnv).concat(":").concat(StringUtils.defaultString(tokenEnv));
        } else if (StringUtils.isNotBlank(userIdEnv) || StringUtils.isNotBlank(tokenEnv)) {
            printUsage(Messages.CLI_BadAuth());
            return -1;
        } // Otherwise, none credentials were set

    }

    if (!url.endsWith("/")) {
        url += '/';
    }

    if (args.isEmpty())
        args = Arrays.asList("help"); // default to help

    if (tryLoadPKey && !provider.hasKeys())
        provider.readFromDefaultLocations();

    if (mode == null) {
        mode = Mode.HTTP;
    }

    LOGGER.log(FINE, "using connection mode {0}", mode);

    if (user != null && auth != null) {
        LOGGER.warning("-user and -auth are mutually exclusive");
    }

    if (mode == Mode.SSH) {
        if (user == null) {
            // TODO SshCliAuthenticator already autodetects the user based on public key; why cannot AsynchronousCommand.getCurrentUser do the same?
            LOGGER.warning("-user required when using -ssh");
            return -1;
        }
        return SSHCLI.sshConnection(url, user, args, provider, strictHostKey);
    }

    if (strictHostKey) {
        LOGGER.warning("-strictHostKey meaningful only with -ssh");
    }

    if (user != null) {
        LOGGER.warning("Warning: -user ignored unless using -ssh");
    }

    CLIConnectionFactory factory = new CLIConnectionFactory().url(url).httpsProxyTunnel(httpProxy);
    String userInfo = new URL(url).getUserInfo();
    if (userInfo != null) {
        factory = factory.basicAuth(userInfo);
    } else if (auth != null) {
        factory = factory.basicAuth(
                auth.startsWith("@") ? FileUtils.readFileToString(new File(auth.substring(1))).trim() : auth);
    }

    if (mode == Mode.HTTP) {
        return plainHttpConnection(url, args, factory);
    }

    CLI cli = factory.connect();
    try {
        if (provider.hasKeys()) {
            try {
                // TODO: server verification
                cli.authenticate(provider.getKeys());
            } catch (IllegalStateException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.warning("The server doesn't support public key authentication");
                    return -1;
                }
            } catch (UnsupportedOperationException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.warning("The server doesn't support public key authentication");
                    return -1;
                }
            } catch (GeneralSecurityException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.log(WARNING, null, e);
                    return -1;
                }
                LOGGER.warning("Failed to authenticate with your SSH keys. Proceeding as anonymous");
                LOGGER.log(FINE, null, e);
            }
        }

        // execute the command
        // Arrays.asList is not serializable --- see 6835580
        args = new ArrayList<String>(args);
        return cli.execute(args, System.in, System.out, System.err);
    } finally {
        cli.close();
    }
}

From source file:com.doculibre.constellio.feedprotocol.FeedProcessor.java

private ContentParse asContentParse(String url, List<FeedContent> feedContents,
        ConnectorInstance connectorInstance) {
    ConnectorInstanceServices connectorInstanceServices = ConstellioSpringUtils.getConnectorInstanceServices();
    ContentParse contentParse = new ContentParse();
    List<RecordMeta> metas = new ArrayList<RecordMeta>();
    contentParse.setMetas(metas);//  ww  w.j  a  va 2  s  . co  m

    List<String> md5s = new ArrayList<String>();
    StringBuffer contentBuffer = new StringBuffer();
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e1) {
        throw new RuntimeException(e1);
    }
    for (FeedContent feedContent : feedContents) {
        InputStream input = null;
        try {
            Metadata metadata = new Metadata();
            ContentHandler handler = new BodyContentHandler(-1);
            ParseContext parseContext = new ParseContext();

            if (feedContent.getEncoding() == FeedContent.ENCODING.BASE64BINARY) {
                input = new BufferedInputStream(new Base64InputStream(
                        new FileInputStream(feedContent.getValue()), false, 80, new byte[] { (byte) '\n' }));
            } else {
                input = new BufferedInputStream(new FileInputStream(feedContent.getValue()));
            }
            // MD5 on the fly
            DigestInputStream dis = new DigestInputStream(input, md);

            if (connectorInstance.getConnectorType().getName().equals("mailbox-connector")) {
                // FIXME : a supprimer et ajouter un Detector qui detecte
                // correctement les fichiers eml
                // CompositeParser parser = new AutoDetectParser();
                // Map<String, Parser> parsers = parser.getParsers();
                // parsers.put("text/plain", new
                // EmlParser());//message/rfc822
                // parser.setParsers(parsers);
                // Autre pb avec detection des fichiers eml
                Parser parser = new EmlParser();
                parser.parse(dis, handler, metadata, parseContext);
            } else {
                // IOUtils.copy(input, new FileOutputStream(new
                // File("C:/tmp/test.pdf")));
                PARSER.parse(dis, handler, metadata, parseContext);
            }

            md5s.add(Base64.encodeBase64String(md.digest()));

            for (String name : metadata.names()) {
                for (String content : metadata.getValues(name)) {
                    if (!"null".equals(content)) {
                        RecordMeta meta = new RecordMeta();
                        ConnectorInstanceMeta connectorInstanceMeta = connectorInstance.getOrCreateMeta(name);
                        if (connectorInstanceMeta.getId() == null) {
                            connectorInstanceServices.makePersistent(connectorInstance);
                        }
                        meta.setConnectorInstanceMeta(connectorInstanceMeta);
                        meta.setContent(content);
                        metas.add(meta);
                    }
                }
            }

            String contentString = handler.toString();
            // remove the duplication of white space, Bin
            contentBuffer.append(contentString.replaceAll("(\\s){2,}", "$1"));
        } catch (Throwable e) {
            LOG.warning("Could not parse document " + StringUtils.defaultString(url) + " for connector : "
                    + connectorInstance.getName() + " Message: " + e.getMessage());
        } finally {
            IOUtils.closeQuietly(input);
            if (feedContent != null) {
                FileUtils.deleteQuietly(feedContent.getValue());
            }
        }
    }
    contentParse.setContent(contentBuffer.toString());
    contentParse.setMd5(md5s);

    return contentParse;
}

From source file:com.redhat.rhn.frontend.taglibs.list.ListTagUtil.java

/**
 * Renders the filter UI//from  w ww . j  av a  2 s .c o  m
 * @param pageContext caller's page context
 * @param filter ListFilter instance
 * @param uniqueName name of the list
 * @param width width of the list
 * @param columnCount list's column count
 * @param searchParent true if list tag allows searching of parent
 * @param searchChild true if the list tag allows searching of child
 * @throws JspException if something bad happens writing to the page
 */
public static void renderFilterUI(PageContext pageContext, ListFilter filter, String uniqueName, String width,
        int columnCount, boolean searchParent, boolean searchChild) throws JspException {
    LocalizationService ls = LocalizationService.getInstance();
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    String filterByKey = makeFilterByLabel(uniqueName);
    String filterBy = request.getParameter(filterByKey);
    String filterValueKey = makeFilterValueByLabel(uniqueName);
    String filterName = makeFilterNameByLabel(uniqueName);
    String filterValue = ListTagHelper.getFilterValue(pageContext.getRequest(), uniqueName);

    //We set this so we know next time around what the old filter value was
    ListTagUtil.write(pageContext, String.format(HIDDEN_TEXT, makeOldFilterValueByLabel(uniqueName),
            StringEscapeUtils.escapeHtml(filterValue)));

    List fields = filter.getFieldNames();
    if (fields == null || fields.size() == 0) {
        throw new JspException("ListFilter.getFieldNames() returned no field names");
    } else if (fields.size() == 1) {
        ListTagUtil.write(pageContext, "<input type=\"hidden\" name=\"");
        ListTagUtil.write(pageContext, filterByKey);
        ListTagUtil.write(pageContext, "\" value=\"");
        ListTagUtil.write(pageContext, fields.get(0).toString());
        ListTagUtil.write(pageContext, "\" />");
    } else {
        ListTagUtil.write(pageContext, ls.getMessage("message.filterby.multiple"));
        ListTagUtil.write(pageContext, "<select name=\"");
        ListTagUtil.write(pageContext, filterByKey);
        ListTagUtil.write(pageContext, "\">");
        for (Iterator iter = fields.iterator(); iter.hasNext();) {
            String field = (String) iter.next();
            ListTagUtil.write(pageContext, "<option value=\"");
            ListTagUtil.write(pageContext, field);
            ListTagUtil.write(pageContext, "\" ");
            if (field.equals(filterBy)) {
                ListTagUtil.write(pageContext, "selected");
            }
            ListTagUtil.write(pageContext, ">");
            ListTagUtil.write(pageContext, field);
            ListTagUtil.write(pageContext, "</option>");
        }
        ListTagUtil.write(pageContext, "</select>");
    }

    filterValue = StringUtil.nullOrValue(filterValue);
    StringBuilder sb = new StringBuilder();

    // create a new row
    sb.append("<div class=\"input-group input-group-sm\">");

    String placeHolder = StringUtils.defaultString(ls.getMessage("message.filterby", fields.get(0).toString()));
    sb.append(String.format(
            "<input autofocus=\"autofocus\" type=\"text\" "
                    + " name=\"%s\" value=\"%s\" class=\"form-control\" placeholder=\"%s\"/>",
            filterValueKey, (filterValue != null ? StringEscapeUtils.escapeHtml(filterValue) : ""),
            StringEscapeUtils.escapeHtml(placeHolder)));
    sb.append("<span class=\"input-group-btn\">");
    sb.append(String.format(
            "<button value=\"%s\" type=\"submit\" name=\"%s\" "
                    + " class=\"btn btn-default spacewalk-button-filter\"><i class=\"fa fa-eye\"></i>",
            ls.getMessage(RequestContext.FILTER_KEY), filterName));
    sb.append("</button>");
    sb.append("</span>");

    sb.append("</div>");

    ListTagUtil.write(pageContext, sb.toString());

}