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

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

Introduction

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

Prototype

public static String trimToNull(String str) 

Source Link

Document

Removes control characters (char <= 32) from both ends of this String returning null if the String is empty ("") after the trim or if it is null.

Usage

From source file:mitm.application.djigzo.james.matchers.IsOriginator.java

@Override
public void init() {
    getLogger().info("Initializing matcher: " + getMatcherName());

    pattern = Pattern.compile(StringUtils.defaultString(StringUtils.trimToNull(getCondition())));

    messageOriginatorIdentifier = SystemServices.getMessageOriginatorIdentifier();
}

From source file:ips1ap101.lib.core.app.ConsultaBusqueda.java

/**
 * @return the criterios parametrizados//from www.  j a va 2 s  .  c om
 */
public String getCriteriosConjugados() {
    InterpreteSql interpreteSql = TLC.getInterpreteSql();
    String conjuncion = "";
    String clausula = "";
    String criteria;
    String criterio;
    criteria = StringUtils.trimToNull(criterios);
    if (criteria != null) {
        if (parametros != null && !parametros.isEmpty()) {
            for (String clave : parametros.keySet()) {
                criterio = interpreteSql.getStringDelimitado(parametros.get(clave));
                if (criterio == null) {
                    criteria = criteria.replace(clave, interpreteSql.getNull());
                } else {
                    criteria = criteria.replace(clave, criterio);
                }
            }
        }
        conjuncion += "(" + criteria + ")";
        clausula = " AND ";
    }
    if (filtro != null) {
        criteria = StringUtils.trimToNull(filtro.toString());
        if (criteria != null) {
            conjuncion += clausula + "(" + criteria + ")";
        }
    }
    return interpreteSql.checkClausulaCriterios(conjuncion);
}

From source file:com.bluexml.side.clazz.alfresco.reverse.action.wizard.ReverseFromAlfrescoWizard.java

@Override
public boolean performFinish() {
    try {/*w w w. j  a  v a 2  s . c  o m*/
        AbstractFieldsPage page = (AbstractFieldsPage) getPage(WelcomePage.ID);
        List<IResource> root = (List<IResource>) page.getFieldValue(WelcomePage.Fields.root.toString());
        String output = page.getFieldValueString(WelcomePage.Fields.output.toString());

        String libraryId = page.getFieldValueString(WelcomePage.Fields.library.toString());
        final List<IFile> sideModels = new ArrayList<IFile>();
        if (StringUtils.trimToNull(libraryId) != null) {
            // reverse may use some SIDE models (reversed)

            // import library
            ToolingUtils.importLibrary(libraryId);

            // models can be acceded in current workspace
            IConfigurationElement libFromLabel = ToolingUtils.getModelLibraryForId(libraryId);
            String projectId = libFromLabel.getAttribute(ToolingUtils.MODEL_LIBRARY_PROJECT_ID);
            IFolder iFolder = IFileHelper.getIFolder("/" + projectId + "/data");
            sideModels.addAll(IFileHelper.getAllFiles(iFolder));

        }

        final File sideModelRepo = new File(output);

        List<IFile> allFiles = new ArrayList<IFile>();

        for (IResource entry : root) {
            IResource value = entry;
            if (value.getType() == IResource.FOLDER) {
                try {
                    allFiles.addAll(IFileHelper.getAllFiles((IFolder) value));
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else if (value.getType() == IResource.FILE) {
                allFiles.add((IFile) value);
            }
        }

        // Convert all Founded IFiles to System.io.File, and avoid duplicate entry
        Map<String, File> map = new HashMap<String, File>();
        for (IFile iFile : allFiles) {
            map.put(iFile.toString(), IFileHelper.getFile(iFile));
        }

        final Collection<File> files = map.values();
        RunnableWithProgress myRunnable = new RunnableWithProgress() {

            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                current = STATE.started;
                monitor.beginTask("reversing", -1);
                try {
                    Reverser.executeReverse(files, sideModelRepo, sideModels, true);
                } catch (Exception e) {
                    throw new InvocationTargetException(e, "Error while executing reverse");
                }
                monitor.done();
                current = STATE.finished;

            }
        };

        this.getContainer().run(true, true, myRunnable);

        while (!myRunnable.getState().equals(RunnableWithState.STATE.finished)) {
            wait(1000);
        }
    } catch (Exception e) {
        e.printStackTrace();
        WizardPage currentPage = (WizardPage) getContainer().getCurrentPage();
        currentPage.setErrorMessage(e.getLocalizedMessage());
        return false;
    }
    return true;
}

From source file:com.opengamma.web.portfolio.WebPortfolioResource.java

@PUT
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)//w ww  . j  a  v a  2s.  c o m
public Response putHTML(@FormParam("name") String name, @FormParam("hidden") Boolean isHidden) {
    PortfolioDocument doc = data().getPortfolio();
    if (doc.isLatest() == false) {
        return Response.status(Status.FORBIDDEN).entity(getHTML()).build();
    }

    name = StringUtils.trimToNull(name);
    DocumentVisibility visibility = BooleanUtils.isTrue(isHidden) ? DocumentVisibility.HIDDEN
            : DocumentVisibility.VISIBLE;
    if (name == null) {
        FlexiBean out = createRootData();
        out.put("err_nameMissing", true);
        String html = getFreemarker().build(HTML_DIR + "portfolio-update.ftl", out);
        return Response.ok(html).build();
    }
    URI uri = updatePortfolio(name, visibility, doc);
    return Response.seeOther(uri).build();
}

From source file:com.thistech.spotlink.util.VastParser.java

public List<Ad> parse(VAST vast) {
    List<Ad> ads = new ArrayList<Ad>();

    for (int i = 0; i < vast.getAd().size(); i++) {
        VAST.Ad vastAd = vast.getAd().get(i);
        Ad ad = getAd(ads, i);//from  www .j av  a2s.  com

        if (vastAd.getInLine() != null) {
            if (vastAd.getInLine().getCreatives() != null) {
                TrackingEventsType trackingEvents = null;
                for (VAST.Ad.InLine.Creatives.Creative creative : vastAd.getInLine().getCreatives()
                        .getCreative()) {
                    if (creative.getLinear() != null) {
                        if (creative.getLinear().getMediaFiles() != null) {
                            for (VAST.Ad.InLine.Creatives.Creative.Linear.MediaFiles.MediaFile vastMediaFile : creative
                                    .getLinear().getMediaFiles().getMediaFile()) {
                                ad.getMediaFiles().add(new MediaFile(vastMediaFile));
                            }
                        }
                        trackingEvents = creative.getLinear().getTrackingEvents();
                    }
                }
                for (ImpressionType impression : vastAd.getInLine().getImpression()) {
                    ad.addTrackingEventUrl("impression", impression.getValue());
                }
                if (trackingEvents != null) {
                    for (TrackingEventsType.Tracking tracking : trackingEvents.getTracking()) {
                        ad.addTrackingEventUrl(tracking.getEvent(),
                                StringUtils.trimToNull(tracking.getValue()));
                    }
                }
            }
        }
    }

    return ads;
}

From source file:com.hmsinc.epicenter.webapp.data.QueryService.java

/**
 * @param params//ww  w. ja v  a2  s. c  om
 * @param algorithmName
 * @param analyzerProperties
 * @return
 */
@Transactional(readOnly = true)
@SuppressWarnings("unchecked")
public TimeSeries queryForTimeSeries(final AnalysisParameters analysisParameters, String algorithmName,
        final Properties analyzerProperties) {

    DateTime start = analysisParameters.getStartDate();
    DescriptiveUnivariateAnalyzer algorithmPipeline = null;

    final String algorithm = StringUtils.trimToNull(algorithmName);

    if (algorithm != null) {

        Validate.isTrue(analyzerDiscoveryService.getUnivariateAnalyzers().contains(algorithm),
                "Invalid algorithm");
        algorithmPipeline = analyzerDiscoveryService.getUnivariateAnalyzer(algorithm);

        final Duration trainingPeriod;
        if (analyzerProperties == null) {
            trainingPeriod = algorithmPipeline.getTrainingPeriod();
        } else {
            trainingPeriod = algorithmPipeline.getTrainingPeriod(analyzerProperties);
        }

        Validate.isTrue(trainingPeriod.getLength() < 365,
                "Training window too large [was: " + trainingPeriod.getLength() + "]");

        DateTime offsetStart = trainingPeriod.subtractFrom(start);
        Validate.isTrue(offsetStart.isBefore(analysisParameters.getEndDate()),
                "Start date must be before end date. [start: " + formatDateTime(offsetStart) + " end: "
                        + formatDateTime(analysisParameters.getEndDate()) + "]");
        analysisParameters.setStartDate(offsetStart);
    }

    logger.trace("Generating timeseries for: {}  ", analysisParameters);

    final Class<? extends Geography> aggregateGeographyType = (Class<? extends Geography>) ModelUtils
            .getRealClass(analysisParameters.getContainer());
    final Map<? extends Geography, TimeSeries> tsc = dataQueryService.queryCombined(analysisParameters,
            aggregateGeographyType);

    Validate.notNull(tsc, "Unable to get timeseries data!");

    TimeSeries ret = null;

    if (tsc.containsKey(analysisParameters.getContainer())) {

        ret = tsc.get(analysisParameters.getContainer());

        if (algorithmPipeline != null && algorithmPipeline.getSupportedPeriods().contains(ret.getPeriod())) {

            if (analyzerProperties == null) {
                logger.debug("Processing timeseries using: {}", algorithmPipeline);
                ret = algorithmPipeline.process(ret);
            } else {
                logger.debug("Processing timeseries using: {}  Parameters: {}", algorithmPipeline,
                        analyzerProperties);
                ret = algorithmPipeline.process(ret, analyzerProperties);
            }
        }
    }

    analysisParameters.setStartDate(start);

    logger.trace("TimeSeries: {}", ret);

    return ret;
}

From source file:com.bluexml.side.portal.alfresco.reverse.action.wizard.ReverseFromAlfrescoWizard.java

@Override
public boolean performFinish() {
    try {//from   w w w.  j a v  a  2 s.co m
        AbstractFieldsPage page = (AbstractFieldsPage) getPage(WelcomePage.ID);
        String root = page.getFieldValueString(WelcomePage.Fields.root.toString());
        String output = page.getFieldValueString(WelcomePage.Fields.output.toString());

        String libraryId = page.getFieldValueString(WelcomePage.Fields.library.toString());
        final List<IFile> sideModels = new ArrayList<IFile>();
        if (StringUtils.trimToNull(libraryId) != null) {
            // reverse may use some SIDE models (reversed)

            // import library
            ToolingUtils.importLibrary(libraryId);

            // models can be acceded in current workspace
            IConfigurationElement libFromLabel = ToolingUtils.getModelLibraryForId(libraryId);
            String projectId = libFromLabel.getAttribute(ToolingUtils.MODEL_LIBRARY_PROJECT_ID);
            IFolder iFolder = IFileHelper.getIFolder("/" + projectId + "/data");
            sideModels.addAll(IFileHelper.getAllFiles(iFolder));

        }

        final File sideModelRepo = new File(output);
        final File rootFile = new File(root);
        // Convert all Founded IFiles to System.io.File, and avoid duplicate entry

        RunnableWithProgress myRunnable = new RunnableWithProgress() {

            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                current = STATE.started;
                monitor.beginTask("reversing", -1);
                try {
                    if (rootFile.isFile()) {
                        Portal createPortal = PortalFactory.eINSTANCE.createPortal();
                        LayoutReverser lr = new LayoutReverser(rootFile, createPortal,
                                rootFile.getAbsolutePath());
                        lr.parse();
                        EResourceUtils.saveModel(new File(
                                "/Users/davidabad/workspaces/runtime-New_configuration/Model-library-Alfresco-4.0.d-CE/portal/alfresco.portal"),
                                createPortal);
                    } else {
                        ReversePortal rp = new ReversePortal(rootFile, sideModelRepo);

                        rp.reverse();
                        rp.postChanges();
                        rp.persist();
                    }

                } catch (Exception e) {
                    throw new InvocationTargetException(e, "Error while executing reverse");
                }
                monitor.done();
                current = STATE.finished;
            }
        };

        this.getContainer().run(true, true, myRunnable);

        while (!myRunnable.getState().equals(RunnableWithState.STATE.finished)) {
            wait(1000);
        }
    } catch (Exception e) {
        e.printStackTrace();
        WizardPage currentPage = (WizardPage) getContainer().getCurrentPage();
        currentPage.setErrorMessage(e.getLocalizedMessage());
        return false;
    }
    return true;
}

From source file:adalid.commons.bundles.Bundle.java

private static String getTrimmedToNullString(String key, ResourceBundle rb) {
    try {/*from w  w w .j a  v  a 2s. co  m*/
        String string = rb.getString(key);
        return StringUtils.trimToNull(string);
    } catch (MissingResourceException e) {
        return null;
    }
}

From source file:com.bluexml.side.util.libs.eclipse.pages.PageControlsHelper.java

/**
 * @param composite//  w  w w . jav  a  2s  .c om
 * @param label
 * @param textField
 */
public Text createTextFieldControl(Composite composite, final String label, final String id,
        final Map<String, Object> values) {
    if (!values.containsKey(id)) {
        values.put(id, null);
    }

    Label artifactIdLabel = new Label(composite, SWT.NONE);
    artifactIdLabel.setText(label);

    final Text textField = StylingUtil.getNewText(composite, null, null);
    Object string = values.get(id);
    if (string != null) {
        textField.setText(string.toString());
    }
    textField.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            // records changed value into map values
            values.put(id, StringUtils.trimToNull(textField.getText()));
            page.checkPageComplite();
        }
    });
    return textField;
}

From source file:net.sf.eclipsecs.core.config.ConfigurationWriter.java

/**
 * Writes the modules of the configuration to the output stream.
 *
 * @param out//from w  w  w  . j  a  v a2 s  .  co m
 *            the ouput stream.
 * @param modules
 *            the modules
 * @param checkConfig
 *            the Check configuration object
 * @throws CheckstylePluginException
 *             error writing the checkstyle configuration
 */
public static void write(OutputStream out, List<Module> modules, ICheckConfiguration checkConfig)
        throws CheckstylePluginException {

    try {
        // pass the configured modules through the save filters
        SaveFilters.process(modules);

        Document doc = DocumentHelper.createDocument();
        doc.addDocType(XMLTags.MODULE_TAG, "-//Puppy Crawl//DTD Check Configuration 1.3//EN",
                "http://www.puppycrawl.com/dtds/configuration_1_3.dtd");

        String lineSeperator = System.getProperty("line.separator"); //$NON-NLS-1$

        String comment = lineSeperator
                + "    This configuration file was written by the eclipse-cs plugin configuration editor" //$NON-NLS-1$
                + lineSeperator;
        doc.addComment(comment);

        // write out name and description as comment
        String description = lineSeperator + "    Checkstyle-Configuration: " //$NON-NLS-1$
                + checkConfig.getName() + lineSeperator + "    Description: " //$NON-NLS-1$
                + (StringUtils.trimToNull(checkConfig.getDescription()) != null
                        ? lineSeperator + checkConfig.getDescription() + lineSeperator
                        : "none" + lineSeperator); //$NON-NLS-1$
        doc.addComment(description);

        // find the root module (Checker)
        // the root module is the only module that has no parent
        List<Module> rootModules = getChildModules(null, modules);
        if (rootModules.size() < 1) {
            throw new CheckstylePluginException(Messages.errorNoRootModule);
        }

        if (rootModules.size() > 1) {
            throw new CheckstylePluginException(Messages.errorMoreThanOneRootModule);
        }

        writeModule(rootModules.get(0), doc, null, modules);

        out.write(XMLUtil.toByteArray(doc));
    } catch (IOException e) {
        CheckstylePluginException.rethrow(e);
    }
}