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:mitm.djigzo.web.pages.GlobalPreferences.java

protected void onValidateForm() throws WebServiceCheckedException, HierarchicalPropertiesException {
    /*// w w w  .j  a v a  2 s .  c o  m
     * The server secret is mandatory
     */
    if (StringUtils.isBlank(getGlobalPreferences().getProperties().getServerSecret().getUserValue())) {
        form.recordError(globalPropertiesEdit.getServerSecret().getField(), "Server secret must be set");
    }

    /*
     * Test whether securityInfoSignedByValidTag is a valid format string
     */
    try {
        String.format(StringUtils.defaultString(
                getGlobalPreferences().getProperties().getSecurityInfoSignedByValidTag().getUserValue()),
                "test@example.com");
    } catch (IllegalFormatException e) {
        form.recordError(securityInfoSignedByValidTag.getField(),
                "Signed by tag does not contain " + "a valid format string.");
    }

    /*
     * If set, test whether subject filter is a valid filter. The format should be /REG-EX/ replace
     */
    if (StringUtils.isNotEmpty(getGlobalPreferences().getProperties().getSubjectFilterRegEx().getUserValue())) {
        String[] filter = RegExprUtils
                .splitRegExp(getGlobalPreferences().getProperties().getSubjectFilterRegEx().getUserValue());

        if (filter != null) {
            /*
             * Should be a valid regular expression
             */
            try {
                Pattern.compile(filter[0]);
            } catch (PatternSyntaxException e) {
                form.recordError(subjectFilter.getField(),
                        "Subject filter regular expression is not a valid " + "regular expression");
            }
        } else {
            form.recordError(subjectFilter.getField(), "Subject filter is not a valid filter");
        }
    }
}

From source file:fr.paris.lutece.plugins.genericattributes.service.entrytype.AbstractEntryTypeArray.java

/**
 * {@inheritDoc}/*from w ww  .ja va 2  s . co  m*/
 */
@Override
public String getRequestData(Entry entry, HttpServletRequest request, Locale locale) {
    String strCode = request.getParameter(PARAMETER_ENTRY_CODE);
    String strTitle = request.getParameter(PARAMETER_TITLE);
    String strComment = request.getParameter(PARAMETER_COMMENT);
    String strNumberRows = request.getParameter(PARAMETER_NUMBER_ROWS);
    String strNumberColumns = request.getParameter(PARAMETER_NUMBER_COLUMNS);
    String strFieldError = StringUtils.EMPTY;

    if (StringUtils.isBlank(strTitle)) {
        strFieldError = FIELD_TITLE;
    } else if (StringUtils.isBlank(strNumberRows)) {
        strFieldError = FIELD_NUMBER_ROWS;
    } else if (StringUtils.isBlank(strNumberColumns)) {
        strFieldError = FIELD_NUMBER_COLUMNS;
    }

    if (StringUtils.isNotBlank(strFieldError)) {
        Object[] tabRequiredFields = { I18nService.getLocalizedString(strFieldError, locale) };

        return AdminMessageService.getMessageUrl(request, MESSAGE_MANDATORY_FIELD, tabRequiredFields,
                AdminMessage.TYPE_STOP);
    } else if (!isValid(strNumberRows)) {
        Object[] tabRequiredFields = { I18nService.getLocalizedString(FIELD_NUMBER_ROWS, locale) };

        return AdminMessageService.getMessageUrl(request, MESSAGE_NUMERIC_FIELD, tabRequiredFields,
                AdminMessage.TYPE_STOP);
    } else if (!isValid(strNumberColumns)) {
        Object[] tabRequiredFields = { I18nService.getLocalizedString(FIELD_NUMBER_COLUMNS, locale) };

        return AdminMessageService.getMessageUrl(request, MESSAGE_NUMERIC_FIELD, tabRequiredFields,
                AdminMessage.TYPE_STOP);
    }

    // for don't update fields listFields=null
    int row = Integer.valueOf(strNumberRows);
    int column = Integer.valueOf(strNumberColumns);
    entry.setCode(strCode);
    entry.setTitle(strTitle);
    entry.setHelpMessage(null);
    entry.setComment(strComment);
    entry.setCSSClass(null);
    entry.setMapProvider(null);
    entry.setNumberColumn(column);
    entry.setNumberRow(row);

    ArrayList<Field> listFields = new ArrayList<Field>();
    List<Field> fields = FieldHome.getFieldListByIdEntry(entry.getIdEntry());

    for (int i = 1; i <= (row + 1); i++) {
        for (int j = 1; j <= (column + 1); j++) {
            Field existingFields = null;

            for (Field f : fields) {
                if (f.getValue().equals(i + "_" + j)) {
                    existingFields = f;

                    break;
                }
            }

            String strTitleRow = request.getParameter("field_" + i + "_" + j);

            if ((i == 1) && (j != 1)) {
                Field field = new Field();

                if (existingFields != null) {
                    field = existingFields;
                }

                field.setParentEntry(entry);
                field.setValue(i + "_" + j);
                field.setTitle(StringUtils.defaultString(strTitleRow));
                listFields.add(field);
            } else if ((i != 1) && (j == 1)) {
                Field field = new Field();

                if (existingFields != null) {
                    field = existingFields;
                }

                field.setParentEntry(entry);
                field.setValue(i + "_" + j);
                field.setTitle(StringUtils.defaultString(strTitleRow));
                listFields.add(field);
            } else {
                Field field = new Field();
                field.setParentEntry(entry);
                field.setValue(i + "_" + j);
                listFields.add(field);
            }
        }
    }

    entry.setFields(listFields);

    return null;
}

From source file:dk.dma.msinm.user.security.SecurityConf.java

/**
 * Returns the list of configured resource endpoints that matches the request
 * @param request the request/*from  w w w.ja v a 2s. c  o m*/
 * @return the list of configured resource endpoints that matches the request
 */
private List<CheckedResource> getMatchingResources(HttpServletRequest request) {
    String uri = request.getServletPath() + StringUtils.defaultString(request.getPathInfo());
    return checkedResources.stream().filter(r -> r.pattern.matcher(uri).matches()).collect(Collectors.toList());
}

From source file:de.thischwa.pmcms.gui.dialog.pojo.DialogFieldsImageComp.java

private void createCompositeFields() {
    Composite composite = new Composite(this, SWT.NONE);
    GridLayout gridLayoutMy = new GridLayout();
    gridLayoutMy.numColumns = 2;/*  www  . ja v a 2 s.co  m*/
    gridLayoutMy.marginWidth = 10;
    gridLayoutMy.verticalSpacing = 5;
    gridLayoutMy.horizontalSpacing = 20;
    gridLayoutMy.marginHeight = 25;
    gridLayoutMy.makeColumnsEqualWidth = false;
    GridData gridDataMy = new org.eclipse.swt.layout.GridData();
    gridDataMy.grabExcessHorizontalSpace = false;
    gridDataMy.verticalAlignment = org.eclipse.swt.layout.GridData.CENTER;
    gridDataMy.horizontalSpan = 1;
    gridDataMy.horizontalAlignment = org.eclipse.swt.layout.GridData.END;
    composite.setLayout(gridLayoutMy);
    composite.setLayoutData(gridDataMy);

    GridData gridDataLabel = new GridData();
    gridDataLabel.widthHint = 100;
    gridDataLabel.verticalAlignment = org.eclipse.swt.layout.GridData.CENTER;
    gridDataLabel.horizontalAlignment = org.eclipse.swt.layout.GridData.END;
    GridData gridDataText = new GridData();
    gridDataText.heightHint = -1;
    gridDataText.widthHint = 150;

    Label labelTitle = new Label(composite, SWT.RIGHT);
    labelTitle.setText(LabelHolder.get("dialog.pojo.image.fields.title")); //$NON-NLS-1$
    labelTitle.setLayoutData(gridDataLabel);
    textTitle = new Text(composite, SWT.BORDER);
    textTitle.setTextLimit(256);
    textTitle.setLayoutData(gridDataText);
    textTitle.setText(StringUtils.defaultString(image.getTitle()));
    textTitle.addModifyListener(new ModifyListenerClearErrorMessages(dialogCreator));

    Label labelDescription = new Label(composite, SWT.RIGHT);
    labelDescription.setText(LabelHolder.get("dialog.pojo.image.fields.description")); //$NON-NLS-1$
    labelDescription.setLayoutData(gridDataLabel);
    textDescription = new Text(composite, SWT.BORDER);
    textDescription.setTextLimit(256);
    textDescription.setLayoutData(gridDataText);
    textDescription.setText(StringUtils.defaultString(image.getDescription()));
    textDescription.addModifyListener(new ModifyListenerClearErrorMessages(dialogCreator));

    GridData gridDataCompositeFile = new org.eclipse.swt.layout.GridData();
    gridDataCompositeFile.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
    gridDataCompositeFile.grabExcessHorizontalSpace = true;
    gridDataCompositeFile.verticalAlignment = org.eclipse.swt.layout.GridData.CENTER;

    Label labelFilename = new Label(composite, SWT.RIGHT);
    labelFilename.setText("*  ".concat(LabelHolder.get("dialog.pojo.image.fields.file"))); //$NON-NLS-1$
    labelFilename.setLayoutData(gridDataLabel);
    Composite compositeFile = new Composite(composite, SWT.NONE);
    GridLayout gridLayoutCompositeFile = new GridLayout();
    gridLayoutCompositeFile.makeColumnsEqualWidth = false;
    gridLayoutCompositeFile.horizontalSpacing = 6;
    gridLayoutCompositeFile.marginHeight = 0;
    gridLayoutCompositeFile.marginWidth = 0;
    gridLayoutCompositeFile.numColumns = 2;
    compositeFile.setLayout(gridLayoutCompositeFile);
    compositeFile.setLayoutData(gridDataCompositeFile);
    GridData gridDataTextFile = new GridData();
    gridDataTextFile.widthHint = 120;
    textFilename = new Text(compositeFile, SWT.BORDER);
    textFilename.setLayoutData(gridDataTextFile);
    textFilename.setEditable(false);
    textFilename.setText(StringUtils.defaultString(image.getFileName()));

    Button button = new Button(compositeFile, SWT.NONE);
    button.setText("..."); //$NON-NLS-1$
    button.addSelectionListener(new SelectionListener() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            FileDialog fileDialog = new FileDialog(e.display.getActiveShell(), SWT.OPEN);
            fileDialog.setText(LabelHolder.get("dialog.pojo.image.fields.image")); //$NON-NLS-1$
            List<String> exts = new ArrayList<String>();
            for (String extension : InitializationManager.getAllowedImageExtensions()) {
                exts.add("*.".concat(extension)); //$NON-NLS-1$
            }
            exts.add(0, StringUtils.join(exts.iterator(), ';'));
            fileDialog.setFilterExtensions(exts.toArray(new String[exts.size()]));
            fileDialog.setFilterPath(PoPathInfo.getSiteGalleryDirectory(image.getParent()).getAbsolutePath());
            String chosenImageFilename = fileDialog.open();
            if (StringUtils.isNotBlank(chosenImageFilename)) {
                chosenImageFile = new File(chosenImageFilename);
                previewCanvas.preview(chosenImageFile);
                if (StringUtils.isNotBlank(chosenImageFilename)) {
                    String tempName = FilenameUtils.getName(chosenImageFilename);
                    textFilename.setText(tempName);
                } else
                    previewCanvas.preview();
            } else {
                chosenImageFile = null;
            }
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }
    });
}

From source file:dk.dma.msiproxy.common.provider.AbstractProviderService.java

/**
 * Computes an ETag token for the given message list
 * @param format the format to return the messages in
 * @param filter the message filter//from  w w  w.  ja  v  a 2 s . co m
 * @param messages the list of messages to compute an ETag token for
 * @return an ETag token for the given message list
 */
public String getETagToken(String format, MessageFilter filter, List<Message> messages) {
    return DigestUtils.md5Hex(String.format("%s_%s_%s", StringUtils.defaultString(format), messages.stream()
            .map(msg -> msg.getId().toString() + msg.getUpdated().getTime()).collect(Collectors.joining()),
            getCacheKey(filter)));
}

From source file:com.predic8.membrane.core.interceptor.oauth2.OAuth2ResourceInterceptor.java

private void showPage(Exchange exc, String state, Object... params) throws Exception {
    String target = StringUtils
            .defaultString(URLParamUtil.getParams(router.getUriFactory(), exc).get("target"));

    exc.getDestinations().set(0, "/index.html");
    wsi.handleRequest(exc);/* www. j av a 2s  .  co m*/

    Engine engine = new Engine();
    engine.setErrorHandler(new ErrorHandler() {

        @Override
        public void error(String arg0, Token arg1, Map<String, Object> arg2) throws ParseException {
            log.error(arg0);
        }

        @Override
        public void error(String arg0, Token arg1) throws ParseException {
            log.error(arg0);
        }
    });
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("loginPath", StringEscapeUtils.escapeXml(loginPath));
    String pathQuery = router.getUriFactory().create(exc.getDestinations().get(0)).getPath(); // TODO: path or pathQuery
    String url = authorizationService.getLoginURL(state, publicURL, pathQuery);
    model.put("loginURL", url);
    model.put("target", StringEscapeUtils.escapeXml(target));
    for (int i = 0; i < params.length; i += 2)
        model.put((String) params[i], params[i + 1]);

    exc.getResponse().setBodyContent(
            engine.transform(exc.getResponse().getBody().toString(), model).getBytes(Constants.UTF_8_CHARSET));
}

From source file:com.redhat.rhn.frontend.xmlrpc.system.crash.CrashHandler.java

/**
 * Returns list of software crashes for a system.
 * @param loggedInUser The current user//from w w w. ja va2s .co m
 * @param serverId Server ID
 * @return Returns list of software crashes for given system id.
 *
 * @xmlrpc.doc Return list of software crashes for a system.
 * @xmlrpc.param #param("string", "sessionKey")
 * @xmlrpc.param #param("int", "serverId")
 * @xmlrpc.returntype
 *     #array()
 *         #struct("crash")
 *             #prop("int", "id")
 *             #prop("string", "crash")
 *             #prop("string", "path")
 *             #prop("int", "count")
 *             #prop("string", "uuid")
 *             #prop("string", "analyzer")
 *             #prop("string", "architecture")
 *             #prop("string", "cmdline")
 *             #prop("string", "component")
 *             #prop("string", "executable")
 *             #prop("string", "kernel")
 *             #prop("string", "reason")
 *             #prop("string", "username")
 *             #prop("date", "created")
 *             #prop("date", "modified")
 *         #struct_end()
 *     #array_end()
 */
public List listSystemCrashes(User loggedInUser, Integer serverId) {
    XmlRpcSystemHelper sysHelper = XmlRpcSystemHelper.getInstance();
    Server server = sysHelper.lookupServer(loggedInUser, serverId);

    List returnList = new ArrayList();

    for (Crash crash : server.getCrashes()) {
        Map crashMap = new HashMap();
        crashMap.put("id", crash.getId());
        crashMap.put("crash", crash.getCrash());
        crashMap.put("path", crash.getPath());
        crashMap.put("count", crash.getCount());
        crashMap.put("uuid", StringUtils.defaultString(crash.getUuid()));
        crashMap.put("analyzer", StringUtils.defaultString(crash.getAnalyzer()));
        crashMap.put("architecture", StringUtils.defaultString(crash.getArchitecture()));
        crashMap.put("cmdline", StringUtils.defaultString(crash.getCmdline()));
        crashMap.put("component", StringUtils.defaultString(crash.getComponent()));
        crashMap.put("executable", StringUtils.defaultString(crash.getExecutable()));
        crashMap.put("kernel", StringUtils.defaultString(crash.getKernel()));
        crashMap.put("reason", StringUtils.defaultString(crash.getReason()));
        crashMap.put("username", StringUtils.defaultString(crash.getUsername()));
        crashMap.put("created", crash.getCreated());
        crashMap.put("modified", crash.getModified());

        if (crash.getPackageNameId() != null) {
            PackageName pname = PackageFactory.lookupPackageName(crash.getPackageNameId());
            crashMap.put("package_name", pname.getName());
        }

        if (crash.getPackageEvrId() != null) {
            PackageEvr pevr = PackageEvrFactory.lookupPackageEvrById(crash.getPackageEvrId());
            crashMap.put("package_epoch", pevr.getEpoch());
            crashMap.put("package_version", pevr.getVersion());
            crashMap.put("package_release", pevr.getRelease());
        }

        if (crash.getPackageArchId() != null) {
            PackageArch parch = PackageFactory.lookupPackageArchById(crash.getPackageArchId());
            crashMap.put("package_arch", parch.getLabel());
        }

        returnList.add(crashMap);
    }

    return returnList;
}

From source file:dk.dma.epd.common.prototype.settings.AisSettings.java

/**
 * Updates the the given {@code props} properties with the the AIS-specific settings
 * /*from   ww w.  ja  v  a 2s  .  co m*/
 * @param props
 *            the properties to update
 */
public void setProperties(Properties props) {
    props.put(PREFIX + "visible", Boolean.toString(visible));
    props.put(PREFIX + "strict", Boolean.toString(strict));
    props.put(PREFIX + "minRedrawInterval", Integer.toString(minRedrawInterval));
    props.put(PREFIX + "allowSending", Boolean.toString(allowSending));
    props.put(PREFIX + "sartPrefix", Integer.toString(sartPrefix));
    props.put(PREFIX + "simulatedSartMmsi",
            StringUtils.defaultString(StringUtils.join(simulatedSartMmsi, ",")));
    props.put(PREFIX + "showNameLabels", Boolean.toString(showNameLabels));
    props.put(PREFIX + "pastTrackMaxTime", Integer.toString(pastTrackMaxTime));
    props.put(PREFIX + "pastTrackDisplayTime", Integer.toString(pastTrackDisplayTime));
    props.put(PREFIX + "pastTrackMinDist", Integer.toString(pastTrackMinDist));
    props.put(PREFIX + "pastTrackOwnShipMinDist", Integer.toString(pastTrackOwnShipMinDist));

    props.put(PREFIX + this.varNameCogVectorLengthMin, Integer.toString(this.cogVectorLengthMin));
    props.put(PREFIX + this.varNameCogVectorLengthMax, Integer.toString(this.cogVectorLengthMax));
    props.put(PREFIX + this.varNameCogVectorLengthScaleInterval,
            Float.toString(this.cogVectorLengthScaleInterval));
    props.put(PREFIX + this.varNameCogVectorHideBelow, Float.toString(this.cogVectorHideBelow));
}

From source file:com.opengamma.web.config.WebConfigsResource.java

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)//from w w w . ja v a2s .com
public Response postHTML(@FormParam("name") String name, @FormParam("configxml") String xml,
        @FormParam("type") String typeName) {
    name = StringUtils.trimToNull(name);
    xml = StringUtils.trimToNull(xml);
    typeName = StringUtils.trimToNull(typeName);

    final Class<?> type = (typeName != null ? data().getTypeMap().get(typeName) : null);
    if (name == null || xml == null || type == null) {
        FlexiBean out = createRootData();
        if (name == null) {
            out.put("err_nameMissing", true);
        }
        if (xml == null) {
            out.put("err_xmlMissing", true);
        }
        if (typeName == null) {
            out.put("err_typeMissing", true);
        } else if (type == null) {
            out.put("err_typeInvalid", true);
        }
        out.put("name", StringUtils.defaultString(name));
        out.put("type", StringUtils.defaultString(typeName));
        out.put("xml", StringUtils.defaultString(xml));
        String html = getFreemarker().build(HTML_DIR + "config-add.ftl", out);
        return Response.ok(html).build();
    }

    final Object configObj = parseXML(xml, type);
    ConfigItem<?> item = ConfigItem.of(configObj);
    item.setName(name);
    item.setType(type);
    ConfigDocument doc = new ConfigDocument(item);

    ConfigDocument added = data().getConfigMaster().add(doc);
    URI uri = data().getUriInfo().getAbsolutePathBuilder().path(added.getUniqueId().toLatest().toString())
            .build();
    return Response.seeOther(uri).build();
}

From source file:mitm.common.security.ca.CAImpl.java

private CertificateRequest toRequest(RequestParameters parameters, String handlerName) throws CAException {
    CertificateRequestEntity request = new CertificateRequestEntity(handlerName);

    String email = EmailAddressUtils.canonicalizeAndValidate(parameters.getEmail(), true);

    if (email == null) {
        throw new CAException(
                StringUtils.defaultString(parameters.getEmail()) + " is not a valid email address.");
    }//from w  w  w  . ja v a2 s .  c om

    request.setSubject(parameters.getSubject());
    request.setEmail(email);
    request.setValidity(parameters.getValidity());
    request.setKeyLength(parameters.getKeyLength());
    request.setSignatureAlgorithm(parameters.getSignatureAlgorithm());
    request.setCRLDistributionPoint(parameters.getCRLDistributionPoint());

    return request;
}